(()=>{var e,t,i={8045(e){"use strict";e.exports=function(e,t){for(var i=Array(arguments.length-1),s=0,r=2,a=!0;r<arguments.length;)i[s++]=arguments[r++];return new Promise(function(r,o){i[s]=function(e){if(a)if(a=!1,e)o(e);else{for(var t=Array(arguments.length-1),i=0;i<t.length;)t[i++]=arguments[i];r.apply(null,t)}};try{e.apply(t||null,i)}catch(e){a&&(a=!1,o(e))}})}},8839(e,t){"use strict";t.length=function(e){var t=e.length;if(!t)return 0;for(var i=0;--t%4>1&&"="===e.charAt(t);)++i;return Math.ceil(3*e.length)/4-i};for(var i=Array(64),s=Array(123),r=0;r<64;)s[i[r]=r<26?r+65:r<52?r+71:r<62?r-4:r-59|43]=r++;t.encode=function(e,t,s){for(var r,a=null,o=[],n=0,d=0;t<s;){var h=e[t++];switch(d){case 0:o[n++]=i[h>>2],r=(3&h)<<4,d=1;break;case 1:o[n++]=i[r|h>>4],r=(15&h)<<2,d=2;break;case 2:o[n++]=i[r|h>>6],o[n++]=i[63&h],d=0}n>8191&&((a||(a=[])).push(String.fromCharCode.apply(String,o)),n=0)}return(d&&(o[n++]=i[r],o[n++]=61,1===d&&(o[n++]=61)),a)?(n&&a.push(String.fromCharCode.apply(String,o.slice(0,n))),a.join("")):String.fromCharCode.apply(String,o.slice(0,n))};var a="invalid encoding";t.decode=function(e,t,i){for(var r,o=i,n=0,d=0;d<e.length;){var h=e.charCodeAt(d++);if(61===h&&n>1)break;if(void 0===(h=s[h]))throw Error(a);switch(n){case 0:r=h,n=1;break;case 1:t[i++]=r<<2|(48&h)>>4,r=h,n=2;break;case 2:t[i++]=(15&r)<<4|(60&h)>>2,r=h,n=3;break;case 3:t[i++]=(3&r)<<6|h,n=0}}if(1===n)throw Error(a);return i-o},t.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},4358(e){"use strict";function t(){this._listeners=Object.create(null)}e.exports=t,t.prototype.on=function(e,t,i){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:i||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners=Object.create(null);else if(void 0===t)this._listeners[e]=[];else{var i=this._listeners[e];if(!i)return this;for(var s=0;s<i.length;)i[s].fn===t?i.splice(s,1):++s}return this},t.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var i=[],s=1;s<arguments.length;)i.push(arguments[s++]);for(s=0;s<t.length;)t[s].fn.apply(t[s++].ctx,i)}return this}},9410(e){"use strict";function t(e){if("u">typeof Float32Array)!function(){var t=new Float32Array([-0]),i=new Uint8Array(t.buffer),s=128===i[3];function r(e,s,r){t[0]=e,s[r]=i[0],s[r+1]=i[1],s[r+2]=i[2],s[r+3]=i[3]}function a(e,s,r){t[0]=e,s[r]=i[3],s[r+1]=i[2],s[r+2]=i[1],s[r+3]=i[0]}function o(e,s){return i[0]=e[s],i[1]=e[s+1],i[2]=e[s+2],i[3]=e[s+3],t[0]}function n(e,s){return i[3]=e[s],i[2]=e[s+1],i[1]=e[s+2],i[0]=e[s+3],t[0]}e.writeFloatLE=s?r:a,e.writeFloatBE=s?a:r,e.readFloatLE=s?o:n,e.readFloatBE=s?n:o}();else{function t(e,t,i,s){var r=+(t<0);if(r&&(t=-t),0===t)e(1/t>0?0:0x80000000,i,s);else if(isNaN(t))e(0x7fc00000,i,s);else if(t>34028234663852886e22)e((r<<31|0x7f800000)>>>0,i,s);else if(t<11754943508222875e-54)e((r<<31|Math.round(t/1401298464324817e-60))>>>0,i,s);else{var a=Math.floor(Math.log(t)/Math.LN2),o=8388607&Math.round(t*Math.pow(2,-a)*8388608);e((r<<31|a+127<<23|o)>>>0,i,s)}}function o(e,t,i){var s=e(t,i),r=(s>>31)*2+1,a=s>>>23&255,o=8388607&s;return 255===a?o?NaN:1/0*r:0===a?1401298464324817e-60*r*o:r*Math.pow(2,a-150)*(o+8388608)}e.writeFloatLE=t.bind(null,i),e.writeFloatBE=t.bind(null,s),e.readFloatLE=o.bind(null,r),e.readFloatBE=o.bind(null,a)}if("u">typeof Float64Array)!function(){var t=new Float64Array([-0]),i=new Uint8Array(t.buffer),s=128===i[7];function r(e,s,r){t[0]=e,s[r]=i[0],s[r+1]=i[1],s[r+2]=i[2],s[r+3]=i[3],s[r+4]=i[4],s[r+5]=i[5],s[r+6]=i[6],s[r+7]=i[7]}function a(e,s,r){t[0]=e,s[r]=i[7],s[r+1]=i[6],s[r+2]=i[5],s[r+3]=i[4],s[r+4]=i[3],s[r+5]=i[2],s[r+6]=i[1],s[r+7]=i[0]}function o(e,s){return i[0]=e[s],i[1]=e[s+1],i[2]=e[s+2],i[3]=e[s+3],i[4]=e[s+4],i[5]=e[s+5],i[6]=e[s+6],i[7]=e[s+7],t[0]}function n(e,s){return i[7]=e[s],i[6]=e[s+1],i[5]=e[s+2],i[4]=e[s+3],i[3]=e[s+4],i[2]=e[s+5],i[1]=e[s+6],i[0]=e[s+7],t[0]}e.writeDoubleLE=s?r:a,e.writeDoubleBE=s?a:r,e.readDoubleLE=s?o:n,e.readDoubleBE=s?n:o}();else{function n(e,t,i,s,r,a){var o,n=+(s<0);if(n&&(s=-s),0===s)e(0,r,a+t),e(1/s>0?0:0x80000000,r,a+i);else if(isNaN(s))e(0,r,a+t),e(0x7ff80000,r,a+i);else if(s>17976931348623157e292)e(0,r,a+t),e((n<<31|0x7ff00000)>>>0,r,a+i);else if(s<22250738585072014e-324)e((o=s/5e-324)>>>0,r,a+t),e((n<<31|o/0x100000000)>>>0,r,a+i);else{var d=Math.floor(Math.log(s)/Math.LN2);1024===d&&(d=1023),e(0x10000000000000*(o=s*Math.pow(2,-d))>>>0,r,a+t),e((n<<31|d+1023<<20|1048576*o&1048575)>>>0,r,a+i)}}function d(e,t,i,s,r){var a=e(s,r+t),o=e(s,r+i),n=(o>>31)*2+1,d=o>>>20&2047,h=0x100000000*(1048575&o)+a;return 2047===d?h?NaN:1/0*n:0===d?5e-324*n*h:n*Math.pow(2,d-1075)*(h+0x10000000000000)}e.writeDoubleLE=n.bind(null,i,0,4),e.writeDoubleBE=n.bind(null,s,4,0),e.readDoubleLE=d.bind(null,r,0,4),e.readDoubleBE=d.bind(null,a,4,0)}return e}function i(e,t,i){t[i]=255&e,t[i+1]=e>>>8&255,t[i+2]=e>>>16&255,t[i+3]=e>>>24}function s(e,t,i){t[i]=e>>>24,t[i+1]=e>>>16&255,t[i+2]=e>>>8&255,t[i+3]=255&e}function r(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function a(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},9390(e){"use strict";e.exports=function(e,t,i){var s=i||8192,r=s>>>1,a=null,o=s;return function(i){if(i<1||i>r)return e(i);o+i>s&&(a=e(s),o=0);var n=t.call(a,o,o+=i);return 7&o&&(o=(7|o)+1),n}}},1447(e,t){"use strict";t.length=function(e){for(var t=0,i=0,s=0;s<e.length;++s)(i=e.charCodeAt(s))<128?t+=1:i<2048?t+=2:(64512&i)==55296&&(64512&e.charCodeAt(s+1))==56320?(++s,t+=4):t+=3;return t},t.read=function(e,t,i){if(i-t<1)return"";for(var s="",r=t;r<i;){var a=e[r++];if(a<=127)s+=String.fromCharCode(a);else if(a>=192&&a<224){var o=(31&a)<<6|63&e[r++];s+=o>=128?String.fromCharCode(o):"�"}else if(a>=224&&a<240){var n=(15&a)<<12|(63&e[r++])<<6|63&e[r++];s+=n>=2048?String.fromCharCode(n):"�"}else if(a>=240){var d=(7&a)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++];d<65536||d>1114111?s+="�":(d-=65536,s+=String.fromCharCode(55296+(d>>10)),s+=String.fromCharCode(56320+(1023&d)))}}return s},t.write=function(e,t,i){for(var s,r,a=i,o=0;o<e.length;++o)(s=e.charCodeAt(o))<128?t[i++]=s:(s<2048?t[i++]=s>>6|192:((64512&s)==55296&&(64512&(r=e.charCodeAt(o+1)))==56320?(s=65536+((1023&s)<<10)+(1023&r),++o,t[i++]=s>>18|240,t[i++]=s>>12&63|128):t[i++]=s>>12|224,t[i++]=s>>6&63|128),t[i++]=63&s|128);return i-a}},9861(e,t,i){"use strict";var s=Uint8Array,r=Uint16Array,a=Int32Array,o=new s([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),n=new s([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),d=new s([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),h=function(e,t){for(var i=new r(31),s=0;s<31;++s)i[s]=t+=1<<e[s-1];for(var o=new a(i[30]),s=1;s<30;++s)for(var n=i[s];n<i[s+1];++n)o[n]=n-i[s]<<5|s;return{b:i,r:o}},c=h(o,2),l=c.b,u=c.r;l[28]=258,u[258]=28;var f=h(n,0),p=f.b;f.r;for(var m=new r(32768),g=0;g<32768;++g){var v=(43690&g)>>1|(21845&g)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,m[g]=((65280&v)>>8|(255&v)<<8)>>1}for(var y=function(e,t,i){for(var s,a=e.length,o=0,n=new r(t);o<a;++o)e[o]&&++n[e[o]-1];var d=new r(t);for(o=1;o<t;++o)d[o]=d[o-1]+n[o-1]<<1;if(i){s=new r(1<<t);var h=15-t;for(o=0;o<a;++o)if(e[o])for(var c=o<<4|e[o],l=t-e[o],u=d[e[o]-1]++<<l,f=u|(1<<l)-1;u<=f;++u)s[m[u]>>h]=c}else for(s=new r(a),o=0;o<a;++o)e[o]&&(s[o]=m[d[e[o]-1]++]>>15-e[o]);return s},b=new s(288),g=0;g<144;++g)b[g]=8;for(var g=144;g<256;++g)b[g]=9;for(var g=256;g<280;++g)b[g]=7;for(var g=280;g<288;++g)b[g]=8;for(var w=new s(32),g=0;g<32;++g)w[g]=5;var k=y(b,9,1),S=y(w,5,1),O=function(e){for(var t=e[0],i=1;i<e.length;++i)e[i]>t&&(t=e[i]);return t},T=function(e,t,i){var s=t/8|0;return(e[s]|e[s+1]<<8)>>(7&t)&i},P=function(e,t){var i=t/8|0;return(e[i]|e[i+1]<<8|e[i+2]<<16)>>(7&t)},I=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],A=function(e,t,i){var s=Error(t||I[e]);if(s.code=e,Error.captureStackTrace&&Error.captureStackTrace(s,A),!i)throw s;return s},x=function(e,t,i,r){var a,h,c,u=e.length,f=r?r.length:0;if(!u||t.f&&!t.l)return i||new s(0);var m=!i,g=m||2!=t.i,v=t.i;m&&(i=new s(3*u));var b=function(e){var t=i.length;if(e>t){var r=new s(Math.max(2*t,e));r.set(i),i=r}},w=t.f||0,I=t.p||0,x=t.b||0,M=t.l,_=t.d,C=t.m,B=t.n,E=8*u;do{if(!M){w=T(e,I,1);var R=T(e,I+1,3);if(I+=3,R)if(1==R)M=k,_=S,C=9,B=5;else if(2==R){var L=T(e,I,31)+257,N=T(e,I+10,15)+4,D=L+T(e,I+5,31)+1;I+=14;for(var q=new s(D),F=new s(19),V=0;V<N;++V)F[d[V]]=T(e,I+3*V,7);I+=3*N;for(var G=O(F),H=(1<<G)-1,U=y(F,G,1),V=0;V<D;){var W=U[T(e,I,H)];I+=15&W;var j=W>>4;if(j<16)q[V++]=j;else{var K=0,z=0;for(16==j?(z=3+T(e,I,3),I+=2,K=q[V-1]):17==j?(z=3+T(e,I,7),I+=3):18==j&&(z=11+T(e,I,127),I+=7);z--;)q[V++]=K}}var Y=q.subarray(0,L),X=q.subarray(L);C=O(Y),B=O(X),M=y(Y,C,1),_=y(X,B,1)}else A(1);else{var j=((I+7)/8|0)+4,Q=e[j-4]|e[j-3]<<8,Z=j+Q;if(Z>u){v&&A(0);break}g&&b(x+Q),i.set(e.subarray(j,Z),x),t.b=x+=Q,t.p=I=8*Z,t.f=w;continue}if(I>E){v&&A(0);break}}g&&b(x+131072);for(var J=(1<<C)-1,$=(1<<B)-1,ee=I;;ee=I){var K=M[P(e,I)&J],et=K>>4;if((I+=15&K)>E){v&&A(0);break}if(K||A(2),et<256)i[x++]=et;else if(256==et){ee=I,M=null;break}else{var ei=et-254;if(et>264){var V=et-257,es=o[V];ei=T(e,I,(1<<es)-1)+l[V],I+=es}var er=_[P(e,I)&$],ea=er>>4;er||A(3),I+=15&er;var X=p[ea];if(ea>3){var es=n[ea];X+=P(e,I)&(1<<es)-1,I+=es}if(I>E){v&&A(0);break}g&&b(x+131072);var eo=x+ei;if(x<X){var en=f-X,ed=Math.min(X,eo);for(en+x<0&&A(3);x<ed;++x)i[x]=r[en+x]}for(;x<eo;++x)i[x]=i[x-X]}}t.l=M,t.p=ee,t.b=x,t.f=w,M&&(w=1,t.m=C,t.d=_,t.n=B)}while(!w);return x!=i.length&&m?(a=i,(h=0)<0&&(h=0),(null==(c=x)||c>a.length)&&(c=a.length),new s(a.subarray(h,c))):i.subarray(0,x)},M=new s(0),_=function(e){(31!=e[0]||139!=e[1]||8!=e[2])&&A(6,"invalid gzip data");var t=e[3],i=10;4&t&&(i+=(e[10]|e[11]<<8)+2);for(var s=(t>>3&1)+(t>>4&1);s>0;s-=!e[i++]);return i+(2&t)},C=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0};function B(e,t){return x(e,{i:2},t&&t.out,t&&t.dictionary)}function E(e,t){var i=_(e);return i+8>e.length&&A(6,"invalid gzip data"),x(e.subarray(i,-8),{i:2},t&&t.out||new s(C(e)),t&&t.dictionary)}var R="u">typeof TextDecoder&&new TextDecoder;try{R.decode(M,{stream:!0})}catch(e){}"function"==typeof queueMicrotask&&queueMicrotask,i.d(t,{gunzipSync:()=>E,inflateSync:()=>B})},6946(e,t,i){"use strict";e.exports=i(4394)},4394(e,t,i){"use strict";function s(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}t.build="minimal",t.Writer=i(3449),t.BufferWriter=i(818),t.Reader=i(6237),t.BufferReader=i(3158),t.util=i(3610),t.rpc=i(5047),t.roots=i(4529),t.configure=s,s()},6237(e,t,i){"use strict";e.exports=h;var s,r,a=i(3610),o=a.LongBits,n=a.utf8;function d(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function h(e){this.buf=e,this.pos=0,this.len=e.length}var c="u">typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new h(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new h(e);throw Error("illegal buffer")},l=function(){return a.Buffer?function(e){return(h.create=function(e){return a.Buffer.isBuffer(e)?new r(e):c(e)})(e)}:c};function u(){var e=new o(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw d(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw d(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function f(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function p(){if(this.pos+8>this.len)throw d(this,8);return new o(f(this.buf,this.pos+=4),f(this.buf,this.pos+=4))}h.create=l(),h.prototype._slice=a.Array.prototype.subarray||a.Array.prototype.slice,h.prototype.uint32=(s=0xffffffff,function(){if(s=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(s=(s|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)||(s=(s|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)||(s=(s|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)||(s=(s|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128))return s;if((this.pos+=5)>this.len)throw this.pos=this.len,d(this,10);return s}),h.prototype.int32=function(){return 0|this.uint32()},h.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},h.prototype.bool=function(){return 0!==this.uint32()},h.prototype.fixed32=function(){if(this.pos+4>this.len)throw d(this,4);return f(this.buf,this.pos+=4)},h.prototype.sfixed32=function(){if(this.pos+4>this.len)throw d(this,4);return 0|f(this.buf,this.pos+=4)},h.prototype.float=function(){if(this.pos+4>this.len)throw d(this,4);var e=a.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},h.prototype.double=function(){if(this.pos+8>this.len)throw d(this,4);var e=a.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},h.prototype.bytes=function(){var e=this.uint32(),t=this.pos,i=this.pos+e;if(i>this.len)throw d(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,i);if(t===i){var s=a.Buffer;return s?s.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,i)},h.prototype.string=function(){var e=this.bytes();return n.read(e,0,e.length)},h.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw d(this,e);this.pos+=e}else do if(this.pos>=this.len)throw d(this);while(128&this.buf[this.pos++]);return this},h.recursionLimit=a.recursionLimit,h.prototype.skipType=function(e,t){if(void 0===t&&(t=0),t>h.recursionLimit)throw Error("maximum nesting depth exceeded");switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e,t+1);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},h._configure=function(e){r=e,h.create=l(),r._configure();var t=a.Long?"toLong":"toNumber";a.merge(h.prototype,{int64:function(){return u.call(this)[t](!1)},uint64:function(){return u.call(this)[t](!0)},sint64:function(){return u.call(this).zzDecode()[t](!1)},fixed64:function(){return p.call(this)[t](!0)},sfixed64:function(){return p.call(this)[t](!1)}})}},3158(e,t,i){"use strict";e.exports=a;var s=i(6237);(a.prototype=Object.create(s.prototype)).constructor=a;var r=i(3610);function a(e){s.call(this,e)}a._configure=function(){r.Buffer&&(a.prototype._slice=r.Buffer.prototype.slice)},a.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},a._configure()},4529(e){"use strict";e.exports=Object.create(null)},5047(e,t,i){"use strict";t.Service=i(7595)},7595(e,t,i){"use strict";e.exports=r;var s=i(3610);function r(e,t,i){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");s.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=!!t,this.responseDelimited=!!i}(r.prototype=Object.create(s.EventEmitter.prototype)).constructor=r,r.prototype.rpcCall=function e(t,i,r,a,o){if(!a)throw TypeError("request must be specified");var n=this;if(!o)return s.asPromise(e,n,t,i,r,a);if(!n.rpcImpl)return void setTimeout(function(){o(Error("already ended"))},0);try{return n.rpcImpl(t,i[n.requestDelimited?"encodeDelimited":"encode"](a).finish(),function(e,i){if(e)return n.emit("error",e,t),o(e);if(null===i)return void n.end(!0);if(!(i instanceof r))try{i=r[n.responseDelimited?"decodeDelimited":"decode"](i)}catch(e){return n.emit("error",e,t),o(e)}return n.emit("data",i,t),o(null,i)})}catch(e){n.emit("error",e,t),setTimeout(function(){o(e)},0);return}},r.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},2239(e,t,i){"use strict";e.exports=r;var s=i(3610);function r(e,t){this.lo=e>>>0,this.hi=t>>>0}var a=r.zero=new r(0,0);a.toNumber=function(){return 0},a.zzEncode=a.zzDecode=function(){return this},a.length=function(){return 1};var o=r.zeroHash="\0\0\0\0\0\0\0\0";r.fromNumber=function(e){if(0===e)return a;var t=e<0;t&&(e=-e);var i=e>>>0,s=(e-i)/0x100000000>>>0;return t&&(s=~s>>>0,i=~i>>>0,++i>0xffffffff&&(i=0,++s>0xffffffff&&(s=0))),new r(i,s)},r.from=function(e){if("number"==typeof e)return r.fromNumber(e);if(s.isString(e))if(!s.Long)return r.fromNumber(parseInt(e,10));else e=s.Long.fromString(e);return e.low||e.high?new r(e.low>>>0,e.high>>>0):a},r.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,i=~this.hi>>>0;return t||(i=i+1>>>0),-(t+0x100000000*i)}return this.lo+0x100000000*this.hi},r.prototype.toLong=function(e){return s.Long?new s.Long(0|this.lo,0|this.hi,!!e):{low:0|this.lo,high:0|this.hi,unsigned:!!e}};var n=String.prototype.charCodeAt;r.fromHash=function(e){return e===o?a:new r((n.call(e,0)|n.call(e,1)<<8|n.call(e,2)<<16|n.call(e,3)<<24)>>>0,(n.call(e,4)|n.call(e,5)<<8|n.call(e,6)<<16|n.call(e,7)<<24)>>>0)},r.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},r.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},r.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},r.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,i=this.hi>>>24;return 0===i?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:i<128?9:10}},3610(e,t,i){"use strict";function s(e){return"__proto__"===e||"prototype"===e||"constructor"===e}function r(e){var t="boolean"==typeof arguments[arguments.length-1],i=t?arguments.length-1:arguments.length;t=t&&arguments[arguments.length-1];for(var r=1;r<i;++r){var a=arguments[r];if(a)for(var o=Object.keys(a),n=0;n<o.length;++n)s(o[n])||void 0!==e[o[n]]&&t||(e[o[n]]=a[o[n]])}return e}function a(e){function t(e,i){if(!(this instanceof t))return new t(e,i);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:Error().stack||""}),i&&r(this,i)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}t.asPromise=i(8045),t.base64=i(8839),t.EventEmitter=i(4358),t.float=i(9410),t.utf8=i(1447),t.pool=i(9390),t.LongBits=i(2239),t.isUnsafeProperty=s,t.isNode=!!(void 0!==i.g&&i.g&&i.g.process&&i.g.process.versions&&i.g.process.versions.node),t.global=t.isNode&&i.g||"u">typeof window&&window||"u">typeof self&&self||this,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},t.isString=function(e){return"string"==typeof e||e instanceof String},t.isObject=function(e){return e&&"object"==typeof e},t.isset=t.isSet=function(e,t){var i=e[t];return!!(null!=i&&Object.hasOwnProperty.call(e,t))&&("object"!=typeof i||(Array.isArray(i)?i.length:Object.keys(i).length)>0)},t.Buffer=function(){try{var e=t.global.Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function(e){return"number"==typeof e?t.Buffer?t._Buffer_allocUnsafe(e):new t.Array(e):t.Buffer?t._Buffer_from(e):"u"<typeof Uint8Array?e:new Uint8Array(e)},t.Array="u">typeof Uint8Array?Uint8Array:Array,t.Long=t.global.dcodeIO&&t.global.dcodeIO.Long||t.global.Long||function(){try{var e=i(5017);return e&&e.isLong?e:null}catch(e){return null}}(),t.key2Re=/^true|false|0|1$/,t.key32Re=/^-?(?:0|[1-9][0-9]*)$/,t.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,t.longToHash=function(e){return e?t.LongBits.from(e).toHash():t.LongBits.zeroHash},t.longFromHash=function(e,i){var s=t.LongBits.fromHash(e);return t.Long?t.Long.fromBits(s.lo,s.hi,i):s.toNumber(!!i)},t.merge=r,t.nestingLimit=32,t.recursionLimit=100,t.makeProp=function(e,t){Object.defineProperty(e,t,{enumerable:!0,configurable:!0,writable:!0})},t.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},t.newError=a,t.ProtocolError=a("ProtocolError"),t.oneOfGetter=function(e){for(var t={},i=0;i<e.length;++i)t[e[i]]=1;return function(){for(var e=Object.keys(this),i=e.length-1;i>-1;--i)if(1===t[e[i]]&&void 0!==this[e[i]]&&null!==this[e[i]])return e[i]}},t.oneOfSetter=function(e){return function(t){for(var i=0;i<e.length;++i)e[i]!==t&&delete this[e[i]]}},t.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},t._configure=function(){var e=t.Buffer;if(!e){t._Buffer_from=t._Buffer_allocUnsafe=null;return}t._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,i){return new e(t,i)},t._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}}},3449(e,t,i){"use strict";e.exports=l;var s,r=i(3610),a=r.LongBits,o=r.base64,n=r.utf8;function d(e,t,i){this.fn=e,this.len=t,this.next=void 0,this.val=i}function h(){}function c(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function l(){this.len=0,this.head=new d(h,0,0),this.tail=this.head,this.states=null}var u=function(){return r.Buffer?function(){return(l.create=function(){return new s})()}:function(){return new l}};function f(e,t,i){t[i]=255&e}function p(e,t){this.len=e,this.next=void 0,this.val=t}function m(e,t,i){for(var s=e.lo,r=e.hi;r;)t[i++]=127&s|128,s=(s>>>7|r<<25)>>>0,r>>>=7;for(;s>127;)t[i++]=127&s|128,s>>>=7;t[i++]=s}function g(e,t,i){t[i]=255&e,t[i+1]=e>>>8&255,t[i+2]=e>>>16&255,t[i+3]=e>>>24}l.create=u(),l.alloc=function(e){return new r.Array(e)},r.Array!==Array&&(l.alloc=r.pool(l.alloc,r.Array.prototype.subarray)),l.prototype._push=function(e,t,i){return this.tail=this.tail.next=new d(e,t,i),this.len+=t,this},p.prototype=Object.create(d.prototype),p.prototype.fn=function(e,t,i){for(;e>127;)t[i++]=127&e|128,e>>>=7;t[i]=e},l.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new p((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<0x10000000?4:5,e)).len,this},l.prototype.int32=function(e){return(e|=0)<0?this._push(m,10,a.fromNumber(e)):this.uint32(e)},l.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},l.prototype.uint64=function(e){var t=a.from(e);return this._push(m,t.length(),t)},l.prototype.int64=l.prototype.uint64,l.prototype.sint64=function(e){var t=a.from(e).zzEncode();return this._push(m,t.length(),t)},l.prototype.bool=function(e){return this._push(f,1,+!!e)},l.prototype.fixed32=function(e){return this._push(g,4,e>>>0)},l.prototype.sfixed32=l.prototype.fixed32,l.prototype.fixed64=function(e){var t=a.from(e);return this._push(g,4,t.lo)._push(g,4,t.hi)},l.prototype.sfixed64=l.prototype.fixed64,l.prototype.float=function(e){return this._push(r.float.writeFloatLE,4,e)},l.prototype.double=function(e){return this._push(r.float.writeDoubleLE,8,e)};var v=r.Array.prototype.set?function(e,t,i){t.set(e,i)}:function(e,t,i){for(var s=0;s<e.length;++s)t[i+s]=e[s]};l.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(f,1,0);if(r.isString(e)){var i=l.alloc(t=o.length(e));o.decode(e,i,0),e=i}return this.uint32(t)._push(v,t,e)},l.prototype.string=function(e){var t=n.length(e);return t?this.uint32(t)._push(n.write,t,e):this._push(f,1,0)},l.prototype.fork=function(){return this.states=new c(this),this.head=this.tail=new d(h,0,0),this.len=0,this},l.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new d(h,0,0),this.len=0),this},l.prototype.ldelim=function(){var e=this.head,t=this.tail,i=this.len;return this.reset().uint32(i),i&&(this.tail.next=e.next,this.tail=t,this.len+=i),this},l.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),i=0;e;)e.fn(e.val,t,i),i+=e.len,e=e.next;return t},l._configure=function(e){s=e,l.create=u(),s._configure()}},818(e,t,i){"use strict";e.exports=a;var s=i(3449);(a.prototype=Object.create(s.prototype)).constructor=a;var r=i(3610);function a(){s.call(this)}function o(e,t,i){e.length<40?r.utf8.write(e,t,i):t.utf8Write?t.utf8Write(e,i):t.write(e,i)}a._configure=function(){a.alloc=r._Buffer_allocUnsafe,a.writeBytesBuffer=r.Buffer&&r.Buffer.prototype instanceof Uint8Array&&"set"===r.Buffer.prototype.set.name?function(e,t,i){t.set(e,i)}:function(e,t,i){if(e.copy)e.copy(t,i,0,e.length);else for(var s=0;s<e.length;)t[i++]=e[s++]}},a.prototype.bytes=function(e){r.isString(e)&&(e=r._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(a.writeBytesBuffer,t,e),this},a.prototype.string=function(e){var t=r.Buffer.byteLength(e);return this.uint32(t),t&&this._push(o,t,e),this},a._configure()},1591(e){"use strict";e.exports=function(){throw Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},5427(e){function t(e){return Promise.resolve().then(function(){var t=Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=5427,e.exports=t},7073(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},9619(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},3268(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},4953(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},3893(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},5077(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},130(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},927(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},2330(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},5987(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},4986(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},2240(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},5458(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},6148(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},7488(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},8418(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},138(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},4705(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},9385(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},3076(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},8498(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},7156(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},5331(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},7567(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},227(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},9980(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},2517(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},9156(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},1355(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},6141(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},6131(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},1251(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},5266(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},9487(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},5936(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},8451(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},3075(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},7436(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},2597(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},8118(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},5561(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},7835(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},5496(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},1065(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},9458(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},7196(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},7854(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},6760(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},3226(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},4139(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},3032(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},2412(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},8512(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},1264(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},2495(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},9447(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},526(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},4135(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},6641(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},4885(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},8740(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},6253(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},3217(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},7790(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},3851(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},1713(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},4748(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},7527(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},4930(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},1852(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},4496(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},2202(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},5287(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},2356(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},2481(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},3214(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},3703(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},7313(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},3496(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},7113(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},2400(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},2819(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},4015(e,t,i){"use strict";var s=i(1374);class r extends s.A{}i.d(t,{},{A:r})},5087(e,t,i){"use strict";var s=i(1374);class r extends s.A{}i.d(t,{},{A:r})},1695(e,t,i){"use strict";var s=i(1374);class r extends s.A{}i.d(t,{},{A:r})},4531(e,t,i){"use strict";var s=i(1374);class r extends s.A{}i.d(t,{},{A:r})},5843(e,t,i){"use strict";var s=i(1374);class r extends s.A{}i.d(t,{},{A:r})},3647(e,t,i){"use strict";var s=i(1374);class r extends s.A{}i.d(t,{},{A:r})},9715(e,t,i){"use strict";var s=i(1374);class r extends s.A{}i.d(t,{},{A:r})},883(e,t,i){"use strict";var s=i(1374);class r extends s.A{}i.d(t,{},{A:r})},7559(e,t,i){"use strict";var s=i(1374);class r extends s.A{}i.d(t,{},{A:r})},7838(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},273(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},726(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},2199(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},950(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},6415(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},8208(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},7758(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},6459(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},9109(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},2610(e,t,i){"use strict";var s=i(6039);class r extends s.k5{}i.d(t,{},{A:r})},7040(e,t,i){"use strict";var s=i(7073),r=i(7749),a=i(1453);class o extends s.A{describe(){return this.deepExtend(super.describe(),{id:"alpaca",name:"Alpaca",countries:["US"],rateLimit:333,hostname:"alpaca.markets",pro:!0,urls:{logo:"https://github.com/user-attachments/assets/e9476df8-a450-4c3e-ab9a-1a7794219e1b",www:"https://alpaca.markets",api:{broker:"https://broker-api.{hostname}",trader:"https://api.{hostname}",market:"https://data.{hostname}"},test:{broker:"https://broker-api.sandbox.{hostname}",trader:"https://paper-api.{hostname}",market:"https://data.{hostname}"},doc:"https://alpaca.markets/docs/",fees:"https://docs.alpaca.markets/docs/crypto-fees"},has:{CORS:!1,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createMarketBuyOrder:!0,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!0,createMarketSellOrderWithCost:!0,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createReduceOnlyOrder:!1,createStopOrder:!0,createTriggerOrder:!0,editOrder:!0,fetchBalance:!0,fetchBidsAsks:!1,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDepositAddress:!0,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchL1OrderBook:!0,fetchL2OrderBook:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrder:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchStatus:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTransactionFees:!1,fetchTransactions:!1,fetchTransfers:!1,fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,sandbox:!0,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,withdraw:!0},api:{broker:{private:{get:{"v1/accounts/{account_id}/tokenization/requests":{cost:1},"v1/accounts/{account_id}/tokenization/requests/{tokenization_request_id}":{cost:1},"v1/accounts/{account_id}/tokenization/requests:by_client_request_id":{cost:1},"v1/accounts/{account_id}/tokenization/requests:by_issuer_request_id":{cost:1},"v1/fpsl/analytics/{account_id}/loans":{cost:1},"v1/ipos":{cost:1},"v1/ipos/{offering_reference}":{cost:1},"v1/wallets/travel-rule/vasps":{cost:1},"v1beta1/acats":{cost:1},"v1beta1/acats/contrabrokers":{cost:1},"v1beta1/acats/{account_id}":{cost:1},"v1beta1/acats/{account_id}/{acats_id}":{cost:1},"v1beta1/acats/{account_id}/{acats_id}/assets":{cost:1}},post:{"v1beta1/acats/{account_id}":{cost:1}},patch:{"v1/accounts/{account_id}/wallets/whitelists/{whitelisted_address_id}/travel-rule-info":{cost:1}}}},trader:{private:{get:{"v2/account":{cost:1},"v2/orders":{cost:1},"v2/orders/{order_id}":{cost:1},"v2/positions":{cost:1},"v2/positions/{symbol_or_asset_id}":{cost:1},"v2/account/portfolio/history":{cost:1},"v2/watchlists":{cost:1},"v2/watchlists/{watchlist_id}":{cost:1},"v2/watchlists:by_name":{cost:1},"v2/account/configurations":{cost:1},"v2/account/activities":{cost:1},"v2/account/activities/{activity_type}":{cost:1},"v2/calendar":{cost:1},"v2/clock":{cost:1},"v2/assets":{cost:1},"v2/assets/{symbol_or_asset_id}":{cost:1},"v2/corporate_actions/announcements/{id}":{cost:1},"v2/corporate_actions/announcements":{cost:1},"v2/wallets":{cost:1},"v2/wallets/transfers":{cost:1},"v1/locates":{cost:1},"v1/locates/{locate_id}":{cost:1},"v1/locates/quotes":{cost:1},"v2/tokenization/requests":{cost:1},"v2/tokenization/requests/{tokenization_request_id}":{cost:1},"v2/tokenization/requests:by_client_request_id":{cost:1},"v2/wallets/travel-rule/vasps":{cost:1}},post:{"v2/orders":{cost:1},"v2/watchlists":{cost:1},"v2/watchlists/{watchlist_id}":{cost:1},"v2/watchlists:by_name":{cost:1},"v2/wallets/transfers":{cost:1},"v1/locates":{cost:1}},put:{"v2/orders/{order_id}":{cost:1},"v2/watchlists/{watchlist_id}":{cost:1},"v2/watchlists:by_name":{cost:1}},patch:{"v2/orders/{order_id}":{cost:1},"v2/account/configurations":{cost:1},"v2/wallets/whitelists/{whitelisted_address_id}/travel-rule-info":{cost:1}},delete:{"v2/orders":{cost:1},"v2/orders/{order_id}":{cost:1},"v2/positions":{cost:1},"v2/positions/{symbol_or_asset_id}":{cost:1},"v2/watchlists/{watchlist_id}":{cost:1},"v2/watchlists:by_name":{cost:1},"v2/watchlists/{watchlist_id}/{symbol}":{cost:1}}}},market:{public:{get:{"v1beta3/crypto/{loc}/bars":{cost:1},"v1beta3/crypto/{loc}/latest/bars":{cost:1},"v1beta3/crypto/{loc}/latest/orderbooks":{cost:1},"v1beta3/crypto/{loc}/latest/quotes":{cost:1},"v1beta3/crypto/{loc}/latest/trades":{cost:1},"v1beta3/crypto/{loc}/quotes":{cost:1},"v1beta3/crypto/{loc}/snapshots":{cost:1},"v1beta3/crypto/{loc}/trades":{cost:1}}},private:{get:{"v1beta1/corporate-actions":{cost:1},"v1beta1/fixed_income/latest/prices":{cost:1},"v1beta1/fixed_income/latest/quotes":{cost:1},"v1beta1/forex/latest/rates":{cost:1},"v1beta1/forex/rates":{cost:1},"v1beta1/logos/{symbol}":{cost:1},"v1beta1/news":{cost:1},"v1beta1/screener/stocks/most-actives":{cost:1},"v1beta1/screener/{market_type}/movers":{cost:1},"v2/stocks/auctions":{cost:1},"v2/stocks/bars":{cost:1},"v2/stocks/bars/latest":{cost:1},"v2/stocks/meta/conditions/{ticktype}":{cost:1},"v2/stocks/meta/exchanges":{cost:1},"v2/stocks/quotes":{cost:1},"v2/stocks/quotes/latest":{cost:1},"v2/stocks/snapshots":{cost:1},"v2/stocks/trades":{cost:1},"v2/stocks/trades/latest":{cost:1},"v2/stocks/{symbol}/auctions":{cost:1},"v2/stocks/{symbol}/bars":{cost:1},"v2/stocks/{symbol}/bars/latest":{cost:1},"v2/stocks/{symbol}/quotes":{cost:1},"v2/stocks/{symbol}/quotes/latest":{cost:1},"v2/stocks/{symbol}/snapshot":{cost:1},"v2/stocks/{symbol}/trades":{cost:1},"v2/stocks/{symbol}/trades/latest":{cost:1}}}}},timeframes:{"1m":"1min","3m":"3min","5m":"5min","15m":"15min","30m":"30min","1h":"1H","2h":"2H","4h":"4H","6h":"6H","8h":"8H","12h":"12H","1d":"1D","3d":"3D","1w":"1W","1M":"1M"},precisionMode:4,requiredCredentials:{apiKey:!0,secret:!0},fees:{trading:{tierBased:!0,percentage:!0,maker:this.parseNumber("0.0015"),taker:this.parseNumber("0.0025"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.0025")],[this.parseNumber("100000"),this.parseNumber("0.0022")],[this.parseNumber("500000"),this.parseNumber("0.0020")],[this.parseNumber("1000000"),this.parseNumber("0.0018")],[this.parseNumber("10000000"),this.parseNumber("0.0015")],[this.parseNumber("25000000"),this.parseNumber("0.0013")],[this.parseNumber("50000000"),this.parseNumber("0.0012")],[this.parseNumber("100000000"),this.parseNumber("0.001")]],maker:[[this.parseNumber("0"),this.parseNumber("0.0015")],[this.parseNumber("100000"),this.parseNumber("0.0012")],[this.parseNumber("500000"),this.parseNumber("0.001")],[this.parseNumber("1000000"),this.parseNumber("0.0008")],[this.parseNumber("10000000"),this.parseNumber("0.0005")],[this.parseNumber("25000000"),this.parseNumber("0.0002")],[this.parseNumber("50000000"),this.parseNumber("0.0002")],[this.parseNumber("100000000"),this.parseNumber("0.00")]]}}},headers:{"APCA-PARTNER-ID":"ccxt"},options:{minCostUSD:10,defaultExchange:"CBSE",exchanges:["CBSE","FTX","GNSS","ERSX"],createOrder:{timeInForce:"gtc"},clientOrderId:"ccxt_{id}"},features:{spot:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:{triggerPriceType:{last:!0,mark:!0,index:!0},price:!0},timeInForce:{IOC:!0,FOK:!1,PO:!1,GTD:!1},hedged:!1,trailing:!0,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:500,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:500,daysBack:1e5,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:500,daysBack:1e5,daysBackCanceled:void 0,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:1e3}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},exceptions:{exact:{"forbidden.":a.PermissionDenied,4041e4:a.InvalidOrder,0x2628111:a.BadRequest,4011e4:a.PermissionDenied,4221e4:a.BadRequest,4291e4:a.RateLimitExceeded},broad:{"Invalid format for parameter":a.BadRequest,"Invalid symbol":a.BadSymbol,"cost basis must be":a.InvalidOrder,"insufficient balance for":a.InsufficientFunds,"orders are rejected by user request":a.PermissionDenied}}})}async fetchTime(e={}){let t=await this.traderPrivateGetV2Clock(e),i=this.parse8601(this.safeString(t,"timestamp"));if(void 0===i)throw new a.ExchangeError(this.id+" fetchTime() missing timestamp");return i}async fetchMarkets(e={}){let t=await this.traderPrivateGetV2Assets(this.extend({asset_class:"crypto",status:"active"},e));return this.parseMarkets(t)}parseMarket(e){let t,i=this.safeString(e,"symbol");if(void 0===i)throw new a.ExchangeError(this.id+" parseMarket() missing marketId");let s=i.split("/"),r=this.safeString(e,"class"),o=this.safeString(s,0),n=this.safeString(s,1),d=this.safeCurrencyCode(o),h=this.safeCurrencyCode(n);if(void 0===h&&"us_equity"===r&&(h="USD"),void 0===d||void 0===h)return;let c=d+"/"+h,l=this.safeString(e,"status"),u=this.safeNumber(e,"min_order_size"),f=this.safeNumber(e,"min_trade_increment"),p=this.safeNumber(e,"price_increment");return"crypto"===r&&"USD"===h&&(t=this.safeNumber(this.options,"minCostUSD",this.parseNumber("10"))),this.safeMarketStructure({id:i,symbol:c,base:d,quote:h,settle:void 0,baseId:o,quoteId:n,settleId:void 0,type:"spot",spot:!0,margin:void 0,swap:!1,future:!1,option:!1,active:"active"===l,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:f,price:p},limits:{leverage:{min:void 0,max:void 0},amount:{min:u,max:void 0},price:{min:void 0,max:void 0},cost:{min:t,max:void 0}},created:void 0,info:e})}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=o.id,d=this.safeString(s,"loc","us"),h=this.safeString(s,"method","marketPublicGetV1beta3CryptoLocTrades"),c={symbols:n,loc:d},l=this.omit(s,["loc","method"]);if("marketPublicGetV1beta3CryptoLocTrades"===h){void 0!==t&&(c.start=this.iso8601(t)),void 0!==i&&(c.limit=i);let e=await this.marketPublicGetV1beta3CryptoLocTrades(this.extend(c,l)),s=this.safeDict(e,"trades",{});r=this.safeList(s,n,[])}else if("marketPublicGetV1beta3CryptoLocLatestTrades"===h){let e=await this.marketPublicGetV1beta3CryptoLocLatestTrades(this.extend(c,l)),t=this.safeDict(e,"trades",{});r=[this.safeDict(t,n,{})]}else throw new a.NotSupported(this.id+" fetchTrades() does not support "+h+", marketPublicGetV1beta3CryptoLocTrades and marketPublicGetV1beta3CryptoLocLatestTrades are supported");let u=[];return void 0!==r&&(u=r),this.parseTrades(u,o,t,i)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=s.id,a=this.safeString(i,"loc","us"),o=await this.marketPublicGetV1beta3CryptoLocLatestOrderbooks(this.extend({symbols:r,loc:a},i)),n=this.safeDict(o,"orderbooks",{}),d=this.safeDict(n,r,{}),h=this.parse8601(this.safeString(d,"t"));return this.parseOrderBook(d,s.symbol,h,"b","a","p","s")}async fetchOHLCV(e,t="1m",i,s,r={}){let o,n;void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h=d.id,c=this.safeString(r,"loc","us"),l=this.safeString(r,"method","marketPublicGetV1beta3CryptoLocBars"),u=!1;[u,o]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);let f=10;[f,o]=this.handleOptionIntegerAndParams(o,"fetchOHLCV","paginationCalls",10);let p={symbols:h,loc:c};if(o=this.omit(o,["loc","method"]),"marketPublicGetV1beta3CryptoLocBars"===l){void 0!==s&&(p.limit=s),void 0!==i&&(p.start=this.iso8601(i));let e=this.safeInteger(o,"until");void 0!==e&&(o=this.omit(o,"until"),p.end=this.iso8601(e)),p.timeframe=this.safeString(this.timeframes,t,t);let r=await this.marketPublicGetV1beta3CryptoLocBars(this.extend(p,o)),a=this.safeDict(r,"bars",{});if(n=this.safeList(a,h,[]),u){let e=this.safeString(r,"next_page_token");for(let t=1;t<f;t++){let t=n.length;if(void 0===e||void 0!==s&&t>=s)break;p.page_token=e,r=await this.marketPublicGetV1beta3CryptoLocBars(this.extend(p,o)),a=this.safeDict(r,"bars",{});let i=this.safeList(a,h,[]);if(0===i.length)break;n=this.arrayConcat(n,i),e=this.safeString(r,"next_page_token")}}}else if("marketPublicGetV1beta3CryptoLocLatestBars"===l){let e=await this.marketPublicGetV1beta3CryptoLocLatestBars(this.extend(p,o)),t=this.safeDict(e,"bars",{});n=[this.safeDict(t,h,{})]}else throw new a.NotSupported(this.id+" fetchOHLCV() does not support "+l+", marketPublicGetV1beta3CryptoLocBars and marketPublicGetV1beta3CryptoLocLatestBars are supported");return this.parseOHLCVs(n,d,t,i,s)}parseOHLCV(e,t){let i=this.safeString(e,"t");return[this.parse8601(i),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.symbol(e),s=await this.fetchTickers([i],t);return this.safeDict(s,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=void 0===e?this.sort(this.symbols):e,s=this.marketSymbols(i),a=this.safeString(t,"loc","us"),o={symbols:this.marketIds(s).join(","),loc:a},n=this.omit(t,"loc"),d=await this.marketPublicGetV1beta3CryptoLocSnapshots(this.extend(o,n)),h=[],c=this.safeDict(d,"snapshots",{}),l=Object.keys(c);for(let e=0;e<l.length;e++){let t=l[e],i=this.safeMarket(t),s=this.safeDict(c,t),a=this.safeDict(s,"dailyBar",{}),o=this.safeDict(s,"prevDailyBar",{}),n=this.safeDict(s,"latestQuote",{}),d=this.safeDict(s,"latestTrade",{}),u=this.safeString(n,"t"),f=this.safeTicker({info:s,symbol:i.symbol,timestamp:this.parse8601(u),datetime:u,high:this.safeString(a,"h"),low:this.safeString(a,"l"),bid:this.safeString(n,"bp"),bidVolume:this.safeString(n,"bs"),ask:this.safeString(n,"ap"),askVolume:this.safeString(n,"as"),vwap:this.safeString(a,"vw"),open:this.safeString(a,"o"),close:this.safeString(a,"c"),last:this.safeString(d,"p"),previousClose:this.safeString(o,"c"),change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(a,"v"),quoteVolume:r.Y.stringMul(this.safeString(a,"v"),this.safeString(a,"vw"))},i);h.push(f)}return this.filterByArray(h,"symbol",s)}generateClientOrderId(e){let t=this.safeString(this.options,"clientOrderId"),i=this.uuid().split("-").join(""),s=this.implodeParams(t,{id:i});return this.safeString(e,"clientOrderId",s)}async createMarketOrderWithCost(e,t,i,s={}){return void 0===this.markets&&await this.loadMarkets(),await this.createOrder(e,"market",t,0,void 0,this.extend({cost:i},s))}async createMarketBuyOrderWithCost(e,t,i={}){return void 0===this.markets&&await this.loadMarkets(),await this.createOrder(e,"market","buy",0,void 0,this.extend({cost:t},i))}async createMarketSellOrderWithCost(e,t,i={}){return void 0===this.markets&&await this.loadMarkets(),await this.createOrder(e,"market","sell",t,void 0,this.extend({cost:t},i))}async createOrder(e,t,i,s,r,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d={symbol:n.id,side:i,type:t},h=this.safeString2(o,"triggerPrice","stop_price");if(void 0!==h){let i;if(t.indexOf("limit")>=0)i="stop_limit";else throw new a.NotSupported(this.id+" createOrder() does not support stop orders for "+t+" orders, only stop_limit orders are supported");d.stop_price=this.priceToPrecision(e,h),d.type=i}t.indexOf("limit")>=0&&(d.limit_price=this.priceToPrecision(e,r));let c=this.safeString(o,"cost");void 0!==c?d.notional=this.costToPrecision(e,c):d.qty=this.amountToPrecision(e,s);let l=void 0!==c?this.omit(o,"cost"):o,[u,f]=this.handleOptionStringAndParams(l,"createOrder","timeInForce");d.time_in_force=void 0!==u?u.toLowerCase():u;let p=this.omit(f,["timeInForce","triggerPrice"]);d.client_order_id=this.generateClientOrderId(p);let m=await this.traderPrivatePostV2Orders(this.extend(d,this.omit(p,["clientOrderId"])));return this.parseOrder(m,n)}async cancelOrder(e,t,i={}){let s=await this.traderPrivateDeleteV2OrdersOrderId(this.extend({order_id:e},i));return this.parseOrder(s)}async cancelAllOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.traderPrivateDeleteV2Orders(t);return Array.isArray(i)?this.parseOrders(i):[this.safeOrder({info:i})]}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.traderPrivateGetV2OrdersOrderId(this.extend({order_id:e},i)),r=this.safeString(s,"symbol"),a=this.safeMarket(r);return this.parseOrder(s,a)}async fetchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={status:"all"};void 0!==e&&(a.symbols=(r=this.market(e)).id);let o=this.safeInteger(s,"until");void 0!==o&&(a.until=this.iso8601(o));let n=void 0!==o?this.omit(s,"until"):s;void 0!==t&&(a.after=this.iso8601(t),void 0===this.safeString(n,"direction")&&(a.direction="asc")),void 0!==i&&(a.limit=i);let d=await this.traderPrivateGetV2Orders(this.extend(a,n));return this.parseOrders(d,r,t,i)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({status:"open"},s))}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({status:"closed"},s))}async editOrder(e,t,i,s,r,a,o={}){let n;void 0===this.markets&&await this.loadMarkets();let d={order_id:e};void 0!==t&&(n=this.market(t)),void 0!==r&&(d.qty=this.amountToPrecision(t,r));let h=this.safeString2(o,"triggerPrice","stop_price");void 0!==h&&(d.stop_price=this.priceToPrecision(t,h));let c=void 0!==h?this.omit(o,"triggerPrice"):o;void 0!==a&&(d.limit_price=this.priceToPrecision(t,a));let[l,u]=this.handleOptionStringAndParams(c,"editOrder","timeInForce","gtc");void 0!==l&&(d.time_in_force=l.toLowerCase()),d.client_order_id=this.generateClientOrderId(u);let f=await this.traderPrivatePatchV2OrdersOrderId(this.extend(d,this.omit(u,["clientOrderId"])));return this.parseOrder(f,n)}parseOrder(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=r.symbol,o=this.safeString(e,"status"),n=this.parseOrderStatus(o),d=this.safeString(e,"commission");void 0!==d&&(i={cost:d,currency:"USD"});let h=this.safeString(e,"order_type");void 0!==h&&h.indexOf("limit")>=0&&(h="limit");let c=this.safeString(e,"submitted_at"),l=this.parse8601(c);return this.safeOrder({id:this.safeString(e,"id"),clientOrderId:this.safeString(e,"client_order_id"),timestamp:l,datetime:c,lastTradeTimestamp:this.parse8601(this.safeString(e,"filled_at")),status:n,symbol:a,type:h,timeInForce:this.parseTimeInForce(this.safeString(e,"time_in_force")),postOnly:void 0,side:this.safeString(e,"side"),price:this.safeNumber(e,"limit_price"),triggerPrice:this.safeNumber(e,"stop_price"),cost:void 0,average:this.safeNumber(e,"filled_avg_price"),amount:this.safeNumber(e,"qty"),filled:this.safeNumber(e,"filled_qty"),remaining:void 0,trades:void 0,fee:i,info:e},r)}parseOrderStatus(e){return this.safeString({pending_new:"open",accepted:"open",accepted_for_bidding:"open",new:"open",partially_filled:"open",activated:"open",done_for_day:"open",stopped:"open",suspended:"open",held:"open",pending_replace:"open",pending_cancel:"canceling",filled:"closed",calculated:"closed",canceled:"canceled",replaced:"canceled",expired:"expired",rejected:"rejected"},e,e)}parseTimeInForce(e){return this.safeString({day:"Day",gtc:"GTC",ioc:"IOC",fok:"FOK"},e,e)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={activity_type:"FILL"};void 0!==e&&(r=this.market(e));let o=this.safeInteger(s,"until");void 0!==o&&(a.until=this.iso8601(o));let n=void 0!==o?this.omit(s,"until"):s;void 0!==t&&(a.after=this.iso8601(t)),void 0!==i&&(a.page_size=i);let[d,h]=this.handleUntilOption("until",a,n),c=await this.traderPrivateGetV2AccountActivitiesActivityType(this.extend(d,h));return this.parseTrades(c,r,t,i)}parseTrade(e,t){let i=this.safeString2(e,"S","symbol"),s=this.safeSymbol(i,t),r=this.safeString2(e,"t","transaction_time"),a=this.parse8601(r),o=this.safeString(e,"tks"),n=this.safeString(e,"side");"B"===o?n="buy":"S"===o&&(n="sell");let d=this.safeString2(e,"p","price"),h=this.safeString2(e,"s","qty");return this.safeTrade({info:e,id:this.safeString2(e,"i","id"),timestamp:a,datetime:this.iso8601(a),symbol:s,order:this.safeString(e,"order_id"),type:void 0,side:n,takerOrMaker:"taker",price:d,amount:h,cost:void 0,fee:void 0},t)}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={asset:i.id},r=await this.traderPrivateGetV2Wallets(this.extend(s,t));return this.parseDepositAddress(r,i)}parseDepositAddress(e,t){let i;return void 0!==t&&(i=this.safeString(t,"id")),{info:e,currency:i,network:void 0,address:this.safeString(e,"address"),tag:void 0}}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d=i;void 0!==a&&""!==a&&(d=i+":"+a);let h={asset:n.id,address:d,amount:this.numberToString(t)},c=await this.traderPrivatePostV2WalletsTransfers(this.extend(h,o));return this.parseTransaction(c,n)}setSandboxMode(e){super.setSandboxMode(e),this.options.sandboxMode=e}async fetchTransactionsHelper(e,t,i,s,a){let o;if(void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(o=this.currency(t)),!0===(this.isSandboxModeEnabled||this.safeBool(this.options,"sandboxMode",!1))){let t=await this.traderPrivateGetV2AccountActivities(this.extend({activity_types:"CSD,CSW,TRANS"},a)),n=[],d=[];Array.isArray(t)&&(d=t);for(let t=0;t<d.length;t++){let i=d[t],s=this.safeString(i,"activity_type"),a=this.safeString(i,"net_amount"),o="CSD"===s||"TRANS"===s&&!r.Y.stringLt(a,"0"),h="OUTGOING";o&&(h="INCOMING"),("BOTH"===e||h===e)&&n.push(i)}return this.parseTransactions(n,o,i,s,a)}let n=await this.traderPrivateGetV2WalletsTransfers(a),d=[],h=[];Array.isArray(n)&&(h=n);for(let t=0;t<h.length;t++){let i=h[t];this.safeString(i,"direction")===e?d.push(i):"BOTH"===e&&d.push(i)}return this.parseTransactions(d,o,i,s,a)}async fetchDepositsWithdrawals(e,t,i,s={}){return await this.fetchTransactionsHelper("BOTH",e,t,i,s)}async fetchDeposits(e,t,i,s={}){return await this.fetchTransactionsHelper("INCOMING",e,t,i,s)}async fetchWithdrawals(e,t,i,s={}){return await this.fetchTransactionsHelper("OUTGOING",e,t,i,s)}parseTransaction(e,t){let i,s,a,o,n,d,h,c,l,u,f,p,m,g,v=this.safeString(e,"activity_type");if(void 0!==v){let i=this.safeString(e,"net_amount"),o="CSD"===v||"TRANS"===v&&!r.Y.stringLt(i,"0");s=this.parse8601(this.safeString(e,"date")+"T00:00:00Z"),a=this.iso8601(s),c=o?"deposit":"withdrawal",l=this.parseNumber(r.Y.stringAbs(i));let n=this.safeString2(e,"symbol","asset");u=void 0!==n?this.safeCurrencyCode(n):"CSD"===v||"CSW"===v?"USD":this.safeCurrencyCode(void 0,t),f=this.parseTransactionStatus(this.safeString(e,"status")),p=v,m="TRANS"!==v}else{i=this.safeString(e,"tx_hash"),a=this.safeString(e,"created_at"),s=this.parse8601(a),o=this.safeString(e,"chain"),n=this.safeString(e,"to_address"),d=this.safeString(e,"to_address"),h=this.safeString(e,"from_address"),c=this.parseTransactionType(this.safeString(e,"direction")),l=this.safeNumber(e,"amount");let p=this.safeString(e,"asset");u=this.safeCurrencyCode(p,t),f=this.parseTransactionStatus(this.safeString(e,"status"));let m=this.safeString(e,"fees"),v=this.safeString(e,"network_fee"),y=r.Y.stringAdd(m,v);g={cost:this.parseNumber(y),currency:u}}return{info:e,id:this.safeString(e,"id"),txid:i,timestamp:s,datetime:a,network:o,address:n,addressTo:d,addressFrom:h,tag:void 0,tagTo:void 0,tagFrom:void 0,type:c,amount:l,currency:u,status:f,updated:void 0,comment:p,internal:m,fee:g}}parseTransactionStatus(e){return this.safeString({PROCESSING:"pending",FAILED:"failed",COMPLETE:"ok",executed:"ok",canceled:"canceled",pending:"pending"},e,e)}parseTransactionType(e){return this.safeString({INCOMING:"deposit",OUTGOING:"withdrawal"},e,e)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.traderPrivateGetV2Account(e),i=await this.traderPrivateGetV2Positions();return this.parseBalance({account:t,positions:i})}parseBalance(e){let t=this.safeDict(e,"account",{}),i=this.safeList(e,"positions",[]),s={info:e},a=this.safeString(t,"currency"),o=this.safeCurrencyCode(a);if(void 0!==o){let e=this.account();e.free=this.safeString(t,"cash");let i=this.safeString(t,"equity"),a=this.safeString(t,"position_market_value");e.total=r.Y.stringSub(i,a),s[o]=e}for(let e=0;e<i.length;e++){let t,r=this.safeDict(i,e),a=this.safeString(r,"symbol");if(void 0===a)continue;if(a.indexOf("/")>=0){let e=a.split("/");t=this.safeString(e,0)}else{let e=a.length-3;e>0&&"USD"===a.slice(e)&&(t=a.slice(0,e))}if(void 0===t)continue;let o=this.safeCurrencyCode(t);if(void 0!==o&&!(o in s)){let e=this.account();e.free=this.safeString(r,"qty_available"),e.total=this.safeString(r,"qty"),s[o]=e}}return this.safeBalance(s)}sign(e,t="public",i="GET",s={},r,o){let n,d="/"+this.implodeParams(e,s),h=this.safeString(this.urls.api,t[0]);if(void 0===h)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let c={};void 0!==r&&(c=r),"private"===t[1]&&(this.checkRequiredCredentials(),c["APCA-API-KEY-ID"]=this.apiKey,c["APCA-API-SECRET-KEY"]=this.secret);let l=this.omit(s,this.extractParams(e));return Object.keys(l).length>0&&("GET"===i||"DELETE"===i?d+="?"+this.urlencode(l):(n=this.json(l),c["Content-Type"]="application/json")),{url:this.implodeHostname(h)+d,method:i,body:void 0===n?o:n,headers:c}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.id+" "+o,l=this.safeString(n,"code");void 0!==e&&this.throwExactlyMatchedException(this.exceptions.exact,l,c);let u=this.safeString(n,"message");if(void 0!==u){this.throwExactlyMatchedException(this.exceptions.exact,u,c),this.throwBroadlyMatchedException(this.exceptions.broad,u,c);let t=e.toString();if(e<400||!(t in this.httpExceptions))throw new a.ExchangeError(c)}}}i.d(t,{A:()=>o})},8818(e,t,i){"use strict";var s=i(4721),r=i(7749),a=i(9619),o=i(1453);class n extends a.A{describe(){return this.deepExtend(super.describe(),{id:"apex",name:"Apex",countries:[],version:"v3",rateLimit:20,certified:!1,pro:!0,dex:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelAllOrdersAfter:!1,cancelOrder:!0,cancelOrders:!1,cancelOrdersForSymbols:!1,closeAllPositions:!1,closePosition:!1,createMarketBuyOrderWithCost:!1,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!1,createPostOnlyOrder:!0,createReduceOnlyOrder:!0,createStopOrder:!0,createTriggerOrder:!0,editOrder:!1,fetchAccounts:!0,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCanceledAndClosedOrders:!1,fetchCanceledOrders:!1,fetchClosedOrders:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDeposits:!1,fetchDepositWithdrawFee:!1,fetchDepositWithdrawFees:!1,fetchFundingHistory:!0,fetchFundingRate:!1,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLedger:!1,fetchLeverage:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchMarginMode:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyLiquidations:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchOrderTrades:!0,fetchPosition:!1,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTransfer:!0,fetchTransfers:!0,fetchVolatilityHistory:!1,fetchWithdrawal:!1,fetchWithdrawals:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,sandbox:!0,setLeverage:!0,setMarginMode:!1,setPositionMode:!1,transfer:!0,withdraw:!1},timeframes:{"1m":"1","5m":"5","15m":"15","30m":"30","1h":"60","2h":"120","4h":"240","6h":"360","12h":"720","1d":"D","1w":"W","1M":"M"},hostname:"omni.apex.exchange",urls:{logo:"https://github.com/user-attachments/assets/8ba7fbfa-0dd0-4ab9-8b72-ff60abe08ac6",api:{public:"https://{hostname}/api",private:"https://{hostname}/api"},test:{public:"https://testnet.omni.apex.exchange/api",private:"https://testnet.omni.apex.exchange/api"},www:"https://apex.exchange/",doc:"https://api-docs.omni.apex.exchange",fees:"https://apex-pro.gitbook.io/apex-pro/apex-omni-live-now/trading-perpetual-contracts/trading-fees",referral:"https://omni.apex.exchange/trade"},api:{public:{get:{"v3/symbols":{cost:1},"v3/history-funding":{cost:1},"v3/ticker":{cost:1},"v3/klines":{cost:1},"v3/trades":{cost:1},"v3/depth":{cost:1},"v3/time":{cost:1},"v3/data/all-ticker-info":{cost:1}}},private:{get:{"v3/account":{cost:1},"v3/account-balance":{cost:1},"v3/fills":{cost:1},"v3/order-fills":{cost:1},"v3/order":{cost:1},"v3/history-orders":{cost:1},"v3/order-by-client-order-id":{cost:1},"v3/funding":{cost:1},"v3/historical-pnl":{cost:1},"v3/open-orders":{cost:1},"v3/transfers":{cost:1},"v3/transfer":{cost:1},"v3/stock/account":{cost:1}},post:{"v3/delete-open-orders":{cost:1},"v3/delete-client-order-id":{cost:1},"v3/delete-order":{cost:1},"v3/order":{cost:1},"v3/set-initial-margin-rate":{cost:1},"v3/transfer-out":{cost:1},"v3/contract-transfer-out":{cost:1},"v3/contract-transfer-to":{cost:1},"v3/submit-withdraw-claim":{cost:1},"v3/stock/register-account":{cost:1},"v3/stock/generate-api":{cost:1}}}},httpExceptions:{403:o.RateLimitExceeded},exceptions:{exact:{20006:"apikey sign error",20016:"request para error",10001:o.BadRequest},broad:{ORDER_PRICE_MUST_GREETER_ZERO:o.InvalidOrder,ORDER_POSSIBLE_LEAD_TO_ACCOUNT_LIQUIDATED:o.InvalidOrder,ORDER_WITH_THIS_PRICE_CANNOT_REDUCE_POSITION_ONLY:o.InvalidOrder}},fees:{swap:{taker:this.parseNumber("0.0005"),maker:this.parseNumber("0.0002")}},requiredCredentials:{apiKey:!0,secret:!0,walletAddress:!1,privateKey:!1,password:!0},precisionMode:4,commonCurrencies:{},options:{defaultType:"swap",brokerId:"6956"},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!0},hedged:!1,selfTradePrevention:!1,trailing:!0,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:500,daysBack:1e5,untilDays:1e5,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:void 0,fetchOHLCV:{limit:200}},swap:{linear:{extends:"default"},inverse:void 0}}})}async fetchTime(e={}){let t=await this.publicGetV3Time(e),i=this.safeDict(t,"data",{});return this.safeInteger(i,"time")}parseBalance(e){let t={info:e,timestamp:void 0,datetime:void 0},i=this.account();return i.free=this.safeString(e,"availableBalance"),i.total=this.safeString(e,"totalEquityValue"),t.USDT=i,this.safeBalance(t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetV3AccountBalance(e),i=this.safeDict(t,"data",{});return this.parseBalance(i)}parseAccount(e){return{id:this.safeString(e,"id","0"),type:void 0,code:void 0,info:e}}async fetchAccount(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetV3Account(e),i=this.safeDict(t,"data",{});return this.parseAccount(i)}async fetchCurrencies(e={}){let t=await this.publicGetV3Symbols(e),i=this.safeDict(t,"data",{}),s=this.safeDict(i,"spotConfig",{}),r=this.safeDict(s,"multiChain",{}),a=this.safeList(s,"assets",[]),o=this.safeList(r,"chains",[]);this.options._temp_currencies_chains=o;let n=this.parseCurrencies(a);return delete this.options._temp_currencies_chains,n}parseCurrency(e){let t=this.safeString(e,"token"),i=this.safeCurrencyCode(t),s=this.safeString(e,"displayName"),r={},a=this.options._temp_currencies_chains;for(let e=0;e<a.length;e++){let s=this.safeDict(a,e),o=this.safeList(s,"tokens",[]);for(let e=0;e<o.length;e++){let a=this.safeDict(o,e);if(this.safeString(a,"token")===t){let e=this.safeString(s,"chainId"),t=this.networkIdToCode(e,i);void 0!==t&&(r[t]={info:s,id:e,network:t,active:void 0,deposit:!this.safeBool(s,"depositDisable",!1),withdraw:this.safeBool(a,"withdrawEnable"),fee:this.safeNumber(a,"minFee"),precision:this.parseNumber(this.parsePrecision(this.safeString(a,"decimals"))),limits:{withdraw:{min:this.safeNumber(a,"minWithdraw"),max:void 0},deposit:{min:this.safeNumber(s,"minDeposit"),max:void 0}}})}}}let o=0!==Object.keys(r).length&&void 0;return this.safeCurrencyStructure({info:e,code:i,id:t,type:"crypto",name:s,active:void 0,deposit:o,withdraw:o,fee:void 0,precision:void 0,limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},networks:r})}async fetchMarkets(e={}){let t=await this.publicGetV3Symbols(e),i=this.safeDict(t,"data",{}),s=this.safeDict(i,"contractConfig",{}),r=this.safeList(s,"perpetualContract",[]);return this.parseMarkets(r)}parseMarket(e){let t=this.safeString(e,"symbol"),i=this.safeString(e,"crossSymbolName"),s=this.safeString(e,"l2PairId"),r=this.safeString(e,"baseTokenId"),a=this.safeString(e,"settleAssetId"),o=this.safeCurrencyCode(r),n=this.safeString(e,"settleAssetId"),d=this.safeCurrencyCode(n);if(void 0===r||void 0===a||void 0===d)return;let h=r+"/"+a+":"+d,c=this.parseNumber("0.0002"),l=this.parseNumber("0.0005");return this.safeMarketStructure({id:t,id2:i,symbol:h,base:o,quote:a,settle:d,baseId:r,quoteId:s,settleId:n,type:"swap",spot:!1,margin:void 0,swap:!0,future:!1,option:!1,active:this.safeBool(e,"enableTrade"),contract:!0,linear:!0,inverse:!1,taker:c,maker:l,contractSize:this.safeNumber(e,"minOrderSize"),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(e,"stepSize"),price:this.safeNumber(e,"tickSize")},limits:{leverage:{min:this.safeNumber(e,"displayMinLeverage"),max:this.safeNumber(e,"displayMaxLeverage")},amount:{min:this.safeNumber(e,"minOrderSize"),max:this.safeNumber(e,"maxOrderSize")},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:e})}parseTicker(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeSymbol(i,s),a=this.safeString(e,"lastPrice"),o=this.safeString(e,"price24hPcnt"),n=this.safeString(e,"turnover24h"),d=this.safeString(e,"volume24h"),h=this.safeString(e,"highPrice24h"),c=this.safeString(e,"lowPrice24h");return this.safeTicker({symbol:r,timestamp:void 0,datetime:void 0,high:h,low:c,bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:void 0,close:a,last:a,previousClose:void 0,change:void 0,percentage:o,average:void 0,baseVolume:d,quoteVolume:n,markPrice:this.safeString(e,"markPrice"),indexPrice:this.safeString(e,"indexPrice"),info:e},s)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:this.safeString(i,"id2")},r=await this.publicGetV3Ticker(this.extend(s,t)),a=this.safeList(r,"data",[]),o=this.safeDict(a,0,{});return this.parseTicker(o,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetV3DataAllTickerInfo(t),s=this.safeList(i,"data",[]);return this.parseTickers(s,e)}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={interval:this.safeString(this.timeframes,t,t),symbol:this.safeString(a,"id2")},n=void 0===s?200:Math.min(s,200);o.limit=n;let[d,h]=this.handleUntilOption("end",o,r,.001);void 0!==i&&(d.start=Math.floor(i/1e3));let c=await this.publicGetV3Klines(this.extend(d,h)),l=this.safeDict(c,"data",{}),u=this.safeList(l,this.safeString(a,"id2"),[]);return this.parseOHLCVs(u,a,t,i,n)}parseOHLCV(e,t){return[this.safeInteger2(e,"start","t"),this.safeNumber2(e,"open","o"),this.safeNumber2(e,"high","h"),this.safeNumber2(e,"low","l"),this.safeNumber2(e,"close","c"),this.safeNumber2(e,"volume","v")]}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:this.safeString(s,"id2")};r.limit=void 0===t?100:t;let a=await this.publicGetV3Depth(this.extend(r,i)),o=this.safeDict(a,"data",{}),n=this.milliseconds(),d=this.parseOrderBook(o,s.symbol,n,"b","a");return d.nonce=this.safeInteger(o,"u"),d}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:this.safeString(r,"id2")},o=void 0===i?500:i;a.limit=o;let n=await this.publicGetV3Trades(this.extend(a,s)),d=this.safeList(n,"data",[]);return this.parseTrades(d,r,t,o)}parseTrade(e,t){let i=this.safeString2(e,"s","symbol"),s=this.safeMarket(i,t),r=this.safeString2(e,"i","id"),a=this.safeIntegerN(e,["t","T","createdAt"]),o=this.safeString2(e,"p","price"),n=this.safeString2(e,"v","size"),d=this.safeStringLower2(e,"S","side"),h=this.safeString(e,"type"),c=this.safeString(e,"fee");return this.safeTrade({info:e,id:r,order:void 0,timestamp:a,datetime:this.iso8601(a),symbol:s.symbol,type:h,takerOrMaker:void 0,side:d,price:o,amount:n,cost:void 0,fee:c},s)}async fetchOpenInterest(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:this.safeString(i,"id2")},r=await this.publicGetV3Ticker(this.extend(s,t)),a=this.safeList(r,"data",[]),o=this.safeDict(a,0,{});return this.parseOpenInterest(o,i)}parseOpenInterest(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeSymbol(i,s);return this.safeOpenInterest({symbol:r,openInterestAmount:this.safeString(e,"openInterest"),openInterestValue:void 0,timestamp:void 0,datetime:void 0,info:e},s)}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r={},a=this.market(e);r.symbol=a.id,void 0!==t&&(r.beginTimeInclusive=t),void 0!==i&&(r.limit=i);let n=this.safeInteger(s,"page");void 0!==n&&(r.page=n);let d=this.safeIntegerN(s,["endTime","endTimeExclusive","until"]);void 0!==d&&(r.endTimeExclusive=d);let h=await this.publicGetV3HistoryFunding(this.extend(r,s)),c=[],l=this.safeDict(h,"data",{}),u=this.safeList(l,"historyFunds",[]);for(let e=0;e<u.length;e++){let t=u[e],i=this.safeInteger(t,"fundingTimestamp"),s=this.safeString(t,"symbol");c.push({info:t,symbol:this.safeSymbol(s,a),fundingRate:this.safeNumber(t,"rate"),timestamp:i,datetime:this.iso8601(i)})}let f=this.sortBy(c,"timestamp");return this.filterBySymbolSinceLimit(f,e,t,i)}parseOrder(e,t){let i=this.safeInteger(e,"createdAt"),s=this.safeString(e,"id"),r=this.safeString(e,"clientId"),a=this.safeString(e,"symbol"),o=this.safeMarket(a,t),n=o.symbol,d=this.safeString(e,"price"),h=this.safeString(e,"size"),c=this.safeString(e,"type"),l=this.safeString(e,"status"),u=this.safeStringLower(e,"side"),f=this.omitZero(this.safeString(e,"remainingSize")),p=this.safeInteger(e,"updatedTime");return this.safeOrder({id:s,clientOrderId:r,timestamp:i,datetime:this.iso8601(i),lastTradeTimestamp:void 0,lastUpdateTimestamp:p,status:this.parseOrderStatus(l),symbol:n,type:this.parseOrderType(c),timeInForce:this.parseTimeInForce(this.safeString(e,"timeInForce")),postOnly:this.safeBool(e,"postOnly"),reduceOnly:this.safeBool(e,"reduceOnly"),side:u,price:d,triggerPrice:this.safeString(e,"triggerPrice"),takeProfitPrice:void 0,stopLossPrice:void 0,average:void 0,amount:h,filled:void 0,remaining:f,cost:void 0,trades:void 0,fee:{cost:this.safeString(e,"fee"),currency:o.settleId},info:e},o)}parseTimeInForce(e){return this.safeString({GOOD_TIL_CANCEL:"GOOD_TIL_CANCEL",FILL_OR_KILL:"FILL_OR_KILL",IMMEDIATE_OR_CANCEL:"IMMEDIATE_OR_CANCEL",POST_ONLY:"POST_ONLY"},e)}parseOrderStatus(e){if(void 0!==e)return this.safeString({PENDING:"open",OPEN:"open",FILLED:"filled",CANCELING:"canceled",CANCELED:"canceled",UNTRIGGERED:"open"},e,e)}parseOrderType(e){return this.safeString({LIMIT:"limit",MARKET:"market",STOP_LIMIT:"limit",STOP_MARKET:"market",TAKE_PROFIT_LIMIT:"limit",TAKE_PROFIT_MARKET:"market"},e,e)}safeMarket(e,t,i,s){let r;if(void 0===t&&void 0!==e){let t=this.markets,i=this.markets_by_id;if(void 0!==t&&e in t)r=t[e];else if(void 0!==i&&e in i)r=i[e];else{let t=this.addHyphenBeforeUsdt(e);void 0!==i&&t in i&&i[t].length>0&&i[t][0].id2===e&&(r=i[t][0])}}let a=void 0===r?t:r;return super.safeMarket(e,a,i,s)}generateRandomClientIdOmni(e){return"apexomni-"+(void 0!==e&&""!==e?e:this.randNumber(12).toString())+"-"+this.milliseconds().toString()+"-"+this.randNumber(6).toString()}addHyphenBeforeUsdt(e){let t=e.toUpperCase().indexOf("USDT"),i=this.safeString(e,t-1);return t>0&&"-"!==i?e.slice(0,t)+"-"+e.slice(t):e}getSeeds(){let e=this.safeString(this.options,"seeds");if(void 0===e)throw new o.ArgumentsRequired(this.id+' the "seeds" key is required in the options to access private endpoints. You can find it in API Management > Omni Key, and then set it as exchange.options["seeds"] = XXXX');return e}async getAccountId(){if("0"===this.safeString(this.options,"accountId","0")){let e=await this.fetchAccount();this.options.accountId=this.safeString(e,"id","0")}return this.options.accountId}async createOrder(e,t,i,s,a,n={}){void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h=t.toUpperCase();this.checkRequiredArgument("createOrder",i,"side");let c=i.toUpperCase(),l=this.amountToPrecision(e,s),u="0";void 0!==a&&(u=this.priceToPrecision(e,a));let f=this.safeDict(this.fees,"swap",{}),p=this.safeString(f,"taker","0.0005"),m=this.safeString(f,"maker","0.0002"),g=this.decimalToPrecision(r.Y.stringAdd(r.Y.stringMul(r.Y.stringMul(u,l),p),this.numberToString(d.precision.price)),0,d.precision.price,this.precisionMode,this.paddingMode),v=this.milliseconds(),y=this.safeString(n,"triggerPrice"),b=this.safeString(n,"stopLossPrice"),w=this.safeString(n,"takeProfitPrice");void 0!==b?(h="MARKET"===h?"STOP_MARKET":"STOP_LIMIT",y=b):void 0!==w&&(h="MARKET"===h?"TAKE_PROFIT_MARKET":"TAKE_PROFIT_LIMIT",y=w);let k="MARKET"===h;if(k&&void 0===a)throw new o.ArgumentsRequired(this.id+" createOrder() requires a price argument for market orders");let S=this.safeStringUpper(n,"timeInForce"),O=this.isPostOnly(k,void 0,n);void 0===S&&(S="GOOD_TIL_CANCEL"),k||(O?S="POST_ONLY":"ioc"===S&&(S="IMMEDIATE_OR_CANCEL"));let T=this.omit(n,"timeInForce"),P=this.omit(T,"postOnly"),I=this.safeStringN(P,["clientId","clientOrderId","client_order_id"]),A=await this.getAccountId();void 0===I&&(I=this.generateRandomClientIdOmni(A));let x=I,M=this.omit(P,["clientId","clientOrderId","client_order_id","stopLossPrice","takeProfitPrice","triggerPrice"]),_=u,C={accountId:A,slotId:x,nonce:x,pairId:d.quoteId,size:l,price:_,direction:c,makerFeeRate:m,takerFeeRate:p};void 0!==y&&(C.triggerPrice=this.priceToPrecision(e,y));let B=await this.getZKContractSignatureObj(this.remove0xPrefix(this.getSeeds()),C),E={symbol:d.id,side:c,type:h,size:l,price:_,limitFee:g,expiration:Math.floor(v/1e3+2592e3),timeInForce:S,clientId:x,brokerId:this.safeString(this.options,"brokerId","6956")};void 0!==y&&(E.triggerPrice=this.priceToPrecision(e,y)),E.signature=B;let R=await this.privatePostV3Order(this.extend(E,M)),L=this.safeDict(R,"data",{});return this.parseOrder(L,d)}async transfer(e,t,i,s,a={}){void 0===this.markets&&await this.loadMarkets();let o=await this.publicGetV3Symbols(a),n=this.safeDict(o,"data",{}),d=this.safeDict(n,"contractConfig",{}),h=this.safeList(d,"assets",[]),c=this.safeDict(n,"spotConfig",{}),l=this.safeList(c,"assets",[]),u=this.safeDict(c,"global",{}),f=this.safeString(u,"contractAssetPoolEthAddress",""),p=this.safeString(u,"contractAssetPoolZkAccountId",""),m=this.safeString(u,"contractAssetPoolSubAccount",""),g=this.safeString(u,"contractAssetPoolAccountId",""),v=await this.privateGetV3Account(a),y=this.safeDict(v,"data",{}),b=this.safeDict(y,"spotAccount",{}),w=this.safeString(b,"zkAccountId",""),k=this.safeString(b,"defaultSubAccountId","0"),S=this.safeList(b,"subAccounts",[]),O="0";S.length>0&&(O=this.safeString(S[0],"nonce","0"));let T=O,P=this.safeString(y,"ethereumAddress",""),I=this.safeString(y,"id",""),A={},x=[];x="contract"===i.toLowerCase()?h:l;for(let t=0;t<x.length;t++)this.safeString(x[t],"token","")===e&&(A=x[t]);let M=this.safeString(A,"tokenId",""),_=this.safeNumber(A,"decimals",0),C=Math.pow(10,void 0===_?0:_),B=this.parseToInt(t*C),E=this.parseToInt(this.milliseconds()/1e3),R=this.safeStringN(a,["clientId","clientOrderId","client_order_id"]);void 0===R&&(R=this.generateRandomClientIdOmni(this.safeString(this.options,"accountId")));let L=R,N=this.omit(a,["clientId","clientOrderId","client_order_id"]);if("contract"===i.toLowerCase()){let i=r.Y.stringMod(I,"4294967295"),s=E+2419200,a={zkAccountId:i,receiverAddress:P,subAccountId:k,receiverSubAccountId:k,tokenId:M,amount:B.toString(),fee:"0",nonce:L,timestampSeconds:s,isContract:!0},o=await this.getZKTransferSignatureObj(this.remove0xPrefix(this.getSeeds()),a),n=await this.privatePostV3ContractTransferOut(this.extend({amount:t,expireTime:s,clientWithdrawId:L,signature:o,token:e,ethAddress:P},N)),d=this.safeDict(n,"data",{}),h=this.milliseconds(),c=this.parseNumber(t);return this.extend(this.parseTransfer(d,this.currency(e)),{timestamp:h,datetime:this.iso8601(h),amount:c,fromAccount:"contract",toAccount:"spot"})}{let i={zkAccountId:w,receiverAddress:f,subAccountId:k,receiverSubAccountId:m,tokenId:M,amount:B.toString(),fee:"0",nonce:T,timestampSeconds:E},s=await this.getZKTransferSignatureObj(this.remove0xPrefix(this.getSeeds()),i),r=t.toString(),a=await this.privatePostV3TransferOut(this.extend({amount:r,timestamp:E,clientTransferId:L,signature:s,zkAccountId:w,subAccountId:k,fee:"0",token:e,tokenId:M,receiverAccountId:g,receiverZkAccountId:p,receiverSubAccountId:m,receiverAddress:f,nonce:T},N)),o=this.safeDict(a,"data",{}),n=this.milliseconds();return this.extend(this.parseTransfer(o,this.currency(e)),{timestamp:n,datetime:this.iso8601(n),amount:this.parseNumber(t),fromAccount:"spot",toAccount:"contract"})}}parseTransfer(e,t){let i=this.safeString(e,"coin"),s=this.safeInteger(e,"timestamp"),r=this.safeString(e,"fromAccount"),a=this.safeString(e,"toAccount");return{info:e,id:this.safeString2(e,"transferId","id"),timestamp:s,datetime:this.iso8601(s),currency:this.safeCurrencyCode(i,t),amount:this.safeNumber(e,"amount"),fromAccount:r,toAccount:a,status:this.safeString(e,"status")}}async cancelAllOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={};void 0!==e&&(s.symbol=(i=this.market(e)).id);let r=await this.privatePostV3DeleteOpenOrders(this.extend(s,t)),a=this.safeDict(r,"data",{});return[this.parseOrder(a,i)]}async cancelOrder(e,t,i={}){let s,r={},a=this.safeStringN(i,["clientId","clientOrderId","client_order_id"]);void 0!==a?(r.id=a,s=await this.privatePostV3DeleteClientOrderId(this.extend(r,this.omit(i,["clientId","clientOrderId","client_order_id"])))):(r.id=e,s=await this.privatePostV3DeleteOrder(this.extend(r,i)));let o=this.safeDict(s,"data",{});return this.safeOrder(o)}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r={},a=this.safeStringN(i,["clientId","clientOrderId","client_order_id"]);void 0!==a?(r.id=a,s=await this.privateGetV3OrderByClientOrderId(this.extend(r,this.omit(i,["clientId","clientOrderId","client_order_id"])))):(r.id=e,s=await this.privateGetV3Order(this.extend(r,i)));let o=this.safeDict(s,"data",{});return this.parseOrder(o)}async fetchOpenOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.privateGetV3OpenOrders(s),a=this.safeList(r,"data",[]);return this.parseOrders(a,void 0,t,i)}async fetchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id),void 0!==t&&(a.beginTimeInclusive=t),void 0!==i&&(a.limit=i);let o=this.safeIntegerN(s,["endTime","endTimeExclusive","until"]);void 0!==o&&(a.endTimeExclusive=o);let n=void 0!==o?this.omit(s,["endTime","endTimeExclusive","until"]):s,d=await this.privateGetV3HistoryOrders(this.extend(a,n)),h=this.safeDict(d,"data",{}),c=this.safeList(h,"orders",[]);return this.parseOrders(c,r,t,i)}async fetchOrderTrades(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a={},o=this.safeString2(r,"clientOrderId","clientId");void 0!==o?a.clientOrderId=o:a.orderId=e;let n=this.omit(r,["clientOrderId","clientId"]),d=await this.privateGetV3OrderFills(this.extend(a,n)),h=this.safeDict(d,"data",{}),c=this.safeList(h,"orders",[]);return this.parseTrades(c,void 0,i,s)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id),void 0!==t&&(a.beginTimeInclusive=t),void 0!==i&&(a.limit=i);let o=this.safeIntegerN(s,["endTime","endTimeExclusive","until"]);void 0!==o&&(a.endTimeExclusive=o);let n=void 0!==o?this.omit(s,["endTime","endTimeExclusive","until"]):s,d=await this.privateGetV3Fills(this.extend(a,n)),h=this.safeDict(d,"data",{}),c=this.safeList(h,"orders",[]);return this.parseTrades(c,r,t,i)}async fetchFundingHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id),void 0!==t&&(a.beginTimeInclusive=t),void 0!==i&&(a.limit=i);let o=this.safeIntegerN(s,["endTime","endTimeExclusive","until"]);void 0!==o&&(a.endTimeExclusive=o);let n=void 0!==o?this.omit(s,["endTime","endTimeExclusive","until"]):s,d=await this.privateGetV3Funding(this.extend(a,n)),h=this.safeDict(d,"data",{}),c=this.safeList(h,"fundingValues",[]);return this.parseIncomes(c,r,t,i)}parseIncome(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t,void 0,"contract"),r=this.safeInteger(e,"fundingTime");return{info:e,symbol:this.safeSymbol(i,s),code:"USDT",timestamp:r,datetime:this.iso8601(r),id:this.safeString(e,"id"),amount:this.safeNumber(e,"fundingValue"),rate:this.safeNumber(e,"rate")}}async setLeverage(e,t,i={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),a=this.numberToString(e),n=r.Y.stringDiv("1",a,4),d={symbol:s.id,initialMarginRate:n},h=await this.privatePostV3SetInitialMarginRate(this.extend(d,i));return this.safeDict(h,"data",{})}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privateGetV3Account(t),s=this.safeDict(i,"data",{}),r=this.safeList(s,"positions",[]);return this.parsePositions(r,e)}parsePosition(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t).symbol,a=this.safeStringLower(e,"side"),o=this.safeString(e,"size"),n=this.safeInteger(e,"updatedTime"),d=20,h=this.safeString2(e,"customInitialMarginRate","customImr","0");return 0!==this.precisionFromString(h)&&(d=this.parseToInt(r.Y.stringDiv("1",h,4))),this.safePosition({info:e,id:this.safeString(e,"id"),symbol:s,entryPrice:this.safeNumber(e,"entryPrice"),markPrice:void 0,notional:void 0,collateral:void 0,unrealizedPnl:void 0,side:a,contracts:this.parseNumber(o),contractSize:void 0,timestamp:n,datetime:this.iso8601(n),hedged:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,initialMargin:void 0,initialMarginPercentage:void 0,leverage:d,liquidationPrice:void 0,marginRatio:void 0,marginMode:void 0,percentage:void 0})}sign(e,t="public",i="GET",r={},a,n){let d=this.safeString(this.urls.api,t);if(void 0===d)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let h=this.implodeHostname(d)+"/"+e,c={"User-Agent":"apex-CCXT",Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},l="/api/"+e,u=n;if("POST"!==i.toUpperCase())Object.keys(r).length>0&&(l+="?"+this.rawencode(r),h+="?"+this.rawencode(r));else{let e=this.keysort(r);u=this.rawencode(e)}if("private"===t){this.checkRequiredCredentials();let e=this.milliseconds().toString(),t=e+i.toUpperCase()+l;void 0!==u&&(t+=u);let r=this.hmac(this.encode(t),this.encode(this.stringToBase64(this.secret)),s.sc,"base64");c["APEX-SIGNATURE"]=r,c["APEX-API-KEY"]=this.apiKey,c["APEX-TIMESTAMP"]=e,c["APEX-PASSPHRASE"]=this.password}return{url:h,method:i,body:u,headers:c}}handleErrors(e,t,i,s,r,a,n,d,h){if(void 0===n)return;let c=this.safeInteger(n,"code");if(void 0!==c&&0!==c){let t=this.id+" "+a,i=this.safeString2(n,"key","msg");this.throwBroadlyMatchedException(this.exceptions.broad,i,t);let s=e.toString();throw this.throwExactlyMatchedException(this.exceptions.exact,s,t),new o.ExchangeError(t)}}}i.d(t,{A:()=>n})},8695(e,t,i){"use strict";var s=i(6834),r=i(6885),a=i(3268),o=i(1453),n=i(7749),d=i(1093);class h extends a.A{describe(){return this.deepExtend(super.describe(),{id:"aster",name:"Aster",countries:["US"],rateLimit:333,certified:!1,pro:!0,dex:!0,urls:{logo:"https://github.com/user-attachments/assets/5e5909d6-c4de-4435-992f-4339c80edbd7",www:"https://www.asterdex.com/en",api:{fapiPublic:"https://fapi.asterdex.com/fapi",fapiPrivate:"https://fapi.asterdex.com/fapi",sapiPublic:"https://sapi.asterdex.com/api",sapiPrivate:"https://sapi.asterdex.com/api"},doc:"https://github.com/asterdex/api-docs",fees:"https://docs.asterdex.com/product/asterex-simple/fees-and-slippage",referral:{url:"https://www.asterdex.com/en/referral/aA1c2B",discount:.1}},has:{CORS:void 0,spot:!0,margin:!1,swap:!0,future:!1,option:!1,addMargin:!0,borrowCrossMargin:!1,borrowIsolatedMargin:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!1,closePosition:!1,createConvertTrade:!1,createDepositAddress:!1,createLimitBuyOrder:!1,createLimitSellOrder:!1,createMarketBuyOrder:!1,createMarketBuyOrderWithCost:!1,createMarketOrderWithCost:!1,createMarketSellOrder:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopLossOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,createTakeProfitOrder:!1,createTrailingPercentOrder:!1,createTriggerOrder:!1,editOrder:!1,editOrders:!1,fetchAccounts:void 0,fetchBalance:!0,fetchBidsAsks:!0,fetchBorrowInterest:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchCanceledAndClosedOrders:"emulated",fetchCanceledOrders:"emulated",fetchClosedOrder:!1,fetchClosedOrders:"emulated",fetchConvertCurrencies:!1,fetchConvertQuote:!1,fetchConvertTrade:!1,fetchConvertTradeHistory:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:!1,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!1,fetchDepositsWithdrawals:!1,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!1,fetchFundingHistory:!0,fetchFundingInterval:"emulated",fetchFundingIntervals:!0,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:"emulated",fetchIsolatedBorrowRates:!1,fetchL3OrderBook:!1,fetchLastPrices:!0,fetchLedger:!0,fetchLedgerEntry:!1,fetchLeverage:"emulated",fetchLeverages:!0,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!0,fetchMarginMode:"emulated",fetchMarginModes:!0,fetchMarketLeverageTiers:"emulated",fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrice:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenOrder:!0,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrders:!0,fetchOrderTrades:!1,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!0,fetchPositions:!0,fetchPositionsHistory:!1,fetchPositionsRisk:!0,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchStatus:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!1,fetchTradingLimits:"emulated",fetchTransactionFee:"emulated",fetchTransactionFees:!1,fetchTransactions:!1,fetchTransfer:!1,fetchTransfers:!1,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,fetchWithdrawAddresses:!1,fetchWithdrawal:!1,fetchWithdrawals:!1,fetchWithdrawalWhitelist:!1,reduceMargin:!0,repayCrossMargin:!1,repayIsolatedMargin:!1,sandbox:!1,setLeverage:!0,setMargin:!1,setMarginMode:!0,setPositionMode:!0,signIn:!0,transfer:!0,withdraw:!0},api:{fapiPublic:{get:{"v1/ping":{cost:1},"v3/ping":{cost:1},"v1/time":{cost:1},"v3/time":{cost:1},"v1/exchangeInfo":{cost:1},"v3/exchangeInfo":{cost:1},"v1/depth":{cost:1},"v3/depth":{cost:2},"v1/trades":{cost:1},"v3/trades":{cost:1},"v1/historicalTrades":{cost:1},"v3/historicalTrades":{cost:20},"v1/aggTrades":{cost:1},"v3/aggTrades":{cost:20},"v1/klines":{cost:1},"v3/klines":{cost:1},"v1/indexPriceKlines":{cost:1},"v3/indexPriceKlines":{cost:1},"v1/markPriceKlines":{cost:1},"v3/markPriceKlines":{cost:1},"v1/premiumIndex":{cost:1},"v3/premiumIndex":{cost:1},"v1/fundingRate":{cost:1},"v3/fundingRate":{cost:1},"v1/fundingInfo":{cost:1},"v3/fundingInfo":{cost:1},"v1/ticker/24hr":{cost:1},"v3/ticker/24hr":{cost:1},"v1/ticker/price":{cost:1},"v3/ticker/price":{cost:1},"v1/ticker/bookTicker":{cost:1},"v3/ticker/bookTicker":{cost:1},"v1/adlQuantile":{cost:1},"v1/forceOrders":{cost:1},"v3/indexreferences":{cost:1}}},fapiPrivate:{get:{"v1/positionSide/dual":{cost:1},"v3/positionSide/dual":{cost:30},"v1/multiAssetsMargin":{cost:1},"v3/multiAssetsMargin":{cost:1},"v1/order":{cost:1},"v3/order":{cost:1},"v1/openOrder":{cost:1},"v3/openOrder":{cost:1},"v1/openOrders":{cost:1},"v3/openOrders":{cost:1},"v1/allOrders":{cost:1},"v3/allOrders":{cost:1},"v2/balance":{cost:1},"v3/balance":{cost:1},"v3/account":{cost:1},"v1/positionMargin/history":{cost:1},"v3/positionMargin/history":{cost:1},"v2/positionRisk":{cost:1},"v3/positionRisk":{cost:1},"v1/userTrades":{cost:1},"v3/userTrades":{cost:5},"v1/income":{cost:1},"v3/income":{cost:1},"v1/leverageBracket":{cost:1},"v3/leverageBracket":{cost:1},"v1/commissionRate":{cost:1},"v3/commissionRate":{cost:1},"v3/adlQuantile":{cost:1},"v3/forceOrders":{cost:1},"v3/mmp":{cost:1},"v3/accountWithJoinMargin":{cost:1},"v4/account":{cost:1},"v3/agent":{cost:1},"v3/builder":{cost:1},"v3/builder/userTrades":{cost:5},"v3/builder/approvedUserList":{cost:5},"v3/stpMode":{cost:30},"v3/asset/migrateUser/history":{cost:50},"v3/strategyOpenOrder":{cost:5},"v3/strategyHistoryOrder":{cost:5}},post:{"v1/positionSide/dual":{cost:1},"v3/positionSide/dual":{cost:1},"v1/multiAssetsMargin":{cost:1},"v3/multiAssetsMargin":{cost:1},"v1/order":{cost:1},"v3/order":{cost:1},"v1/order/test":{cost:1},"v3/order/test":{cost:1},"v1/batchOrders":{cost:1},"v3/batchOrders":{cost:1},"v1/asset/wallet/transfer":{cost:1},"v3/asset/wallet/transfer":{cost:1},"v1/countdownCancelAll":{cost:1},"v3/countdownCancelAll":{cost:1},"v1/leverage":{cost:1},"v3/leverage":{cost:1},"v1/marginType":{cost:1},"v3/marginType":{cost:1},"v1/positionMargin":{cost:1},"v3/positionMargin":{cost:1},"v1/listenKey":{cost:1},"v3/listenKey":{cost:1},"v3/mmp":{cost:1},"v3/mmpReset":{cost:1},"v3/noop":{cost:1},"v3/approveAgent":{cost:1},"v3/updateAgent":{cost:1},"v3/approveBuilder":{cost:1},"v3/updateBuilder":{cost:1},"v3/registerAndApproveAgent":{cost:50},"v3/asset/migrateUser":{cost:50},"v3/chase":{cost:1},"v3/stpMode":{cost:1},"v3/placeStrategyOrder":{cost:50},"v3/updateStrategyOrder":{cost:50}},put:{"v1/listenKey":{cost:1},"v3/listenKey":{cost:1}},delete:{"v1/order":{cost:1},"v3/order":{cost:1},"v1/allOpenOrders":{cost:1},"v3/allOpenOrders":{cost:1},"v1/batchOrders":{cost:1},"v3/batchOrders":{cost:1},"v3/guardedCancelOrder":{cost:1},"v3/guardedBatchOrders":{cost:1},"v3/mmp":{cost:1},"v1/listenKey":{cost:1},"v3/listenKey":{cost:1},"v3/agent":{cost:1},"v3/builder":{cost:1}}},sapiPublic:{get:{"v1/ping":{cost:1},"v1/time":{cost:1},"v1/exchangeInfo":{cost:1},"v1/depth":{cost:1},"v1/trades":{cost:1},"v1/historicalTrades":{cost:1},"v1/aggTrades":{cost:1},"v1/klines":{cost:1},"v1/ticker/24hr":{cost:1},"v1/ticker/price":{cost:1},"v1/ticker/bookTicker":{cost:1},"v1/aster/withdraw/estimateFee":{cost:1},"v3/ping":{cost:1},"v3/time":{cost:1},"v3/exchangeInfo":{cost:1},"v3/depth":{cost:2,byLimit:[[50,2],[100,5],[500,10],[1e3,20]]},"v3/trades":{cost:1},"v3/historicalTrades":{cost:20},"v3/aggTrades":{cost:20},"v3/klines":{cost:1,byLimit:[[99,1],[499,2],[1e3,5],[1e4,10]]},"v3/ticker/24hr":{cost:1,noSymbol:40},"v3/ticker/price":{cost:1,noSymbol:2},"v3/ticker/bookTicker":{cost:1,noSymbol:2},"v3/aster/withdraw/estimateFee":{cost:1}}},sapiPrivate:{get:{"v1/commissionRate":{cost:1},"v1/order":{cost:1},"v1/openOrders":{cost:1},"v1/allOrders":{cost:1},"v1/transactionHistory":{cost:1},"v1/account":{cost:1},"v1/userTrades":{cost:1},"v3/commissionRate":{cost:1,noSymbol:2},"v3/order":{cost:1},"v3/openOrders":{cost:1},"v3/allOrders":{cost:5},"v3/account":{cost:5},"v3/userTrades":{cost:5},"v3/openOrder":{cost:1}},post:{"v1/order":{cost:1},"v1/asset/wallet/transfer":{cost:5},"v1/asset/sendToAddress":{cost:1},"v1/listenKey":{cost:1},"v3/order":{cost:1},"v3/asset/wallet/transfer":{cost:5},"v3/aster/user-withdraw":{cost:1},"v3/listenKey":{cost:1}},put:{"v1/listenKey":{cost:1},"v3/listenKey":{cost:1}},delete:{"v1/order":{cost:1},"v1/allOpenOrders":{cost:1},"v1/listenKey":{cost:1},"v3/allOpenOrders":{cost:1},"v3/order":{cost:1},"v3/listenKey":{cost:1}}}},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","8h":"8h","12h":"12h","1d":"1d","3d":"3d","1w":"1w","1M":"1M"},precisionMode:4,requiredCredentials:{apiKey:!1,secret:!1,privateKey:!0},fees:{trading:{tierBased:!0,percentage:!0,maker:this.parseNumber("0.0001"),taker:this.parseNumber("0.00035")}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:void 0,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:void 0,untilDays:void 0,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:1e3,daysBack:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:void 0,fetchOHLCV:{limit:1500}},forDerivs:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:{last:!0,mark:!0,index:!1},triggerDirection:!1,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!0,trailing:!0,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:void 0,untilDays:void 0,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:1e3,daysBack:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:void 0,fetchOHLCV:{limit:1500}},swap:{linear:{extends:"forDerivs"},inverse:void 0}},options:{defaultType:"spot",recvWindow:1e4,zeroAddress:"0x0000000000000000000000000000000000000000",v3ChainId:1666,createOrder:{timeInForce:"GTC",quoteOrderQty:!0},accountsByType:{spot:"SPOT",swap:"FUTURE",future:"FUTURE",linear:"FUTURE"},networks:{ERC20:"ETH",BEP20:"BSC",ARBITRUM:"Arbitrum"},networksToChainId:{ETH:1,BSC:56,Arbitrum:42161},fetchOpenOrders:{warnIfNoSymbol:!0},builderFee:!0,builder:"0x1F5877C19e3777Cfd15F9d57253eA4aA5254Ec39",builderRate:"0.001"},exceptions:{exact:{"-1000":o.OperationRejected,"-1001":o.NetworkError,"-1002":o.AuthenticationError,"-1003":o.RateLimitExceeded,"-1004":o.DuplicateOrderId,"-1005":o.BadRequest,"-1006":o.BadResponse,"-1007":o.RequestTimeout,"-1010":o.OperationRejected,"-1011":o.PermissionDenied,"-1013":o.BadRequest,"-1014":o.OrderNotFillable,"-1015":o.RateLimitExceeded,"-1016":o.ExchangeClosedByUser,"-1020":o.NotSupported,"-1021":o.InvalidNonce,"-1022":o.AuthenticationError,"-1023":o.BadRequest,"-1100":o.BadRequest,"-1101":o.BadRequest,"-1102":o.ArgumentsRequired,"-1103":o.BadRequest,"-1104":o.BadRequest,"-1105":o.ArgumentsRequired,"-1106":o.BadRequest,"-1108":o.BadRequest,"-1109":o.BadRequest,"-1110":o.BadSymbol,"-1111":o.BadRequest,"-1112":o.BadRequest,"-1113":o.BadRequest,"-1114":o.BadRequest,"-1115":o.InvalidOrder,"-1116":o.InvalidOrder,"-1117":o.InvalidOrder,"-1118":o.InvalidOrder,"-1119":o.InvalidOrder,"-1120":o.BadRequest,"-1121":o.BadSymbol,"-1125":o.AuthenticationError,"-1127":o.BadRequest,"-1128":o.BadRequest,"-1130":o.BadRequest,"-1136":o.InvalidOrder,"-2010":o.InvalidOrder,"-2011":o.OrderNotFound,"-2013":o.OrderNotFound,"-2014":o.AuthenticationError,"-2015":o.AuthenticationError,"-2016":o.MarketClosed,"-2018":o.InsufficientFunds,"-2019":o.InsufficientFunds,"-2020":o.OrderNotFillable,"-2021":o.OrderImmediatelyFillable,"-2022":o.OperationRejected,"-2023":o.AccountSuspended,"-2024":o.InsufficientFunds,"-2025":o.RateLimitExceeded,"-2026":o.NotSupported,"-2027":o.BadRequest,"-2028":o.BadRequest,"-4000":o.InvalidOrder,"-4001":o.InvalidOrder,"-4002":o.InvalidOrder,"-4003":o.InvalidOrder,"-4004":o.InvalidOrder,"-4005":o.InvalidOrder,"-4006":o.InvalidOrder,"-4007":o.InvalidOrder,"-4008":o.InvalidOrder,"-4009":o.InvalidOrder,"-4010":o.InvalidOrder,"-4011":o.InvalidOrder,"-4012":o.RateLimitExceeded,"-4013":o.InvalidOrder,"-4014":o.InvalidOrder,"-4015":o.InvalidOrder,"-4016":o.InvalidOrder,"-4017":o.InvalidOrder,"-4018":o.InvalidOrder,"-4019":o.BadRequest,"-4020":o.BadRequest,"-4021":o.BadRequest,"-4022":o.MarketClosed,"-4023":o.InvalidOrder,"-4024":o.InvalidOrder,"-4025":o.BadRequest,"-4026":o.BadRequest,"-4027":o.BadRequest,"-4028":o.BadRequest,"-4029":o.BadRequest,"-4030":o.BadRequest,"-4031":o.BadRequest,"-4032":o.RateLimitExceeded,"-4033":o.AccountNotEnabled,"-4044":o.BadRequest,"-4045":o.RateLimitExceeded,"-4046":o.NoChange,"-4047":o.OperationRejected,"-4048":o.OperationRejected,"-4049":o.OperationRejected,"-4050":o.InsufficientFunds,"-4051":o.InsufficientFunds,"-4052":o.NoChange,"-4053":o.OperationRejected,"-4054":o.OperationRejected,"-4055":o.ArgumentsRequired,"-4056":o.AuthenticationError,"-4057":o.AuthenticationError,"-4058":o.InvalidOrder,"-4059":o.NoChange,"-4060":o.InvalidOrder,"-4061":o.InvalidOrder,"-4062":o.OperationRejected,"-4063":o.BadRequest,"-4064":o.BadRequest,"-4065":o.BadRequest,"-4066":o.BadRequest,"-4067":o.OperationRejected,"-4068":o.OperationRejected,"-4069":o.BadRequest,"-4070":o.InvalidOrder,"-4071":o.InvalidOrder,"-4072":o.NoChange,"-4073":o.BadRequest,"-4074":o.InvalidOrder,"-4075":o.OperationRejected,"-4076":o.OperationRejected,"-4077":o.RateLimitExceeded,"-4078":o.BadRequest,"-4079":o.BadRequest,"-4080":o.BadRequest,"-4081":o.BadRequest,"-4082":o.RateLimitExceeded,"-4083":o.OperationFailed,"-4084":o.NotSupported,"-4085":o.BadRequest,"-4086":o.BadRequest,"-4087":o.PermissionDenied,"-4088":o.PermissionDenied,"-4104":o.BadSymbol,"-4114":o.InvalidOrder,"-4115":o.DuplicateOrderId,"-4118":o.InsufficientFunds,"-4131":o.InvalidOrder,"-4135":o.InvalidOrder,"-4137":o.InvalidOrder,"-4138":o.OperationRejected,"-4139":o.InvalidOrder,"-4140":o.OperationRejected,"-4141":o.MarketClosed,"-4142":o.InvalidOrder,"-4144":o.BadSymbol,"-4161":o.OperationRejected,"-4164":o.InvalidOrder,"-4165":o.BadRequest,"-4183":o.InvalidOrder,"-4184":o.InvalidOrder,"-5060":o.OperationRejected,"-5076":o.OperationRejected,"-4168":o.OperationRejected},broad:{}}})}isInverse(e,t){return void 0===t?"delivery"===e:"inverse"===t}isLinear(e,t){return void 0===t?"future"===e||"swap"===e:"linear"===t}async fetchCurrencies(e={}){let t=await this.sapiPublicGetV3ExchangeInfo(e),i=this.safeList(t,"assets",[]);return this.parseCurrencies(i)}parseCurrency(e){let t=this.safeString(e,"asset"),i=this.safeCurrencyCode(t);return this.safeCurrencyStructure({info:e,code:i,id:t,name:i,active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,precision:void 0,margin:this.safeBool(e,"marginAvailable"),limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},networks:void 0,type:"crypto"})}async fetchMarkets(e={}){let t=[this.sapiPublicGetV3ExchangeInfo(e),this.fapiPublicGetV3ExchangeInfo(e)];t.push(this.signIn());let i=await Promise.all(t),s=this.safeDict(i,0,{}),r=this.safeList(s,"symbols",[]),a=this.safeDict(i,1,{}),o=this.safeList(a,"symbols",[]),n=[];for(let e=0;e<o.length;e++){let t=o[e];void 0!==this.safeString(t,"baseAsset")&&n.push(t)}let d=this.arrayConcat(r,n);return this.parseMarkets(d)}parseMarket(e){let t,i,s,r,a,o,n,d,h=this.safeString(e,"symbol"),c=this.safeString(e,"baseAsset"),l=this.safeString(e,"quoteAsset"),u=this.safeCurrencyCode(c),f=this.safeCurrencyCode(l);if(void 0===u||void 0===f)return;let p="TRADING"===this.safeString(e,"status"),m=void 0!==this.safeString(e,"contractType");m?(t=!1,a=!0,r=this.safeString(e,"marginAsset"),i=u+"/"+f+":"+(s=this.safeCurrencyCode(r)),o=s===f,n=s===u,d=this.safeNumber2(e,"contractSize","unit",this.parseNumber("1"))):(t=!0,a=!1,i=u+"/"+f);let g=this.safeList(e,"filters",[]),v=this.indexBy(g,"filterType"),y=this.safeDict2(v,"MIN_NOTIONAL","NOTIONAL"),b=this.safeDict(v,"PRICE_FILTER"),w=this.safeDict(v,"LOT_SIZE"),k=this.safeDict(v,"MARKET_LOT_SIZE",{}),S=this.safeNumber(b,"tickSize");void 0===S&&(S=this.parseNumber(this.parsePrecision(this.safeString(e,"pricePrecision"))));let O=void 0!==w?this.safeNumber(w,"stepSize"):this.parseNumber(this.parsePrecision(this.safeString(e,"quantityPrecision")));return this.safeMarketStructure({id:h,symbol:i,base:u,quote:f,settle:s,baseId:c,quoteId:l,settleId:r,type:m?"swap":"spot",spot:t,margin:!1,swap:a,future:!1,option:!1,active:p,contract:m,linear:o,inverse:n,taker:this.fees.trading.taker,maker:this.fees.trading.maker,contractSize:d,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:O,price:S,base:this.parseNumber(this.parsePrecision(this.safeString(e,"baseAssetPrecision"))),quote:this.parseNumber(this.parsePrecision(this.safeString(e,"quotePrecision")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(w,"minQty"),max:this.safeNumber(w,"maxQty")},price:{min:this.safeNumber(b,"minPrice"),max:this.safeNumber(b,"maxPrice")},cost:{min:this.safeNumber2(y,"notional","minNotional"),max:void 0},market:{min:this.safeNumber(k,"minQty"),max:this.safeNumber(k,"maxQty")}},created:this.safeInteger2(e,"listingTime","createTime"),info:e})}async fetchTime(e={}){let t,[i,s]=this.handleMarketTypeAndParams("fetchTime",void 0,e);return t="swap"===i?await this.fapiPublicGetV3Time(s):await this.sapiPublicGetV3Time(s),this.safeInteger(t,"serverTime")}parseOHLCV(e,t){return[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]}async fetchOHLCV(e,t="1m",i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={};void 0!==i&&(n.startTime=i),void 0!==s&&(n.limit=Math.min(s,1500));let[d,h]=this.handleUntilOption("endTime",n,r);d.interval=this.safeString(this.timeframes,t,t);let c=this.safeString(h,"price"),l=this.omit(h,"price");return"mark"===c?(d.symbol=o.id,a=await this.fapiPublicGetV3MarkPriceKlines(this.extend(d,l))):"index"===c?(d.pair=o.id,a=await this.fapiPublicGetV3IndexPriceKlines(this.extend(d,l))):(d.symbol=o.id,a=!0===o.linear?await this.fapiPublicGetV3Klines(this.extend(d,l)):await this.sapiPublicGetV3Klines(this.extend(d,l))),this.parseOHLCVs(this.toArray(a),o,t,i,s)}parseTrade(e,t){let i,s=this.safeString2(e,"id","a"),r=this.safeString(e,"symbol"),a="spot";"positionSide"in e&&(a="swap");let o=this.safeMarket(r,t,void 0,a),d=this.safeString2(e,"commissionAsset","marginAsset"),h=this.safeCurrencyCode(d),c=this.safeString2(e,"qty","q"),l=this.safeString2(e,"price","p"),u=this.safeString2(e,"quoteQty","baseQty"),f=this.safeInteger2(e,"time","T"),p=this.safeStringLower(e,"side"),m=this.safeBool(e,"maker");if(void 0!==m&&(i=m?"maker":"taker",void 0===p)){let t=this.safeBool(e,"buyer");void 0!==t&&(p=t?"buy":"sell")}let g=this.safeBool2(e,"isBuyerMaker","m");return void 0!==g&&(p=g?"sell":"buy"),this.safeTrade({id:s,info:e,timestamp:f,datetime:this.iso8601(f),symbol:o.symbol,order:this.safeString(e,"orderId"),type:void 0,side:p,takerOrMaker:i,price:l,amount:c,cost:u,fee:{cost:this.parseNumber(n.A.stringAbs(this.safeString(e,"commission"))),currency:h}},o)}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={symbol:a.id};void 0!==i&&(o.limit=Math.min(i,1e3));let n="until"in s;return void 0!==t&&(o.startTime=t),n&&(o=this.handleUntilOption("endTime",o,s)),r="startTime"in o?!0===a.swap?await this.fapiPublicGetV3AggTrades(this.extend(o,s)):await this.sapiPublicGetV3AggTrades(this.extend(o,s)):!0===a.swap?await this.fapiPublicGetV3Trades(this.extend(o,s)):await this.sapiPublicGetV3Trades(this.extend(o,s)),this.parseTrades(r,a,t,i)}async fetchMyTrades(e,t,i,s={}){let r,a;await this.loadMarketsAndSignIn();let o={};void 0!==e&&(o.symbol=(a=this.market(e)).id);let[n,d]=this.handleMarketTypeAndParams("fetchMyTrades",a,s);void 0!==t&&(o.startTime=t),void 0!==i&&(o.limit=Math.min(i,1e3));let[h,c]=this.handleUntilOption("endTime",o,d);return r="swap"===n?await this.fapiPrivateGetV3UserTrades(this.extend(h,c)):await this.sapiPrivateGetV3UserTrades(this.extend(h,c)),this.parseTrades(r,a,t,i,c)}async fetchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id};void 0!==t&&(a.limit=this.findNearestCeiling([5,10,20,50,100,500,1e3],t)),s=!0===r.swap?await this.fapiPublicGetV3Depth(this.extend(a,i)):await this.sapiPublicGetV3Depth(this.extend(a,i));let o=this.safeInteger(s,"T");return this.parseOrderBook(s,e,o,"bids","asks")}parseTicker(e,t){let i,s=this.safeInteger(e,"closeTime"),r=this.safeString(e,"lastPrice"),a=this.safeString(e,"openPrice"),o=this.safeString(e,"priceChangePercent"),n=this.safeString(e,"quoteVolume"),d=this.safeString(e,"volume"),h=this.safeString(e,"highPrice"),c=this.safeString(e,"lowPrice");i="priceChange"in e?"baseAsset"in e?"spot":"swap":"lastUpdateId"in e?"swap":"spot";let l=this.safeString(e,"symbol"),u=this.safeMarket(l,t,void 0,i);return this.safeTicker({symbol:u.symbol,timestamp:s,datetime:this.iso8601(s),high:h,low:c,bid:this.safeString(e,"bidPrice"),bidVolume:this.safeString(e,"bidQty"),ask:this.safeString(e,"askPrice"),askVolume:this.safeString(e,"askQty"),vwap:void 0,open:a,close:r,last:r,previousClose:void 0,change:void 0,percentage:o,average:void 0,baseVolume:d,quoteVolume:n,markPrice:void 0,indexPrice:void 0,info:e},u)}async fetchTicker(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};return i=!0===s.swap?await this.fapiPublicGetV3Ticker24hr(this.extend(r,t)):await this.sapiPublicGetV3Ticker24hr(this.extend(r,t)),this.parseTicker(i,s)}async fetchTickers(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!0,!0,!0),r=this.getMarketFromSymbols(s),[a,o]=this.handleMarketTypeAndParams("fetchTickers",r,t);return"swap"===a?i=await this.fapiPublicGetV3Ticker24hr(o):"spot"===a&&(i=await this.sapiPublicGetV3Ticker24hr(o)),this.parseTickers(i,s)}async fetchLastPrices(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!0,!0,!0),r=this.getMarketFromSymbols(s),[a,n]=this.handleMarketTypeAndParams("fetchLastPrices",r,t);if("swap"===a?i=await this.fapiPublicGetV3TickerPrice(n):"spot"===a&&(i=await this.sapiPublicGetV3TickerPrice(n)),void 0===i)throw new o.NullResponse(this.id+" fetchLastPrices() returned empty response");let d=this.toArray(i),h=[];for(let e=0;e<d.length;e++){let t=this.safeString(d[e],"symbol"),i=this.safeMarket(t,void 0,void 0,a),s=this.extend(this.parseLastPrice(d[e],i),n);h.push(s)}let c=this.marketSymbols(s);return this.filterByArray(h,"symbol",c)}parseLastPrice(e,t){let i=this.safeInteger(e,"time");return{symbol:this.safeString(t,"symbol"),timestamp:i,datetime:this.iso8601(i),price:this.safeNumberOmitZero(e,"price"),side:void 0,info:e}}async fetchBidsAsks(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!0,!0,!0),r=this.getMarketFromSymbols(s),[a,o]=this.handleMarketTypeAndParams("fetchBidsAsks",r,t);return"swap"===a?i=await this.fapiPublicGetV3TickerBookTicker(o):"spot"===a&&(i=await this.sapiPublicGetV3TickerBookTicker(o)),this.parseTickers(i,s)}parseFundingRate(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeInteger(e,"nextFundingTime"),a=this.safeInteger(e,"time"),o=this.safeString(e,"fundingIntervalHours");return void 0!==o&&(i=o+"h"),{info:e,symbol:this.safeSymbol(s,t,void 0,"contract"),markPrice:this.safeNumber(e,"markPrice"),indexPrice:this.safeNumber(e,"indexPrice"),interestRate:this.safeNumber(e,"interestRate"),estimatedSettlePrice:this.safeNumber(e,"estimatedSettlePrice"),timestamp:a,datetime:this.iso8601(a),fundingRate:this.safeNumber(e,"lastFundingRate"),fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:void 0,nextFundingTimestamp:r,nextFundingDatetime:this.iso8601(r),previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:i}}async fetchFundingRate(e,t={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchFundingRate() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.fapiPublicGetV3PremiumIndex(this.extend(s,t));return this.parseFundingRate(r,i)}async fetchFundingRates(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.fapiPublicGetV3PremiumIndex(this.extend(t));return this.parseFundingRates(s,i)}async fetchFundingIntervals(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.fapiPublicGetV3FundingInfo(t);return this.parseFundingRates(s,i)}async fetchFundingRateHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id),void 0!==t&&(a.startTime=t),void 0!==i&&(a.limit=Math.min(i,1e3));let[o,n]=this.handleUntilOption("endTime",a,s),d=await this.fapiPublicGetV3FundingRate(this.extend(o,n));return this.parseFundingRateHistories(d,r)}parseFundingRateHistory(e,t){let i=this.safeInteger(e,"fundingTime");return{info:e,symbol:this.safeSymbol(this.safeString(e,"symbol"),void 0,void 0,"swap"),fundingRate:this.safeNumber(e,"fundingRate"),timestamp:i,datetime:this.iso8601(i)}}async fetchBalance(e={}){let t,i;await this.loadMarketsAndSignIn();let[s,r]=this.handleMarketTypeAndParams("fetchBalance",void 0,e);return"swap"===s?i=await this.fapiPrivateGetV3Balance(r):"spot"===s&&(t=await this.sapiPrivateGetV3Account(r),i=this.safeList(t,"balances",[])),this.parseBalance(i)}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"asset"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString2(s,"free","availableBalance"),o.used=this.safeString(s,"locked"),o.total=this.safeString(s,"balance"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async setMarginMode(e,t,i={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");let s=e.toUpperCase(),r="CROSS"===s?"CROSSED":s;if("ISOLATED"!==r&&"CROSSED"!==r)throw new o.BadRequest(this.id+" marginMode must be either isolated or cross");await this.loadMarketsAndSignIn();let a={symbol:this.market(t).id,marginType:r};return await this.fapiPrivatePostV3MarginType(this.extend(a,i))}async fetchPositionMode(e,t={}){let i=await this.fapiPrivateGetV3PositionSideDual(t);return{info:i,hedged:this.safeBool(i,"dualSidePosition")}}async setPositionMode(e,t,i={}){let s="false";e&&(s="true");let r={dualSidePosition:s};return await this.fapiPrivatePostV3PositionSideDual(this.extend(r,i))}parseTradingFee(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t);return{info:e,symbol:this.safeSymbol(i,s),maker:this.safeNumber(e,"makerCommissionRate"),taker:this.safeNumber(e,"takerCommissionRate"),percentage:!1,tierBased:!1}}async fetchTradingFee(e,t={}){let i;await this.loadMarketsAndSignIn();let s=this.market(e),r={symbol:s.id};return i=!0===s.swap?await this.fapiPrivateGetV3CommissionRate(this.extend(r,t)):await this.sapiPrivateGetV3CommissionRate(this.extend(r,t)),this.parseTradingFee(i,s)}parseOrderStatus(e){return this.safeString({NEW:"open",PARTIALLY_FILLED:"open",FILLED:"closed",CANCELED:"canceled",REJECTED:"canceled",EXPIRED:"canceled"},e,e)}parseOrderType(e){return this.safeString({LIMIT:"limit",MARKET:"market",STOP:"limit",STOP_MARKET:"market",TAKE_PROFIT:"limit",TAKE_PROFIT_MARKET:"market",TRAILING_STOP_MARKET:"market"},e,e)}parseOrder(e,t){let i=this.safeString(e,"positionSide"),s="spot";void 0!==i&&(s="swap");let r=this.safeString(e,"symbol"),a=this.safeMarket(r,t,void 0,s),o=this.safeStringLower(e,"side"),n=this.safeInteger(e,"time"),d=this.safeStringUpper(e,"status"),h=this.safeStringUpper(e,"type"),c=this.safeString(e,"stopPrice"),l=this.parseNumber(this.omitZero(c));return this.safeOrder({info:e,id:this.safeString(e,"orderId"),clientOrderId:this.safeString(e,"clientOrderId"),symbol:this.safeSymbol(r,a),timestamp:n,datetime:this.iso8601(n),lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeInteger(e,"updateTime"),type:this.parseOrderType(h),timeInForce:this.safeString(e,"timeInForce"),postOnly:void 0,side:o,price:this.safeString(e,"price"),triggerPrice:l,average:this.safeString(e,"avgPrice"),cost:this.safeString(e,"cumQuote"),amount:this.safeString(e,"origQty"),filled:this.safeString(e,"executedQty"),remaining:void 0,status:this.parseOrderStatus(d),fee:void 0,trades:void 0,reduceOnly:this.safeBool2(e,"reduceOnly","ro")},a)}async fetchOrder(e,t,i={}){let s;if(void 0===t)throw new o.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");await this.loadMarketsAndSignIn();let r=this.market(t),a={symbol:r.id},n=this.safeString2(i,"clientOrderId","clientOid"),d=this.omit(i,["clientOrderId","clientOid"]);return void 0!==n?a.origClientOrderId=n:a.orderId=e,s=!0===r.swap?await this.fapiPrivateGetV3Order(this.extend(a,d)):await this.sapiPrivateGetV3Order(this.extend(a,d)),this.parseOrder(s,r)}async fetchOpenOrder(e,t,i={}){let s;if(void 0===t)throw new o.ArgumentsRequired(this.id+" fetchOpenOrder() requires a symbol argument");await this.loadMarketsAndSignIn();let r=this.market(t),a={symbol:r.id},n=this.safeString2(i,"clientOrderId","clientOid"),d=this.omit(i,["clientOrderId","clientOid"]);return void 0!==n?a.origClientOrderId=n:a.orderId=e,s=!0===r.spot?await this.sapiPrivateGetV3OpenOrder(this.extend(a,d)):await this.fapiPrivateGetV3OpenOrder(this.extend(a,d)),this.parseOrder(s,r)}async fetchOrders(e,t,i,s={}){let r;if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchOrders() requires a symbol argument");await this.loadMarketsAndSignIn();let a=this.market(e),n={symbol:a.id};void 0!==i&&(n.limit=Math.min(i,1e3)),void 0!==t&&(n.startTime=t);let[d,h]=this.handleUntilOption("endTime",n,s);return r=!0===a.swap?await this.fapiPrivateGetV3AllOrders(this.extend(d,h)):await this.sapiPrivateGetV3AllOrders(this.extend(d,h)),this.parseOrders(r,a,t,i)}async fetchOpenOrders(e,t,i,s={}){let r,a;await this.loadMarketsAndSignIn();let n={};if(void 0!==e&&(n.symbol=(r=this.market(e)).id),void 0===e){if(this.safeBool(this.options.fetchOpenOrders,"warnIfNoSymbol",!1))throw new o.ExchangeError(this.id+' fetchOpenOrders(): WARNING - this method without providing "symbol" argument uses 40 times more rate-limit quota. If you acknowledge this warning, set '+this.id+'.options["fetchOpenOrders"]["warnIfNoSymbol"] = false to suppress this warning message.')}else n.symbol=(r=this.market(e)).id;let[d,h]=this.handleMarketTypeAndParams("fetchOpenOrders",r,s),[c,l]=this.handleSubTypeAndParams("fetchOpenOrders",r,h);return this.isLinear(d,c)?a=await this.fapiPrivateGetV3OpenOrders(this.extend(n,l)):"spot"===d&&(a=await this.sapiPrivateGetV3OpenOrders(this.extend(n,l))),this.parseOrders(a,r,t,i)}async createOrder(e,t,i,s,r,a={}){let o;await this.loadMarketsAndSignIn();let n=this.market(e),d=this.createOrderRequest(e,t,i,s,r,a);return o=!0===n.swap?await this.fapiPrivatePostV3Order(d):await this.sapiPrivatePostV3Order(d),this.parseOrder(o,n)}async createOrders(e,t={}){await this.loadMarketsAndSignIn();let i=[],s=[];if(e.length>5)throw new o.InvalidOrder(this.id+" createOrders() order list max 5 orders");for(let t=0;t<e.length;t++){let r=this.safeDict(e,t),a=this.safeString(r,"symbol"),o=this.market(a);s.push(o.symbol);let n=this.safeString(r,"type"),d=this.safeString(r,"side"),h=this.safeValue(r,"amount"),c=this.safeValue(r,"price"),l=this.safeDict(r,"params",{}),u=this.createOrderRequest(a,n,d,h,c,l);i.push(u)}let r=this.marketSymbols(s,void 0,!1,!0,!0),a=this.market(r[0]);if(!0===a.spot)throw new o.NotSupported(this.id+" createOrders() does not support "+a.type+" orders");let n=await this.fapiPrivatePostV3BatchOrders(this.extend({batchOrders:i},t));return this.parseOrders(n)}createOrderRequest(e,t,i,s,r,a={}){let d,h;if(void 0===t)throw new o.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new o.ArgumentsRequired(this.id+" requires a side argument");let c=this.market(e),l=t.toUpperCase(),u="MARKET"===l,f="LIMIT"===l,p={symbol:c.id,side:i.toUpperCase()},m=this.safeString2(a,"newClientOrderId","clientOrderId");void 0!==m&&(p.newClientOrderId=m);let g=this.safeString2(a,"triggerPrice","stopPrice"),v=this.safeString(a,"stopLossPrice",g),y=this.safeString(a,"takeProfitPrice"),b=this.safeString(a,"trailingDelta"),w=this.safeString2(a,"trailingTriggerPrice","activationPrice"),k=this.safeStringN(a,["trailingPercent","callbackRate","trailingDelta"]),S=l;void 0!==k?!0===c.swap&&(S="TRAILING_STOP_MARKET",p.callbackRate=k,void 0!==w&&(p.activationPrice=this.priceToPrecision(e,w))):void 0!==v||void 0!==b?(d=v,u?S="STOP_MARKET":f&&(S="STOP")):void 0!==y&&(d=y,u?S="TAKE_PROFIT_MARKET":f&&(S="TAKE_PROFIT")),this.isPostOnly(u,void 0,a)&&(p.timeInForce="GTX");let O=this.safeBool(a,"closePosition",!1),T=!1,P=!1,I=!1,A=!1;if(p.type=S,"MARKET"===S)if(!0===c.spot)if(!0===this.handleOption("createOrder","quoteOrderQty",!0)){let e=this.safeString2(a,"quoteOrderQty","cost"),t=c.precision.price;if(void 0!==e)p.quoteOrderQty=this.decimalToPrecision(e,0,t,this.precisionMode);else if(void 0!==r){let e=this.numberToString(s),i=this.numberToString(r),a=n.A.stringMul(e,i);p.quoteOrderQty=this.decimalToPrecision(a,0,t,this.precisionMode)}else A=!0}else A=!0;else A=!0;else"LIMIT"===S?(T=!0,A=!0,P=!0):"STOP"===S||"TAKE_PROFIT"===S?(A=!0,P=!0,I=!0):"STOP_MARKET"===S||"TAKE_PROFIT_MARKET"===S?(!0!==O&&(A=!0),I=!0):"TRAILING_STOP_MARKET"===S&&(p.callbackRate=k,void 0!==w&&(p.activationPrice=this.priceToPrecision(e,w)));if(A&&(void 0!==this.safeString(c.precision,"amount")?p.quantity=this.amountToPrecision(e,s):p.quantity=this.parseToNumeric(s)),P){if(void 0===r)throw new o.InvalidOrder(this.id+" createOrder() requires a price argument for a "+t+" order");void 0!==this.safeString(c.precision,"price")?p.price=this.priceToPrecision(e,r):p.price=this.parseToNumeric(r)}if(I){if(void 0===d)throw new o.InvalidOrder(this.id+" createOrder() requires a stopPrice extra param for a "+t+" order");void 0!==d&&(p.stopPrice=this.priceToPrecision(e,d))}let[x,M]=this.handleOptionStringAndParams(a,"createOrder","timeInForce"),_=T&&void 0===this.safeString(a,"timeInForce")&&void 0===this.safeString(p,"timeInForce"),C=["newClientOrderId","clientOrderId","stopPrice","triggerPrice","trailingTriggerPrice","trailingPercent","trailingDelta","stopPrice","stopLossPrice","takeProfitPrice"];return _?(p.timeInForce=x,h=this.omit(M,C)):h=this.omit(a,C),this.safeBool(this.options,"builderFee",!1)&&!0===c.swap&&(p.builder=this.safeString(this.options,"builder"),p.feeRate=this.safeString(this.options,"builderRate")),this.extend(p,h)}async cancelAllOrders(e,t={}){let i;if(void 0===e)throw new o.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument");await this.loadMarketsAndSignIn();let s=this.market(e),r={symbol:s.id};return i=!0===s.swap?await this.fapiPrivateDeleteV3AllOpenOrders(this.extend(r,t)):await this.sapiPrivateDeleteV3AllOpenOrders(this.extend(r,t)),[this.safeOrder({info:i})]}async cancelOrder(e,t,i={}){let s;if(void 0===t)throw new o.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");await this.loadMarketsAndSignIn();let r=this.market(t),a={symbol:r.id},n=this.safeString2(i,"origClientOrderId","clientOrderId");void 0!==n?a.origClientOrderId=n:a.orderId=e;let d=this.omit(i,["origClientOrderId","clientOrderId"]);return s=!0===r.swap?await this.fapiPrivateDeleteV3Order(this.extend(a,d)):await this.sapiPrivateDeleteV3Order(this.extend(a,d)),this.parseOrder(s,r)}async cancelOrders(e,t,i={}){let s;if(void 0===t)throw new o.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument");await this.loadMarketsAndSignIn();let r=this.market(t),a={symbol:r.id},n=this.safeList(i,"origClientOrderIdList");return void 0!==n?a.origClientOrderIdList=n:a.orderIdList=e,s=!0===r.swap?await this.fapiPrivateDeleteV3BatchOrders(this.extend(a,i)):await this.sapiPrivateDeleteV3AllOpenOrders(this.extend(a,i)),this.parseOrders(s,r)}async setLeverage(e,t,i={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");if(e<1||e>125)throw new o.BadRequest(this.id+" leverage should be between 1 and 125");await this.loadMarketsAndSignIn();let s={symbol:this.market(t).id,leverage:e};return await this.fapiPrivatePostV3Leverage(this.extend(s,i))}async fetchLeverages(e,t={}){await this.loadMarketsAndSignIn();let i=await this.fapiPrivateGetV3PositionRisk(t);return this.parseLeverages(this.toArray(i),e,"symbol")}parseLeverage(e,t){let i,s,r=this.safeString(e,"symbol"),a=this.safeStringLower(e,"marginType"),o=this.safeStringLower(e,"positionSide"),n=this.safeInteger(e,"leverage");return void 0===o||"both"===o?(i=n,s=n):"long"===o?i=n:"short"===o&&(s=n),{info:e,symbol:this.safeSymbol(r,t),marginMode:a,longLeverage:i,shortLeverage:s}}async fetchMarginModes(e,t={}){await this.loadMarketsAndSignIn();let i=await this.fapiPrivateGetV3PositionRisk(t);return this.parseMarginModes(this.toArray(i),e,"symbol","swap")}parseMarginMode(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t,void 0,"swap");return{info:e,symbol:this.safeString(s,"symbol"),marginMode:this.safeStringLower(e,"marginType")}}async fetchMarginAdjustmentHistory(e,t,i,s,r={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchMarginAdjustmentHistory () requires a symbol argument");await this.loadMarketsAndSignIn();let a=this.market(e),n=this.safeInteger(r,"until"),d=this.omit(r,"until"),h={symbol:a.id};void 0!==t&&(h.type="add"===t?1:2),void 0!==s&&(h.limit=Math.min(s,1e3)),void 0!==i&&(h.startTime=i),void 0!==n&&(h.endTime=n);let c=await this.fapiPrivateGetV3PositionMarginHistory(this.extend(h,d)),l=this.parseMarginModifications(this.toArray(c));return this.filterBySymbolSinceLimit(l,e,i,s)}parseMarginModification(e,t){let i=this.safeInteger(e,"type"),s=this.safeString(e,"code"),r=this.safeString(e,"symbol"),a=this.safeInteger(e,"time");return{info:e,symbol:this.safeMarket(r,t,void 0,"swap").symbol,type:1===i?"add":"reduce",marginMode:"isolated",amount:this.safeNumber(e,"amount"),code:this.safeString(e,"asset"),total:void 0,status:"200"===s||void 0===s?"ok":"failed",timestamp:a,datetime:this.iso8601(a)}}async modifyMarginHelper(e,t,i,s={}){await this.loadMarketsAndSignIn();let r=this.market(e),a=this.amountToPrecision(e,t),o={type:i,symbol:r.id,amount:a},n=r.quote,d=await this.fapiPrivatePostV3PositionMargin(this.extend(o,s));return this.extend(this.parseMarginModification(d,r),{code:n})}async reduceMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,2,i)}async addMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,1,i)}parseIncome(e,t){let i=this.safeString(e,"symbol"),s=this.safeString(e,"asset"),r=this.safeInteger(e,"time");return{info:e,symbol:this.safeSymbol(i,t,void 0,"swap"),code:this.safeCurrencyCode(s),timestamp:r,datetime:this.iso8601(r),id:this.safeString(e,"tranId"),amount:this.safeNumber(e,"income")}}async fetchFundingHistory(e,t,i,s={}){let r;await this.loadMarketsAndSignIn();let a={incomeType:"FUNDING_FEE"};void 0!==e&&(a.symbol=(r=this.market(e)).id);let[o,n]=this.handleUntilOption("endTime",a,s);void 0!==t&&(o.startTime=t),void 0!==i&&(o.limit=Math.min(i,1e3));let d=await this.fapiPrivateGetV3Income(this.extend(o,n));return this.parseIncomes(d,r,t,i)}parseLedgerEntry(e,t){let i,s=this.safeString(e,"income");n.A.stringLe(s,"0")?(i="out",s=n.A.stringMul("-1",s)):i="in";let r=this.safeString(e,"asset"),a=this.safeCurrencyCode(r,t),o=this.safeCurrency(r,t),d=this.safeInteger(e,"time"),h=this.safeString(e,"incomeType");return this.safeLedgerEntry({info:e,id:this.safeString(e,"tranId"),direction:i,account:void 0,referenceAccount:void 0,referenceId:this.safeString(e,"tradeId"),type:this.parseLedgerEntryType(h),currency:a,amount:this.parseNumber(s),timestamp:d,datetime:this.iso8601(d),before:void 0,after:void 0,status:void 0,fee:void 0},o)}parseLedgerEntryType(e){return this.safeString({TRANSFER:"transfer",WELCOME_BONUS:"cashback",REALIZED_PNL:"trade",FUNDING_FEE:"fee",COMMISSION:"commission",INSURANCE_CLEAR:"settlement",MARKET_MERCHANT_RETURN_REWARD:"cashback"},e,e)}async fetchLedger(e,t,i,s={}){let r;await this.loadMarketsAndSignIn(),void 0!==e&&(r=this.currency(e));let a={};void 0!==t&&(a.startTime=t),void 0!==i&&(a.limit=Math.min(i,1e3));let o=this.safeInteger(s,"until"),n=void 0!==o?this.omit(s,"until"):s;void 0!==o&&(a.endTime=o);let d=await this.fapiPrivateGetV3Income(this.extend(a,n));return this.parseLedger(d,r,t,i)}parsePositionRisk(e,t){let i,s,r,a,o,d,h,c=this.safeString(e,"symbol"),l=this.safeMarket(c,t,void 0,"contract"),u=this.safeString(l,"symbol"),f=this.safeString(e,"isolatedMargin"),p=this.safeDict(this.options,"leverageBrackets",{}),m=this.safeList(p,u,[]),g=this.safeString2(e,"notional","notionalValue"),v=n.A.stringAbs(g);for(let e=0;e<m.length;e++){let t=m[e];if(n.A.stringLt(v,t[0]))break;i=this.safeString(t,1)}let y=this.parseNumber(v),b=n.A.stringAbs(this.safeString(e,"positionAmt")),w=this.parseNumber(b),k=this.safeString(e,"unRealizedProfit"),S=this.parseNumber(k),O=this.omitZero(this.safeString(e,"liquidationPrice")),T=this.parseNumber(O),P=this.safeString(e,"marginType");void 0===P&&void 0!==f&&(P=n.A.stringEq(f,"0")?"cross":"isolated"),n.A.stringGt(g,"0")?r="long":n.A.stringLt(g,"0")&&(r="short");let I=this.safeString(e,"entryPrice"),A=this.parseNumber(I),x=this.safeNumber(l,"contractSize"),M=this.numberToString(x),_="notional"in e;if("cross"===P){let e=this.safeDict(l,"precision",{}),t=this.safeString(e,"base"),a=this.safeString2(e,"quote","price");if(void 0!==t||void 0!==a)if(_){let t,a=I;"short"===r?(t=n.A.stringAdd("1",i),a=n.A.stringMul("-1",a)):t=n.A.stringAdd("-1",i);let o=n.A.stringMul(O,t),d=n.A.stringAdd(o,a),h=this.precisionFromString(this.safeString2(e,"quote","price"));s=n.A.stringDiv(n.A.stringMul(d,b),"1",h)}else{let t,a=I;"short"===r?t=n.A.stringSub("1",i):(t=n.A.stringSub("-1",i),a=n.A.stringMul("-1",a));let o=n.A.stringMul(b,M),d=n.A.stringSub(n.A.stringDiv("1",a),n.A.stringDiv(t,O)),h=this.precisionFromString(this.safeString(e,"base"));s=n.A.stringDiv(n.A.stringMul(o,d),"1",h)}}else s=this.safeString(e,"isolatedMargin");s=void 0===s?"0":s;let C=this.parseNumber(s),B=this.parseNumber(this.omitZero(this.safeString(e,"markPrice"))),E=this.safeInteger(e,"updateTime");0===E&&(E=void 0);let R=this.parseNumber(i),L=n.A.stringMul(i,v);void 0===L&&(L=this.safeString(e,"maintMargin"));let N=this.parseNumber(L),D=this.safeString(e,"leverage");if(void 0!==D){let e=parseInt(D),t=this.isRoundNumber(1e3%e);o=n.A.stringDiv("1",D,8),t||(o=n.A.stringAdd(o,"1e-8"));let i=n.A.stringMul(v,o);a=n.A.stringDiv(i,"1",8)}else{a=this.safeString(e,"initialMargin");let t=n.A.stringMul(a,"1");o=n.A.stringDiv(t,v,8)}n.A.stringEquals(s,"0")||(d=this.parseNumber(n.A.stringDiv(n.A.stringAdd(n.A.stringDiv(L,s),"5e-5"),"1",4)),h=this.parseNumber(n.A.stringMul(n.A.stringDiv(k,a,4),"100")));let q=this.safeString(e,"positionSide");return this.safePosition({info:e,id:void 0,symbol:u,contracts:w,contractSize:x,unrealizedPnl:S,leverage:this.parseNumber(D),liquidationPrice:T,collateral:C,notional:y,markPrice:B,entryPrice:A,timestamp:E,initialMargin:this.parseNumber(a),initialMarginPercentage:this.parseNumber(o),maintenanceMargin:N,maintenanceMarginPercentage:R,marginRatio:d,datetime:this.iso8601(E),marginMode:P,side:r,hedged:"BOTH"!==q,percentage:h,stopLossPrice:void 0,takeProfitPrice:void 0})}async fetchPositionsRisk(e,t={}){if(void 0!==e&&!Array.isArray(e))throw new o.ArgumentsRequired(this.id+" fetchPositionsRisk() requires an array argument for symbols");await this.loadMarketsAndSignIn(),await this.loadLeverageBrackets(!1,t);let i=await this.fapiPrivateGetV3PositionRisk(this.extend({},t)),s=this.toArray(i),r=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.safeString(t,"entryPrice");n.A.stringGt(i,"0")&&r.push(this.parsePositionRisk(t))}let a=this.marketSymbols(e);return this.filterByArrayPositions(r,"symbol",a)}async fetchPositions(e,t={}){let[i,s]=this.handleOptionStringAndParams(t,"fetchPositions","method"),r=i;if(void 0===r&&(r=void 0===this.safeDict(this.options,"fetchPositions")?this.safeString(this.options,"fetchPositions","positionRisk"):"positionRisk"),"positionRisk"===r)return await this.fetchPositionsRisk(e,s);if("account"===r)return await this.fetchAccountPositions(e,s);throw new o.NotSupported(this.id+'.options["fetchPositions"]["method"] or params["method"] = "'+r+'" is invalid, please choose between "account" and "positionRisk"')}parseAccountPositions(e,t=!1){let i=this.safeList(e,"positions",[]),s=this.safeList(e,"assets",[]),r={};for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),i=this.safeString(t,"asset"),a=this.safeCurrencyCode(i),o=this.safeString(t,"crossWalletBalance"),d=this.safeString(t,"crossUnPnl");void 0!==a&&(r[a]={crossMargin:n.A.stringAdd(o,d),crossWalletBalance:o})}let a=[];for(let e=0;e<i.length;e++){let s=i[e],o=this.safeString(s,"symbol"),n=this.safeMarket(o,void 0,void 0,"contract"),d=!0===n.linear?n.quote:n.base,h=this.safeString(s,"maintMargin"),c="0"!==h&&"0.00000000"!==h;if((!t||c)&&d in r){let e=this.parseAccountPosition(this.extend(s,{crossMargin:r[d].crossMargin,crossWalletBalance:r[d].crossWalletBalance}),n);a.push(e)}}return a}parseAccountPosition(e,t){let i,s,r,a,d,h,c,l,u,f,p=this.safeString(e,"symbol"),m=this.safeMarket(p,t,void 0,"contract"),g=this.safeString(m,"symbol"),v=this.safeString(e,"leverage"),y=void 0!==v?parseInt(v):void 0,b=this.safeString(e,"initialMargin"),w=this.parseNumber(b);if(void 0!==v){if(i=n.A.stringDiv("1",v,8),void 0===y)throw new o.ExchangeError(this.id+" parseAccountPosition() missing leverage");this.isRoundNumber(1e3%y)||(i=n.A.stringDiv(n.A.stringAdd(i,"1e-8"),"1",8))}let k="notional"in e,S=this.safeString(e,"maintMargin"),O=this.parseNumber(S),T=this.safeString(e,"entryPrice"),P=this.parseNumber(T),I=this.safeString2(e,"notional","notionalValue"),A=n.A.stringAbs(I),x=this.parseNumber(A),M=this.safeString(e,"positionAmt"),_=n.A.stringAbs(M);if(void 0===M){let e=n.A.stringMul(n.A.stringMul(v,b),T),t=this.safeString(m,"contractSize");M=n.A.stringDiv(e,t),_=n.A.stringDiv(n.A.stringAdd(M,"0.5"),"1",0)}let C=this.parseNumber(_),B=this.safeDict(this.options,"leverageBrackets",{}),E=this.safeList(B,g,[]);for(let e=0;e<E.length;e++){let t=E[e];if(n.A.stringLt(A,t[0]))break;s=this.safeString(t,1)}let R=this.parseNumber(s),L=this.safeString(e,"unrealizedProfit"),N=this.parseNumber(L),D=this.safeInteger(e,"updateTime");0===D&&(D=void 0);let q=this.safeBool(e,"isolated");if(void 0===q){let t=this.safeString(e,"isolatedMargin");q=!n.A.stringEq(t,"0")}q?(r="isolated",d=this.safeString(e,"isolatedWallet"),a=n.A.stringAdd(d,L)):(r="cross",d=this.safeString(e,"crossWalletBalance"),a=this.safeString(e,"crossMargin"));let F=this.parseNumber(a),V=this.safeNumber(m,"contractSize"),G=this.numberToString(V);if(n.A.stringEquals(I,"0"))P=void 0;else{if(c=n.A.stringLt(I,"0")?"short":"long",h=this.parseNumber(n.A.stringDiv(n.A.stringAdd(n.A.stringDiv(S,a),"5e-5"),"1",4)),l=this.parseNumber(n.A.stringMul(n.A.stringDiv(L,b,4),"100")),k){let e,t=T;"short"===c?e=n.A.stringAdd("1",s):(e=n.A.stringAdd("-1",s),t=n.A.stringMul("-1",t));let i=n.A.stringDiv(d,n.A.stringMul(_,e)),r=n.A.stringDiv(t,e);u=n.A.stringAdd(i,r)}else{let e,t=T;"short"===c?e=n.A.stringSub("1",s):(e=n.A.stringSub("-1",s),t=n.A.stringMul("-1",t));let i=n.A.stringMul(_,G),r=n.A.stringMul(i,e),a=n.A.stringSub(n.A.stringMul(n.A.stringDiv("1",t),i),d);u=n.A.stringDiv(r,a)}let e=this.precisionFromString(this.safeString(m.precision,"price")),t=(e+1).toString(),i=new n.A("5e-"+t).toString(),r=n.A.stringAdd(i,u),p=n.A.stringDiv(r,"1",e);if(void 0===p)throw new o.ExchangeError(this.id+" method() missing truncatedLiquidationPrice");"-"===p[0]&&(p=void 0),f=this.parseNumber(p)}let H=this.safeString(e,"positionSide");return{info:e,id:void 0,symbol:g,timestamp:D,datetime:this.iso8601(D),initialMargin:w,initialMarginPercentage:this.parseNumber(i),maintenanceMargin:O,maintenanceMarginPercentage:R,entryPrice:P,notional:x,leverage:this.parseNumber(v),unrealizedPnl:N,contracts:C,contractSize:V,marginRatio:h,liquidationPrice:f,markPrice:void 0,collateral:F,marginMode:r,side:c,hedged:"BOTH"!==H,percentage:l}}async fetchAccountPositions(e,t={}){if(void 0!==e&&!Array.isArray(e))throw new o.ArgumentsRequired(this.id+" fetchPositions() requires an array argument for symbols");await this.loadMarketsAndSignIn(),await this.loadLeverageBrackets(!1,t);let i=await this.fapiPrivateGetV4Account(t),s=this.handleOptionBoolAndParams(t,"fetchAccountPositions","filterClosed",!1)[0],r=this.parseAccountPositions(i,s),a=this.marketSymbols(e);return this.filterByArrayPositions(r,"symbol",a)}async loadLeverageBrackets(e=!1,t={}){if(await this.loadMarketsAndSignIn(),void 0===this.safeDict(this.options,"leverageBrackets")||e){let e=await this.fapiPrivateGetV3LeverageBracket(t);this.options.leverageBrackets=this.createSafeDictionary();let i=this.toArray(e);for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),s=this.safeString(t,"symbol"),r=this.safeSymbol(s,void 0,void 0,"contract"),a=this.safeList(t,"brackets",[]),o=[];for(let e=0;e<a.length;e++){let t=this.safeDict(a,e),i=this.safeString(t,"notionalFloor"),s=this.safeString(t,"maintMarginRatio");o.push([i,s])}this.options.leverageBrackets[r]=o}}return this.options.leverageBrackets}keccakMessage(e){return"0x"+this.hash(e,s.lY,"hex")}signMessage(e,t){return this.signHash(this.keccakMessage(e),t.slice(-64))}signWithdrawPayload(e,t){let i={chainId:this.safeInteger(e,"chainId"),name:"Aster",verifyingContract:this.safeString(this.options,"zeroAddress"),version:"1"},s={type:"Withdraw",destination:this.safeString(e,"receiver"),"destination Chain":t,token:this.safeString(e,"asset"),amount:this.safeString(e,"amount"),fee:this.safeString(e,"fee"),nonce:this.safeInteger(e,"userNonce"),"aster chain":"Mainnet"},r=this.ethEncodeStructuredData(i,{Action:[{name:"type",type:"string"},{name:"destination",type:"address"},{name:"destination Chain",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"fee",type:"string"},{name:"nonce",type:"uint256"},{name:"aster chain",type:"string"}]},s);return this.signMessage(r,this.privateKey)}async withdraw(e,t,i,s,r={}){let a=this.handleWithdrawTagAndParams(s,r)[1];this.checkAddress(i),await this.loadMarketsAndSignIn();let n=this.currency(e),d=1e3*this.milliseconds(),h={asset:n.id,receiver:i,userNonce:d.toString()},c=this.safeInteger(a,"chainId"),l=this.safeDict(this.options,"networks",{}),u=this.safeStringUpper(a,"network");if(u=this.safeString(l,u,u),void 0===c&&void 0!==u){let e=this.safeDict(this.options,"networksToChainId",{});c=this.safeInteger(e,u)}if(void 0===c)throw new o.ArgumentsRequired(this.id+" withdraw require chainId or network parameter");h.chainId=c;let f=this.safeString(a,"fee");if(void 0===f)throw new o.ArgumentsRequired(this.id+" withdraw require fee parameter");h.fee=f;let p=this.omit(a,["chainId","network","fee"]);h.amount=this.currencyToPrecision(e,t,u),h.userSignature=this.signWithdrawPayload(h,u);let m=await this.sapiPrivatePostV3AsterUserWithdraw(this.extend(h,p));return this.parseTransaction(m,n)}parseTransaction(e,t){return{info:e,id:this.safeString(e,"withdrawId"),txid:this.safeString(e,"hash"),timestamp:void 0,datetime:void 0,network:void 0,address:void 0,addressTo:void 0,addressFrom:void 0,tag:void 0,tagTo:void 0,tagFrom:void 0,type:"withdrawal",amount:void 0,currency:void 0,status:void 0,updated:void 0,internal:void 0,comment:void 0,fee:void 0}}async transfer(e,t,i,s,r={}){let a;await this.loadMarketsAndSignIn();let n=this.currency(e),d={asset:n.id,amount:this.currencyToPrecision(e,t)},h=this.convertTypeToAccount(i).toUpperCase(),c=this.convertTypeToAccount(s).toUpperCase();if("SPOT"===h&&"FUTURE"===c?a="SPOT_FUTURE":"FUTURE"===h&&"SPOT"===c&&(a="FUTURE_SPOT"),void 0===a)throw new o.ArgumentsRequired(this.id+" transfer() requires fromAccount and toAccount parameters to be either SPOT or FUTURE");let l=this.numberToString(this.milliseconds()),u=this.safeString(r,"clientTranId",l);d.kindType=a,d.clientTranId=u;let f=await this.sapiPrivatePostV3AssetWalletTransfer(this.extend(d,r));return this.parseTransfer(f,n)}parseTransfer(e,t){let i=this.safeString(e,"code");return{info:e,id:this.safeString(e,"tranId"),timestamp:void 0,datetime:void 0,currency:this.safeCurrencyCode(i,t),amount:void 0,fromAccount:void 0,toAccount:void 0,status:this.parseTransferStatus(this.safeString(e,"status"))}}parseTransferStatus(e){return this.safeString({SUCCESS:"ok"},e,e)}hashMessage(e){let t=this.binaryLength(e),i=this.base16ToBinary("19"),r=this.base16ToBinary("0a"),a=this.binaryConcat(i,this.encode("Ethereum Signed Message:"),r,this.encode(this.numberToString(t)));return"0x"+this.hash(this.binaryConcat(a,e),s.lY,"hex")}signHash(e,t){this.checkRequiredCredentials();let i=(0,d.h1)(e.slice(-64),t.slice(-64),r.bI,void 0),s=i.r,a=i.s,o=this.intToBase16(this.sum(27,i.v));return"0x"+s.padStart(64,"0")+a.padStart(64,"0")+o}sign(e,t="public",i="GET",r={},a,n){let d=this.safeString(this.urls.api,t);if(void 0===d)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let h=d+"/"+e;if("fapiPublic"===t||"sapiPublic"===t)Object.keys(r).length>0&&(h+="?"+this.rawencode(r));else if("fapiPrivate"===t||"sapiPrivate"===t){let t,a;this.checkRequiredCredentials();let n=1e3*this.milliseconds(),d=this.safeString(this.options,"zeroAddress","0x0000000000000000000000000000000000000000"),c=this.safeInteger(this.options,"v3ChainId",1666),l=this.safeString(this.options,"cachedWalletAddress"),u=this.hash(this.encode(this.privateKey),s.lY,"hex"),f=this.safeString(this.options,"privateKeyHashForCachedWalletAddress");(void 0===l||f!==u)&&(l=this.ethGetAddressFromPrivateKey(this.privateKey),this.options.cachedWalletAddress=l,this.options.privateKeyHashForCachedWalletAddress=u);let p=this.safeString(this.options,"signerAddress",l);if(void 0===p)throw new o.ArgumentsRequired(this.id+" requires signerAddress in options when use v3 api");let m={Message:[{name:"msg",type:"string"}]},g=this.extend({nonce:n.toString(),user:l,signer:p},r);e.indexOf("/approveBuilder")>=0?(m={ApproveBuilder:[{name:"Builder",type:"string"},{name:"MaxFeeRate",type:"string"},{name:"BuilderName",type:"string"},{name:"AsterChain",type:"string"},{name:"User",type:"string"},{name:"Nonce",type:"uint256"}]},delete g.signer,a=this.encodeValuesWithJson(g),t=this.capitalizeKeys(g)):t={msg:a=this.encodeValuesWithJson(g)};let v=this.ethEncodeStructuredData({name:"AsterSignTransaction",version:"1",chainId:c,verifyingContract:d},m,t),y=a+"&signature="+this.signMessage(v,this.privateKey);if("GET"!==i)return{url:h,method:i,body:y,headers:{"Content-Type":"application/x-www-form-urlencoded"}};h+="?"+y}return{url:h,method:i,body:n,headers:a}}encodeValuesWithJson(e){let t="",i=Object.keys(e);for(let s=0;s<i.length;s++){let r=i[s],a=e[r],o=Array.isArray(a)||this.isDictionary(a)?this.json(a):a.toString();t+=r+"="+this.encodeURIComponent(o)+"&"}return t.slice(0,-1)}capitalizeKeys(e){let t={},i=Object.keys(e);for(let s=0;s<i.length;s++){let r=i[s],a=e[r];t[this.capitalize(r)]=a}return t}async loadMarketsAndSignIn(){await Promise.all([this.loadMarkets(),this.signIn()])}async signIn(e={}){if(this.isEmptyString(this.privateKey)){if(!this.isEmptyString(this.apiKey)||!this.isEmptyString(this.secret))throw new o.NotSupported(this.id+"after the latest upgrade (v4.5.52), CCXT now expects the l1 private key to be provided in the credentials.");return!1}if(this.privateKey.length>66)throw new o.NotSupported(this.id+" after the latest update (v4.5.52), CCXT now expects the l1 private key to be provided in the credentials.");return await this.initializeClient(e),!0}async initializeClient(e={}){if(!0!==this.safeBool(e,"builderFee",this.safeBool(this.options,"builderFee",!0)))return!1;if(!0===this.safeBool(this.options,"approvedBuilderFee",!1))return!0;let t=await this.fapiPrivateGetV3Builder(),i=t.length,s=!1;for(let e=0;e<i;e++){let i=this.safeDict(t,e,{});if(this.safeString(i,"builderAddress")===this.safeString(this.options,"builder")){s=!0;break}}if(!s){this.options.approvedBuilderFee=!0;try{let t={builder:this.safeString(this.options,"builder"),builderName:this.safeString(this.options,"builderName","ccxt"),maxFeeRate:this.safeString(this.options,"builderRate"),signatureChainId:this.safeInteger(this.options,"v3ChainId",1666),asterChain:"Mainnet"},i=await this.fapiPrivatePostV3ApproveBuilder(this.extend(t,e)),s=this.safeInteger(i,"code");if(200!==s)throw new o.ExchangeError("Builder authorization failed, "+this.json(i))}catch(e){this.options.approvedBuilderFee=!1,this.options.builderFee=!1}}}handleErrors(e,t,i,s,r,a,n,d,h){if(void 0===n)return;let c=this.safeString(n,"code"),l=this.safeString(n,"msg");if(void 0!==c&&"200"!==c){let e=this.id+" "+a;throw this.throwExactlyMatchedException(this.exceptions.exact,l,e),this.throwExactlyMatchedException(this.exceptions.exact,c,e),this.throwBroadlyMatchedException(this.exceptions.broad,l,e),new o.ExchangeError(e)}}}i.d(t,{A:()=>h})},9264(e,t,i){"use strict";var s=i(7468),r=i(4953),a=i(1453),o=i(7749),n=i(1093);class d extends r.A{describe(){return this.deepExtend(super.describe(),{id:"backpack",name:"Backpack",countries:["JP"],rateLimit:50,version:"v1",certified:!1,pro:!0,has:{CORS:void 0,spot:!0,margin:!0,swap:!0,future:!1,option:!1,addMargin:!1,cancelAllOrders:!0,cancelAllOrdersAfter:!1,cancelOrder:!0,cancelOrders:!1,cancelWithdraw:!1,closePosition:!1,createConvertTrade:!1,createDepositAddress:!1,createLimitBuyOrder:!0,createLimitOrder:!0,createLimitSellOrder:!0,createMarketBuyOrder:!0,createMarketBuyOrderWithCost:!0,createMarketOrder:!0,createMarketOrderWithCost:!0,createMarketSellOrder:!0,createMarketSellOrderWithCost:!0,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!0,createPostOnlyOrder:!0,createReduceOnlyOrder:!0,createStopLossOrder:!1,createTakeProfitOrder:!1,createTrailingAmountOrder:!1,createTrailingPercentOrder:!1,createTriggerOrder:!0,fetchAccounts:!1,fetchAllGreeks:!1,fetchBalance:!0,fetchCanceledAndClosedOrders:!1,fetchCanceledOrders:!1,fetchClosedOrder:!1,fetchClosedOrders:!1,fetchConvertCurrencies:!1,fetchConvertQuote:!1,fetchConvertTrade:!1,fetchConvertTradeHistory:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDeposits:!0,fetchDepositsWithdrawals:!1,fetchDepositWithdrawFees:!1,fetchFundingHistory:!0,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!0,fetchLedger:!1,fetchLeverage:!1,fetchLeverageTiers:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!0,fetchOpenOrder:!0,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!1,fetchOrderBook:!0,fetchOrders:!0,fetchOrderTrades:!1,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPremiumIndexOHLCV:!1,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTransactions:!1,fetchTransfers:!1,fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!1,sandbox:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,withdraw:!0},timeframes:{"1m":"1m","3m":"3m","5m":"5m",15:"15m",30:"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","8h":"8h","12h":"12h","1d":"1d","3d":"3d","1w":"1w","1M":"1month"},urls:{logo:"https://github.com/user-attachments/assets/7f682234-3eb1-48ab-a5ec-250a3227c985",api:{public:"https://api.backpack.exchange",private:"https://api.backpack.exchange"},www:"https://backpack.exchange/",doc:"https://docs.backpack.exchange/",referral:"https://backpack.exchange/join/ccxt"},api:{public:{get:{"api/v1/assets":{cost:1},"api/v1/collateral":{cost:1},"api/v1/borrowLend/markets":{cost:1},"api/v1/borrowLend/markets/history":{cost:1},"api/v1/borrowLend/apy":{cost:1},"api/v1/markets":{cost:1},"api/v1/market":{cost:1},"api/v1/ticker":{cost:1},"api/v1/tickers":{cost:1},"api/v1/depth":{cost:1},"api/v1/prediction":{cost:1},"api/v1/prediction/tags":{cost:1},"api/v1/market-sessions":{cost:1},"api/v1/market-holidays":{cost:1},"api/v1/securities":{cost:1},"api/v1/klines":{cost:1},"api/v1/markPrices":{cost:1},"api/v1/openInterest":{cost:1},"api/v1/fundingRates":{cost:1},"api/v1/status":{cost:1},"api/v1/ping":{cost:1},"api/v1/time":{cost:1},"api/v1/wallets":{cost:1},"api/v1/trades":{cost:1},"api/v1/trades/history":{cost:1}}},private:{get:{"api/v1/account":{cost:1},"api/v1/account/limits/borrow":{cost:1},"api/v1/account/limits/order":{cost:1},"api/v1/account/limits/withdrawal":{cost:1},"api/v1/borrowLend/positions":{cost:1},"api/v1/borrowLend/position/liquidationPrice":{cost:1},"api/v1/capital":{cost:1},"api/v1/capital/collateral":{cost:1},"wapi/v1/capital/deposits":{cost:1},"wapi/v1/capital/deposit/address":{cost:1},"wapi/v1/capital/withdrawals":{cost:1},"api/v1/position":{cost:1},"wapi/v1/history/borrowLend":{cost:1},"wapi/v1/history/interest":{cost:1},"wapi/v1/history/borrowLend/positions":{cost:1},"wapi/v1/history/dust":{cost:1},"wapi/v1/history/fills":{cost:1},"wapi/v1/history/funding":{cost:1},"wapi/v1/history/position":{cost:1},"wapi/v1/history/orders":{cost:1},"api/v1/rfqs":{cost:1},"wapi/v1/history/rfq":{cost:1},"wapi/v1/history/quote":{cost:1},"wapi/v1/history/rfq/fill":{cost:1},"wapi/v1/history/quote/fill":{cost:1},"wapi/v1/history/settlement":{cost:1},"wapi/v1/history/strategies":{cost:1},"api/v1/strategy":{cost:1},"api/v1/strategies":{cost:1},"api/v1/order":{cost:1},"api/v1/orders":{cost:1}},post:{"api/v1/account/convertDust":{cost:1},"api/v1/borrowLend":{cost:1},"wapi/v1/capital/withdrawals":{cost:1},"api/v1/order":{cost:1},"api/v1/orders":{cost:1},"api/v1/rfq":{cost:1},"api/v1/rfq/accept":{cost:1},"api/v1/rfq/refresh":{cost:1},"api/v1/rfq/cancel":{cost:1},"api/v1/rfq/quote":{cost:1},"api/v1/strategy":{cost:1}},delete:{"api/v1/order":{cost:1},"api/v1/orders":{cost:1},"api/v1/strategy":{cost:1},"api/v1/strategies":{cost:1}},patch:{"api/v1/account":{cost:1}}}},features:{default:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{GTC:!0,IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!0,selfTradePrevention:{EXPIRE_MAKER:!0,EXPIRE_TAKER:!0,EXPIRE_BOTH:!0,NONE:!1},iceberg:!1},createOrders:{max:20},fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:void 0,untilDays:void 0,symbolRequired:!1},fetchOrder:void 0,fetchOpenOrders:{marginMode:!1,limit:1e3,trigger:!0,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:1e3,daysBack:void 0,untilDays:void 0,trigger:!0,trailing:!1,symbolRequired:!0},fetchClosedOrders:void 0,fetchOHLCV:{paginate:!1,limit:1e3}},spot:{extends:"default"},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},requiredCredentials:{apiKey:!0,secret:!0},precisionMode:4,options:{instructions:{"api/v1/account":{GET:"accountQuery",PATCH:"accountUpdate"},"api/v1/capital":{GET:"balanceQuery"},"api/v1/account/limits/borrow":{GET:"maxBorrowQuantity"},"api/v1/account/limits/order":{GET:"maxOrderQuantity"},"api/v1/account/limits/withdrawal":{GET:"maxWithdrawalQuantity"},"api/v1/borrowLend/positions":{GET:"borrowLendPositionQuery"},"api/v1/borrowLend":{POST:"borrowLendExecute"},"wapi/v1/history/borrowLend/positions":{GET:"borrowPositionHistoryQueryAll"},"wapi/v1/history/borrowLend":{GET:"borrowHistoryQueryAll"},"wapi/v1/history/dust":{GET:"dustHistoryQueryAll"},"api/v1/capital/collateral":{GET:"collateralQuery"},"wapi/v1/capital/deposit/address":{GET:"depositAddressQuery"},"wapi/v1/capital/deposits":{GET:"depositQueryAll"},"wapi/v1/history/fills":{GET:"fillHistoryQueryAll"},"wapi/v1/history/funding":{GET:"fundingHistoryQueryAll"},"wapi/v1/history/interest":{GET:"interestHistoryQueryAll"},"api/v1/order":{GET:"orderQuery",POST:"orderExecute",DELETE:"orderCancel"},"api/v1/orders":{GET:"orderQueryAll",POST:"orderExecute",DELETE:"orderCancelAll"},"wapi/v1/history/orders":{GET:"orderHistoryQueryAll"},"wapi/v1/history/pnl":{GET:"pnlHistoryQueryAll"},"wapi/v1/history/rfq":{GET:"rfqHistoryQueryAll"},"wapi/v1/history/quote":{GET:"quoteHistoryQueryAll"},"wapi/v1/history/settlement":{GET:"settlementHistoryQueryAll"},"api/v1/position":{GET:"positionQuery"},"api/v1/rfq/quote":{POST:"quoteSubmit"},"wapi/v1/history/strategies":{GET:"strategyHistoryQueryAll"},"wapi/v1/capital/withdrawals":{GET:"withdrawalQueryAll",POST:"withdraw"}},recvWindow:5e3,brokerId:"",currencyIdsListForParseMarket:void 0,broker:"",timeDifference:0,adjustForTimeDifference:!1,networks:{APT:"Aptos",ARBITRUM:"Arbitrum",AVAX:"Avalanche",BASE:"Base",BERA:"Berachain",BTC:"Bitcoin",BCH:"BitcoinCash",BSC:"Bsc",ADA:"Cardano",DOGE:"Dogecoin",ECLIPSE:"Eclipse",EQUALSMONEY:"EqualsMoney",ERC20:"Ethereum",HYP:"Hyperliquid",LTC:"Litecoin",OPTIMISM:"Optimism",MATIC:"Polygon",SEI:"Sei",SUI:"Sui",SOL:"Solana",STORY:"Story",TRC20:"Tron",XRP:"XRP"},networksById:{aptos:"APT",arbitrum:"ARBITRUM",avalanche:"AVAX",base:"BASE",berachain:"BERA",bitcoin:"BTC",bitcoincash:"BCH",bsc:"BSC",cardano:"ADA",dogecoin:"DOGE",eclipse:"ECLIPSE",equalsmoney:"EQUALSMONEY",ethereum:"ERC20",hyperliquid:"HYP",litecoin:"LTC",optimism:"OPTIMISM",polygon:"MATIC",sei:"SEI",sui:"SUI",solana:"SOL",story:"STORY",tron:"TRC20",xrp:"XRP"}},commonCurrencies:{},exceptions:{exact:{INVALID_CLIENT_REQUEST:a.BadRequest,INVALID_ORDER:a.InvalidOrder,ACCOUNT_LIQUIDATING:a.BadRequest,BORROW_LIMIT:a.BadRequest,BORROW_REQUIRES_LEND_REDEEM:a.BadRequest,FORBIDDEN:a.OperationRejected,INSUFFICIENT_FUNDS:a.InsufficientFunds,INSUFFICIENT_MARGIN:a.InsufficientFunds,INSUFFICIENT_SUPPLY:a.InsufficientFunds,INVALID_ASSET:a.BadRequest,INVALID_MARKET:a.BadSymbol,INVALID_PRICE:a.InvalidOrder,INVALID_POSITION_ID:a.BadRequest,INVALID_QUANTITY:a.BadRequest,INVALID_RANGE:a.BadRequest,INVALID_SIGNATURE:a.AuthenticationError,INVALID_SOURCE:a.BadRequest,INVALID_SYMBOL:a.BadSymbol,INVALID_TWO_FACTOR_CODE:a.BadRequest,LEND_LIMIT:a.BadRequest,LEND_REQUIRES_BORROW_REPAY:a.BadRequest,MAINTENANCE:a.ExchangeError,MAX_LEVERAGE_REACHED:a.InsufficientFunds,NOT_IMPLEMENTED:a.OperationFailed,ORDER_LIMIT:a.OperationRejected,POSITION_LIMIT:a.OperationRejected,PRECONDITION_FAILED:a.OperationFailed,RESOURCE_NOT_FOUND:a.ExchangeNotAvailable,SERVER_ERROR:a.NetworkError,TIMEOUT:a.RequestTimeout,TOO_MANY_REQUESTS:a.RateLimitExceeded,TRADING_PAUSED:a.ExchangeNotAvailable,UNAUTHORIZED:a.AuthenticationError},broad:{}}})}async fetchCurrencies(e={}){let t=await this.publicGetApiV1Assets(e);return this.parseCurrencies(t)}parseCurrency(e){let t,i,s,r=this.safeString(e,"symbol"),a=this.safeCurrencyCode(r),o=this.safeList(e,"tokens",[]),n={};for(let e=0;e<o.length;e++){let t=o[e],i=this.safeString(t,"blockchain"),s=this.safeStringLower(t,"blockchain"),r=this.networkIdToCode(s,a);void 0!==r&&(n[r]={id:i,network:r,limits:{withdraw:{min:this.safeNumber(t,"minimumWithdrawal"),max:this.parseNumber(this.omitZero(this.safeString(t,"maximumWithdrawal")))},deposit:{min:this.safeNumber(t,"minimumDeposit"),max:void 0}},active:void 0,deposit:this.safeBool(t,"depositEnabled"),withdraw:this.safeBool(t,"withdrawEnabled"),fee:this.safeNumber(t,"withdrawalFee"),precision:void 0,info:t})}return this.isEmpty(n)&&(t=!1,i=!1,s=!1),this.safeCurrencyStructure({id:r,code:a,precision:void 0,type:"crypto",name:this.safeString(e,"displayName"),active:t,deposit:i,withdraw:s,fee:void 0,limits:{deposit:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}},networks:n,info:e})}async fetchMarkets(e={}){this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference();let t=await this.publicGetApiV1Markets(e);return this.parseMarkets(t)}parseMarket(e){let t,i,s,r,a,o,n=this.safeString(e,"symbol"),d=this.safeString(e,"baseSymbol"),h=this.safeString(e,"quoteSymbol"),c=this.safeCurrencyCode(d),l=this.safeCurrencyCode(h);if(void 0===c||void 0===l)return;let u=c+"/"+l,f=this.safeDict(e,"filters",{}),p=this.safeDict(f,"price",{}),m=this.safeNumber(p,"maxPrice"),g=this.safeNumber(p,"minPrice"),v=this.safeNumber(p,"tickSize"),y=this.safeDict(f,"quantity",{}),b=this.safeNumber(y,"maxQuantity"),w=this.safeNumber(y,"minQuantity"),k=this.safeNumber(y,"stepSize"),S=this.parseMarketType(this.safeString(e,"marketType"));"spot"===S?t="spot":"swap"===S&&(t="swap",i=!0,s=!1,a=this.safeString(e,"quoteSymbol"),u+=":"+(r=this.safeCurrencyCode(a)),o=1);let O=this.safeString(e,"orderBookState");return this.safeMarketStructure({id:n,symbol:u,base:c,quote:l,settle:r,baseId:d,quoteId:h,settleId:a,type:t,spot:"spot"===t,margin:"spot"===t,swap:"swap"===t,future:!1,option:!1,active:"Open"===O,contract:"spot"!==t,linear:i,inverse:s,taker:void 0,maker:void 0,contractSize:o,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:k,price:v},limits:{leverage:{min:void 0,max:void 0},amount:{min:w,max:b},price:{min:g,max:m},cost:{min:void 0,max:void 0}},created:this.parse8601(this.safeString(e,"createdAt")),info:e})}parseMarketType(e){return this.safeString({SPOT:"spot",PERP:"swap"},e,e)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetApiV1Tickers(this.extend({},t)),s=this.parseTickers(i);return this.filterByArrayTickers(s,"symbol",e)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetApiV1Ticker(this.extend(s,t));return this.parseTicker(r,i)}parseTicker(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=this.safeSymbol(s,r),n=this.safeString(e,"firstPrice"),d=this.safeString(e,"lastPrice"),h=this.safeString(e,"high"),c=this.safeString(e,"low"),l=this.safeString(e,"volume"),u=this.safeString(e,"quoteVolume");void 0!==this.safeFloat(e,"priceChangePercent")&&(i=o.Y.stringMul(this.safeString(e,"priceChangePercent"),"100"));let f=this.safeString(e,"priceChange");return this.safeTicker({symbol:a,timestamp:void 0,datetime:void 0,high:h,low:c,bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:n,close:d,last:d,previousClose:void 0,change:f,percentage:i,average:void 0,baseVolume:l,quoteVolume:u,markPrice:void 0,indexPrice:void 0,info:e},r)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={symbol:this.market(e).id},r=await this.publicGetApiV1Depth(this.extend(s,i)),o=this.safeInteger(r,"timestamp");if(void 0===o)throw new a.ExchangeError(this.id+" fetchOrderBook() missing microseconds");let n=this.parseToInt(o/1e3),d=this.parseOrderBook(r,e,n);return d.nonce=this.safeInteger(r,"lastUpdateId"),d}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=this.safeString(this.timeframes,t,t),n={symbol:a.id,interval:o},[d,h]=this.handleOptionIntegerAndParams(r,"fetchOHLCV","until");void 0!==d&&(n.endTime=this.parseToInt(d/1e3));let c=s;if(void 0===i&&void 0===s&&(c=100),void 0===i){let e=this.parseTimeframe(t);n.startTime=(null!=d&&0!==d?this.parseToInt(d/1e3):this.seconds())-(void 0===s?100:s)*e}else n.startTime=this.parseToInt(i/1e3);let l=this.safeString(h,"price"),u=void 0!==l?this.omit(h,"price"):h;void 0!==l&&(n.priceType=this.capitalize(l));let f=await this.publicGetApiV1Klines(this.extend(n,u)),p=this.toArray(f);return this.parseOHLCVs(p,a,t,i,c)}parseOHLCV(e,t){return[this.parse8601(this.safeString(e,"start")),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0===i.spot)throw new a.BadRequest(this.id+" fetchFundingRate() symbol does not support market "+e);let s={symbol:i.id},r=await this.publicGetApiV1MarkPrices(this.extend(s,t)),o=this.safeDict(r,0,{});return this.parseFundingRate(o,i)}parseFundingRate(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeSymbol(i,s),a=this.safeInteger(e,"nextFundingTimestamp");return{info:e,symbol:r,markPrice:this.safeNumber(e,"markPrice"),indexPrice:this.safeNumber(e,"indexPrice"),interestRate:void 0,estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:this.safeNumber(e,"fundingRate"),fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:void 0,nextFundingTimestamp:a,nextFundingDatetime:this.iso8601(a),previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:"1h"}}async fetchOpenInterest(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0===i.spot)throw new a.BadRequest(this.id+" fetchOpenInterest() symbol does not support market "+e);let s={symbol:i.id},r=await this.publicGetApiV1OpenInterest(this.extend(s,t)),o=this.safeDict(r,0,{});return this.parseOpenInterest(o,i)}parseOpenInterest(e,t){let i=this.safeInteger(e,"timestamp"),s=this.safeNumber(e,"openInterest");return this.safeOpenInterest({symbol:this.safeString(t,"symbol"),openInterestAmount:void 0,openInterestValue:s,timestamp:i,datetime:this.iso8601(i),info:e},t)}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={symbol:r.id};void 0!==i&&(o.limit=Math.min(i,1e3));let n=await this.publicGetApiV1FundingRates(this.extend(o,s)),d=[],h=this.toArray(n);for(let e=0;e<h.length;e++){let t=h[e],i=this.safeString(t,"intervalEndTimestamp"),s=this.parse8601(i);d.push({info:t,symbol:r.symbol,fundingRate:this.safeNumber(t,"fundingRate"),timestamp:s,datetime:i})}let c=this.sortBy(d,"timestamp");return this.filterBySymbolSinceLimit(c,this.safeString(r,"symbol"),t,i)}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={symbol:a.id};void 0!==i&&(o.limit=Math.min(i,1e3)),r=void 0!==this.safeInteger(s,"offset")?await this.publicGetApiV1TradesHistory(this.extend(o,s)):await this.publicGetApiV1Trades(this.extend(o,s));let n=this.toArray(r);return this.parseTrades(n,a,t,i)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id),void 0!==t&&(a.from=t),void 0!==i&&(a.limit=i);let o=this.safeInteger(s,"until"),n=void 0!==o?this.omit(s,["until"]):s;void 0!==o&&(a.to=o),void 0===this.safeString(n,"fillType")&&(a.fillType="User");let d=await this.privateGetWapiV1HistoryFills(this.extend(a,n)),h=this.toArray(d);return this.parseTrades(h,r,t,i)}parseTrade(e,t){let i,s,r=this.safeString2(e,"id","tradeId"),a=this.safeString(e,"symbol"),o=this.safeMarket(a,t),n=this.safeString(e,"price"),d=this.safeString(e,"quantity"),h=this.safeBool(e,"isBuyerMaker"),c=this.parseOrderSide(this.safeString(e,"side")),l=this.safeBool(e,"isMaker");void 0!==l?i=l?"maker":"taker":void 0!==h&&(i="taker",c=h?"sell":"buy");let u=this.safeString(e,"orderId"),f=this.safeString(e,"fee"),p=this.safeInteger(e,"timestamp");if(void 0!==f){let t=this.safeString(e,"timestamp");p=this.parse8601(t)}let m=this.safeCurrencyCode(this.safeString(e,"feeSymbol"));return void 0!==f&&(s={cost:f,currency:m,rate:void 0}),this.safeTrade({info:e,timestamp:p,datetime:this.iso8601(p),symbol:o.symbol,id:r,order:u,type:void 0,side:c,takerOrMaker:i,price:n,amount:d,cost:void 0,fee:s},o)}async fetchStatus(e={}){let t=await this.publicGetApiV1Status(e),i=this.safeString(t,"status");if(void 0===i)throw new a.ExchangeError(this.id+" fetchStatus() missing status");return{status:i.toLowerCase(),updated:void 0,eta:void 0,url:void 0,info:t}}async fetchTime(e={}){let t=await this.publicGetApiV1Time(e);return this.safeInteger(t,0,this.milliseconds())}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetApiV1Capital(e);return this.parseBalance(t)}parseBalance(e){let t=Object.keys(e),i={};for(let s=0;s<t.length;s++){let r=t[s],a=this.safeCurrencyCode(r),n=this.safeDict(e,r),d=this.account(),h=this.safeString(n,"locked"),c=this.safeString(n,"staked"),l=o.Y.stringAdd(h,c);d.free=this.safeString(n,"available"),d.used=l,void 0!==a&&(i[a]=d)}return this.safeBalance(i)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(r=this.currency(e)),void 0!==t&&(a.from=t),void 0!==i&&(a.limit=i);let[o,n]=this.handleOptionIntegerAndParams(s,"fetchDeposits","until");void 0!==o&&(a.endTime=o);let d=await this.privateGetWapiV1CapitalDeposits(this.extend(a,n));return this.parseTransactions(d,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(r=this.currency(e)),void 0!==t&&(a.from=t),void 0!==i&&(a.limit=i);let[o,n]=this.handleOptionIntegerAndParams(s,"fetchWithdrawals","until");void 0!==o&&(a.to=o);let d=await this.privateGetWapiV1CapitalWithdrawals(this.extend(a,n));return this.parseTransactions(d,r,t,i)}async withdraw(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let o=this.currency(e),n={symbol:o.id,quantity:this.numberToString(t),address:i};void 0!==s&&(n.clientId=s);let[d,h]=this.handleNetworkCodeAndParams(r),c=this.networkCodeToId(d,this.safeString(o,"code"));if(void 0===c)throw new a.BadRequest(this.id+" withdraw() requires a network parameter");n.blockchain=c;let l=await this.privatePostWapiV1CapitalWithdrawals(this.extend(n,h));return this.parseTransaction(l,o)}parseTransaction(e,t){let i,s=this.parseTransactionStatus(this.safeString(e,"status")),r=this.safeString(e,"id"),a=this.safeString(e,"transactionHash"),o=this.safeString(e,"symbol"),n=this.safeCurrencyCode(o,t),d=this.parse8601(this.safeString(e,"createdAt")),h=this.safeNumber(e,"quantity"),c=this.safeStringLower2(e,"source","blockchain"),l=this.networkIdToCode(c,n),u=this.safeString(e,"toAddress"),f=this.safeString(e,"fromAddress"),p=this.safeString(e,"platformMemo"),m=this.safeNumber(e,"fee"),g=this.safeBool(e,"isInternal",!1);return void 0!==m&&(i={cost:m,currency:n}),{info:e,id:r,txid:a,timestamp:d,datetime:this.iso8601(d),network:l,address:void 0,addressTo:u,addressFrom:f,tag:p,tagTo:void 0,tagFrom:void 0,type:void 0,amount:h,currency:n,status:s,updated:void 0,internal:g,comment:void 0,fee:i}}parseTransactionStatus(e){return this.safeString({cancelled:"cancelled",confirmed:"ok",declined:"declined",expired:"expired",initiated:"initiated",pending:"pending",refunded:"refunded","information required":"pending"},e,e)}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleNetworkCodeAndParams(t);if(void 0===i)throw new a.ArgumentsRequired(this.id+" fetchDepositAddress() requires a network parameter, see https://docs.ccxt.com/?id=network-codes");let r=this.currency(e),o={blockchain:this.networkCodeToId(i,this.safeString(r,"code"))},n=await this.privateGetWapiV1CapitalDepositAddress(this.extend(o,s));return this.parseDepositAddress(n,r)}parseDepositAddress(e,t){let i=this.safeString(e,"address"),s=this.safeString(e,"currency");return{info:e,currency:this.safeCurrency(s,t).code,network:void 0,address:i,tag:void 0}}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=this.createOrderRequest(e,t,i,s,r,a),d=await this.privatePostApiV1Order(n);return this.parseOrder(d,o)}async createOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=[];for(let s=0;s<e.length;s++){let r=this.safeDict(e,s),a=this.safeString(r,"symbol"),o=this.safeString(r,"type"),n=this.safeString(r,"side"),d=this.safeNumber(r,"amount"),h=this.safeNumber(r,"price"),c=this.safeDict(r,"params",{}),l=this.extend(c,t),u=this.createOrderRequest(a,o,n,d,h,l);i.push(u)}let s=await this.privatePostApiV1Orders(i);return this.parseOrders(s)}createOrderRequest(e,t,i,s,r,o={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let n={symbol:this.market(e).id,side:this.encodeOrderSide(i),orderType:this.capitalize(t)},d=this.safeString(o,"triggerPrice"),h=void 0!==d,c="quantity";h&&(c="triggerQuantity");let l=[];if("limit"===t)n.price=this.priceToPrecision(e,r),n[c]=this.amountToPrecision(e,s);else if("market"===t){let t=this.safeString2(o,"cost","quoteQuantity");void 0!==t?(n.quoteQuantity=this.costToPrecision(e,t),l.push("cost"),l.push("quoteQuantity")):n[c]=this.amountToPrecision(e,s)}h&&(n.triggerPrice=this.priceToPrecision(e,d),l.push("triggerPrice"));let u=this.safeInteger(o,"clientOrderId");void 0!==u&&(n.clientId=u,l.push("clientOrderId"));let[f,p]=this.handlePostOnly("market"===t,!1,this.omit(o,l));f&&(p.postOnly=!0);let m=[],g=this.safeDict(p,"takeProfit");if(void 0!==g){let t=this.safeString(g,"triggerPrice");void 0!==t&&(n.takeProfitTriggerPrice=this.priceToPrecision(e,t));let i=this.safeString(g,"price");void 0!==i&&(n.takeProfitLimitPrice=this.priceToPrecision(e,i)),m.push("takeProfit")}let v=this.safeDict(p,"stopLoss");if(void 0!==v){let t=this.safeString(v,"triggerPrice");void 0!==t&&(n.stopLossTriggerPrice=this.priceToPrecision(e,t));let i=this.safeString(v,"price");void 0!==i&&(n.stopLossLimitPrice=this.priceToPrecision(e,i)),m.push("stopLoss")}let[y,b]=this.handleOptionStringAndParams(this.omit(p,m),"createOrder","selfTradePrevention");return void 0!==y&&("EXPIRE_MAKER"===y?n.selfTradePrevention="RejectMaker":"EXPIRE_TAKER"===y?n.selfTradePrevention="RejectTaker":"EXPIRE_BOTH"===y&&(n.selfTradePrevention="RejectBoth")),this.extend(n,b)}encodeOrderSide(e){return this.safeString({buy:"Bid",sell:"Ask"},e,e)}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id);let o=await this.privateGetApiV1Orders(this.extend(a,s));return this.parseOrders(o,r,t,i)}async fetchOpenOrder(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOpenOrder() requires a symbol argument");let s={symbol:this.market(t).id,orderId:e},r=await this.privateGetApiV1Order(this.extend(s,i));return this.parseOrder(r)}async cancelOrder(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");let s={orderId:e,symbol:this.market(t).id},r=await this.privateDeleteApiV1Order(this.extend(s,i));return this.parseOrder(r)}async cancelAllOrders(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");let i=this.market(e),s={symbol:i.id},r=await this.privateDeleteApiV1Orders(this.extend(s,t));return this.parseOrders(r,i)}async fetchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id),void 0!==i&&(a.limit=i);let o=await this.privateGetWapiV1HistoryOrders(this.extend(a,s));return this.parseOrders(o,r,t,i)}parseOrder(e,t){let i=this.safeInteger(e,"createdAt"),s=this.parse8601(this.safeString(e,"createdAt"));void 0!==s&&(i=s);let r=this.safeString(e,"id"),a=this.safeString(e,"clientId"),o=this.safeSymbol(this.safeString(e,"symbol"),t),n=this.safeStringLower(e,"orderType"),d=this.safeString(e,"timeInForce"),h=this.parseOrderSide(this.safeString(e,"side")),c=this.safeString2(e,"quantity","triggerQuantity"),l=this.safeString(e,"price"),u=this.safeString(e,"executedQuoteQuantity"),f=this.parseOrderStatus(this.safeString(e,"status")),p=this.safeString(e,"triggerPrice"),m=this.safeString(e,"executedQuantity"),g=this.safeBool(e,"reduceOnly"),v=this.safeBool(e,"postOnly"),y=this.safeString2(e,"stopLossLimitPrice","stopLossTriggerPrice"),b=this.safeString2(e,"takeProfitLimitPrice","takeProfitTriggerPrice");return this.safeOrder({info:e,id:r,clientOrderId:a,timestamp:i,datetime:this.iso8601(i),lastTradeTimestamp:void 0,symbol:o,type:n,timeInForce:d,postOnly:v,reduceOnly:g,side:h,price:l,triggerPrice:p,stopLossPrice:y,takeProfitPrice:b,amount:c,cost:u,average:void 0,filled:m,remaining:void 0,status:f,fee:void 0,trades:void 0},t)}parseOrderStatus(e){return this.safeString({New:"open",Filled:"closed",Cancelled:"canceled",Expired:"canceled",PartiallyFilled:"open",TriggerPending:"open",TriggerFailed:"rejected"},e,e)}parseOrderSide(e){return this.safeString({Bid:"buy",Ask:"sell"},e,e)}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privateGetApiV1Position(t),s=this.parsePositions(i);if(this.isEmpty(e))return s;let r=this.marketSymbols(e);return this.filterByArrayPositions(s,"symbol",r)}parsePosition(e,t){let i=this.safeString(e,"positionId"),s=this.safeString(e,"symbol"),r=this.safeMarket(s,t).symbol,a=this.safeString(e,"entryPrice"),n=this.safeString(e,"markPrice"),d=this.safeString(e,"netCost"),h=!1,c="long";o.Y.stringLt(d,"0")&&(c="short"),void 0===d&&(h=void 0,c=void 0);let l=this.safeString(e,"pnlUnrealized"),u=this.safeString(e,"pnlRealized"),f=this.safeString(e,"estLiquidationPrice");return this.safePosition({info:e,id:i,symbol:r,timestamp:this.parse8601(this.safeString(e,"timestamp")),datetime:this.iso8601(this.parse8601(this.safeString(e,"timestamp"))),lastUpdateTimestamp:void 0,hedged:h,side:c,contracts:this.safeString(e,"netExposureQuantity"),contractSize:void 0,entryPrice:a,markPrice:n,lastPrice:void 0,notional:o.Y.stringAbs(d),leverage:void 0,collateral:void 0,initialMargin:void 0,initialMarginPercentage:this.safeString(e,"imf"),maintenanceMargin:void 0,maintenanceMarginPercentage:this.safeString(e,"mmf"),realizedPnl:u,unrealizedPnl:l,liquidationPrice:f,marginMode:void 0,marginRatio:void 0,percentage:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}async fetchFundingHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id),void 0!==i&&(a.limit=i);let o=await this.privateGetWapiV1HistoryFunding(this.extend(a,s));return this.parseIncomes(o,r,t,i)}parseIncome(e,t){let i=this.safeString(e,"symbol"),s=this.safeSymbol(i,t),r=this.safeNumber(e,"quantity"),a=this.safeString(e,"userId"),o=this.parse8601(this.safeString(e,"intervalEndTimestamp")),n=this.safeNumber(e,"fundingRate");return{info:e,symbol:s,code:void 0,timestamp:o,datetime:this.iso8601(o),id:a,amount:r,rate:n}}nonce(){let e=this.safeInteger(this.options,"timeDifference");if(void 0===e)throw new a.ExchangeError(this.id+' nonce() requires a numeric options["timeDifference"]');return this.milliseconds()-e}sign(e,t="public",i="GET",r={},o,d){let h,c,l="/"+e,u=this.safeString(this.urls.api,t);if(void 0===u)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let f=u,p=Array.isArray(r)?r:this.keysort(r);if("private"===t){this.checkRequiredCredentials();let t=this.nonce().toString(),r=this.safeString2(this.options,"recvWindow","X-Window","5000"),a=this.safeDict(this.options,"instructions",{}),o=this.safeDict(a,e,{}),d=this.safeString(o,i,""),l="";if("api/v1/orders"===e&&"POST"===i)l=this.generateBatchPayload(p,t,r,d);else{let e=this.urlencode(p);e.length>0&&(e+="&"),l="instruction="+d+"&"+e+"timestamp="+t+"&window="+r}let u=this.base64ToBinary(this.secret),f=this.arraySlice(u,0,32),m=(0,n.q4)(this.encode(l),f,s.ev);h={"X-Timestamp":t,"X-Window":r,"X-API-Key":this.apiKey,"X-Signature":m,"X-Broker-Id":"1400"},"GET"!==i&&(c=this.json(p),h["Content-Type"]="application/json")}if("GET"===i){let e=this.urlencode(p);0!==e.length&&(l+="?"+e)}f+=l;let m="private"===t?h:o,g=d;return"private"===t&&"GET"!==i&&(g=c),{url:f,method:i,body:g,headers:m}}generateBatchPayload(e,t,i,s){let r="";for(let a=0;a<e.length;a++){let o=this.safeDict(e,a,{}),n=this.keysort(o);r+="instruction="+s+"&"+this.urlencode(n)+"&",a===e.length-1&&(r+="timestamp="+t+"&window="+i)}return r}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"code"),l=this.safeString(n,"message");if(void 0!==c){let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,c,e),this.throwExactlyMatchedException(this.exceptions.exact,l,e),this.throwBroadlyMatchedException(this.exceptions.broad,l,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>d})},6039(e,t,i){"use strict";let s,r,a,o,n,d,h,c;var l=i(6885),u=i(6834),f=i(789),p=i(4721),m=i(8858),g=i(1805),v=i(420),y=i(1453),b=i(7749),w=i(8794),k=i(5560),S=i(1718),O=i(6637),T=i(9759),P=i(7661),I=i(300),A=i(1291),x=i.n(A);function M(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}let{isNode:_,isBun:C,selfIsDefined:B,deepExtend:E,extend:R,clone:L,unique:N,indexBy:D,sortBy:q,sortBy2:F,safeFloat2:V,groupBy:G,aggregate:H,uuid:U,unCamelCase:W,precisionFromString:j,Throttler:K,capitalize:z,now:Y,decimalToPrecision:X,safeValue:Q,safeValue2:Z,safeString:J,safeString2:$,seconds:ee,milliseconds:et,binaryToBase16:ei,numberToBE:es,base16ToBinary:er,iso8601:ea,omit:eo,isJsonEncodedObject:en,safeInteger:ed,sum:eh,omitZero:ec,implodeParams:el,extractParams:eu,json:ef,binaryConcat:ep,hash:em,arrayConcat:eg,encode:ev,urlencode:ey,hmac:eb,numberToString:ew,roundTimeframe:ek,parseTimeframe:eS,safeInteger2:eO,safeStringLower:eT,parse8601:eP,yyyymmdd:eI,safeStringUpper:eA,safeTimestamp:ex,binaryConcatArray:eM,ymdhms:e_,stringToBase64:eC,decode:eB,uuid22:eE,safeIntegerProduct2:eR,safeIntegerProduct:eL,safeStringLower2:eN,yymmdd:eD,base58ToBinary:eq,binaryToBase58:eF,safeTimestamp2:eV,rawencode:eG,keysort:eH,sort:eU,inArray:eW,isEmpty:ej,filterBy:eK,uuid16:ez,safeFloat:eY,base64ToBinary:eX,safeStringUpper2:eQ,urlencodeWithArrayRepeat:eZ,microseconds:eJ,binaryToBase64:e$,strip:e0,toArray:e1,safeFloatN:e2,safeIntegerN:e3,safeIntegerProductN:e5,safeTimestampN:e4,safeValueN:e6,safeStringN:e8,safeStringLowerN:e7,safeStringUpperN:e9,urlencodeNested:te,urlencodeBase64:tt,parseDate:ti,ymd:ts,base64ToString:tr,crc32:ta,packb:to,TRUNCATE:tn,ROUND:td,DECIMAL_PLACES:th,NO_PADDING:tc,TICK_SIZE:tl,SIGNIFICANT_DIGITS:tu,sleep:tf,readFile:tp,writeFile:tm,existsFile:tg,getTempDir:tv,filePathToFileUrlForWindows:ty}=g,tb=async e=>await import(e),tw=/":([+.0-9eE-]+)(?=[,}])/g;class tk{async loadExchangeSpecificFiles(){if("mexc"===this.id)try{s=await Promise.resolve().then(i.t.bind(i,2373,23))}catch(e){}}uuid5(e,t){let i=new Uint8Array([...e.replace(/-/g,"").match(/.{1,2}/g).map(e=>parseInt(e,16)),...new TextEncoder().encode(t)]),s=(0,m.e8)(i);s[6]=15&s[6]|80,s[8]=63&s[8]|128;let r=[...s.slice(0,16)].map(e=>e.toString(16).padStart(2,"0")).join("");return[r.substring(0,8),r.substring(8,12),r.substring(12,16),r.substring(16,20),r.substring(20,32)].join("-")}encodeURIComponent(...e){return encodeURIComponent(...e)}getCcxtVersion(){let e=tS.ccxtVersion;return void 0===e?"unknown":e}throttle(e){return this.throttler.throttle(e)}initThrottler(){this.throttler=new K(this.tokenBucket)}defineRestApiEndpoint(e,t,i,s,r,a,o={}){let n=r.split(/[^a-zA-Z0-9]/),d=n.map(this.capitalize).join(""),h=n.map(e=>e.trim().toLowerCase()).filter(e=>e.length>0).join("_"),c=[a[0]].concat(a.slice(1).map(this.capitalize)).join(""),l=[a[0]].concat(a.slice(1).map(e=>e.trim()).filter(e=>e.length>0)).join("_"),u=c+s+this.capitalize(d),f=a.length>1?a:a[0],p=async(i={},s={})=>this[e](r,f,t,i,void 0,void 0,o,s);this[u]=p,this[l+"_"+i+"_"+h]=p}defineRestApi(e,t,i=[]){let s=Object.keys(e);for(let r=0;r<s.length;r++){let a=s[r],o=e[a],n=a.toUpperCase(),d=a.toLowerCase(),h=this.capitalize(d);if(Array.isArray(o))for(let e=0;e<o.length;e++){let s=o[e].trim();this.defineRestApiEndpoint(t,n,d,h,s,i)}else if(null!==a.match(/^(?:get|post|put|delete|head|patch)$/i)){let e=Object.keys(o);for(let s=0;s<e.length;s++){let r=e[s],a=r.trim(),c=o[r];if("object"==typeof c)this.defineRestApiEndpoint(t,n,d,h,a,i,c);else if("number"==typeof c)this.defineRestApiEndpoint(t,n,d,h,a,i,{cost:c});else throw new y.NotSupported(this.id+" defineRestApi() API format is not supported, API leafs must strings, objects or numbers")}}else this.defineRestApi(o,t,i.concat([a]))}}log(...e){console.log(...e)}async loadProxyModules(){return void 0===this.proxiesModulesLoading&&(this.proxiesModulesLoading=(async()=>{try{this.httpProxyAgentModule=await tb("http-proxy-agent"),this.httpsProxyAgentModule=await tb("https-proxy-agent")}catch(e){}if(!1===this.socksProxyAgentModuleChecked){try{this.socksProxyAgentModule=await tb("socks-proxy-agent")}catch(e){}this.socksProxyAgentModuleChecked=!0}})()),await this.proxiesModulesLoading}setProxyAgents(e,t,i){let s,r=null!=e&&""!==e,a=null!=t&&""!==t,o=null!=i&&""!==i;if(!_&&(r||a||o))throw new y.NotSupported(this.id+' - proxies in browser-side projects are not supported. You have several choices: [A] Use `exchange.proxyUrl` property to redirect requests through local/remote cors-proxy server (find sample file named "sample-local-proxy-server-with-cors" in https://github.com/ccxt/ccxt/tree/master/examples/ folder, which can be used for REST requests only) [B] override `exchange.fetch` && `exchange.watch` methods to send requests through your custom proxy');if(r){if(void 0===this.httpProxyAgentModule)throw new y.NotSupported(this.id+' - to use httpProxy with ccxt, at first you need install module "npm i http-proxy-agent" and then initialize proxies with `await instance.loadProxyModules()` method');let t=this.proxyDictionaries[e];(void 0===t||"function"==typeof t.dispatch)&&this.cacheProxyDictionary(e,new this.httpProxyAgentModule.HttpProxyAgent(e)),s=this.proxyDictionaries[e]}else if(a){if(void 0===this.httpsProxyAgentModule)throw new y.NotSupported(this.id+' - to use httpsProxy with ccxt, at first you need install module "npm i https-proxy-agent" and then initialize proxies with `await instance.loadProxyModules()` method');let e=this.proxyDictionaries[t];if((void 0===e||"function"==typeof e.dispatch)&&this.cacheProxyDictionary(t,new this.httpsProxyAgentModule.HttpsProxyAgent(t)),void 0===(s=this.proxyDictionaries[t]))throw new y.ExchangeError(this.id+" setProxyAgents() missing chosenAgent");s.keepAlive=!0}else if(o){if(void 0===this.socksProxyAgentModule)throw new y.NotSupported(this.id+' - to use SOCKS proxy with ccxt, at first you need install module "npm i socks-proxy-agent" and then initialize proxies with `await instance.loadProxyModules()` method');let e=this.proxyDictionaries[i];(void 0===e||"function"==typeof e.dispatch)&&this.cacheProxyDictionary(i,new this.socksProxyAgentModule.SocksProxyAgent(i)),s=this.proxyDictionaries[i]}return s}async loadHttpProxyAgent(){if(void 0===this.httpAgent){let e=await import("node:http");this.httpAgent=new e.Agent}return this.httpAgent}getHttpAgentIfNeeded(e){if(_&&"ws://"===e.substring(0,5)){if(void 0===this.httpAgent)throw new y.NotSupported(this.id+" to use proxy with non-ssl ws:// urls, at first run  `await exchange.loadHttpProxyAgent()` method");return this.httpAgent}}addFetchCache(e){this.fetchHistoryCacheSize<=0||(this.fetchHistoryCache.length>=this.fetchHistoryCacheSize&&this.fetchHistoryCache.shift(),this.fetchHistoryCache.push(e))}getFetchCache(){return this.fetchHistoryCache}isBinaryMessage(e){return e instanceof Uint8Array||e instanceof ArrayBuffer}stringToBinary(e){return this.encode(e)}binaryToString(e){return this.decode(e)}decodeProtoMsg(e){if(void 0===s)throw new y.NotSupported(this.id+" requires protobuf to decode messages, please install it with `npm install protobufjs`");let t=e;return(e instanceof ArrayBuffer&&(t=new Uint8Array(e)),t instanceof Uint8Array)?s.default.PushDataV3ApiWrapper.decode(t).toJSON():t}async loadFetchImplementation(){return void 0===this.fetchImplementationLoading&&(this.fetchImplementationLoading=(async()=>{if(void 0!==this.fetchImplementation){void 0===this.AbortError&&(this.AbortError=DOMException),void 0===this.FetchError&&(this.FetchError=TypeError);return}if(this.AbortError=DOMException,this.FetchError=TypeError,!_||C){if(B())this.fetchImplementation=self.fetch;else if("function"==typeof fetch)this.fetchImplementation=fetch;else throw new y.NotSupported(this.id+' the built-in "fetch" function is not available in this environment, please use a modern browser, bun, or node.js 18+');this.fetchIsNative=!0;return}try{let e=await import("undici");this.undiciModule=e,this.fetchImplementation=e.fetch,this.fetchDispatcher=new e.Agent(this.getDispatcherOptions(!0)),this.zlibModule=await import("node:zlib");let t=await import("node:http");this.httpStatusTexts=t.STATUS_CODES,this.fetchIsNative=!0;return}catch(e){}if("function"==typeof fetch)this.fetchImplementation=fetch,this.fetchIsNative=!0;else throw new y.NotSupported(this.id+' the built-in "fetch" function is not available in this environment, please use node.js 18+, bun, or a modern browser')})()),await this.fetchImplementationLoading}getDispatcherOptions(e=!1){let t={keepAliveTimeout:6e4,keepAliveMaxTimeout:6e5,connections:256,pipelining:1,allowH2:!1,autoSelectFamily:!0};if(!this.shouldValidateServerSsl()){let i={rejectUnauthorized:!1};e?t.connect=i:t.requestTls=i}return t}shouldValidateServerSsl(){if(!this.validateServerSsl)return!1;let e=[this.agent,this.httpsAgent];for(let t=0;t<e.length;t++){let i=e[t],s=null!=i?i.options:void 0;if(null!=s&&!1===s.rejectUnauthorized)return!1}return!0}extractProxyFromAgent(e){if(null!=e){let t=e.proxy;if(null!=t){if("string"==typeof t)return t;if(void 0!==t.href)return t.href}}}cacheProxyDictionary(e,t){let i=this.proxyDictionaries[e];if(void 0!==i)this.releaseProxyDictionaryEntry(i);else{let e=Object.keys(this.proxyDictionaries);if(e.length>=this.proxyDictionariesMaxSize){let t=e[0],i=this.proxyDictionaries[t];delete this.proxyDictionaries[t],this.releaseProxyDictionaryEntry(i)}}return this.proxyDictionaries[e]=t,t}releaseProxyDictionaryEntry(e){null!=e&&"function"==typeof e.dispatch&&"function"==typeof e.close&&e.close().catch(()=>{})}getFetchProxyDispatcher(e){let t=this.proxyDictionaries[e];if(void 0!==t&&"function"==typeof t.dispatch)return t;let i=e.toLowerCase();if(0===i.indexOf("socks4:")||0===i.indexOf("socks4a:"))throw new y.NotSupported(this.id+" - socks4 proxies are not supported by the built-in fetch, please use a socks5:// proxy");let s=this.getDispatcherOptions(!1);return s.uri=e,this.cacheProxyDictionary(e,new this.undiciModule.ProxyAgent(s))}async undiciRequest(e,t){let i=t.headers;"Accept-Encoding"in i||"accept-encoding"in i||(i["Accept-Encoding"]="gzip, deflate, br");let s=await this.undiciModule.request(e,{method:t.method,headers:i,body:t.body,signal:t.signal,dispatcher:t.dispatcher}),r=s.statusCode,a=s.headers.location;if(r>=300&&r<400&&void 0!==a){try{await s.body.dump()}catch(e){}throw new y.NetworkError(this.id+" "+t.method+" "+e+" redirect to "+a+" was not followed (HTTP "+r+", following redirects is disabled)")}let o=this.httpStatusTexts[s.statusCode];return{status:s.statusCode,statusText:null!=o?o:"",headers:s.headers,text:()=>this.undiciBody(s,!1),arrayBuffer:()=>this.undiciBody(s,!0)}}async undiciBody(e,t=!1){let i,s=e.headers["content-encoding"];if((204===e.statusCode||304===e.statusCode)&&(s=void 0),"gzip"===s||"x-gzip"===s?i=this.zlibModule.createGunzip():"br"===s?i=this.zlibModule.createBrotliDecompress():"deflate"===s&&(i=this.zlibModule.createInflate()),void 0===i)return t?await e.body.arrayBuffer():await e.body.text();let r=[];for await(let t of(e.body.pipe(i),i))r.push(t);let a=Buffer.concat(r);return t?a:a.toString("utf8")}setFetchProxyOptions(e,t,i,s){let r;if(null!=t&&""!==t?r=t:null!=i&&""!==i?r=i:null!=s&&""!==s&&(r=s),null==r||""===r){let e=this.extractProxyFromAgent(this.agent),t=this.extractProxyFromAgent(this.httpsAgent),i=this.extractProxyFromAgent(this.httpAgent);r=void 0!==e&&""!==e?e:void 0!==t&&""!==t?t:i}if(null==r||""===r){void 0!==this.fetchDispatcher&&(e.dispatcher=this.fetchDispatcher);return}if(!_)throw new y.NotSupported(this.id+' - proxies in browser-side projects are not supported. You have several choices: [A] Use `exchange.proxyUrl` property to redirect requests through local/remote cors-proxy server (find sample file named "sample-local-proxy-server-with-cors" in https://github.com/ccxt/ccxt/tree/master/examples/ folder, which can be used for REST requests only) [B] override `exchange.fetch` && `exchange.watch` methods to send requests through your custom proxy');if(C){e.proxy=r;return}if(void 0===this.undiciModule)throw new y.NotSupported(this.id+' - proxy support with the built-in fetch requires the undici module, please install it with "npm i undici"');e.dispatcher=this.getFetchProxyDispatcher(r)}async fetch(e,t="GET",i,s){let r,a,o,n=this.extend(this.headers,i),d=this.checkProxyUrlSettings(e,t,n,s);void 0!==d&&_&&(n=this.extend({Origin:this.origin},n));let h=e;void 0!==d&&(h=d+this.urlEncoderForProxyUrl(e));let[c,l,u]=this.checkProxySettings(h,t,n,s);r=void 0!==c&&""!==c?c:void 0!==l&&""!==l?l:u,this.checkConflictingProxies(r,d),_&&await this.loadProxyModules();let f=void 0!==this.userAgent?this.userAgent:this.user_agent;void 0===f&&_&&(f=this.userAgents.chrome),null!=f&&""!==f&&_&&("string"==typeof f?n=this.extend({"User-Agent":f},n):this.isDictionary(f)&&"User-Agent"in f&&(n=this.extend(f,n)));let p=Object.keys(n=this.setHeaders(n));for(let e=0;e<p.length;e++){let t=p[e];if("content-type"===t.toLowerCase()){let e=n[t];if("multipart/form-data"===e){let i=Object.keys(s),r="--------------------------"+this.randomBytes(12),o="";for(let e=0;e<i.length;e++){let t=i[e];o+="--"+r+'\r\nContent-Disposition: form-data; name="'+t+'"\r\n\r\n'+s[t]+"\r\n"}o+="--"+r+"--\r\n",e+="; boundary="+r,n[t]=e,a=o;break}}}let m=void 0!==a?a:s;this.verbose&&this.log("fetch Request:\n",this.id,t,h,"\nRequestHeaders:\n",n,"\nRequestBody:\n",m,"\n"),(void 0===this.fetchImplementationLoading||void 0===this.fetchImplementation)&&await this.loadFetchImplementation();let g=this.fetchImplementation,v={method:t,headers:n,body:m};if(this.fetchIsNative)v.redirect="error",this.setFetchProxyOptions(v,c,l,u);else{v.timeout=this.timeout;let e=this.setProxyAgents(c,l,u);null==e&&(e=this.agent),null==e&&(e=this.httpsAgent),null!=e&&(v.agent=e)}let b=new AbortController;v.signal=b.signal;let w=setTimeout(()=>{b.abort()},this.timeout);try{o=this.fetchIsNative&&void 0!==this.undiciModule?await this.undiciRequest(h,v):await g(h,v)}catch(i){if(i instanceof this.AbortError||void 0!==i&&("AbortError"===i.name||"TimeoutError"===i.name))throw new y.RequestTimeout(this.id+" "+t+" "+h+" request timed out ("+this.timeout+" ms)");let e=void 0!==i&&void 0!==i.cause&&null!==i.cause&&void 0!==i.cause.message?": "+i.cause.message:"";if(i instanceof this.FetchError||i instanceof TypeError)throw new y.NetworkError(this.id+" "+t+" "+h+" fetch failed"+e);if(void 0!==i&&"string"==typeof i.code&&-1!==["ConnectionRefused","ConnectionClosed","ConnectionReset","DNSError","FailedToOpenSocket","ECONNREFUSED","ECONNRESET","ENOTFOUND","ETIMEDOUT","EPIPE","EAI_AGAIN","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"].indexOf(i.code))throw new y.NetworkError(this.id+" "+t+" "+h+" fetch failed: "+i.message);throw i}finally{clearTimeout(w)}return await this.handleRestResponse(o,h,t,n,m)}jsonStringifyWithNull(e){return JSON.stringify(e,(e,t)=>void 0===t?null:t)}hasUnsafeInteger(e){if("number"==typeof e)return e>Number.MAX_SAFE_INTEGER||e<-Number.MAX_SAFE_INTEGER;if(null!==e&&"object"==typeof e){if(Array.isArray(e)){for(let t=0;t<e.length;t++)if(this.hasUnsafeInteger(e[t]))return!0}else for(let t in e)if(this.hasUnsafeInteger(e[t]))return!0}return!1}parseJson(e){try{if(this.isJsonEncodedObject(e)){if(!this.quoteJsonNumbers)return JSON.parse(e);let t=JSON.parse(e);if(this.hasUnsafeInteger(t))return JSON.parse(this.onJsonResponse(e));return t}}catch(e){return}}getResponseHeaders(e){let t={},i=e.headers;if("function"==typeof i.forEach)return i.forEach((e,i)=>{t[i.split("-").map(e=>this.capitalize(e)).join("-")]=e}),t;let s=Object.keys(i);for(let e=0;e<s.length;e++){let r=s[e],a=i[r];Array.isArray(a)&&(a=a.join(", ")),t[r.split("-").map(e=>this.capitalize(e)).join("-")]=a}return t}handleRestResponse(e,t,i="GET",s,r){let a=this.getResponseHeaders(e);if(this.handleContentTypeApplicationZip&&"application/zip"===a["Content-Type"]){let s=e.arrayBuffer().then(e=>"u">typeof Buffer?Buffer.from(e):new Uint8Array(e));return this.enableLastResponseHeaders&&(this.last_response_headers=a),this.enableLastHttpResponse&&(this.last_http_response=s),this.verbose&&this.log("handleRestResponse:\n",this.id,i,t,e.status,e.statusText,"\nResponseHeaders:\n",a,"ZIP redacted","\n"),s}return e.text().then(o=>{let n=this.onRestResponse(e.status,e.statusText,t,i,a,o,s,r),d=this.parseJson(n);this.enableLastResponseHeaders&&(this.last_response_headers=a),this.enableLastHttpResponse&&(this.last_http_response=o),this.enableLastJsonResponse&&(this.last_json_response=d),this.verbose&&this.log("handleRestResponse:\n",this.id,i,t,e.status,e.statusText,"\nResponseHeaders:\n",a,"\nResponseBody:\n",o,"\n"),void 0===this.handleErrors(e.status,e.statusText,t,i,a,o,d,s,r)&&this.handleHttpStatusCode(e.status,e.statusText,t,i,o);let h=null!=d&&!1!==d&&0!==d&&""!==d;return h&&!Array.isArray(d)&&this.returnResponseHeaders&&(d.responseHeaders=a),h?d:o})}onRestResponse(e,t,i,s,r,a,o,n){return a.trim()}onJsonResponse(e){return e.replace(tw,'":"$1"')}async loadMarketsHelper(e=!1,t={}){let i;if(!e&&void 0!==this.markets&&null!==this.markets)return void 0===this.markets_by_id||null===this.markets_by_id?this.setMarkets(this.markets):this.markets;!0===this.has.fetchCurrencies&&(i=await this.fetchCurrencies(),this.options.cachedCurrencies=i);let s=await this.fetchMarkets(t);return"cachedCurrencies"in this.options&&delete this.options.cachedCurrencies,this.setMarkets(s,i)}async loadMarkets(e=!1,t={}){return(e&&!0!==this.reloadingMarkets||void 0===this.marketsLoading)&&(this.reloadingMarkets=!0,this.marketsLoading=this.loadMarketsHelper(e,t).then(e=>(this.reloadingMarkets=!1,e),e=>{throw this.reloadingMarkets=!1,e})),this.marketsLoading}async fetchCurrencies(e={}){return new Promise((e,t)=>{e(this.currencies)})}async fetchCurrenciesWs(e={}){return new Promise((e,t)=>{e(this.currencies)})}async fetchMarkets(e={}){return new Promise((e,t)=>{let i=this.markets;e(void 0===i?[]:Object.values(i))})}async fetchMarketsWs(e={}){return new Promise((e,t)=>{let i=this.markets;e(void 0===i?[]:Object.values(i))})}checkRequiredDependencies(){}parseNumber(e,t){if(void 0===e)return t;try{let i=this.numberToString(e);if(void 0===i)return t;if(i.indexOf("e-")>-1)return this.number(ew(parseFloat(i)));let s=this.number(i);return Number.isNaN(s)?t:s}catch(e){return t}}checkOrderArguments(e,t,i,s,r,a){if(void 0===r&&"limit"===t)throw new y.ArgumentsRequired(this.id+" createOrder() requires a price argument for a limit order");if(s<=0)throw new y.ArgumentsRequired(this.id+" createOrder() amount should be above 0")}handleHttpStatusCode(e,t,i,s,r){let a=e.toString();if(a in this.httpExceptions)throw new this.httpExceptions[a](this.id+" "+s+" "+i+" "+a+" "+t+" "+r)}remove0xPrefix(e){return"0x"===e.slice(0,2)?e.slice(2):e}mapToSafeMap(e){return e}safeMapToMap(e){return e}spawn(e,...t){let i=(0,k.K)();return i.catch(()=>{}),setTimeout(()=>{e.apply(this,t).then(i.resolve).catch(i.reject)},0),i}delay(e,t,...i){setTimeout(()=>{this.spawn(t,...i)},e)}orderBook(e={},t=Number.MAX_SAFE_INTEGER){return new S.gX(e,t)}indexedOrderBook(e={},t=Number.MAX_SAFE_INTEGER){return new S.nS(e,t)}countedOrderBook(e={},t=Number.MAX_SAFE_INTEGER){return new S.if(e,t)}handleMessage(e,t){}ping(e){}client(e){if(void 0===e)throw new y.ArgumentsRequired(this.id+" client() requires a url argument");if(void 0===this.clients&&(this.clients={}),void 0===this.clients[e]){let t=this.handleMessage.bind(this),i=this.onError.bind(this),s=this.onClose.bind(this),r=this.onConnected.bind(this),a=this.safeValue(this.options,"ws",{}),[o,n,d]=this.checkWsProxySettings(),h=this.setProxyAgents(o,n,d),c=this.getHttpAgentIfNeeded(e),l=this.agent;null!=h?l=h:null!=c&&(l=c);let u=new K(this.tokenBucket),f=this.deepExtend(this.streaming,{log:void 0!==this.log?this.log.bind(this):this.log,ping:void 0!==this.ping?this.ping.bind(this):this.ping,throttle:u.throttle.bind(u),verbose:this.verbose,throttler:u,options:{agent:l},decompressBinary:this.safeBool(this.options,"decompressBinary",!0)},a);this.clients[e]=new w.A(e,t,i,s,r,f)}return this.clients[e]}calculateWsBackoffDelay(e){let t=this.safeDict(this.options,"ws",{}),i=this.safeDict(t,"backoff",{}),s=this.safeInteger(i,"base",1e3),r=this.safeInteger(i,"factor",2),a=this.safeInteger(i,"max",6e4),o=this.safeInteger(i,"stableAfter",3e4),n=this.safeDict(t,"backoffState");void 0===n&&(n={});let d=this.milliseconds(),h=this.safeDict(n,e,{}),c=this.safeInteger(h,"lastAttempt",0),l=this.safeInteger(h,"attempts",0);if(c>0&&d-c>o&&(l=0),h.attempts=l+1,h.lastAttempt=d,n[e]=h,t.backoffState=n,this.options.ws=t,0===l)return 0;let u=s,f=Math.min(l,20);for(let e=1;e<f;e++)u*=r;return Math.min(this.parseToInt(u*(.8+d%1e3/2500)),a)}watchMultiple(e,t,i,s,r){if(void 0===e)throw new y.ArgumentsRequired(this.id+" watchMultiple() requires a url argument");let a=e in this.clients,o=this.client(e),n=k.K.race(t.map(e=>o.future(e))),d=[];if(void 0!==s)for(let e=0;e<s.length;e++){let t=s[e];void 0===o.subscriptions[t]&&(d.push(t),o.subscriptions[t]=void 0===r||r)}let h=0;a||(h=this.calculateWsBackoffDelay(e));let c=o.connect(h);return(void 0===s||d.length>0)&&c.then(()=>{let e=this.safeValue(this.options,"ws"),t=this.safeValue(e,"cost",1);null!=i&&(this.enableRateLimit&&void 0!==o.throttle?o.throttle(t).then(()=>{o.send(i)}).catch(e=>{for(let e=0;e<d.length;e++){let t=d[e];delete o.subscriptions[t]}n.reject(e)}):o.send(i).catch(e=>{for(let e=0;e<d.length;e++){let t=d[e];delete o.subscriptions[t]}n.reject(e)}))}).catch(e=>{for(let e=0;e<d.length;e++){let t=d[e];delete o.subscriptions[t]}n.reject(e)}),n}watch(e,t,i,s,r){if(void 0===e)throw new y.ArgumentsRequired(this.id+" watch() requires a url argument");if(void 0===t)throw new y.ArgumentsRequired(this.id+" watch() requires a messageHash argument");let a=e in this.clients,o=this.client(e);if(void 0===s&&void 0!==t&&t in o.futures)return o.futures[t];let n=o.future(t),d=o.subscriptions[s];void 0===d&&(o.subscriptions[s]=void 0===r||r);let h=0;a||(h=this.calculateWsBackoffDelay(e));let c=o.connect(h);return void 0===d&&c.then(()=>{let e=this.safeValue(this.options,"ws"),t=this.safeValue(e,"cost",1);null!=i&&(this.enableRateLimit&&void 0!==o.throttle?o.throttle(t).then(()=>{o.send(i)}).catch(e=>{o.onError(e)}):o.send(i).catch(e=>{o.onError(e)}))}).catch(e=>{delete o.subscriptions[s],n.reject(e)}),n}onConnected(e,t){}onError(e,t){e.url in this.clients&&void 0!==this.clients[e.url].error&&delete this.clients[e.url]}onClose(e,t){void 0!==e.error||void 0!==this.clients[e.url]&&delete this.clients[e.url]}async close(e=!1){await this.sleep(0);let t=Object.values(void 0!==this.clients?this.clients:{}),i=[];for(let e=0;e<t.length;e++){let s=t[e];s.error=new y.ExchangeClosedByUser(this.id+" closedByUser"),i.push(s.close())}for(let e=0;e<t.length;e++){let s=t[e];delete this.clients[s.url],i.push(s.close())}await Promise.all(i),e&&this.cleanWsData(),e&&this.cleanRestData()}convertToBigInt(e){return BigInt(e)}stringToCharsArray(e){return e.split("")}valueIsDefined(e){return null!=e}arraySlice(e,t,i){return void 0===i?e.slice(t):e.slice(t,i)}getProperty(e,t,i){return t in e?e[t]:i}setProperty(e,t,i){e[t]=i}isDictionary(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}exceptionMessage(e,t=!0){let i="["+e.constructor.name+"] "+(t?e.stack:e.message),s=Math.min(1e5,i.length);return i.slice(0,s)}fixStringifiedJsonMembers(e){let t=e.replaceAll("\\","");return(t=t.replaceAll('"{',"{")).replaceAll('}"',"}")}ethAbiEncode(e,t){return this.base16ToBinary((0,T.vg)(e,t).slice(2))}ethEncodeStructuredData(e,t,i){return this.base16ToBinary(T.zl.encode(e,t,i).slice(-132))}ethGetAddressFromPrivateKey(e){let t=this.remove0xPrefix(e),i=l.bI.getPublicKey(this.base16ToBinary(t)),s=l.bI.Point.fromBytes(i).toBytes(!1).slice(1),r=(0,u.lY)(s).slice(-20);return"0x"+this.binaryToBase16(r)}retrieveStarkAccount(e,t,i){let s=(0,f.b)(e),r=(0,f.$u)(s),a=I.Yo({implementation:t,selector:I.BK("initialize"),calldata:I.Yo({signer:r,guardian:"0"})}),o=I.r4(r,i,a,0);return{privateKey:s,publicKey:r,address:o}}starknetEncodeStructuredData(e,t,i,s){let r=Object.keys(t);if(r.length>1)throw new y.NotSupported(this.id+" starknetEncodeStructuredData only support single type");let a={domain:e,primaryType:r[0],types:this.extend({StarkNetDomain:[{name:"name",type:"felt"},{name:"chainId",type:"felt"},{name:"version",type:"felt"}]},t),message:i};return I.E(a,s)}starknetSign(e,t){let i=(0,f._S)(e.replace("0x",""),t.replace("0x",""));return this.json([i.r.toString(),i.s.toString()])}extendedStarknetSign(e,t){let i=(0,f._S)(e.replace("0x",""),t.replace("0x",""));return this.json([i.r.toString(),i.s.toString()])}extendedStarknetGetSelectorFromName(e){return I.BK(e)}extendedStarknetComputePoseidonHashOnElements(e){return I.dl(e)}async getZKContractSignatureObj(e,t={}){let i=BigInt("0x"+this.remove0xPrefix(this.hash(this.encode(this.safeString(t,"slotId","")),p.sc,"hex"))).toString(),s=BigInt("0x"+this.remove0xPrefix(this.hash(this.encode(this.safeString(t,"nonce","")),p.sc,"hex"))).toString(),r="4294967295",a=b.Y.stringMod(this.safeString(t,"accountId","0"),r);void 0===a&&(a="0");let o=b.Y.stringDiv(b.Y.stringMod(i,"18446744073709551615"),r);void 0===o&&(o="0");let n=b.Y.stringMod(s,r);void 0===n&&(n="0");let d=parseInt(a,10),h=parseInt(o,10),c=parseInt(n,10);await (0,P.Ay)();let l=P.$s({});await l.initZklinkSigner(e);let u=this.safeInteger(t,"pairId",0),f=b.Y.stringMul(this.safeString(t,"size","0"),"1e18");void 0===f&&(f="0");let m=b.Y.stringMul(this.safeString(t,"price","0"),"1e18");void 0===m&&(m="0");let g=b.Y.stringMul(this.safeString(t,"makerFeeRate","0"),"10000");void 0===g&&(g="0");let v=b.Y.stringMul(this.safeString(t,"takerFeeRate","0"),"10000");void 0===v&&(v="0");let y=new P.KR(d,0,h,c,u,f,m,"BUY"===this.safeString(t,"direction"),parseInt(g),parseInt(v),!1),w=P.JF(y);w?.sign(l?.getZkLinkSigner());let k=w.jsValue();return k?.signature?.signature}async getZKTransferSignatureObj(e,t={}){await (0,P.Ay)();let i=P.$s({});await i.initZklinkSigner(e);let s=this.safeString(t,"nonce","0");if(this.safeBool(t,"isContract",!1)){let e=BigInt("0x"+this.remove0xPrefix(this.hash(this.encode(s),p.sc,"hex"))).toString();s=b.Y.stringMod(e,"4294967295")}let r=this.safeNumber(t,"zkAccountId",0),a=this.safeNumber(t,"subAccountId",0),o=this.safeNumber(t,"receiverSubAccountId",0),n=this.safeNumber(t,"tokenId",0),d=this.safeNumber(t,"timestampSeconds",0),h=new P.H3(void 0===r?0:r,this.safeString(t,"receiverAddress",""),void 0===a?0:a,void 0===o?0:o,void 0===n?0:n,this.safeString(t,"fee","0"),this.safeString(t,"amount","0"),this.parseToInt(s),void 0===d?0:d),c=P.qj(h);c?.sign(i?.getZkLinkSigner());let l=c.jsValue();return l?.signature?.signature}async loadDydxProtos(){let e=[Promise.resolve().then(i.bind(i,9475)),Promise.resolve().then(i.bind(i,5145)),Promise.resolve().then(i.bind(i,5422))],t=await Promise.all(e);r=t[0].encodeAsAny,a=t[1].AuthInfo,o=t[1].Tx,n=t[1].TxBody,d=t[1].TxRaw,h=t[1].SignDoc,c=t[2].SignMode}toDydxLong(e){return x().fromString(e)}retrieveDydxCredentials(e){let t=this.base16ToBinary(this.remove0xPrefix(e)),i=l.bI.getPublicKey(t,!0);return{privateKey:t,publicKey:i}}encodeDydxTxForSimulation(e,t,i,s){let d=r;if(void 0===d||void 0===o||void 0===n||void 0===a||void 0===c)throw new y.NotSupported(this.id+" requires protobuf to encode messages, please install it with `npm install protobufjs`");if(null==s)throw Error("Public key cannot be undefined");let h=[e].map(e=>d(e)),l=o.fromPartial({body:n.fromPartial({messages:h,memo:t}),authInfo:a.fromPartial({fee:{},signerInfos:[{publicKey:d({typeUrl:"/cosmos.crypto.secp256k1.PubKey",value:s}),sequence:i,modeInfo:{single:{mode:c.SIGN_MODE_UNSPECIFIED}}}]}),signatures:[new Uint8Array]});return this.binaryToBase64(o.encode(l).finish())}encodeDydxTxForSigning(e,t,i,s,o,d){let l=r;if(void 0===l||void 0===n||void 0===a||void 0===c||void 0===h)throw new y.NotSupported(this.id+" requires protobuf to encode messages, please install it with `npm install protobufjs`");if(void 0===s.pub_key||null===s.pub_key)throw Error("Public key cannot be undefined");let u=this.milliseconds(),f=[e].map(e=>l(e)),m=[l({typeUrl:"/dydxprotocol.accountplus.TxExtension",value:{selectedAuthenticators:o??[]}})],g=n.encode(n.fromPartial({messages:f,memo:t,extensionOptions:[],nonCriticalExtensionOptions:m})).finish(),v=a.encode(a.fromPartial({fee:void 0===d?{amount:[],gasLimit:1e6}:d,signerInfos:[{publicKey:l({typeUrl:"/cosmos.crypto.secp256k1.PubKey",value:s.pub_key}),sequence:u,modeInfo:{single:{mode:c.SIGN_MODE_DIRECT}}}]})).finish(),b=h.fromPartial({accountNumber:s.account_number,authInfoBytes:v,bodyBytes:g,chainId:i});return[this.hash(h.encode(b).finish(),p.sc,"hex"),b]}encodeDydxTxRaw(e,t){if(void 0===r||void 0===d)throw new y.NotSupported(this.id+" requires protobuf to encode messages, please install it with `npm install protobufjs`");return"0x"+this.binaryToBase16(d.encode(d.fromPartial({bodyBytes:e.bodyBytes,authInfoBytes:e.authInfoBytes,signatures:[this.base16ToBinary(t)]})).finish())}intToBase16(e){return e.toString(16)}extendExchangeOptions(e){this.options=this.extend(this.options,e)}createSafeDictionary(e=!1){return{}}convertToSafeDictionary(e){return e}checkOptionString(e,t,i){return i}checkOptionBool(e,t,i){return i}checkOptionInteger(e,t,i){return i}randomBytes(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),this.binaryToBase16(t)}randNumber(e){let t="";for(let i=0;i<e;i++)t+=Math.floor(10*Math.random());return parseInt(t,10)}binaryLength(e){return e.length}lockId(){}unlockId(){}lockLastNonce(){}unlockLastNonce(){}async loadLighterLibrary(e,t,s,r,a,o=!1){if(void 0===e||""===e)throw Error('loadLighterLibrary() requires "libraryPath" that should point to "lighter-signer.wasm". The binaries this version of ccxt is built against are in the ccxt repository under "ts/src/test/static/binaries", they can also be built from source using the official Lighter SDK or downloaded here https://github.com/ccxt/lighter-wasm. Please provide the path to it, the binary has to match your ccxt version.\nExample: exchanges.options["libraryPath"] = "/user/cjg/Git/lighter-wasm/lighter-signer.wasm"');if(!_)throw new y.NotSupported(this.id+" loadLighterLibrary() is only supported in node environment.");await v.eK();let n=this.safeString(this.options,"wasmExecPath");if(void 0===n||""===n)throw Error('loadLighterLibrary() requires "wasmExecPath" that should point to `wasm_exec.js`. You can check the location of the file locally if you have GO installed or download it here https://github.com/ccxt/lighter-wasm.\nExample: exchanges.options["wasmExecPath"] = "/opt/homebrew/opt/go/libexec/lib/wasm/wasm_exec.js"');await i(5427)(ty(n));let d=new globalThis.Go,h=new Uint8Array(tp(e,null)),{instance:c}=await WebAssembly.instantiate(h,d.importObject);return d.run(c),o&&this.lighterCreateClient(void 0,t,s,r,a),{}}lighterCreateClient(e,t,i,s,r){let a=globalThis.CreateClient(this.implodeHostname(this.urls.api.public),i,t,s,r);return this.checkLighterSignedError("lighterCreateClient",a,{api_key_index:s,account_index:r}),e}lighterSignCreateGroupedOrders(e,t){let i=t.orders,s=[];for(let e=0;e<i.length;e++){let t=i[e];s.push({MarketIndex:parseInt(t.market_index),ClientOrderIndex:t.client_order_index,BaseAmount:t.base_amount,Price:t.avg_execution_price,IsAsk:t.is_ask,Type:t.order_type,TimeInForce:t.time_in_force,ReduceOnly:t.reduce_only,TriggerPrice:t.trigger_price,OrderExpiry:t.order_expiry})}let r=globalThis.SignCreateGroupedOrders(t.grouping_type,s,this.safeInteger(t,"integrator_account_index",0),this.safeInteger(t,"integrator_taker_fee",0),this.safeInteger(t,"integrator_maker_fee",0),this.safeInteger(t,"self_trade_behavior_mode",0),this.safeInteger(t,"self_trade_equality_mode",0),1,t.nonce,t.api_key_index,t.account_index);return this.checkLighterSignedError("lighterSignCreateGroupedOrders",r,t),[r.txType,r.txInfo]}lighterSignCreateOrder(e,t){let i=globalThis.SignCreateOrder(parseInt(t.market_index),t.client_order_index,t.base_amount,t.avg_execution_price,t.is_ask,t.order_type,t.time_in_force,t.reduce_only,t.trigger_price,t.order_expiry,this.safeInteger(t,"integrator_account_index",0),this.safeInteger(t,"integrator_taker_fee",0),this.safeInteger(t,"integrator_maker_fee",0),this.safeInteger(t,"self_trade_behavior_mode",0),this.safeInteger(t,"self_trade_equality_mode",0),1,t.nonce,t.api_key_index,t.account_index);return this.checkLighterSignedError("lighterSignCreateOrder",i,t),[i.txType,i.txInfo]}checkLighterSignedError(e,t,i){"error"in t&&this.raiseLighterSignerError(e,t.error,i)}raiseLighterSignerError(e,t,i){let s=String(t),r=e+"() failed with error: "+s;if(s.indexOf("client is not created for")>=0){let e="";void 0!==i&&(e=" ccxt signed this request with apiKeyIndex: "+this.safeString(i,"api_key_index")+" accountIndex: "+this.safeString(i,"account_index")+"."),r+="."+e+' If those indices are not the ones reported above then the signer binary set in options["libraryPath"] is not the one this version of ccxt binds against. The signer has to match this version of ccxt: use the binaries ccxt is tested against, in the ccxt repository under "ts/src/test/static/binaries", or upgrade ccxt if your binary is newer than it.'}throw Error(r)}lighterSignCancelOrder(e,t){let i=globalThis.SignCancelOrder(t.market_index,t.order_index,1,t.nonce,t.api_key_index,t.account_index);return this.checkLighterSignedError("lighterSignCancelOrder",i,t),[i.txType,i.txInfo]}lighterSignWithdraw(e,t){let i=globalThis.SignWithdraw(t.asset_index,t.route_type,t.amount,1,t.nonce,t.api_key_index,t.account_index);return this.checkLighterSignedError("lighterSignWithdraw",i,t),[i.txType,i.txInfo]}lighterSignCreateSubAccount(e,t){let i=globalThis.SignCreateSubAccount(1,t.nonce,t.api_key_index,t.account_index);return this.checkLighterSignedError("lighterSignCreateSubAccount",i,t),[i.txType,i.txInfo]}lighterSignCancelAllOrders(e,t){let i=globalThis.SignCancelAllOrders(t.time_in_force,t.time,this.safeInteger(t,"cancel_all_market_index",255),1,t.nonce,t.api_key_index,t.account_index);return this.checkLighterSignedError("lighterSignCancelAllOrders",i,t),[i.txType,i.txInfo]}lighterSignModifyOrder(e,t){let i=globalThis.SignModifyOrder(t.market_index,t.index,t.base_amount,t.price,t.trigger_price,this.safeInteger(t,"integrator_account_index",0),this.safeInteger(t,"integrator_taker_fee",0),this.safeInteger(t,"integrator_maker_fee",0),this.safeInteger(t,"self_trade_behavior_mode",0),this.safeInteger(t,"self_trade_equality_mode",0),1,t.nonce,this.safeInteger(t,"order_version",0),t.api_key_index,t.account_index);return this.checkLighterSignedError("lighterSignModifyOrder",i,t),[i.txType,i.txInfo]}lighterSignTransfer(e,t){let i=globalThis.SignTransfer(t.to_account_index,t.asset_index,t.from_route_type,t.to_route_type,t.amount,t.usdc_fee,t.memo,1,t.nonce,t.api_key_index,t.account_index);return this.checkLighterSignedError("lighterSignTransfer",i,t),[i.txType,i.txInfo]}lighterSignUpdateLeverage(e,t){let i=globalThis.SignUpdateLeverage(t.market_index,t.initial_margin_fraction,t.margin_mode,1,t.nonce,t.api_key_index,t.account_index);return this.checkLighterSignedError("lighterSignUpdateLeverage",i,t),[i.txType,i.txInfo]}lighterCreateAuthToken(e,t){let i=globalThis.CreateAuthToken(t.deadline,t.api_key_index,t.account_index);return this.checkLighterSignedError("lighterCreateAuthToken",i,t),i.authToken}lighterSignUpdateMargin(e,t){let i=globalThis.SignUpdateMargin(t.market_index,t.usdc_amount,t.direction,1,t.nonce,t.api_key_index,t.account_index);return this.checkLighterSignedError("lighterSignUpdateMargin",i,t),[i.txType,i.txInfo]}lighterSignApproveIntegrator(e,t){let i=globalThis.SignApproveIntegrator(t.integrator_account_index,t.integrator_taker_fee,t.integrator_maker_fee,t.integrator_taker_fee,t.integrator_maker_fee,t.approval_expiry,1,t.nonce,t.api_key_index,t.account_index);return this.checkLighterSignedError("lighterSignApproveIntegrator",i,t),[i.txType,i.txInfo,i.messageToSign]}lighterGenerateApiKey(e){let t=globalThis.GenerateAPIKey();return this.checkLighterSignedError("lighterGenerateApiKey",t,void 0),[t.privateKey,t.publicKey]}lighterSignChangePubkey(e,t){let i=globalThis.SignChangePubKey(Buffer.from(t.pubkey).toString(),1,t.nonce,t.api_key_index,t.account_index);return this.checkLighterSignedError("lighterSignChangePubkey",i,t),[i.txType,i.txInfo,i.messageToSign]}setLastRestRequestTimestamp(){this.lastRestRequestTimestamp=this.milliseconds()}setLastRequest(e){this.last_request_headers=e.headers,this.last_request_body=e.body,this.last_request_url=e.url}describe(){return{id:this.id,name:this.name,countries:this.countries,enableRateLimit:this.enableRateLimit,rateLimit:this.rateLimit,rateLimiterAlgorithm:this.rateLimiterAlgorithm,timeout:this.timeout,certified:this.certified,pro:this.pro,alias:this.alias,dex:!1,has:{publicAPI:!0,privateAPI:!0,CORS:void 0,sandbox:void 0,spot:void 0,margin:void 0,swap:void 0,future:void 0,option:void 0,index:void 0,addMargin:void 0,borrowCrossMargin:void 0,borrowIsolatedMargin:void 0,borrowMargin:void 0,cancelAllOrders:void 0,cancelAllOrdersWs:void 0,cancelOrder:!0,cancelOrderWithClientOrderId:void 0,cancelOrderWs:void 0,cancelOrders:void 0,cancelOrdersWithClientOrderId:void 0,cancelOrdersWs:void 0,closeAllPositions:void 0,closePosition:void 0,createDepositAddress:void 0,createLimitBuyOrder:void 0,createLimitBuyOrderWs:void 0,createLimitOrder:!0,createLimitOrderWs:void 0,createLimitSellOrder:void 0,createLimitSellOrderWs:void 0,createMarketBuyOrder:void 0,createMarketBuyOrderWs:void 0,createMarketBuyOrderWithCost:void 0,createMarketBuyOrderWithCostWs:void 0,createMarketOrder:!0,createMarketOrderWs:!0,createMarketOrderWithCost:void 0,createMarketOrderWithCostWs:void 0,createMarketSellOrder:void 0,createMarketSellOrderWs:void 0,createMarketSellOrderWithCost:void 0,createMarketSellOrderWithCostWs:void 0,createOrder:!0,createOrderWs:void 0,createOrders:void 0,createOrderWithTakeProfitAndStopLoss:void 0,createOrderWithTakeProfitAndStopLossWs:void 0,createPostOnlyOrder:void 0,createPostOnlyOrderWs:void 0,createReduceOnlyOrder:void 0,createReduceOnlyOrderWs:void 0,createStopLimitOrder:void 0,createStopLimitOrderWs:void 0,createStopLossOrder:void 0,createStopLossOrderWs:void 0,createStopMarketOrder:void 0,createStopMarketOrderWs:void 0,createStopOrder:void 0,createStopOrderWs:void 0,createTakeProfitOrder:void 0,createTakeProfitOrderWs:void 0,createTrailingAmountOrder:void 0,createTrailingAmountOrderWs:void 0,createTrailingPercentOrder:void 0,createTrailingPercentOrderWs:void 0,createTriggerOrder:void 0,createTriggerOrderWs:void 0,deposit:void 0,editOrder:"emulated",editOrderWithClientOrderId:void 0,editOrders:void 0,editOrderWs:void 0,fetchAccounts:void 0,fetchADLRank:void 0,fetchBalance:!0,fetchBalanceWs:void 0,fetchBidsAsks:void 0,fetchBorrowInterest:void 0,fetchBorrowRate:void 0,fetchBorrowRateHistories:void 0,fetchBorrowRateHistory:void 0,fetchBorrowRates:void 0,fetchBorrowRatesPerSymbol:void 0,fetchCanceledAndClosedOrders:void 0,fetchCanceledOrders:void 0,fetchClosedOrder:void 0,fetchClosedOrders:void 0,fetchClosedOrdersWs:void 0,fetchConvertCurrencies:void 0,fetchConvertQuote:void 0,fetchConvertTrade:void 0,fetchConvertTradeHistory:void 0,fetchCrossBorrowRate:void 0,fetchCrossBorrowRates:void 0,fetchCurrencies:"emulated",fetchCurrenciesWs:"emulated",fetchDeposit:void 0,fetchDepositAddress:void 0,fetchDepositAddresses:void 0,fetchDepositAddressesByNetwork:void 0,fetchDeposits:void 0,fetchDepositsWithdrawals:void 0,fetchDepositsWs:void 0,fetchDepositWithdrawFee:void 0,fetchDepositWithdrawFees:void 0,fetchFundingHistory:void 0,fetchFundingRate:void 0,fetchFundingRateHistory:void 0,fetchFundingInterval:void 0,fetchFundingIntervals:void 0,fetchFundingRates:void 0,fetchGreeks:void 0,fetchIndexOHLCV:void 0,fetchIsolatedBorrowRate:void 0,fetchIsolatedBorrowRates:void 0,fetchMarginAdjustmentHistory:void 0,fetchIsolatedPositions:void 0,fetchL2OrderBook:!0,fetchL3OrderBook:void 0,fetchLastPrices:void 0,fetchLedger:void 0,fetchLedgerEntry:void 0,fetchLeverage:void 0,fetchLeverages:void 0,fetchLeverageTiers:void 0,fetchLiquidations:void 0,fetchLongShortRatio:void 0,fetchLongShortRatioHistory:void 0,fetchMarginMode:void 0,fetchMarginModes:void 0,fetchMarketLeverageTiers:void 0,fetchMarkets:!0,fetchMarketsWs:void 0,fetchMarkOHLCV:void 0,fetchMyLiquidations:void 0,fetchMySettlementHistory:void 0,fetchMyTrades:void 0,fetchMyTradesWs:void 0,fetchOHLCV:void 0,fetchOHLCVWs:void 0,fetchOpenInterest:void 0,fetchOpenInterests:void 0,fetchOpenInterestHistory:void 0,fetchOpenOrder:void 0,fetchOpenOrders:void 0,fetchOpenOrdersWs:void 0,fetchOption:void 0,fetchOptionChain:void 0,fetchOrder:void 0,fetchOrderWithClientOrderId:void 0,fetchOrderBook:!0,fetchOrderBooks:void 0,fetchOrderBookWs:void 0,fetchOrders:void 0,fetchOrdersByStatus:void 0,fetchOrdersWs:void 0,fetchOrderTrades:void 0,fetchOrderWs:void 0,fetchPosition:void 0,fetchPositionADLRank:void 0,fetchPositionsADLRank:void 0,fetchPositionHistory:void 0,fetchPositionsHistory:void 0,fetchPositionWs:void 0,fetchPositionMode:void 0,fetchPositions:void 0,fetchPositionsWs:void 0,fetchPositionsForSymbol:void 0,fetchPositionsForSymbolWs:void 0,fetchPositionsRisk:void 0,fetchPremiumIndexOHLCV:void 0,fetchSettlementHistory:void 0,fetchStatus:void 0,fetchTicker:!0,fetchTickerWs:void 0,fetchTickers:void 0,fetchMarkPrices:void 0,fetchTickersWs:void 0,fetchTime:void 0,fetchTrades:!0,fetchTradesWs:void 0,fetchTradingFee:void 0,fetchTradingFees:void 0,fetchTradingFeesWs:void 0,fetchTradingLimits:void 0,fetchTransactionFee:void 0,fetchTransactionFees:void 0,fetchTransactions:void 0,fetchTransfer:void 0,fetchTransfers:void 0,fetchUnderlyingAssets:void 0,fetchVolatilityHistory:void 0,fetchWithdrawAddresses:void 0,fetchWithdrawal:void 0,fetchWithdrawals:void 0,fetchWithdrawalsWs:void 0,fetchWithdrawalWhitelist:void 0,reduceMargin:void 0,repayCrossMargin:void 0,repayIsolatedMargin:void 0,setLeverage:void 0,setMargin:void 0,setMarginMode:void 0,setPositionMode:void 0,signIn:void 0,transfer:void 0,watchBalance:void 0,watchMyTrades:void 0,watchOHLCV:void 0,watchOHLCVForSymbols:void 0,watchOrderBook:void 0,watchBidsAsks:void 0,watchOrderBookForSymbols:void 0,watchOrders:void 0,watchOrdersForSymbols:void 0,watchPosition:void 0,watchPositions:void 0,watchStatus:void 0,watchTicker:void 0,watchTickers:void 0,watchTrades:void 0,watchTradesForSymbols:void 0,watchLiquidations:void 0,watchLiquidationsForSymbols:void 0,watchMyLiquidations:void 0,unWatchOrders:void 0,unWatchTrades:void 0,unWatchTradesForSymbols:void 0,unWatchOHLCVForSymbols:void 0,unWatchOrderBookForSymbols:void 0,unWatchPositions:void 0,unWatchOrderBook:void 0,unWatchTickers:void 0,unWatchMyTrades:void 0,unWatchTicker:void 0,unWatchOHLCV:void 0,watchMyLiquidationsForSymbols:void 0,withdraw:void 0,ws:void 0},urls:{logo:void 0,api:void 0,test:void 0,www:void 0,doc:void 0,api_management:void 0,fees:void 0,referral:void 0},api:void 0,requiredCredentials:{apiKey:!0,secret:!0,uid:!1,accountId:!1,login:!1,password:!1,twofa:!1,privateKey:!1,walletAddress:!1,token:!1},markets:void 0,currencies:{},timeframes:void 0,fees:{trading:{tierBased:void 0,percentage:void 0,taker:void 0,maker:void 0},funding:{tierBased:void 0,percentage:void 0,withdraw:{},deposit:{}}},status:{status:"ok",updated:void 0,eta:void 0,url:void 0,info:void 0},exceptions:void 0,httpExceptions:{422:y.ExchangeError,418:y.DDoSProtection,429:y.RateLimitExceeded,404:y.ExchangeNotAvailable,409:y.ExchangeNotAvailable,410:y.ExchangeNotAvailable,451:y.ExchangeNotAvailable,500:y.ExchangeNotAvailable,501:y.ExchangeNotAvailable,502:y.ExchangeNotAvailable,520:y.ExchangeNotAvailable,521:y.ExchangeNotAvailable,522:y.ExchangeNotAvailable,525:y.ExchangeNotAvailable,526:y.ExchangeNotAvailable,400:y.ExchangeNotAvailable,403:y.ExchangeNotAvailable,405:y.ExchangeNotAvailable,503:y.ExchangeNotAvailable,530:y.ExchangeNotAvailable,408:y.RequestTimeout,504:y.RequestTimeout,401:y.AuthenticationError,407:y.AuthenticationError,511:y.AuthenticationError},commonCurrencies:{XBT:"BTC",BCHSV:"BSV"},precisionMode:tl,paddingMode:tc,limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},rollingWindowSize:6e4}}cleanRestData(){this.ids=void 0,this.markets=void 0,this.markets_by_id=void 0,this.symbols=[],this.codes=void 0,this.currencies=this.createSafeDictionary(),this.currencies_by_id=void 0,this.baseCurrencies=void 0,this.quoteCurrencies=void 0,this.last_http_response=void 0,this.last_response_headers=void 0,this.last_request_headers=void 0}cleanWsData(){this.balance=this.createSafeDictionary(!0),this.orderbooks=this.createSafeDictionary(!0),this.tickers=this.createSafeDictionary(!0),this.liquidations=void 0,this.myLiquidations=void 0,this.orders=void 0,this.trades=this.createSafeDictionary(!0),this.transactions=this.createSafeDictionary(),this.ohlcvs=this.createSafeDictionary(!0),this.myTrades=void 0,this.positions=void 0}safeBoolN(e,t,i){let s=this.safeValueN(e,t,i);return"boolean"==typeof s?s:i}safeBool2(e,t,i,s){let r=this.safeValue(e,t);if("boolean"==typeof r)return r;let a=this.safeValue(e,i);return"boolean"==typeof a?a:s}safeBool(e,t,i){let s=this.safeValue(e,t,i);return"boolean"==typeof s?s:i}safeDictN(e,t,i){let s=this.safeValueN(e,t,i);return void 0===s?i:this.isDictionary(s)?s:i}safeDict(e,t,i){let s=this.safeValue(e,t,i);return void 0===s?i:this.isDictionary(s)?s:i}safeDict2(e,t,i,s){let r=this.safeValue(e,t);if(this.isDictionary(r))return r;let a=this.safeValue(e,i);return this.isDictionary(a)?a:s}safeListN(e,t,i){let s=this.safeValueN(e,t,i);return void 0===s?i:Array.isArray(s)?s:i}safeList2(e,t,i,s){let r=this.safeValue(e,t);if(void 0!==r&&Array.isArray(r))return r;let a=this.safeValue(e,i);return void 0!==a&&Array.isArray(a)?a:s}safeList(e,t,i){let s=this.safeValue(e,t,i);return void 0===s?i:Array.isArray(s)?s:i}storeByKey(e,t,i){void 0!==t&&(e[t]=i)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}handleDelta(e,t){throw new y.NotSupported(this.id+" handleDelta not supported yet")}handleBookDeltas(e,t){for(let i=0;i<t.length;i++)this.handleBookDelta(e,t[i])}handleBookDelta(e,t){throw new y.NotSupported(this.id+" handleBookDelta not supported yet")}handleDeltasWithKeys(e,t,i=0,s=1,r=2){for(let a=0;a<t.length;a++){let o=this.parseOrderBookBidAsk(t[a],i,s,r);e.storeArray(o)}}getCacheIndex(e,t){return -1}arraysConcat(e){let t=[];for(let i=0;i<e.length;i++)t=this.arrayConcat(t,e[i]);return t}findTimeframe(e,t){let i=void 0===t?this.timeframes:t,s=Object.keys(i);for(let t=0;t<s.length;t++){let r=s[t];if(i[r]===e)return r}}checkProxyUrlSettings(e,t,i,s){let r,a=[];if(void 0!==this.proxyUrl&&(a.push("proxyUrl"),r=this.proxyUrl),void 0!==this.proxy_url&&(a.push("proxy_url"),r=this.proxy_url),void 0!==this.proxyUrlCallback&&(a.push("proxyUrlCallback"),r=this.proxyUrlCallback(e,t,i,s)),void 0!==this.proxy_url_callback&&(a.push("proxy_url_callback"),r=this.proxy_url_callback(e,t,i,s)),void 0!==this.proxy&&(a.push("proxy"),r="function"==typeof this.proxy?this.proxy(e,t,i,s):this.proxy),a.length>1){let e=a.join(",");throw new y.InvalidProxySettings(this.id+" you have multiple conflicting proxy settings ("+e+"), please use only one from : proxyUrl, proxy_url, proxyUrlCallback, proxy_url_callback")}return r}urlEncoderForProxyUrl(e){return e.indexOf("?")>=0?this.encodeURIComponent(e):e}checkProxySettings(e,t,i,s){let r,a,o,n=[],d=this.valueIsDefined(this.httpProxy),h=this.valueIsDefined(this.http_proxy);(d||h)&&(n.push("httpProxy"),r=d?this.httpProxy:this.http_proxy);let c=this.valueIsDefined(this.httpProxyCallback),l=this.valueIsDefined(this.http_proxy_callback);(c||l)&&(n.push("httpProxyCallback"),r=c?this.httpProxyCallback(e,t,i,s):this.http_proxy_callback(e,t,i,s));let u=this.valueIsDefined(this.httpsProxy),f=this.valueIsDefined(this.https_proxy);(u||f)&&(n.push("httpsProxy"),a=u?this.httpsProxy:this.https_proxy);let p=this.valueIsDefined(this.httpsProxyCallback),m=this.valueIsDefined(this.https_proxy_callback);(p||m)&&(n.push("httpsProxyCallback"),a=p?this.httpsProxyCallback(e,t,i,s):this.https_proxy_callback(e,t,i,s));let g=this.valueIsDefined(this.socksProxy),v=this.valueIsDefined(this.socks_proxy);(g||v)&&(n.push("socksProxy"),o=g?this.socksProxy:this.socks_proxy);let b=this.valueIsDefined(this.socksProxyCallback),w=this.valueIsDefined(this.socks_proxy_callback);if((b||w)&&(n.push("socksProxyCallback"),o=b?this.socksProxyCallback(e,t,i,s):this.socks_proxy_callback(e,t,i,s)),n.length>1){let e=n.join(",");throw new y.InvalidProxySettings(this.id+" you have multiple conflicting proxy settings ("+e+"), please use only one from: httpProxy, httpsProxy, httpProxyCallback, httpsProxyCallback, socksProxy, socksProxyCallback")}return[r,a,o]}checkWsProxySettings(){let e,t,i,s=[],r=this.valueIsDefined(this.wsProxy),a=this.valueIsDefined(this.ws_proxy);(r||a)&&(s.push("wsProxy"),e=r?this.wsProxy:this.ws_proxy);let o=this.valueIsDefined(this.wssProxy),n=this.valueIsDefined(this.wss_proxy);(o||n)&&(s.push("wssProxy"),t=o?this.wssProxy:this.wss_proxy);let d=this.valueIsDefined(this.wsSocksProxy),h=this.valueIsDefined(this.ws_socks_proxy);if((d||h)&&(s.push("wsSocksProxy"),i=d?this.wsSocksProxy:this.ws_socks_proxy),s.length>1){let e=s.join(",");throw new y.InvalidProxySettings(this.id+" you have multiple conflicting proxy settings ("+e+"), please use only one from: wsProxy, wssProxy, wsSocksProxy")}return[e,t,i]}checkConflictingProxies(e,t){if(null!=e&&""!==e&&null!=t&&""!==t)throw new y.InvalidProxySettings(this.id+" you have multiple conflicting proxy settings, please use only one from : proxyUrl, httpProxy, httpsProxy, socksProxy")}checkAddress(e){if(void 0===e)throw new y.InvalidAddress(this.id+" address is undefined");if(1===this.unique(this.stringToCharsArray(e)).length||e.length<this.minFundingAddressLength||e.indexOf(" ")>-1)throw new y.InvalidAddress(this.id+" address is invalid or has less than "+this.minFundingAddressLength.toString()+' characters: "'+e.toString()+'"');return e}findMessageHashes(e,t){let i=[],s=Object.keys(e.futures);for(let e=0;e<s.length;e++){let r=s[e];r.indexOf(t)>=0&&i.push(r)}return i}filterByLimit(e,t,i="timestamp",s=!1){if(this.valueIsDefined(t)){let r=e.length;if(r>0){let a=!0;if(i in e[0]){let t=e[0][i],s=e[r-1][i];void 0!==t&&void 0!==s&&(a=t<=s)}if(s){let i=t>r?r:t;return a?this.arraySlice(e,0,i):this.arraySlice(e,-i)}return a?this.arraySlice(e,-t):this.arraySlice(e,0,t)}}return e}filterBySinceLimit(e,t,i,s="timestamp",r=!1){if(void 0===e)return[];let a=this.valueIsDefined(t),o=this.toArray(e),n=o;if(a){n=[];for(let e=0;e<o.length;e++){let i=o[e],r=this.safeValue(i,s);null!=r&&0!==r&&r>=t&&n.push(i)}}return r&&void 0!==i?this.arraySlice(n,-i):this.filterByLimit(n,i,s,!r&&a)}filterByValueSinceLimit(e,t,i,s,r,a="timestamp",o=!1){let n=this.valueIsDefined(i),d=this.valueIsDefined(s),h=this.toArray(e),c=h;if(n||d){c=[];for(let e=0;e<h.length;e++){let r=h[e],o=this.safeValue(r,t)===i,l=!n||o,u=this.safeValue(r,a),f=null!=u&&0!==u&&void 0!==s&&u>=s,p=!d||f;l&&p&&c.push(r)}}return o&&void 0!==r?this.arraySlice(c,-r):this.filterByLimit(c,r,a,d)}setSandboxMode(e){if(e){if("test"in this.urls)"string"==typeof this.urls.api?(this.urls.apiBackup=this.urls.api,this.urls.api=this.urls.test):(this.urls.apiBackup=this.clone(this.urls.api),this.urls.api=this.clone(this.urls.test));else throw new y.NotSupported(this.id+" does not have a sandbox URL");this.isSandboxModeEnabled=!0}else if("apiBackup"in this.urls){"string"==typeof this.urls.api?this.urls.api=this.urls.apiBackup:this.urls.api=this.clone(this.urls.apiBackup);let e=this.omit(this.urls,"apiBackup");this.urls=e,this.isSandboxModeEnabled=!1}}enableDemoTrading(e){if(this.isSandboxModeEnabled)throw new y.NotSupported(this.id+" demo trading does not support in sandbox environment. Please check https://www.binance.com/en/support/faq/detail/9be58f73e5e14338809e3b705b9687dd to see the differences");if(e)this.urls.apiBackupDemoTrading=this.urls.api,this.urls.api=this.urls.demo;else if("apiBackupDemoTrading"in this.urls){this.urls.api=this.urls.apiBackupDemoTrading;let e=this.omit(this.urls,"apiBackupDemoTrading");this.urls=e}this.options.enableDemoTrading=e}sign(e,t="public",i="GET",s={},r,a){return{url:void 0,method:void 0,headers:void 0,body:void 0}}async fetchAccounts(e={}){throw new y.NotSupported(this.id+" fetchAccounts() is not supported yet")}async watchLiquidations(e,t,i,s={}){if(void 0!==this.has.watchLiquidationsForSymbols&&!1!==this.has.watchLiquidationsForSymbols)return await this.watchLiquidationsForSymbols([e],t,i,s);throw new y.NotSupported(this.id+" watchLiquidations() is not supported yet")}async watchLiquidationsForSymbols(e,t,i,s={}){throw new y.NotSupported(this.id+" watchLiquidationsForSymbols() is not supported yet")}async watchMyLiquidations(e,t,i,s={}){if(void 0!==this.has.watchMyLiquidationsForSymbols&&!1!==this.has.watchMyLiquidationsForSymbols)return this.watchMyLiquidationsForSymbols([e],t,i,s);throw new y.NotSupported(this.id+" watchMyLiquidations() is not supported yet")}async watchMyLiquidationsForSymbols(e,t,i,s={}){throw new y.NotSupported(this.id+" watchMyLiquidationsForSymbols() is not supported yet")}async unWatchOrders(e,t={}){throw new y.NotSupported(this.id+" unWatchOrders() is not supported yet")}async unWatchTrades(e,t={}){throw new y.NotSupported(this.id+" unWatchTrades() is not supported yet")}async unWatchTradesForSymbols(e,t={}){throw new y.NotSupported(this.id+" unWatchTradesForSymbols() is not supported yet")}async watchOHLCVForSymbols(e,t,i,s={}){throw new y.NotSupported(this.id+" watchOHLCVForSymbols() is not supported yet")}async unWatchOHLCVForSymbols(e,t={}){throw new y.NotSupported(this.id+" unWatchOHLCVForSymbols() is not supported yet")}async unWatchOrderBookForSymbols(e,t={}){throw new y.NotSupported(this.id+" unWatchOrderBookForSymbols() is not supported yet")}async unWatchPositions(e,t={}){throw new y.NotSupported(this.id+" unWatchPositions() is not supported yet")}async unWatchTicker(e,t={}){throw new y.NotSupported(this.id+" unWatchTicker() is not supported yet")}async unWatchMarkPrice(e,t={}){throw new y.NotSupported(this.id+" unWatchMarkPrice() is not supported yet")}async unWatchMarkPrices(e,t={}){throw new y.NotSupported(this.id+" unWatchMarkPrices() is not supported yet")}async fetchDepositAddresses(e,t={}){throw new y.NotSupported(this.id+" fetchDepositAddresses() is not supported yet")}async fetchMarginMode(e,t={}){if(void 0!==this.has.fetchMarginModes&&!1!==this.has.fetchMarginModes){let i=await this.fetchMarginModes([e],t);return this.safeDict(i,e)}throw new y.NotSupported(this.id+" fetchMarginMode() is not supported yet")}async fetchMarginModes(e,t={}){throw new y.NotSupported(this.id+" fetchMarginModes () is not supported yet")}async unWatchOrderBook(e,t={}){throw new y.NotSupported(this.id+" unWatchOrderBook() is not supported yet")}async fetchTime(e={}){throw new y.NotSupported(this.id+" fetchTime() is not supported yet")}async fetchTradingLimits(e,t={}){throw new y.NotSupported(this.id+" fetchTradingLimits() is not supported yet")}parseCurrency(e){throw new y.NotSupported(this.id+" parseCurrency() is not supported yet")}parseCurrencies(e){let t={},i=this.toArray(e);for(let e=0;e<i.length;e++){let s=this.parseCurrency(i[e]);void 0!==s&&(t[s.code]=s)}return t}parseMarket(e){throw new y.NotSupported(this.id+" parseMarket() is not supported yet")}parseMarkets(e){let t=[];for(let i=0;i<e.length;i++){let s=this.parseMarket(e[i]);void 0!==s&&t.push(s)}return t}parseTicker(e,t){throw new y.NotSupported(this.id+" parseTicker() is not supported yet")}parseDepositAddress(e,t){throw new y.NotSupported(this.id+" parseDepositAddress() is not supported yet")}parseTrade(e,t){throw new y.NotSupported(this.id+" parseTrade() is not supported yet")}parseTransaction(e,t){throw new y.NotSupported(this.id+" parseTransaction() is not supported yet")}parseTransfer(e,t){throw new y.NotSupported(this.id+" parseTransfer() is not supported yet")}parseAccount(e){throw new y.NotSupported(this.id+" parseAccount() is not supported yet")}parseLedgerEntry(e,t){throw new y.NotSupported(this.id+" parseLedgerEntry() is not supported yet")}parseOrder(e,t){throw new y.NotSupported(this.id+" parseOrder() is not supported yet")}async fetchCrossBorrowRates(e={}){throw new y.NotSupported(this.id+" fetchCrossBorrowRates() is not supported yet")}async fetchIsolatedBorrowRates(e={}){throw new y.NotSupported(this.id+" fetchIsolatedBorrowRates() is not supported yet")}parseMarketLeverageTiers(e,t){throw new y.NotSupported(this.id+" parseMarketLeverageTiers() is not supported yet")}async fetchLeverageTiers(e,t={}){throw new y.NotSupported(this.id+" fetchLeverageTiers() is not supported yet")}parsePosition(e,t){throw new y.NotSupported(this.id+" parsePosition() is not supported yet")}parseFundingRateHistory(e,t){throw new y.NotSupported(this.id+" parseFundingRateHistory() is not supported yet")}parseBorrowInterest(e,t){throw new y.NotSupported(this.id+" parseBorrowInterest() is not supported yet")}parseIsolatedBorrowRate(e,t){throw new y.NotSupported(this.id+" parseIsolatedBorrowRate() is not supported yet")}parseWsTrade(e,t){throw new y.NotSupported(this.id+" parseWsTrade() is not supported yet")}parseWsOrder(e,t){throw new y.NotSupported(this.id+" parseWsOrder() is not supported yet")}parseWsOrderTrade(e,t){throw new y.NotSupported(this.id+" parseWsOrderTrade() is not supported yet")}parseWsOHLCV(e,t){return this.parseOHLCV(e,t)}async fetchFundingRates(e,t={}){throw new y.NotSupported(this.id+" fetchFundingRates() is not supported yet")}async fetchFundingIntervals(e,t={}){throw new y.NotSupported(this.id+" fetchFundingIntervals() is not supported yet")}async watchFundingRate(e,t={}){throw new y.NotSupported(this.id+" watchFundingRate() is not supported yet")}async watchFundingRates(e,t={}){throw new y.NotSupported(this.id+" watchFundingRates() is not supported yet")}async unWatchFundingRates(e,t={}){throw new y.NotSupported(this.id+" unWatchFundingRates() is not supported yet")}async watchFundingRatesForSymbols(e,t={}){return await this.watchFundingRates(e,t)}async transfer(e,t,i,s,r={}){throw new y.NotSupported(this.id+" transfer() is not supported yet")}async withdraw(e,t,i,s,r={}){throw new y.NotSupported(this.id+" withdraw() is not supported yet")}async createDepositAddress(e,t={}){throw new y.NotSupported(this.id+" createDepositAddress() is not supported yet")}async setLeverage(e,t,i={}){throw new y.NotSupported(this.id+" setLeverage() is not supported yet")}async fetchLeverage(e,t={}){if(void 0!==this.has.fetchLeverages&&!1!==this.has.fetchLeverages){let i=await this.fetchLeverages([e],t);return this.safeDict(i,e)}throw new y.NotSupported(this.id+" fetchLeverage() is not supported yet")}async fetchLeverages(e,t={}){throw new y.NotSupported(this.id+" fetchLeverages() is not supported yet")}async setPositionMode(e,t,i={}){throw new y.NotSupported(this.id+" setPositionMode() is not supported yet")}async addMargin(e,t,i={}){throw new y.NotSupported(this.id+" addMargin() is not supported yet")}async reduceMargin(e,t,i={}){throw new y.NotSupported(this.id+" reduceMargin() is not supported yet")}async setMargin(e,t,i={}){throw new y.NotSupported(this.id+" setMargin() is not supported yet")}async fetchLongShortRatio(e,t,i={}){throw new y.NotSupported(this.id+" fetchLongShortRatio() is not supported yet")}async fetchLongShortRatioHistory(e,t,i,s,r={}){throw new y.NotSupported(this.id+" fetchLongShortRatioHistory() is not supported yet")}async fetchMarginAdjustmentHistory(e,t,i,s,r={}){throw new y.NotSupported(this.id+" fetchMarginAdjustmentHistory() is not supported yet")}async setMarginMode(e,t,i={}){throw new y.NotSupported(this.id+" setMarginMode() is not supported yet")}async fetchDepositAddressesByNetwork(e,t={}){throw new y.NotSupported(this.id+" fetchDepositAddressesByNetwork() is not supported yet")}async fetchOpenInterestHistory(e,t="1h",i,s,r={}){throw new y.NotSupported(this.id+" fetchOpenInterestHistory() is not supported yet")}async fetchOpenInterests(e,t={}){throw new y.NotSupported(this.id+" fetchOpenInterests() is not supported yet")}async signIn(e={}){throw new y.NotSupported(this.id+" signIn() is not supported yet")}async fetchPaymentMethods(e={}){throw new y.NotSupported(this.id+" fetchPaymentMethods() is not supported yet")}parseToInt(e){return parseInt(parseFloat(this.numberToString(e)))}parseToNumeric(e){let t=this.numberToString(e);return t.indexOf(".")>=0?parseFloat(t):parseInt(t)}isRoundNumber(e){return 0===this.parseToNumeric(e%1)}isEmptyString(e){return!this.valueIsDefined(e)||""===e}safeNumberOmitZero(e,t,i){let s=this.safeString(e,t),r=this.parseNumber(this.omitZero(s));return void 0===r?i:r}safeIntegerOmitZero(e,t,i){let s=this.safeInteger(e,t,i);if(void 0!==s&&0!==s)return s}afterConstruct(){this.createNetworksByIdObject(),this.featuresGenerator(),void 0!==this.markets&&this.setMarkets(this.markets),this.initRestRateLimiter();let e=this.safeBool2(this.options,"sandbox","testnet",!1);!0===e&&this.setSandboxMode(e)}initRestRateLimiter(){if(void 0===this.rateLimit||void 0!==this.id&&-1===this.rateLimit)throw new y.ExchangeError(this.id+".rateLimit property is not configured");let e=this.MAX_VALUE;this.rateLimit>0&&(e=1/this.rateLimit);let t={delay:.001,capacity:1,cost:1,refillRate:e,algorithm:0===this.rollingWindowSize||"leakyBucket"===this.rateLimiterAlgorithm?"leakyBucket":"rollingWindow",windowSize:this.rollingWindowSize,rateLimit:this.rateLimit},i=void 0===this.tokenBucket?{}:this.tokenBucket;this.tokenBucket=this.extend(t,i),this.initThrottler()}featuresGenerator(){if(void 0===this.features)return;let e=this.features;this.features={};let t=["spot","swap","future","option"],i=["linear","inverse"];for(let s=0;s<t.length;s++){let r=t[s];if(r in e)if("spot"===r)this.features[r]=this.featuresMapper(e,r);else{this.features[r]={};for(let t=0;t<i.length;t++){let s=i[t];this.features[r][s]=this.featuresMapper(e,r,s)}}else this.features[r]=void 0}}featuresMapper(e,t,i){let s=void 0!==i?e[t][i]:e[t];if(void 0===s)return;let r=this.safeString(s,"extends");if(void 0!==r){s=this.omit(s,"extends");let t=this.featuresMapper(e,r);s=this.deepExtend(t,s)}if("createOrder"in s){let e=this.safeDict(s.createOrder,"attachedStopLossTakeProfit");s.createOrder.stopLoss=e,s.createOrder.takeProfit=e,"spot"===t&&(s.createOrder.hedged=!1,"leverage"in s.createOrder||(s.createOrder.leverage=!1)),void 0===this.safeBool(s.createOrder.timeInForce,"GTC")&&(s.createOrder.timeInForce.GTC=!0)}let a=Object.keys(s);for(let e=0;e<a.length;e++){let t=a[e],i=s[t];this.inArray(t,["sandbox"])||void 0===i||"symbolRequired"in i||(i.symbolRequired=this.inArray(t,["createOrder","createOrders","fetchOHLCV"]))}return s}featureValue(e,t,i,s){let r=this.market(e);return this.featureValueByType(r.type,r.subType,t,i,s)}featureValueByType(e,t,i,s,r){if(void 0===this.features||void 0===e||!(e in this.features)||void 0===this.features[e])return r;let a=this.features[e];if(void 0===t){if("spot"!==e)return r}else{if(!(t in this.features[e])||void 0===this.features[e][t])return r;a=this.features[e][t]}if(void 0===i)return void 0!==r?r:a;if(!(i in a))return r;let o=a[i];if(void 0===o)return r;if(void 0===s)return void 0!==r?r:o;let n=s.split("."),d=n[0],h=this.safeString(n,1);return d in o?void 0===this.safeDict(o,d)||void 0===h?o[d]:h in o[d]?o[d][h]:r:r}orderbookChecksumMessage(e){if(void 0===e)throw new y.ArgumentsRequired(this.id+" orderbookChecksumMessage() requires a symbol argument");return e+' : orderbook data checksum validation failed. You can reconnect by calling watchOrderBook again or you can mute the error by setting exchange.options["watchOrderBook"]["checksum"] = false'}createNetworksByIdObject(){let e=this.invertFlatStringDictionary(this.safeValue(this.options,"networks",{}));this.options.networksById=this.extend(e,this.safeValue(this.options,"networksById",{}))}getDefaultOptions(){return{defaultNetworkCodeReplacements:{ETH:{primary:"ETH",secondary:"ERC20",default:"secondary"},CRO:{primary:"CRONOS",secondary:"CRC20",default:"secondary"},TRX:{primary:"TRX",secondary:"TRC20",default:"secondary"},BTC:{primary:"BTC",secondary:"BRC20",default:"primary"}},backwardSupportedNetworkCodes:{ARB:"ARBITRUM",ARBONE:"ARBITRUM",ARBNOVA:"ARBITRUM_NOVA"}}}safeLedgerEntry(e,t){let i=this.safeCurrency(void 0,t),s=this.safeString(e,"direction"),r=this.safeString(e,"before"),a=this.safeString(e,"after"),o=this.safeString(e,"amount");void 0!==o&&(void 0===r&&void 0!==a?r=b.Y.stringSub(a,o):void 0!==r&&void 0===a&&(a=b.Y.stringAdd(r,o))),void 0!==r&&void 0!==a&&void 0===s&&(b.Y.stringGt(r,a)&&(s="out"),b.Y.stringGt(a,r)&&(s="in"));let n=this.safeValue(e,"fee");void 0!==n&&(n.cost=this.safeNumber(n,"cost"));let d=this.safeInteger(e,"timestamp"),h=this.safeDict(e,"info",{});return{id:this.safeString(e,"id"),timestamp:d,datetime:this.iso8601(d),direction:s,account:this.safeString(e,"account"),referenceId:this.safeString(e,"referenceId"),referenceAccount:this.safeString(e,"referenceAccount"),type:this.safeString(e,"type"),currency:i.code,amount:this.parseNumber(o),before:this.parseNumber(r),after:this.parseNumber(a),status:this.safeString(e,"status"),fee:n,info:h}}safeCurrencyStructure(e){let t=this.safeDict(e,"networks",{}),i=Object.keys(t),s=i.length;if(0!==s)for(let r=0;r<s;r++){let s=t[i[r]],a=this.safeBool(s,"deposit");(void 0===this.safeBool(e,"deposit")||!0===a)&&(e.deposit=a);let o=this.safeBool(s,"withdraw");(void 0===this.safeBool(e,"withdraw")||!0===o)&&(e.withdraw=o);let n=this.safeString(s,"fee"),d=this.safeString(e,"fee");(void 0===d||b.Y.stringLt(n,d))&&(e.fee=this.parseNumber(n));let h=this.safeString(s,"precision"),c=this.safeString(e,"precision");(void 0===c||b.Y.stringGt(h,c))&&(e.precision=this.parseNumber(h));let l=this.safeDict(s,"limits"),u=this.safeDict(e,"limits");void 0===u&&(e.limits={});let f=this.safeDict(l,"deposit"),p=this.safeDict(u,"deposit");void 0===p&&(e.limits.deposit={});let m=this.safeString(f,"min"),g=this.safeString(f,"max"),v=this.safeString(p,"min"),y=this.safeString(p,"max");(void 0===v||b.Y.stringLt(m,v))&&(e.limits.deposit.min=this.parseNumber(m)),(void 0===y||b.Y.stringGt(g,y))&&(e.limits.deposit.max=this.parseNumber(g));let w=this.safeDict(l,"withdraw"),k=this.safeDict(u,"withdraw");void 0===k&&(e.limits.withdraw={});let S=this.safeString(w,"min"),O=this.safeString(w,"max"),T=this.safeString(k,"min"),P=this.safeString(k,"max");(void 0===T||b.Y.stringLt(S,T))&&(e.limits.withdraw.min=this.parseNumber(S)),(void 0===P||b.Y.stringGt(O,P))&&(e.limits.withdraw.max=this.parseNumber(O))}return this.extend({info:void 0,id:void 0,numericId:void 0,code:void 0,precision:void 0,type:void 0,name:void 0,active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,fees:{},networks:{},limits:{deposit:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}}},e)}safeMarketStructure(e){let t={id:void 0,lowercaseId:void 0,symbol:void 0,base:void 0,quote:void 0,settle:void 0,baseId:void 0,quoteId:void 0,settleId:void 0,type:void 0,spot:void 0,margin:void 0,swap:void 0,future:void 0,option:void 0,index:void 0,active:void 0,contract:void 0,linear:void 0,inverse:void 0,subType:void 0,taker:void 0,maker:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:void 0,price:void 0,cost:void 0,base:void 0,quote:void 0},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},marginModes:{cross:void 0,isolated:void 0},created:void 0,info:void 0};if(void 0!==e){let i=this.extend(t,e);return!0===i.spot&&(void 0===i.contract&&(i.contract=!1),void 0===i.swap&&(i.swap=!1),void 0===i.future&&(i.future=!1),void 0===i.option&&(i.option=!1),void 0===i.index&&(i.index=!1)),i}return this.extend(t)}setMarkets(e,t){let i=[];this.markets_by_id=this.createSafeDictionary();let s=this.sortBy(this.toArray(e),"spot",!0,!0);for(let e=0;e<s.length;e++){let t=s[e];if(t.id in this.markets_by_id){let e=this.markets_by_id[t.id];e.push(t),this.markets_by_id[t.id]=e}else this.markets_by_id[t.id]=[t];let r={},a=Object.keys(t);for(let e=0;e<a.length;e++){let i=a[e];void 0!==t[i]&&(r[i]=t[i])}let o=this.deepExtend(this.safeMarketStructure(),{precision:this.precision,limits:this.limits},this.fees.trading,r);!0===o.linear?o.subType="linear":!0===o.inverse?o.subType="inverse":o.subType=void 0,i.push(o)}this.markets=this.mapToSafeMap(this.indexBy(i,"symbol"));let r=this.keysort(this.markets),a=this.keysort(this.markets_by_id);this.symbols=Object.keys(r),this.ids=Object.keys(a);let o=0;if(void 0!==t&&(o=Object.keys(t).length),o>0)this.currencies=this.mapToSafeMap(this.deepExtend(this.currencies,t));else{let e=[],t=[];for(let s=0;s<i.length;s++){let r=i[s],a=this.precisionMode===th?8:this.parseNumber("1e-8"),o=this.safeDict(r,"precision",{});if("base"in r){let t=this.safeCurrencyStructure({id:this.safeString2(r,"baseId","base"),numericId:this.safeInteger(r,"baseNumericId"),code:this.safeString(r,"base"),precision:this.safeValue2(o,"base","amount",a)});e.push(t)}if("quote"in r){let e=this.safeCurrencyStructure({id:this.safeString2(r,"quoteId","quote"),numericId:this.safeInteger(r,"quoteNumericId"),code:this.safeString(r,"quote"),precision:this.safeValue2(o,"quote","price",a)});t.push(e)}}e=this.sortBy(e,"code",!1,""),t=this.sortBy(t,"code",!1,""),this.baseCurrencies=this.mapToSafeMap(this.indexBy(e,"code")),this.quoteCurrencies=this.mapToSafeMap(this.indexBy(t,"code"));let s=this.arrayConcat(e,t),r=this.groupBy(s,"code"),a=Object.keys(r),o=[];for(let e=0;e<a.length;e++){let t=a[e],i=this.safeList(r,t,[]),s=this.safeValue(i,0);for(let e=1;e<i.length;e++){let t=i[e],r=this.safeNumber(t,"precision"),a=this.safeNumber(s,"precision");void 0!==r&&void 0!==a&&(this.precisionMode===tl?r<a&&(s=t):r>a&&(s=t))}o.push(s)}let n=this.sortBy(o,"code");this.currencies=this.mapToSafeMap(this.deepExtend(this.currencies,this.indexBy(n,"code")))}this.currencies_by_id=this.indexBySafe(this.currencies,"id");let n=this.keysort(this.currencies);if(this.codes=Object.keys(n),void 0===this.markets)throw new y.ExchangeError(this.id+" setMarkets() markets not set");return this.markets}setMarketsFromExchange(e){if(this.id!==e.id)throw new y.ArgumentsRequired(this.id+" shareMarkets() can only share markets with exchanges of the same type (got "+e.id+")");if(void 0===e.markets||null===e.markets)throw new y.ExchangeError("setMarketsFromExchange() source exchange must have loaded markets first. Can call by using loadMarkets function");this.markets=e.markets,this.markets_by_id=e.markets_by_id,this.symbols=e.symbols,this.ids=e.ids,this.currencies=e.currencies,this.currencies_by_id=e.currencies_by_id,this.baseCurrencies=e.baseCurrencies,this.quoteCurrencies=e.quoteCurrencies,this.codes=e.codes;let t=this.safeList(e.options,"marketHelperProps",[]);for(let i=0;i<t.length;i++){let s=t[i];void 0!==e.options[s]&&(this.options[s]=e.options[s])}return this}getDescribeForExtendedWsExchange(e,t,i){let s=this.deepExtend(t.describe(),e.describe());return this.deepExtend(s,i)}safeBalance(e){let t=Object.keys(this.omit(e,["info","timestamp","datetime","free","used","total"]));e.free={},e.used={},e.total={};let i={};for(let s=0;s<t.length;s++){let r=t[s],a=this.safeString(e[r],"total"),o=this.safeString(e[r],"free"),n=this.safeString(e[r],"used"),d=this.safeString(e[r],"debt");void 0===a&&void 0!==o&&void 0!==n&&(a=b.Y.stringAdd(o,n)),void 0===o&&void 0!==a&&void 0!==n&&(o=b.Y.stringSub(a,n)),void 0===n&&void 0!==a&&void 0!==o&&(n=b.Y.stringSub(a,o)),e[r].free=this.parseNumber(o),e[r].used=this.parseNumber(n),e[r].total=this.parseNumber(a),e.free[r]=e[r].free,e.used[r]=e[r].used,e.total[r]=e[r].total,void 0!==d&&(e[r].debt=this.parseNumber(d),i[r]=e[r].debt)}let s=Object.keys(i).length;return void 0!==s&&0!==s&&(e.debt=i),e}safeOrder(e,t){let i=e;void 0===e&&(i={});let s=this.omitZero(this.safeString(i,"amount")),r=this.safeString(i,"remaining"),a=this.safeString(i,"filled"),o=this.safeString(i,"cost"),n=this.omitZero(this.safeString(i,"average")),d=this.omitZero(this.safeString(i,"price")),h=this.safeInteger(i,"lastTradeTimestamp"),c=this.safeString(i,"symbol"),l=this.safeString(i,"side"),u=this.safeString(i,"status"),f=void 0===a,p=void 0===o,m=void 0===h,g=this.safeValue(i,"fee"),v=void 0===g,y=void 0===this.safeValue(i,"fees"),w=void 0===c,k=void 0===l,S=v||y,O=this.safeList(i,"fees",[]),T=[],P=void 0!==this.safeString(i,"triggerPrice")||void 0!==this.safeString(i,"stopLossPrice")||void 0!==this.safeString(i,"takeProfitPrice");if(f||p||S){let e=this.safeValue(i,"trades",T),s=this.safeValue(e,0);T=void 0!==s&&"info"in s&&"id"in s?e:this.parseTrades(e,t);let r=0,n=Array.isArray(T);if(n&&(r=T.length),n&&r>0){void 0===i.symbol&&(i.symbol=T[0].symbol),void 0===i.side&&(i.side=T[0].side),void 0===i.type&&(i.type=T[0].type),void 0===i.id&&(i.id=T[0].order),f&&(a="0"),p&&(o="0");for(let e=0;e<T.length;e++){let t=T[e],i=this.safeString(t,"amount");f&&void 0!==i&&(a=b.Y.stringAdd(a,i));let s=this.safeString(t,"cost");p&&void 0!==s&&(o=b.Y.stringAdd(o,s)),w&&(c=this.safeString(t,"symbol")),k&&(l=this.safeString(t,"side"));let r=this.safeValue(t,"timestamp");if(m&&void 0!==r&&(h=void 0===h?r:Math.max(h,r)),S){let e=this.safeValue(t,"fees");if(void 0!==e)for(let t=0;t<e.length;t++){let i=e[t];O.push(this.extend({},i))}else{let e=this.safeValue(t,"fee");void 0!==e&&O.push(this.extend({},e))}}}}}if(S){let e=O;this.reduceFees&&(e=this.reduceFeesByCurrency(O)),void 0===e&&(e=[]);let t=e.length;for(let i=0;i<t;i++)e[i].cost=this.safeNumber(e[i],"cost"),"rate"in e[i]&&(e[i].rate=this.safeNumber(e[i],"rate"));if(!v&&0===t){let t=this.deepExtend(g);t.cost=this.safeNumber(t,"cost"),"rate"in t&&(t.rate=this.safeNumber(t,"rate")),e.push(t)}i.fees=e,v&&1===t&&(i.fee=e[0])}void 0===s&&(void 0!==a&&void 0!==r?s=b.Y.stringAdd(a,r):"closed"===u&&(s=a)),void 0===a&&(void 0!==s&&void 0!==r?a=b.Y.stringSub(s,r):"closed"===u&&void 0!==s&&(a=s)),void 0===r&&(void 0!==s&&void 0!==a?r=b.Y.stringSub(s,a):"closed"===u&&(r="0"));let I=this.safeBool(t,"inverse",!1),A=this.numberToString(this.safeValue(t,"contractSize",1));if(void 0===n&&void 0!==a&&void 0!==o&&b.Y.stringGt(a,"0")){let e=b.Y.stringMul(a,A);n=!0===I?b.Y.stringDiv(e,o):b.Y.stringDiv(o,e)}let x=void 0!==n||void 0!==d;if(p&&void 0!==a&&x){let e;e=void 0===n?d:n;let t=b.Y.stringMul(a,A);o=!0===I?b.Y.stringDiv(t,e):b.Y.stringMul(t,e)}let M=this.safeValue(i,"type");(void 0===d||b.Y.stringEquals(d,"0"))&&"market"===M&&(d=n);for(let e=0;e<T.length;e++){let t=T[e];t.amount=this.safeNumber(t,"amount"),t.price=this.safeNumber(t,"price"),t.cost=this.safeNumber(t,"cost");let i=this.safeDict(t,"fee",{});i.cost=this.safeNumber(i,"cost"),"rate"in i&&(i.rate=this.safeNumber(i,"rate"));let s=this.safeList(t,"fees",[]);for(let e=0;e<s.length;e++)s[e].cost=this.safeNumber(s[e],"cost");t.fees=s,t.fee=i}let _=this.safeString(i,"timeInForce"),C=this.safeValue(i,"postOnly");void 0===_?(P||"market"!==this.safeString(i,"type")||(_="IOC"),!0===C&&(_="PO")):void 0===C&&(C="PO"===_);let B=this.safeInteger(i,"timestamp"),E=this.safeInteger(i,"lastUpdateTimestamp"),R=this.safeString(i,"datetime");void 0===R&&(R=this.iso8601(B));let L=this.parseNumber(this.safeString2(i,"triggerPrice","stopPrice")),N=this.parseNumber(this.safeString(i,"takeProfitPrice")),D=this.parseNumber(this.safeString(i,"stopLossPrice"));return this.extend(i,{id:this.safeString(i,"id"),clientOrderId:this.safeString(i,"clientOrderId"),timestamp:B,datetime:R,symbol:c,type:this.safeString(i,"type"),side:l,lastTradeTimestamp:h,lastUpdateTimestamp:E,price:this.parseNumber(d),amount:this.parseNumber(s),cost:this.parseNumber(o),average:this.parseNumber(n),filled:this.parseNumber(a),remaining:this.parseNumber(r),timeInForce:_,postOnly:C,trades:T,reduceOnly:this.safeValue(i,"reduceOnly"),stopPrice:L,triggerPrice:L,takeProfitPrice:N,stopLossPrice:D,status:u,fee:this.safeValue(i,"fee")})}parseOrders(e,t,i,s,r={}){if(void 0===e)return[];let a=[];if(Array.isArray(e))for(let i=0;i<e.length;i++){let s=this.parseOrder(e[i],t),o=this.extend(s,r);a.push(o)}else{let i=Object.keys(e);for(let s=0;s<i.length;s++){let o=i[s],n=this.extend({id:o},e[o]),d=this.parseOrder(n,t),h=this.extend(d,r);a.push(h)}}a=this.sortBy(a,"timestamp");let o=this.safeString(t,"symbol");return this.filterBySymbolSinceLimit(a,o,i,s)}calculateFeeWithRate(e,t,i,s,r,a="taker",o,n={}){let d;if("market"===t&&"maker"===a)throw new y.ArgumentsRequired(this.id+' calculateFee() - you have provided incompatible arguments - "market" type order can not be "maker". Change either the "type" or the "takerOrMaker" argument to calculate the fee.');let h=this.markets;if(void 0===h)throw new y.ExchangeError(this.id+" markets not loaded");let c=h[e],l=this.safeString(c,"feeSide","quote"),u=this.numberToString(s);if("get"===l?"sell"===i:"give"===l?"buy"===i:"quote"===l){let e=this.numberToString(r);u=b.Y.stringMul(u,e),d="quote"}else d="base";!0!==c.spot&&(d="settle");let f="market"===t?"taker":a,p=void 0!==o?this.numberToString(o):this.safeString(c,f);return u=b.Y.stringMul(u,p),{type:f,currency:c[d],rate:this.parseNumber(p),cost:this.parseNumber(u)}}calculateFee(e,t,i,s,r,a="taker",o={}){return this.calculateFeeWithRate(e,t,i,s,r,a,void 0,o)}safeLiquidation(e,t){let i=this.safeString(e,"contracts"),s=this.safeString(t,"contractSize"),r=this.safeString(e,"price"),a=this.safeString(e,"baseValue"),o=this.safeString(e,"quoteValue");return void 0===a&&void 0!==i&&void 0!==s&&void 0!==r&&(a=b.Y.stringMul(i,s)),void 0===o&&void 0!==a&&void 0!==r&&(o=b.Y.stringMul(a,r)),e.contracts=this.parseNumber(i),e.contractSize=this.parseNumber(s),e.price=this.parseNumber(r),e.baseValue=this.parseNumber(a),e.quoteValue=this.parseNumber(o),e}safeTrade(e,t){let i=this.safeString(e,"amount"),s=this.safeString(e,"price"),r=this.safeString(e,"cost");if(void 0===r){let e=this.safeString(t,"contractSize"),a=s;void 0!==e&&(!0===this.safeBool(t,"inverse",!1)&&(a=b.Y.stringDiv("1",s)),a=b.Y.stringMul(a,e)),r=b.Y.stringMul(a,i)}let[a,o]=this.parsedFeeAndFees(e);return e.fee=a,e.fees=o,e.amount=this.parseNumber(i),e.price=this.parseNumber(s),e.cost=this.parseNumber(r),e}createCcxtTradeId(e,t,i,s,r){let a;return void 0!==e&&(a=this.numberToString(e),void 0!==t&&(a+="-"+t),void 0!==i&&(a+="-"+this.numberToString(i)),void 0!==s&&(a+="-"+this.numberToString(s)),void 0!==r&&(a+="-"+r)),a}parsedFeeAndFees(e){let t=this.safeDict(e,"fee"),i=this.safeList(e,"fees"),s=void 0!==t,r=void 0!==i;if(s||r){s&&(t=this.parseFeeNumeric(t)),r||(i=[t]);let e=i;this.reduceFees&&(e=this.reduceFeesByCurrency(i)),void 0===e&&(e=[]);let a=e.length;for(let t=0;t<a;t++)e[t]=this.parseFeeNumeric(e[t]);i=e,1===a?t=e[0]:0===a&&(t=void 0)}return void 0===t&&(t={cost:void 0,currency:void 0}),void 0===i&&(i=[]),[t,i]}parseFeeNumeric(e){return e.cost=this.safeNumber(e,"cost"),"rate"in e&&(e.rate=this.safeNumber(e,"rate")),e}findNearestCeiling(e,t){let i=e.length;for(let s=0;s<i;s++){let i=e[s];if(t<=i)return i}return e[i-1]}addKeyInArrayItems(e,t){let i=[],s=Object.keys(e);for(let r=0;r<s.length;r++){let a=s[r],o=e[a];if(void 0===o)continue;let n=this.extend({},o);n[t]=a,i.push(n)}return i}invertFlatStringDictionary(e){let t={},i=Object.keys(e);for(let s=0;s<i.length;s++){let r=i[s],a=e[r];"string"==typeof a&&(t[a]=r)}return t}stringToBase16(e){return"0x"+this.binaryToBase16(this.base64ToBinary(this.stringToBase64(e)))}reduceFeesByCurrency(e){let t={};for(let i=0;i<e.length;i++){let s=e[i],r=this.safeString(s,"currency"),a=void 0!==r?r:i.toString();if(void 0!==a){let e=this.safeString(s,"rate"),i=this.safeString(s,"cost");if(void 0===i)continue;a in t||(t[a]={});let o=void 0===e?"":e;o in t[a]?t[a][o].cost=b.Y.stringAdd(t[a][o].cost,i):(t[a][o]={currency:r,cost:i},void 0!==e&&(t[a][o].rate=e))}}let i=[],s=Object.values(t);for(let e=0;e<s.length;e++){let t=Object.values(s[e]);i=this.arrayConcat(i,t)}return i}safeTicker(e,t){let i=this.omitZero(this.safeString(e,"open")),s=this.omitZero(this.safeString2(e,"close","last")),r=this.safeString(e,"change"),a=this.omitZero(this.safeString(e,"percentage")),o=this.omitZero(this.safeString(e,"average")),n=this.safeString(e,"vwap"),d=this.safeString(e,"baseVolume"),h=this.safeString(e,"quoteVolume");if(void 0===n&&(n=b.Y.stringDiv(this.omitZero(h),d)),void 0!==r)void 0===s&&void 0!==o&&(s=b.Y.stringAdd(o,b.Y.stringDiv(r,"2"))),void 0===i&&void 0!==s&&(i=b.Y.stringSub(s,r));else if(void 0!==a){if(void 0===s&&void 0!==o){let e=b.Y.stringMul(o,"2"),t=b.Y.stringAdd("2",b.Y.stringDiv(a,"100")),r=void 0!==i?i:b.Y.stringDiv(e,t);s=b.Y.stringMul(r,b.Y.stringAdd("1",b.Y.stringDiv(a,"100")))}void 0===i&&void 0!==s&&(i=b.Y.stringDiv(s,b.Y.stringAdd("1",b.Y.stringDiv(a,"100"))))}if(void 0===r&&(void 0!==s&&void 0!==i?r=b.Y.stringSub(s,i):void 0!==s&&void 0!==a?r=b.Y.stringMul(b.Y.stringDiv(a,"100"),b.Y.stringDiv(s,"100")):void 0!==i&&void 0!==a&&(r=b.Y.stringMul(i,b.Y.stringDiv(a,"100")))),void 0!==i&&(void 0===a&&void 0!==r&&(a=b.Y.stringMul(b.Y.stringDiv(r,i),"100")),void 0===s&&void 0!==r&&(s=b.Y.stringAdd(i,r)),void 0===s&&void 0!==o&&(s=b.Y.stringSub(b.Y.stringMul(o,"2"),i)),void 0===o&&void 0!==s)){let e=18;if(void 0!==t&&this.isTickPrecision()){let i=this.safeDict(t,"precision"),s=this.safeString(i,"price");void 0!==s&&(e=this.precisionFromString(s))}o=b.Y.stringDiv(b.Y.stringAdd(i,s),"2",e)}let c=this.parseNumber(this.omitZero(s));return this.extend(e,{bid:this.parseNumber(this.omitZero(this.safeString(e,"bid"))),bidVolume:this.safeNumber(e,"bidVolume"),ask:this.parseNumber(this.omitZero(this.safeString(e,"ask"))),askVolume:this.safeNumber(e,"askVolume"),high:this.parseNumber(this.omitZero(this.safeString(e,"high"))),low:this.parseNumber(this.omitZero(this.safeString(e,"low"))),open:this.parseNumber(this.omitZero(i)),close:c,last:c,change:this.parseNumber(r),percentage:this.parseNumber(a),average:this.parseNumber(o),vwap:this.parseNumber(n),baseVolume:this.parseNumber(d),quoteVolume:this.parseNumber(h),previousClose:this.safeNumber(e,"previousClose"),indexPrice:this.safeNumber(e,"indexPrice"),markPrice:this.safeNumber(e,"markPrice")})}async fetchBorrowRate(e,t,i={}){throw new y.NotSupported(this.id+" fetchBorrowRate is deprecated, please use fetchCrossBorrowRate or fetchIsolatedBorrowRate instead")}async repayCrossMargin(e,t,i={}){throw new y.NotSupported(this.id+" repayCrossMargin is not support yet")}async repayIsolatedMargin(e,t,i,s={}){throw new y.NotSupported(this.id+" repayIsolatedMargin is not support yet")}async borrowCrossMargin(e,t,i={}){throw new y.NotSupported(this.id+" borrowCrossMargin is not support yet")}async borrowIsolatedMargin(e,t,i,s={}){throw new y.NotSupported(this.id+" borrowIsolatedMargin is not support yet")}async borrowMargin(e,t,i,s={}){throw new y.NotSupported(this.id+" borrowMargin is deprecated, please use borrowCrossMargin or borrowIsolatedMargin instead")}async repayMargin(e,t,i,s={}){throw new y.NotSupported(this.id+" repayMargin is deprecated, please use repayCrossMargin or repayIsolatedMargin instead")}async fetchOHLCV(e,t="1m",i,s,r={}){let a="";throw void 0!==this.has.fetchTrades&&!1!==this.has.fetchTrades&&(a='. If you want to build OHLCV candles from trade executions data, visit https://github.com/ccxt/ccxt/tree/master/examples/ and see "build-ohlcv-bars" file'),new y.NotSupported(this.id+" fetchOHLCV() is not supported yet"+a)}async fetchSpotOHLCV(e,t="1m",i,s,r={}){throw new y.NotSupported(this.id+" fetchSpotOHLCV() is not supported yet")}async fetchContractOHLCV(e,t="1m",i,s,r={}){throw new y.NotSupported(this.id+" fetchContractOHLCV() is not supported yet")}async fetchOHLCVWs(e,t="1m",i,s,r={}){let a="";throw void 0!==this.has.fetchTradesWs&&!1!==this.has.fetchTradesWs&&(a='. If you want to build OHLCV candles from trade executions data, visit https://github.com/ccxt/ccxt/tree/master/examples/ and see "build-ohlcv-bars" file'),new y.NotSupported(this.id+" fetchOHLCVWs() is not supported yet. Try using fetchOHLCV instead."+a)}async watchOHLCV(e,t="1m",i,s,r={}){throw new y.NotSupported(this.id+" watchOHLCV() is not supported yet")}convertTradingViewToOHLCV(e,t="t",i="o",s="h",r="l",a="c",o="v",n=!1){let d=[],h=this.safeList(e,t,[]),c=this.safeList(e,i,[]),l=this.safeList(e,s,[]),u=this.safeList(e,r,[]),f=this.safeList(e,a,[]),p=this.safeList(e,o,[]);for(let e=0;e<h.length;e++)d.push([n?this.safeInteger(h,e):this.safeTimestamp(h,e),this.safeValue(c,e),this.safeValue(l,e),this.safeValue(u,e),this.safeValue(f,e),this.safeValue(p,e)]);return d}convertOHLCVToTradingView(e,t="t",i="o",s="h",r="l",a="c",o="v",n=!1){let d={};d[t]=[],d[i]=[],d[s]=[],d[r]=[],d[a]=[],d[o]=[];for(let h=0;h<e.length;h++){let c=n?e[h][0]:this.parseToInt(e[h][0]/1e3);d[t].push(c),d[i].push(e[h][1]),d[s].push(e[h][2]),d[r].push(e[h][3]),d[a].push(e[h][4]),d[o].push(e[h][5])}return d}async fetchWebEndpoint(e,t,i,s,r){let a="",o=this.safeValue(this.options,e,{}),n=this.safeBool(o,"webApiMuteFailure",!0);try{let e;if(!this.safeBool(o,"webApiEnable",!0))return;let a=this.safeInteger(o,"webApiRetries",10),n=0,d=!1;for(;n<a;){try{e=await this[t]({}),d=!0;break}catch(e){if((n+=1)===a)throw e}if(d)break}let h=e;if(void 0===h||(void 0!==s&&(h=h.split(s)[1]),void 0===h))throw new y.NullResponse(this.id+" fetchWebEndpoint() returned empty content");if(void 0!==r&&(h=h.split(r)[0]),!0!==i||"string"!=typeof h)return h;{let e=this.parseJson(h.trim());if(null!=e)return e;throw new y.BadResponse("could not parse the response into json")}}catch(t){a=this.id+" "+e+"() failed to fetch correct data from website. Probably webpage markup has been changed, breaking the page custom parser."}if(!0!==n)throw new y.BadResponse(a)}marketIds(e){if(void 0===e)return e;let t=[];for(let i=0;i<e.length;i++){let s=this.marketId(e[i]);void 0!==s&&t.push(s)}return t}currencyIds(e){if(void 0===e)return e;let t=[];for(let i=0;i<e.length;i++){let s=this.currencyId(e[i]);void 0!==s&&t.push(s)}return t}marketsForSymbols(e){if(void 0===e)return;let t=[];for(let i=0;i<e.length;i++)t.push(this.market(e[i]));return t}marketSymbols(e,t,i=!0,s=!1,r=!1){let a,o;if(void 0===e||0===e.length){if(!i)throw new y.ArgumentsRequired(this.id+" empty list of symbols is not supported");return e}let n=[];for(let i=0;i<e.length;i++){let d=this.market(e[i]);if(s&&void 0!==a&&d.type!==a)throw new y.BadRequest(this.id+" symbols must be of the same type, either "+a+" or "+d.type+".");if(r&&void 0!==o&&d.linear!==o)throw new y.BadRequest(this.id+" symbols must be of the same subType, either linear or inverse.");if(void 0!==t&&d.type!==t)throw new y.BadRequest(this.id+" symbols must be of the same type "+t+". If the type is incorrect you can change it in options or the params of the request");a=this.safeString(d,"type"),!0!==d.spot&&(o=this.safeBool(d,"linear"));let h=this.safeString(d,"symbol",e[i]);n.push(h)}return n}marketCodes(e){if(void 0===e)return e;let t=[];for(let i=0;i<e.length;i++)t.push(this.commonCurrencyCode(e[i]));return t}parseOrderBookBidsAsks(e,t=0,i=1,s=2){let r=this.toArray(e),a=[];for(let e=0;e<r.length;e++)a.push(this.parseOrderBookBidAsk(r[e],t,i,s));return a}filterByKey(e,t,i){if(void 0===i)return e;let s=[];for(let r=0;r<e.length;r++)this.safeString(e[r],t)===i&&s.push(e[r]);return s}filterBySymbol(e,t){return this.filterByKey(e,"symbol",t)}parseOHLCV(e,t){return Array.isArray(e)?[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]:e}safeNetwork(e){let t=this.safeBool(e,"withdraw"),i=this.safeBool(e,"deposit"),s=this.safeDict(e,"limits"),r=this.safeDict(s,"withdraw"),a=this.safeDict(s,"deposit"),o=t;return!0===t&&(o=i),{info:e.info,id:this.safeString(e,"id"),name:this.safeString(e,"name"),network:this.safeString(e,"network"),active:this.safeBool(e,"active",o),deposit:i,withdraw:t,fee:this.safeNumber(e,"fee"),precision:this.safeNumber(e,"precision"),limits:{withdraw:{min:this.safeNumber(r,"min"),max:this.safeNumber(r,"max")},deposit:{min:this.safeNumber(a,"min"),max:this.safeNumber(a,"max")}}}}prioritizedNetworkAliases(e,t,i=!1){if(void 0===e)return;let s=this.safeDict(this.options,"defaultNetworkCodeReplacements",{}),r=Object.keys(s);for(let a=0;a<r.length;a++){let o=r[a],n=s[o],d=n.primary,h=n.secondary;if(e===d||e===h)return t===o||void 0===t&&(i?"primary"===n.default:e===d)?[d,h]:[h,d]}return[e,e]}networkCodeToId(e,t){if(void 0===e)return;let i=this.safeDict(this.options,"networks",{}),s=this.prioritizedNetworkAliases(e,t,!1),r=void 0===s?e:s[0],a=void 0===s?e:s[1],o=this.safeString2(i,r,a);if(void 0!==o)return o;let n=[];n=void 0===t?Object.keys(this.currencies):[this.safeDict(this.currencies,t)];for(let t=0;t<n.length;t++){let i=this.safeDict(n[t],"networks",{});if(e in i)return this.safeString(i[e],"id")}let d=this.safeDict(this.options,"backwardSupportedNetworkCodes",{});return e in d?this.networkCodeToId(d[e],t):e}networkIdToCode(e,t){if(void 0===e)return;let i=this.safeDict(this.options,"networksById",{}),s=this.safeString(i,e,e),r=this.prioritizedNetworkAliases(s,t,!0);if(void 0===r)return s;let a=r[0],o=r[1];if(void 0===t){let e=this.safeDict(this.options,"networks",{});if(a in e&&o in e)return s}return a}handleNetworkCodeAndParams(e){let t=this.safeString2(e,"networkCode","network"),i=void 0!==t?this.omit(e,["networkCode","network"]):e;return[t,i]}defaultNetworkCode(e){let t,i=this.safeDict(this.options,"defaultNetworks",{});if(e in i)t=i[e];else{let e=this.safeString(this.options,"defaultNetwork");void 0!==e&&(t=e)}return t}selectNetworkCodeFromUnifiedNetworks(e,t,i){return this.selectNetworkKeyFromNetworks(e,t,i,!0)}selectNetworkIdFromRawNetworks(e,t,i){return this.selectNetworkKeyFromNetworks(e,t,i,!1)}selectNetworkKeyFromNetworks(e,t,i,s=!1){let r,a=Object.keys(i),o=a.length;if(void 0!==t)if(0===o)throw new y.NotSupported(this.id+" - "+t+" network did not return any result for "+e);else{let o=s?t:this.networkCodeToId(t,e);if(void 0===o)throw new y.NotSupported(this.id+" - "+t+" network was not found for "+e);if(o in i)r=o;else throw new y.NotSupported(this.id+" - "+o+" network was not found for "+e+", use one of "+a.join(", "))}else if(0===o)throw new y.NotSupported(this.id+" - no networks were returned for "+e);else{let t=this.defaultNetworkCode(e),r=s?t:this.networkCodeToId(t,e);if(void 0===r)throw new y.ExchangeError(this.id+" selectNetworkKeyFromNetworks() missing defaultNetworkId");if(r in i)return r;throw new y.NotSupported(this.id+' - can not determine the default network, please pass param["network"] one from : '+a.join(", "))}return r}safeNumber2(e,t,i,s){let r=this.safeString2(e,t,i);return this.parseNumber(r,s)}parseOrderBook(e,t,i,s="bids",r="asks",a=0,o=1,n=2){let d=this.parseOrderBookBidsAsks(this.safeValue(e,s,[]),a,o,n),h=this.parseOrderBookBidsAsks(this.safeValue(e,r,[]),a,o,n);return{symbol:t,bids:this.sortBy(d,0,!0),asks:this.sortBy(h,0),timestamp:i,datetime:this.iso8601(i),nonce:void 0}}parseOHLCVs(e,t,i="1m",s,r,a=!1){if(void 0===e)return[];let o=[];for(let i=0;i<e.length;i++)o.push(this.parseOHLCV(e[i],t));let n=this.sortBy(o,0);return this.filterBySinceLimit(n,s,r,0,a)}parseLeverageTiers(e,t,i){let s=this.marketSymbols(t),r={},a=0;void 0!==s&&(a=s.length);let o=void 0===s||0===a;if(Array.isArray(e))for(let t=0;t<e.length;t++){let a=e[t],n=void 0===i?void 0:this.safeString(a,i),d=this.safeMarket(n,void 0,void 0,"swap"),h=d.symbol;!0===this.safeBool(d,"contract",!1)&&(o||void 0!==s&&this.inArray(h,s))&&(r[h]=this.parseMarketLeverageTiers(a,d))}else{let t=Object.keys(e);for(let i=0;i<t.length;i++){let a=t[i],n=e[a],d=this.safeMarket(a,void 0,void 0,"swap"),h=d.symbol;!0===this.safeBool(d,"contract",!1)&&(o||void 0!==s&&this.inArray(h,s))&&(r[h]=this.parseMarketLeverageTiers(n,d))}}return r}async loadTradingLimits(e,t=!1,i={}){if(void 0!==this.has.fetchTradingLimits&&!1!==this.has.fetchTradingLimits&&(t||!("limitsLoaded"in this.options))){let t=await this.fetchTradingLimits(e),i=this.requireValue(e,"loadTradingLimits() requires a symbols argument"),s=this.markets;if(void 0===s)throw new y.ExchangeError(this.id+" markets not loaded");for(let e=0;e<i.length;e++){let r=i[e];s[r]=this.deepExtend(s[r],t[r])}this.options.limitsLoaded=this.milliseconds()}return this.markets}safePosition(e){let t,i=this.safeString(e,"unrealizedPnl"),s=this.safeString(e,"initialMargin");if(void 0===this.safeValue(e,"percentage")&&void 0!==i&&void 0!==s){let t=b.Y.stringMul(b.Y.stringDiv(i,s,4),"100");e.percentage=this.parseNumber(t)}let r=this.safeNumber(e,"contractSize"),a=this.safeString(e,"symbol");return void 0!==a&&(t=this.safeValue(this.markets,a)),void 0===r&&void 0!==t&&(e.contractSize=r=this.safeNumber(t,"contractSize")),e}parsePositions(e,t,i={}){let s=this.marketSymbols(t),r=this.toArray(e),a=[];for(let e=0;e<r.length;e++){let t=this.extend(this.parsePosition(r[e]),i);a.push(t)}return this.filterByArrayPositions(a,"symbol",s)}parseADLRank(e,t){throw new y.NotSupported(this.id+" parseADLRank() is not supported yet")}parseADLRanks(e,t,i={}){let s=this.marketSymbols(t),r=this.toArray(e),a=[];for(let e=0;e<r.length;e++){let t=this.extend(this.parseADLRank(r[e]),i);a.push(t)}return this.filterByArrayPositions(a,"symbol",s)}parseAccounts(e,t={}){let i=this.toArray(e),s=[];for(let e=0;e<i.length;e++){let r=this.extend(this.parseAccount(i[e]),t);s.push(r)}return s}parseTradesHelper(e,t,i,s,r,a={}){let o=this.toArray(t),n=[];for(let t=0;t<o.length;t++){let s;s=e?this.parseWsTrade(o[t],i):this.parseTrade(o[t],i);let r=this.extend(s,a);n.push(r)}n=this.sortBy2(n,"timestamp","id");let d=this.safeString(i,"symbol");return this.filterBySymbolSinceLimit(n,d,s,r)}parseTrades(e,t,i,s,r={}){return this.parseTradesHelper(!1,e,t,i,s,r)}parseWsTrades(e,t,i,s,r={}){return this.parseTradesHelper(!0,e,t,i,s,r)}parseTransactions(e,t,i,s,r={}){let a=this.toArray(e),o=[];for(let e=0;e<a.length;e++){let i=this.extend(this.parseTransaction(a[e],t),r);o.push(i)}o=this.sortBy(o,"timestamp");let n=void 0!==t?t.code:void 0;return this.filterByCurrencySinceLimit(o,n,i,s)}parseTransfers(e,t,i,s,r={}){let a=this.toArray(e),o=[];for(let e=0;e<a.length;e++){let i=this.extend(this.parseTransfer(a[e],t),r);o.push(i)}o=this.sortBy(o,"timestamp");let n=void 0!==t?t.code:void 0;return this.filterByCurrencySinceLimit(o,n,i,s)}parseLedger(e,t,i,s,r={}){let a=[],o=this.toArray(e);for(let e=0;e<o.length;e++){let i=this.parseLedgerEntry(o[e],t);if(Array.isArray(i))for(let e=0;e<i.length;e++)a.push(this.extend(i[e],r));else a.push(this.extend(i,r))}a=this.sortBy(a,"timestamp");let n=void 0!==t?t.code:void 0;return this.filterByCurrencySinceLimit(a,n,i,s)}nonce(){return this.seconds()}incrementingNonce(){let e=this.nonce();this.lockLastNonce();let t=this.safeInteger(this.options,"lastNonce",0),i=e>t?e:t+1;return this.options.lastNonce=i,this.unlockLastNonce(),i}setHeaders(e){return e}currencyId(e){if(void 0===e)return e;let t=this.safeDict(this.currencies,e);return(void 0===t&&(t=this.safeCurrency(e)),void 0!==t)?t.id:e}marketId(e){let t=this.market(e);return void 0!==t?t.id:e}symbol(e){if(void 0===e)throw new y.ArgumentsRequired(this.id+" symbol() requires a symbol argument");let t=this.market(e);return this.safeString(t,"symbol",e)}handleParamString(e,t,i){let s=this.safeString(e,t,i),r=void 0!==s?this.omit(e,t):e;return[s,r]}handleParamString2(e,t,i,s){let r=this.safeString2(e,t,i,s),a=void 0!==r?this.omit(e,[t,i]):e;return[r,a]}handleParamInteger(e,t,i){let s=this.safeInteger(e,t,i),r=void 0!==s?this.omit(e,t):e;return[s,r]}handleParamInteger2(e,t,i,s){let r=this.safeInteger2(e,t,i,s),a=void 0!==r?this.omit(e,[t,i]):e;return[r,a]}handleParamBool(e,t,i){let s=this.safeBool(e,t,i),r=void 0!==s?this.omit(e,t):e;return[s,r]}handleParamBool2(e,t,i,s){let r=this.safeBool2(e,t,i,s),a=void 0!==r?this.omit(e,[t,i]):e;return[r,a]}handleRequestNetwork(e,t,i,s,r=!1){let[a,o]=this.handleNetworkCodeAndParams(e);if(void 0!==a)t[i]=this.networkCodeToId(a,s);else if(r)throw new y.ArgumentsRequired(this.id+' - "network" param is required for this request');return[t,o]}resolvePath(e,t){return[this.implodeParams(e,t),this.omit(t,this.extractParams(e))]}getListFromObjectValues(e,t){let i=e;Array.isArray(e)||(i=this.toArray(e));let s=[];for(let e=0;e<i.length;e++)s.push(i[e][t]);return s}getSymbolsForMarketType(e,t,i=!0,s=!0){let r=this.markets;void 0!==e&&(r=this.filterBy(r,"type",e)),void 0!==t&&(this.checkRequiredArgument("getSymbolsForMarketType",t,"subType",["linear","inverse","quanto"]),r=this.filterBy(r,"subType",t));let a=[];return i&&a.push(!0),s&&a.push(void 0),r=this.filterByArray(r,"active",a,!1),this.getListFromObjectValues(r,"symbol")}filterByArray(e,t,i,s=!0){let r=this.toArray(e);if(null==i||!1===i||0===i||""===i)if(s)return this.indexBy(r,t);else return r;let a=[];for(let e=0;e<r.length;e++)this.inArray(r[e][t],i)&&a.push(r[e]);return s?this.indexBy(a,t):a}filterOutByArray(e,t,i,s=!0){let r=this.toArray(e);if(null==i||!1===i||0===i||""===i)if(s)return this.indexBy(r,t);else return r;let a=[];for(let e=0;e<r.length;e++)this.inArray(r[e][t],i)||a.push(r[e]);return s?this.indexBy(a,t):a}async fetch2(e,t="public",i="GET",s={},r,a,o={}){if(this.enableRateLimit){let r=this.calculateRateLimiterCost(t,i,e,s,o);await this.throttle(r)}let[n,d]=this.handleOptionIntegerAndParams(s,e,"maxRetriesOnFailure",0),[h,c]=this.handleOptionIntegerAndParams(d,e,"maxRetriesOnFailureDelay",0),l=this.fetchHistoryCacheSize>0;for(let s=0;s<n+1;s++){let o;l&&(o={request:void 0,response:{body:void 0},error:void 0});try{this.setLastRestRequestTimestamp();let s=this.sign(e,t,i,c,r,a);void 0!==o&&(o.request=s),this.setLastRequest(s);let n=await this.fetch(s.url,s.method,s.headers,s.body);return void 0!==o&&(o.response.body=n,this.addFetchCache(o)),n}catch(e){if(void 0!==o&&(o.error=e,this.addFetchCache(o)),e instanceof y.OperationFailed)if(s<n){if(this.verbose){let t=s+1;this.log("Request failed with the error: "+e.toString()+", retrying "+t.toString()+" of "+n.toString()+"...")}void 0!==h&&0!==h&&await this.sleep(h)}else throw e;else throw e}}}async request(e,t="public",i="GET",s={},r,a,o={}){return await this.fetch2(e,t,i,s,r,a,o)}async loadAccounts(e=!1,t={}){if(e)this.accounts=await this.fetchAccounts(t);else{if(void 0!==this.accounts)return this.accounts;this.accounts=await this.fetchAccounts(t)}return this.accountsById=this.indexBy(this.accounts,"id"),this.accounts}buildOHLCVC(e,t="1m",i=0,s=0x7fffffff){let r=1e3*this.parseTimeframe(t),a=[],o=Math.min(e.length,s),n=this.safeDict(this.options,"buildOHLCVC",{}),d=this.safeBool(n,"skipZeroPrices",!0);for(let t=0;t<o;t++){let s=e[t],o=s.timestamp,n=s.price;if(void 0===o||void 0===n||o<i)continue;if(void 0===o)throw new y.ExchangeError(this.id+" buildOHLCVC() missing ts");let h=Math.floor(o/r)*r;if(h<i)continue;let c=a.length-1;if(void 0===n)throw new y.ArgumentsRequired(this.id+" buildOHLCVC() requires a price argument");if(!0===d&&!(n>0)&&!(n<0))continue;let l=-1===c;if(!l){let e=a[c][0];if(void 0===e)throw new y.ExchangeError(this.id+" buildOHLCVC() missing candle timestamp");l=h>=e+r}if(l)a.push([h,n,n,n,n,s.amount,1]);else{let e=a[c][2],t=a[c][3],i=void 0===e?n:e,r=void 0===t?n:t;a[c][2]=Math.max(i,n),a[c][3]=Math.min(r,n),a[c][4]=n,a[c][5]=this.sum(a[c][5],s.amount),a[c][6]=this.sum(a[c][6],1)}}return a}parseTradingViewOHLCV(e,t,i="1m",s,r){let a=this.convertTradingViewToOHLCV(e);return this.parseOHLCVs(a,t,i,s,r)}async fetchBorrowInterest(e,t,i,s,r={}){throw new y.NotSupported(this.id+" fetchBorrowInterest() is not supported yet")}async fetchLedger(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchLedger() is not supported yet")}async fetchLedgerEntry(e,t,i={}){throw new y.NotSupported(this.id+" fetchLedgerEntry() is not supported yet")}parseOrderBookBidAsk(e,t=0,i=1,s=2){let r=this.safeFloat(e,t),a=this.safeFloat(e,i),o=this.safeInteger(e,s),n=[r,a];return void 0!==o&&n.push(o),n}safeCurrency(e,t){if(void 0===e&&void 0!==t)return t;if(void 0!==e&&void 0!==this.currencies_by_id&&e in this.currencies_by_id&&void 0!==this.currencies_by_id[e])return this.currencies_by_id[e];let i=e;return void 0!==e&&(i=this.commonCurrencyCode(e.toUpperCase())),this.safeCurrencyStructure({id:e,code:i,precision:void 0})}safeMarket(e,t,i,s){if(void 0!==e){if(void 0!==this.markets_by_id&&e in this.markets_by_id){let i=this.markets_by_id[e];if(1===i.length)return i[0];{if(void 0===s&&void 0===t)throw new y.ArgumentsRequired(this.id+" safeMarket() requires a fourth argument for "+e+" to disambiguate between different markets with the same market id");let r=void 0===s?this.safeString(t,"type",""):s;for(let e=0;e<i.length;e++){let t=i[e];if(!0===t[r])return t}}}else if(void 0!==i&&""!==i){let t=e.split(i),s=t.length,r=this.safeMarketStructure({symbol:e,marketId:e});if(void 0===r)throw new y.ExchangeError(this.id+" safeMarket() failed to build market structure");if(2===s){let e=this.safeString(t,0),i=this.safeString(t,1),s=this.safeCurrencyCode(e),a=this.safeCurrencyCode(i);r.baseId=e,r.quoteId=i,void 0!==s&&(r.base=s),void 0!==a&&(r.quote=a),void 0!==s&&void 0!==a&&(r.symbol=s+"/"+a)}return r}}if(void 0!==t)return t;let r=this.safeMarketStructure({symbol:e,marketId:e});if(void 0===r)throw new y.ExchangeError(this.id+" safeMarket() failed to build market structure");return r}marketOrNull(e){if(void 0!==e)return this.market(e)}checkRequiredCredentials(e=!0){let t=Object.keys(this.requiredCredentials);for(let i=0;i<t.length;i++){let s=t[i],r=this[s],a=null==r||!1===r||""===r;if(!0===this.requiredCredentials[s]&&a)if(!e)return!1;else throw new y.AuthenticationError(this.id+' requires "'+s+'" credential')}return!0}oath(){if(void 0!==this.twofa)return(0,O.O)(this.twofa);throw new y.ExchangeError(this.id+" exchange.twofa has not been set for 2FA Two-Factor Authentication")}async fetchBalance(e={}){throw new y.NotSupported(this.id+" fetchBalance() is not supported yet")}async fetchBalanceWs(e={}){throw new y.NotSupported(this.id+" fetchBalanceWs() is not supported yet")}parseBalance(e){throw new y.NotSupported(this.id+" parseBalance() is not supported yet")}async watchBalance(e={}){throw new y.NotSupported(this.id+" watchBalance() is not supported yet")}async fetchPartialBalance(e,t={}){return(await this.fetchBalance(t))[e]}async fetchFreeBalance(e={}){return await this.fetchPartialBalance("free",e)}async fetchUsedBalance(e={}){return await this.fetchPartialBalance("used",e)}async fetchTotalBalance(e={}){return await this.fetchPartialBalance("total",e)}async fetchStatus(e={}){throw new y.NotSupported(this.id+" fetchStatus() is not supported yet")}async fetchTransactionFee(e,t={}){if(void 0===this.has.fetchTransactionFees||!1===this.has.fetchTransactionFees)throw new y.NotSupported(this.id+" fetchTransactionFee() is not supported yet");return await this.fetchTransactionFees([e],t)}async fetchTransactionFees(e,t={}){throw new y.NotSupported(this.id+" fetchTransactionFees() is not supported yet")}async fetchDepositWithdrawFees(e,t={}){throw new y.NotSupported(this.id+" fetchDepositWithdrawFees() is not supported yet")}async fetchDepositWithdrawFee(e,t={}){if(void 0===this.has.fetchDepositWithdrawFees||!1===this.has.fetchDepositWithdrawFees)throw new y.NotSupported(this.id+" fetchDepositWithdrawFee() is not supported yet");let i=await this.fetchDepositWithdrawFees([e],t);return this.safeValue(i,e)}getSupportedMapping(e,t={}){if(void 0===e)throw new y.ArgumentsRequired(this.id+" getSupportedMapping() requires a key argument");if(e in t)return t[e];{let i=Object.keys(t);throw new y.NotSupported(this.id+" "+e+" does not have a value in mapping, must be one of "+i.join(", "))}}async fetchCrossBorrowRate(e,t={}){if(await this.loadMarkets(),void 0===this.has.fetchBorrowRates||!1===this.has.fetchBorrowRates)throw new y.NotSupported(this.id+" fetchCrossBorrowRate() is not supported yet");let i=await this.fetchCrossBorrowRates(t),s=this.safeDict(i,e);if(void 0===s)throw new y.ExchangeError(this.id+" fetchCrossBorrowRate() could not find the borrow rate for currency code "+e);return s}async fetchIsolatedBorrowRate(e,t={}){if(await this.loadMarkets(),void 0===this.has.fetchBorrowRates||!1===this.has.fetchBorrowRates)throw new y.NotSupported(this.id+" fetchIsolatedBorrowRate() is not supported yet");let i=await this.fetchIsolatedBorrowRates(t),s=this.safeDict(i,e);if(void 0===s)throw new y.ExchangeError(this.id+" fetchIsolatedBorrowRate() could not find the borrow rate for market symbol "+e);return s}requireValue(e,t){if(void 0===e)throw new y.ArgumentsRequired(this.id+" "+(void 0!==t?t:"value is required"));return e}handleOptionAndParams(e,t,i,s){let r="default"+this.capitalize(i),a=this.safeValue2(e,i,r);if(void 0!==a)return[a,this.omit(e,[i,r])];{let[o,n]=this.handleParamString(e,"callerMethodName",t),d=this.safeValue(this.options,o);return void 0!==d&&(a=this.safeValue2(d,i,r)),void 0===a&&(a=this.safeValue2(this.options,i,r)),[a=void 0!==a?a:s,n]}}handleOptionAndParams2(e,t,i,s,r){let[a,o]=this.handleOptionAndParams(e,t,i);return void 0!==a?[a,this.omit(o,s)]:this.handleOptionAndParams(o,t,s,r)}handleOptionStringAndParams(e,t,i,s){let[r,a]=this.handleOptionAndParams(e,t,i,s);return[this.checkOptionString(t,i,r),a]}handleOptionStringAndParams2(e,t,i,s,r){let[a,o]=this.handleOptionAndParams2(e,t,i,s,r);return[this.checkOptionString(t,i,a),o]}handleOptionBoolAndParams(e,t,i,s){let[r,a]=this.handleOptionAndParams(e,t,i,s);return[this.checkOptionBool(t,i,r),a]}handleOptionBoolAndParams2(e,t,i,s,r){let[a,o]=this.handleOptionAndParams2(e,t,i,s,r);return[this.checkOptionBool(t,i,a),o]}handleOptionIntegerAndParams(e,t,i,s){let[r,a]=this.handleOptionAndParams(e,t,i,s);return[this.checkOptionInteger(t,i,r),a]}handleOptionIntegerAndParams2(e,t,i,s,r){let[a,o]=this.handleOptionAndParams2(e,t,i,s,r);return[this.checkOptionInteger(t,i,a),o]}handleOption(e,t,i){let s=this.handleOptionAndParams({},e,t,i);return this.safeValue(s,0)}handleMarketTypeAndParams(e,t,i={},s){let r=this.safeString2(i,"defaultType","type");if(void 0!==r)return[r,this.omit(i,["defaultType","type"])];if(void 0!==t)return[t.type,i];if(void 0!==s)return[s,i];let a=this.safeDict(this.options,e);if(void 0!==a)if("string"==typeof a)return[a,i];else{let e=this.safeString2(a,"defaultType","type");if(void 0!==e)return[e,i]}return[this.safeString2(this.options,"defaultType","type","spot"),i]}handleSubTypeAndParams(e,t,i={},s){let r,a=this.safeString2(i,"subType","defaultSubType");return void 0!==a?(("linear"===a||"inverse"===a)&&(r=a),[r,this.omit(i,["subType","defaultSubType"])]):(void 0!==t&&(!0===t.linear?r="linear":!0===t.inverse&&(r="inverse")),void 0===r&&(r=this.handleOptionAndParams({},e,"subType",s)[0]),[r,i])}handleMarginModeAndParams(e,t={},i){return this.handleOptionStringAndParams(t,e,"marginMode",i)}throwExactlyMatchedException(e,t,i){if(void 0!==t&&t in e)throw new e[t](i)}throwBroadlyMatchedException(e,t,i){let s=this.findBroadlyMatchedKey(e,t);if(void 0!==s)throw new e[s](i)}findBroadlyMatchedKey(e,t){let i=Object.keys(e);for(let e=0;e<i.length;e++){let s=i[e];if(void 0!==t&&t.indexOf(s)>=0)return s}}handleErrors(e,t,i,s,r,a,o,n,d){}calculateRateLimiterCost(e,t,i,s,r={}){return this.safeValue(r,"cost",1)}async fetchSpotTickers(e,t={}){throw new y.NotSupported(this.id+" fetchSpotTickers() is not supported yet")}async fetchContractTickers(e,t={}){throw new y.NotSupported(this.id+" fetchContractTickers() is not supported yet")}async fetchOrderBooks(e,t,i={}){throw new y.NotSupported(this.id+" fetchOrderBooks() is not supported yet")}async unWatchTickers(e,t={}){throw new y.NotSupported(this.id+" unWatchTickers() is not supported yet")}async unWatchFundingRate(e,t={}){throw new y.NotSupported(this.id+" unWatchFundingRate() is not supported yet")}async createTwapOrder(e,t,i,s,r={}){throw new y.NotSupported(this.id+" createTwapOrder() is not supported yet")}async createConvertTrade(e,t,i,s,r={}){throw new y.NotSupported(this.id+" createConvertTrade() is not supported yet")}async fetchConvertTrade(e,t,i={}){throw new y.NotSupported(this.id+" fetchConvertTrade() is not supported yet")}async fetchConvertTradeHistory(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchConvertTradeHistory() is not supported yet")}async fetchPositionMode(e,t={}){throw new y.NotSupported(this.id+" fetchPositionMode() is not supported yet")}async fetchADLRank(e,t={}){throw new y.NotSupported(this.id+" fetchADLRank() is not supported yet")}async fetchPositionsADLRank(e,t={}){throw new y.NotSupported(this.id+" fetchPositionsADLRank() is not supported yet")}async fetchPositionADLRank(e,t={}){if(void 0!==this.has.fetchPositionsADLRank&&!1!==this.has.fetchPositionsADLRank){await this.loadMarkets();let i=this.market(e).symbol,s=await this.fetchPositionsADLRank([i],t),r=this.safeDict(s,0);if(void 0!==r)return r;throw new y.NullResponse(this.id+" fetchPositionsADLRank() could not find a rank for "+i)}throw new y.NotSupported(this.id+" fetchPositionsADLRank() is not supported yet")}setTakeProfitAndStopLossParams(e,t,i,s,r,a,o,n={}){if(void 0===a&&void 0===o)throw new y.ArgumentsRequired(this.id+" createOrderWithTakeProfitAndStopLoss() requires either a takeProfit or stopLoss argument");void 0!==a&&(n.takeProfit={triggerPrice:a}),void 0!==o&&(n.stopLoss={triggerPrice:o});let d=this.safeString(n,"takeProfitType"),h=this.safeString(n,"takeProfitPriceType"),c=this.safeString(n,"takeProfitLimitPrice"),l=this.safeString(n,"takeProfitAmount"),u=this.safeString(n,"stopLossType"),f=this.safeString(n,"stopLossPriceType"),p=this.safeString(n,"stopLossLimitPrice"),m=this.safeString(n,"stopLossAmount");return void 0!==d&&(n.takeProfit.type=d),void 0!==h&&(n.takeProfit.priceType=h),void 0!==c&&(n.takeProfit.price=this.parseToNumeric(c)),void 0!==l&&(n.takeProfit.amount=this.parseToNumeric(l)),void 0!==u&&(n.stopLoss.type=u),void 0!==f&&(n.stopLoss.priceType=f),void 0!==p&&(n.stopLoss.price=this.parseToNumeric(p)),void 0!==m&&(n.stopLoss.amount=this.parseToNumeric(m)),this.omit(n,["takeProfitType","takeProfitPriceType","takeProfitLimitPrice","takeProfitAmount","stopLossType","stopLossPriceType","stopLossLimitPrice","stopLossAmount"])}async createSpotOrders(e,t={}){throw new y.NotSupported(this.id+" createSpotOrders() is not supported yet")}async createContractOrders(e,t={}){throw new y.NotSupported(this.id+" createContractOrders() is not supported yet")}async cancelSpotOrder(e,t,i={}){throw new y.NotSupported(this.id+" cancelSpotOrder() is not supported yet")}async cancelContractOrder(e,t,i={}){throw new y.NotSupported(this.id+" cancelContractOrder() is not supported yet")}async cancelAllSpotOrders(e,t={}){throw new y.NotSupported(this.id+" cancelAllSpotOrders() is not supported yet")}async cancelAllContractOrders(e,t={}){throw new y.NotSupported(this.id+" cancelAllContractOrders() is not supported yet")}async cancelAllOrdersAfter(e,t={}){throw new y.NotSupported(this.id+" cancelAllOrdersAfter() is not supported yet")}async cancelOrdersForSymbols(e,t={}){throw new y.NotSupported(this.id+" cancelOrdersForSymbols() is not supported yet")}async fetchMyLiquidations(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchMyLiquidations() is not supported yet")}async fetchLiquidations(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchLiquidations() is not supported yet")}async fetchGreeks(e,t={}){throw new y.NotSupported(this.id+" fetchGreeks() is not supported yet")}async fetchAllGreeks(e,t={}){throw new y.NotSupported(this.id+" fetchAllGreeks() is not supported yet")}async fetchOptionChain(e,t={}){throw new y.NotSupported(this.id+" fetchOptionChain() is not supported yet")}async fetchOption(e,t={}){throw new y.NotSupported(this.id+" fetchOption() is not supported yet")}async fetchConvertQuote(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchConvertQuote() is not supported yet")}async fetchDepositsWithdrawals(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchDepositsWithdrawals() is not supported yet")}async fetchDeposits(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchDeposits() is not supported yet")}async fetchWithdrawals(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchWithdrawals() is not supported yet")}async fetchDepositsWs(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchDepositsWs() is not supported yet")}async fetchWithdrawalsWs(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchWithdrawalsWs() is not supported yet")}async fetchFundingRateHistory(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchFundingRateHistory() is not supported yet")}async fetchFundingHistory(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchFundingHistory() is not supported yet")}parseLastPrice(e,t){throw new y.NotSupported(this.id+" parseLastPrice() is not supported yet")}async fetchDepositAddress(e,t={}){if(void 0!==this.has.fetchDepositAddresses&&!1!==this.has.fetchDepositAddresses){let i=await this.fetchDepositAddresses([e],t),s=this.safeValue(i,e);if(void 0!==s)return s;throw new y.InvalidAddress(this.id+" fetchDepositAddress() could not find a deposit address for "+e+", make sure you have created a corresponding deposit address in your wallet on the exchange website")}if(void 0!==this.has.fetchDepositAddressesByNetwork&&!1!==this.has.fetchDepositAddressesByNetwork){let i=this.safeString(t,"network"),s=this.omit(t,"network"),r=await this.fetchDepositAddressesByNetwork(e,s);if(void 0!==i)return this.safeDict(r,i);{let e=Object.keys(r)[0];return this.safeDict(r,e)}}throw new y.NotSupported(this.id+" fetchDepositAddress() is not supported yet")}async fetchContractDepositAddress(e,t={}){throw new y.NotSupported(this.id+" fetchContractDepositAddress() is not supported yet")}account(){return{free:void 0,used:void 0,total:void 0}}mergeBalanceAccount(e,t,i){if(!(t in e))return e[t]=i,e;let s=["free","used","total","debt"];for(let r=0;r<s.length;r++){let a=s[r],o=this.safeString(e[t],a),n=this.safeString(i,a);void 0===o?e[t][a]=n:void 0!==n&&(e[t][a]=b.Y.stringAdd(o,n))}return e}commonCurrencyCode(e){return this.substituteCommonCurrencyCodes?this.safeString(this.commonCurrencies,e,e):e}currency(e){if(void 0===e)throw new y.ArgumentsRequired(this.id+" currency() requires a code argument");if(0===Object.keys(this.currencies).length)throw new y.ExchangeError(this.id+" currencies not loaded");if("string"==typeof e){let t=this.currencies,i=this.currencies_by_id;if(e in t)return t[e];if(void 0!==i&&e in i)return i[e]}throw new y.ExchangeError(this.id+" does not have currency code "+e)}market(e){if(void 0===e)throw new y.ArgumentsRequired(this.id+" market() requires a symbol argument");let t=this.markets;if(void 0===t)throw new y.ExchangeError(this.id+" markets not loaded");let i=this.markets_by_id;if(e in t)return t[e];if(void 0!==i&&e in i){let t=i[e],s=this.safeString2(this.options,"defaultType","defaultSubType","spot");for(let e=0;e<t.length;e++){let i=t[e];if(!0===i[s])return i}return t[0]}if(e.endsWith("-C")||e.endsWith("-P")||e.startsWith("C-")||e.startsWith("P-"))return this.createExpiredOptionMarket(e);throw new y.BadSymbol(this.id+" does not have market symbol "+e)}createExpiredOptionMarket(e){throw new y.NotSupported(this.id+" createExpiredOptionMarket () is not supported yet")}isLeveragedCurrency(e,t=!1,i){let s=["2L","2S","3L","3S","4L","4S","5L","5S","UP","DOWN","BULL","BEAR"];for(let r=0;r<s.length;r++){let a=s[r];if(e.endsWith(a))if(!t)return!0;else{let t=e.replace(a,"");if(void 0!==i&&t in i)return!0}}return!1}handleWithdrawTagAndParams(e,t){let i=t,s=e;this.isDictionary(e)&&(i=this.extend(e,t),s=void 0);let r=void 0===s?this.safeString(i,"tag"):s,a=i;return void 0===s&&void 0!==r&&(a=this.omit(i,"tag")),[r,a]}costToPrecision(e,t){if(void 0===t)return;let i=this.market(e);return this.decimalToPrecision(t,tn,this.safeString2(i.precision,"cost","price"),this.precisionMode,this.paddingMode)}priceToPrecision(e,t){if(void 0===t)return;let i=this.market(e),s=this.decimalToPrecision(t,td,i.precision.price,this.precisionMode,this.paddingMode);if("0"===s){let e=this.numberToString(i.precision.price);if(void 0===e)throw new y.BadSymbol(this.id+" priceToPrecision() market "+i.symbol+" has no price precision");throw new y.InvalidOrder(this.id+" price of "+i.symbol+" must be greater than minimum price precision of "+e)}return s}amountToPrecision(e,t){if(void 0===t)return;let i=this.market(e),s=this.decimalToPrecision(t,tn,i.precision.amount,this.precisionMode,this.paddingMode);if("0"===s){let e=this.numberToString(i.precision.amount);if(void 0===e)throw new y.BadSymbol(this.id+" amountToPrecision() market "+i.symbol+" has no amount precision");throw new y.InvalidOrder(this.id+" amount of "+i.symbol+" must be greater than minimum amount precision of "+e)}return s}feeToPrecision(e,t){if(void 0===t)return;let i=this.market(e);return this.decimalToPrecision(t,td,i.precision.price,this.precisionMode,this.paddingMode)}currencyToPrecision(e,t,i){if(void 0===e)throw new y.ArgumentsRequired(this.id+" currencyToPrecision() requires a code argument");let s=this.currencies[e],r=this.safeValue(s,"precision");if(void 0!==i){let e=this.safeDict(s,"networks",{}),t=this.safeDict(e,i,{});r=this.safeValue(t,"precision",r)}if(void 0===r)return this.forceString(t);{let e=this.safeInteger(this.options,"currencyToPrecisionRoundingMode",td);return this.decimalToPrecision(t,e,r,this.precisionMode,this.paddingMode)}}forceString(e){return"string"!=typeof e?this.numberToString(e):e}isTickPrecision(){return this.precisionMode===tl}isSignificantPrecision(){return this.precisionMode===tu}safeNumber(e,t,i){let s=this.safeString(e,t);return this.parseNumber(s,i)}safeNumberN(e,t,i){let s=this.safeStringN(e,t);return this.parseNumber(s,i)}parsePrecision(e){if(void 0===e)return;let t=parseInt(e);if(0===t)return"1";if(t>0){let e="0.";for(let i=0;i<t-1;i++)e+="0";return e+"1"}{let e="1";for(let i=0;i<-1*t-1;i++)e+="0";return e+"0"}}integerPrecisionToAmount(e){if(void 0!==e)if(b.Y.stringGe(e,"0"))return this.parsePrecision(e);else{let t=b.Y.stringAbs(e);if(void 0===t)return;let i=parseInt(t),s="1";for(let e=0;e<i-1;e++)s+="0";return s+"0"}}async loadTimeDifference(e={}){let t=await this.fetchTime(e),i=this.milliseconds();if(void 0===t)throw new y.ExchangeError(this.id+" loadTimeDifference() missing serverTime");return this.options.timeDifference=i-t,this.options.timeDifference}implodeHostname(e){return this.implodeParams(e,{hostname:this.hostname})}async fetchMarketLeverageTiers(e,t={}){if(void 0!==this.has.fetchLeverageTiers&&!1!==this.has.fetchLeverageTiers){if(!0!==this.market(e).contract)throw new y.BadSymbol(this.id+" fetchMarketLeverageTiers() supports contract markets only");let t=await this.fetchLeverageTiers([e]);return this.safeValue(t,e)}throw new y.NotSupported(this.id+" fetchMarketLeverageTiers() is not supported yet")}async createSubAccount(e,t={}){throw new y.NotSupported(this.id+" createSubAccount() is not supported yet")}safeCurrencyCode(e,t){return this.safeCurrency(e,t).code}filterBySymbolSinceLimit(e,t,i,s,r=!1){return this.filterByValueSinceLimit(e,"symbol",t,i,s,"timestamp",r)}filterByCurrencySinceLimit(e,t,i,s,r=!1){return this.filterByValueSinceLimit(e,"currency",t,i,s,"timestamp",r)}filterBySymbolsSinceLimit(e,t,i,s,r=!1){let a=this.filterByArray(e,"symbol",t,!1);return this.filterBySinceLimit(a,i,s,"timestamp",r)}parseLastPrices(e,t,i={}){let s=[];if(Array.isArray(e))for(let t=0;t<e.length;t++){let r=this.extend(this.parseLastPrice(e[t]),i);s.push(r)}else{let t=Object.keys(e);for(let r=0;r<t.length;r++){let a=t[r],o=this.safeMarket(a),n=this.extend(this.parseLastPrice(e[a],o),i);s.push(n)}}let r=this.marketSymbols(t);return this.filterByArray(s,"symbol",r)}parseTickers(e,t,i={}){let s=[];if(Array.isArray(e))for(let t=0;t<e.length;t++){let r=this.parseTicker(e[t]),a=this.extend(r,i);s.push(a)}else{let t=Object.keys(e);for(let r=0;r<t.length;r++){let a=t[r],o=this.safeMarket(a),n=this.parseTicker(e[a],o),d=this.extend(n,i);s.push(d)}}let r=this.marketSymbols(t);return this.filterByArrayTickers(s,"symbol",r)}parseDepositAddresses(e,t,i=!0,s={}){let r=[];for(let t=0;t<e.length;t++){let i=this.extend(this.parseDepositAddress(e[t]),s);r.push(i)}return void 0!==t&&(r=this.filterByArray(r,"currency",t,!1)),i&&(r=this.filterByArray(r,"currency",void 0,i)),r}parseBorrowInterests(e,t){let i=[];for(let s=0;s<e.length;s++){let r=e[s];i.push(this.parseBorrowInterest(r,t))}return i}parseBorrowRate(e,t){throw new y.NotSupported(this.id+" parseBorrowRate() is not supported yet")}parseBorrowRateHistory(e,t,i,s){let r=[];for(let t=0;t<e.length;t++){let i=e[t],s=this.parseBorrowRate(i);r.push(s)}let a=this.sortBy(r,"timestamp");return this.filterByCurrencySinceLimit(a,t,i,s)}parseIsolatedBorrowRates(e){let t={};for(let i=0;i<e.length;i++){let s=e[i],r=this.parseIsolatedBorrowRate(s);t[this.safeString(r,"symbol")]=r}return t}parseFundingRateHistories(e,t,i,s){let r=[];for(let i=0;i<e.length;i++){let s=e[i];r.push(this.parseFundingRateHistory(s,t))}let a=this.sortBy(r,"timestamp"),o=void 0===t?void 0:t.symbol;return this.filterBySymbolSinceLimit(a,o,i,s)}safeSymbol(e,t,i,s){return this.safeMarket(e,t,i,s).symbol}parseFundingRate(e,t){throw new y.NotSupported(this.id+" parseFundingRate() is not supported yet")}parseFundingRates(e,t){let i={};for(let t=0;t<e.length;t++){let s=e[t],r=this.parseFundingRate(s);void 0!==r.symbol&&(i[r.symbol]=r)}return this.indexBy(this.filterByArray(i,"symbol",t,!1),"symbol")}parseLongShortRatio(e,t){throw new y.NotSupported(this.id+" parseLongShortRatio() is not supported yet")}parseLongShortRatioHistory(e,t,i,s){let r=[];for(let i=0;i<e.length;i++){let s=e[i];r.push(this.parseLongShortRatio(s,t))}let a=this.sortBy(r,"timestamp"),o=void 0===t?void 0:t.symbol;return this.filterBySymbolSinceLimit(a,o,i,s)}handleTriggerPricesAndParams(e,t,i=!0){let s,r,a,o=this.safeString2(t,"triggerPrice","stopPrice"),n=this.safeString(t,"stopLossPrice"),d=this.safeString(t,"takeProfitPrice"),h=[];return void 0!==o&&(i&&(h.push("triggerPrice"),h.push("stopPrice")),s=this.priceToPrecision(e,parseFloat(o))),void 0!==n&&(i&&h.push("stopLossPrice"),r=this.priceToPrecision(e,parseFloat(n))),void 0!==d&&(i&&h.push("takeProfitPrice"),a=this.priceToPrecision(e,parseFloat(d))),[s,r,a,h.length>0?this.omit(t,h):t]}handleTriggerDirectionAndParams(e,t,i=!1){let s=this.safeString(e,"triggerDirection"),r=void 0!==t&&t in e,a=void 0!==s?this.omit(e,"triggerDirection"):e;if(!this.inArray(s,["ascending","descending","up","down","above","below"])&&!r&&!i)throw new y.ArgumentsRequired(this.id+' createOrder() : trigger orders require params["triggerDirection"] to be either "ascending" or "descending"');return"up"===s||"above"===s?s="ascending":("down"===s||"below"===s)&&(s="descending"),[s,a]}handleTriggerAndParams(e){let t=this.safeBool2(e,"trigger","stop"),i=!0===t?this.omit(e,["trigger","stop"]):e;return[t,i]}isTriggerOrder(e){return this.handleTriggerAndParams(e)}isPostOnly(e,t,i={}){let s=this.safeStringUpper(i,"timeInForce"),r=this.safeBool2(i,"postOnly","post_only",!1);if(!0!==r&&(r="PO"===s),!0!==r&&(r=t),!0!==r)return!1;if("IOC"===s||"FOK"===s)throw new y.InvalidOrder(this.id+" postOnly orders cannot have timeInForce equal to "+s);if(!e)return!0;throw new y.InvalidOrder(this.id+" market orders cannot be postOnly")}handlePostOnly(e,t,i={}){let s=this.safeStringUpper(i,"timeInForce"),r=this.safeBool(i,"postOnly",!1),a="PO"===s;if(!0!==r&&(r=a),!0!==r&&(r=t),!0===r)if("IOC"===s||"FOK"===s)throw new y.InvalidOrder(this.id+" postOnly orders cannot have timeInForce equal to "+s);else if(e)throw new y.InvalidOrder(this.id+" market orders cannot be postOnly");else{let e;return e=a?["timeInForce","postOnly"]:["postOnly"],[!0,this.omit(i,e)]}return[!1,i]}async fetchLastPrices(e,t={}){throw new y.NotSupported(this.id+" fetchLastPrices() is not supported yet")}async fetchTradingFees(e={}){throw new y.NotSupported(this.id+" fetchTradingFees() is not supported yet")}async fetchTradingFeesWs(e={}){throw new y.NotSupported(this.id+" fetchTradingFeesWs() is not supported yet")}async fetchConvertCurrencies(e={}){throw new y.NotSupported(this.id+" fetchConvertCurrencies() is not supported yet")}parseOpenInterest(e,t){throw new y.NotSupported(this.id+" parseOpenInterest () is not supported yet")}parseOpenInterests(e,t){let i={};for(let t=0;t<e.length;t++){let s=e[t],r=this.parseOpenInterest(s);void 0!==r.symbol&&(i[r.symbol]=r)}return this.filterByArray(i,"symbol",t)}parseOpenInterestsHistory(e,t,i,s){let r=[];for(let i=0;i<e.length;i++){let s=e[i],a=this.parseOpenInterest(s,t);r.push(a)}let a=this.sortBy(r,"timestamp"),o=this.safeString(t,"symbol");return this.filterBySymbolSinceLimit(a,o,i,s)}async fetchFundingRate(e,t={}){if(void 0!==this.has.fetchFundingRates&&!1!==this.has.fetchFundingRates){await this.loadMarkets();let i=this.market(e),s=i.symbol;if(!0!==i.contract)throw new y.BadSymbol(this.id+" fetchFundingRate() supports contract markets only");let r=await this.fetchFundingRates([s],t),a=this.safeDict(r,s);if(void 0!==a)return a;throw new y.NullResponse(this.id+" fetchFundingRate () returned no data for "+s)}throw new y.NotSupported(this.id+" fetchFundingRate () is not supported yet")}async fetchFundingInterval(e,t={}){if(void 0!==this.has.fetchFundingIntervals&&!1!==this.has.fetchFundingIntervals){await this.loadMarkets();let i=this.market(e),s=i.symbol;if(!0!==i.contract)throw new y.BadSymbol(this.id+" fetchFundingInterval() supports contract markets only");let r=await this.fetchFundingIntervals([s],t),a=this.safeDict(r,s);if(void 0!==a)return a;throw new y.NullResponse(this.id+" fetchFundingInterval() returned no data for "+s)}throw new y.NotSupported(this.id+" fetchFundingInterval() is not supported yet")}async fetchMarkOHLCV(e,t="1m",i,s,r={}){if(void 0!==this.has.fetchMarkOHLCV&&!1!==this.has.fetchMarkOHLCV)return await this.fetchOHLCV(e,t,i,s,this.extend({price:"mark"},r));throw new y.NotSupported(this.id+" fetchMarkOHLCV () is not supported yet")}async fetchIndexOHLCV(e,t="1m",i,s,r={}){if(void 0!==this.has.fetchIndexOHLCV&&!1!==this.has.fetchIndexOHLCV)return await this.fetchOHLCV(e,t,i,s,this.extend({price:"index"},r));throw new y.NotSupported(this.id+" fetchIndexOHLCV () is not supported yet")}async fetchPremiumIndexOHLCV(e,t="1m",i,s,r={}){if(void 0!==this.has.fetchPremiumIndexOHLCV&&!1!==this.has.fetchPremiumIndexOHLCV)return await this.fetchOHLCV(e,t,i,s,this.extend({price:"premiumIndex"},r));throw new y.NotSupported(this.id+" fetchPremiumIndexOHLCV () is not supported yet")}handleTimeInForce(e={}){let t=this.safeStringUpper(e,"timeInForce");if(void 0!==t){let e=this.safeString(this.options.timeInForce,t);if(void 0===e)throw new y.ExchangeError(this.id+' does not support timeInForce "'+t+'"');return e}}convertTypeToAccount(e){let t=this.safeDict(this.options,"accountsByType",{}),i=e.toLowerCase();if(i in t)return t[i];let s=this.markets,r=this.markets_by_id;return void 0!==s&&e in s||void 0!==r&&e in r?this.market(e).id:e}checkRequiredArgument(e,t,i,s=[]){let r=s.length;if(void 0===t||r>0&&!this.inArray(t,s)){let t=s.join(", "),r=this.id+" "+e+"() requires a "+i+" argument";throw""!==t&&(r+=", one of ("+t+")"),new y.ArgumentsRequired(r)}}checkRequiredMarginArgument(e,t,i){if("isolated"===i&&void 0===t)throw new y.ArgumentsRequired(this.id+" "+e+"() requires a symbol argument for isolated margin");if("cross"===i&&void 0!==t)throw new y.ArgumentsRequired(this.id+" "+e+"() cannot have a symbol argument for cross margin")}parseDepositWithdrawFees(e,t,i){let s={},r=Array.isArray(e),a=e;r||(a=Object.keys(e));for(let o=0;o<a.length;o++){let n=a[o],d=r?n:e[n],h=n;r&&(h=void 0===i?void 0:this.safeString(d,i));let c=this.safeCurrency(h),l=this.safeString(c,"code");(void 0===t||this.inArray(l,t))&&(s[l]=this.parseDepositWithdrawFee(d,c))}return s}parseDepositWithdrawFee(e,t){throw new y.NotSupported(this.id+" parseDepositWithdrawFee() is not supported yet")}depositWithdrawFee(e){return{info:e,withdraw:{fee:void 0,percentage:void 0},deposit:{fee:void 0,percentage:void 0},networks:{}}}assignDefaultDepositWithdrawFees(e,t){let i=Object.keys(e.networks),s=i.length;if(1===s)return e.withdraw=e.networks[i[0]].withdraw,e.deposit=e.networks[i[0]].deposit,e;let r=this.safeString(t,"code");for(let t=0;t<s;t++)i[t]===r&&(e.withdraw=e.networks[i[t]].withdraw,e.deposit=e.networks[i[t]].deposit);return e}parseIncome(e,t){throw new y.NotSupported(this.id+" parseIncome () is not supported yet")}parseIncomes(e,t,i,s){let r=[];for(let i=0;i<e.length;i++){let s=e[i],a=this.parseIncome(s,t);r.push(a)}let a=this.sortBy(r,"timestamp"),o=this.safeString(t,"symbol");return this.filterBySymbolSinceLimit(a,o,i,s)}getMarketFromSymbols(e){if(void 0===e)return;let t=this.safeString(e,0);if(void 0!==t)return this.market(t)}parseWsOHLCVs(e,t,i="1m",s,r){let a=[];for(let i=0;i<e.length;i++)a.push(this.parseWsOHLCV(e[i],t));return a}async fetchTransactions(e,t,i,s={}){if(void 0!==this.has.fetchDepositsWithdrawals&&!1!==this.has.fetchDepositsWithdrawals)return await this.fetchDepositsWithdrawals(e,t,i,s);throw new y.NotSupported(this.id+" fetchTransactions () is not supported yet")}filterByArrayPositions(e,t,i){return this.toArray(this.filterByArray(e,t,i,!1))}filterByArrayTickers(e,t,i){return this.indexBy(this.filterByArray(e,t,i,!1),t)}filterByArrayADLRanks(e,t,i,s=!0){return this.filterByArray(e,t,i,s)}createOHLCVObject(e,t,i){let s={};return s[e]={},s[e][t]=i,s}handleMaxEntriesPerRequestAndParams(e,t,i={}){let[s,r]=this.handleOptionIntegerAndParams(i,e,"maxEntriesPerRequest"),a=void 0!==s?s:t;return[void 0===a?1e3:a,r]}async fetchPaginatedCallDynamic(e,t,i,s,r={},a,o=!0){let n,[d,h]=this.handleOptionIntegerAndParams(r,e,"paginationCalls",10),[c,l]=this.handleOptionIntegerAndParams(h,e,"maxRetries",3),[u,f]=this.handleOptionAndParams(l,e,"paginationDirection","backward"),[p,m]=this.handleOptionAndParams(f,e,"removeRepeated",o),g=0,v=[],b=0,w=this.safeIntegerN(m,["until","untill","till"]),[k,S]=this.handleMaxEntriesPerRequestAndParams(e,a,m);if("forward"===u){if(void 0===i)throw new y.ArgumentsRequired(this.id+" pagination requires a since argument when paginationDirection set to forward");n=i}for(;g<d;){g+=1;try{if("backward"===u){void 0!==n&&(S.until=n-1);let s=await this[e](t,void 0,k,S),r=s.length;if(this.verbose){let t="Dynamic pagination call "+this.numberToString(g)+" method "+e+" response length "+this.numberToString(r);void 0!==n&&(t+=" timestamp "+this.numberToString(n)),this.log(t)}if(0===r)break;b=0,v=this.arrayConcat(v,s);let a=this.safeValue(s,0);if(n=this.safeInteger2(a,"timestamp",0),void 0===n||void 0!==i&&n<=i)break}else{let i=await this[e](t,n,k,S),s=i.length;if(this.verbose){let t="Dynamic pagination call "+this.numberToString(g)+" method "+e+" response length "+this.numberToString(s);void 0!==n&&(t+=" timestamp "+this.numberToString(n)),this.log(t)}if(0===s)break;b=0,v=this.arrayConcat(v,i);let r=this.safeValue(i,s-1),a=this.safeInteger(r,"timestamp",0);if(void 0===a)break;let o=a+1;if(n=o,void 0!==w&&o>=w)break}}catch(e){if((b+=1)>c)throw e}}let O=v;p&&(O=this.removeRepeatedElementsFromArray(v));let T="fetchOHLCV"===e?0:"timestamp",P=this.sortBy(O,T);return this.filterBySinceLimit(P,i,s,T)}async safeDeterministicCall(e,t,i,s,r,a={}){let[o,n]=this.handleOptionIntegerAndParams(a,e,"maxRetries",3),d=0;for(;d<=o;)try{if(void 0!==r&&""!==r&&"fetchFundingRateHistory"!==e)return await this[e](t,r,i,s,n);return await this[e](t,i,s,n)}catch(e){if(e instanceof y.RateLimitExceeded||(d+=1)>o)throw e}return[]}async fetchPaginatedCallDeterministic(e,t,i,s,r,a={},o){let[n,d]=this.handleOptionIntegerAndParams(a,e,"paginationCalls",10),[h,c]=this.handleMaxEntriesPerRequestAndParams(e,o,d),l=this.omit(c,"paginationDirection"),u=this.milliseconds(),f=[],p=1e3*this.parseTimeframe(r),m=this.requireValue(h,"fetchPaginatedCallDeterministic() maxEntriesPerRequest is required"),g=p*m,v=this.safeInteger2(l,"until","till"),b=u-n*g-1;if(b=void 0!==i?void 0!==v?i:Math.max(b,i):Math.max(b,1241440531e3),void 0!==v){if(void 0===i)throw new y.ArgumentsRequired(this.id+" fetchPaginatedCallDeterministic() requires a since argument when until is set");let e=Math.ceil((v-i)/g);if(e>n)throw new y.BadRequest(this.id+" the number of required calls is greater than the max number of calls allowed, either increase the paginationCalls or decrease the since-until gap. Current paginationCalls limit is "+n.toString()+" required calls is "+e.toString())}for(let i=0;i<n&&(void 0===v||!(b>=v))&&!(b>=u);i++)f.push(this.safeDeterministicCall(e,t,b,m,r,l)),b=b+g-1;let w=await Promise.all(f),k=[];for(let e=0;e<w.length;e++)k=this.arrayConcat(k,w[e]);let S=this.removeRepeatedElementsFromArray(k),O="fetchOHLCV"===e?0:"timestamp";return this.filterBySinceLimit(S,i,s,O)}async fetchPaginatedCallCursor(e,t,i,s,r={},a,o,n,d){let h,[c,l]=this.handleOptionIntegerAndParams(r,e,"paginationCalls",10),[u,f]=this.handleOptionIntegerAndParams(l,e,"maxRetries",3),[p,m]=this.handleMaxEntriesPerRequestAndParams(e,d,f),g=0,v=0,b=[],w=this.safeString(m,"timeframe"),k=this.omit(m,"timeframe");for(;g<c;){try{let s;if(void 0!==h&&(void 0!==n&&(h=this.parseToInt(h)+n),k[o]=h),"fetchAccounts"===e)s=await this[e](k);else if("getLeverageTiersPaginated"===e||"fetchPositions"===e)s=await this[e](t,k);else if("fetchOpenInterestHistory"===e){if("string"!=typeof t)throw new y.ArgumentsRequired(this.id+" fetchPaginatedCallCursor() requires a symbol argument");if(void 0===w)throw new y.ArgumentsRequired(this.id+" fetchPaginatedCallCursor() requires a timeframe argument");s=await this[e](t,w,i,p,k)}else s=await this[e](t,i,p,k);if(v=0,void 0===s)throw new y.NullResponse(this.id+" fetchPaginatedCallCursor() returned empty response");let r=s.length;if(this.verbose){let t=void 0===h?"":h,i=g+1,s="Cursor pagination call "+i.toString()+" method "+e+" response length "+r.toString()+" cursor "+t;this.log(s)}if(0===r)break;void 0!==s&&(b=this.arrayConcat(b,s));let d=this.safeDict(s,r-1);h=void 0;for(let e=0;e<r;e++){let t=r-e-1,i=this.safeDict(s,t),o=this.safeDict(i,"info"),n=void 0===a?void 0:this.safeValue(o,a);if(void 0!==n){h=n;break}}if(void 0===h)break;let c=this.safeInteger(d,"timestamp");if(void 0===i)throw new y.ArgumentsRequired(this.id+" fetchPaginatedCallCursor() requires a since argument");if(void 0!==c&&c<i)break}catch(e){if((v+=1)>u)throw e}g+=1}let S=this.sortCursorPaginatedResult(b),O="fetchOHLCV"===e?0:"timestamp";return this.filterBySinceLimit(S,i,s,O)}async fetchPaginatedCallIncremental(e,t,i,s,r={},a,o){let[n,d]=this.handleOptionIntegerAndParams(r,e,"paginationCalls",10),[h,c]=this.handleOptionIntegerAndParams(d,e,"maxRetries",3),[l,u]=this.handleMaxEntriesPerRequestAndParams(e,o,c),f=0,p=0,m=[];for(;f<n;){try{u[a]=f+1;let s=await this[e](t,i,l,u);p=0;let r=s.length;if(this.verbose){let t=(f+1).toString(),i="Incremental pagination call "+t+" method "+e+" response length "+r.toString();this.log(i)}if(0===r)break;m=this.arrayConcat(m,s)}catch(e){if((p+=1)>h)throw e}f+=1}let g=this.sortCursorPaginatedResult(m),v="fetchOHLCV"===e?0:"timestamp";return this.filterBySinceLimit(g,i,s,v)}sortCursorPaginatedResult(e){let t=this.safeValue(e,0);if(void 0!==t){if("timestamp"in t)return this.sortBy(e,"timestamp",!0);if("id"in t)return this.sortBy(e,"id",!0)}return e}removeRepeatedElementsFromArray(e,t=!0){let i={},s=[];for(let r=0;r<e.length;r++){let a=e[r],o=t?this.safeStringN(a,["id","timestamp",0]):this.safeString(a,"id");void 0===o||o in i||(i[o]=1,s.push(a))}return s.length>0?s:e}removeRepeatedTradesFromArray(e){let t={};for(let i=0;i<e.length;i++){let s=e[i],r=this.safeString(s,"id");if(void 0===r){let e=this.safeString(s,"price"),t=this.safeString(s,"amount"),i=this.safeString(s,"timestamp"),a=this.safeString(s,"side");if(void 0===i)throw new y.ExchangeError(this.id+" removeRepeatedTradesFromArray() missing timestamp");r="t_"+i.toString()+"_",void 0!==a&&(r+=a),r+="_",void 0!==e&&(r+=e),r+="_",void 0!==t&&(r+=t)}void 0===r||r in t||(t[r]=s)}return Object.values(t)}removeKeysFromDict(e,t){let i=Object.keys(e),s={};for(let r=0;r<i.length;r++){let a=i[r];this.inArray(a,t)||(s[a]=e[a])}return s}handleUntilOption(e,t,i,s=1){let r=this.safeInteger2(i,"until","till");return void 0!==r&&(t[e]=this.parseToInt(r*s)),[t,void 0!==r?this.omit(i,["until","till"]):i]}safeOpenInterest(e,t){let i=this.safeString(e,"symbol");return void 0===i&&(i=this.safeString(t,"symbol")),this.extend(e,{symbol:i,baseVolume:this.safeNumber(e,"baseVolume"),quoteVolume:this.safeNumber(e,"quoteVolume"),openInterestAmount:this.safeNumber(e,"openInterestAmount"),openInterestValue:this.safeNumber(e,"openInterestValue"),timestamp:this.safeInteger(e,"timestamp"),datetime:this.safeString(e,"datetime"),info:this.safeValue(e,"info")})}parseLiquidation(e,t){throw new y.NotSupported(this.id+" parseLiquidation () is not supported yet")}parseLiquidations(e,t,i,s){let r=[];for(let i=0;i<e.length;i++){let s=e[i],a=this.parseLiquidation(s,t);r.push(a)}let a=this.sortBy(r,"timestamp"),o=this.safeString(t,"symbol");return this.filterBySymbolSinceLimit(a,o,i,s)}parseGreeks(e,t){throw new y.NotSupported(this.id+" parseGreeks () is not supported yet")}parseAllGreeks(e,t,i={}){let s=[];if(Array.isArray(e))for(let t=0;t<e.length;t++){let r=this.parseGreeks(e[t]),a=this.extend(r,i);s.push(a)}else{let t=Object.keys(e);for(let r=0;r<t.length;r++){let a=t[r],o=this.safeMarket(a),n=this.parseGreeks(e[a],o),d=this.extend(n,i);s.push(d)}}let r=this.marketSymbols(t);return this.filterByArray(s,"symbol",r)}parseOption(e,t,i){throw new y.NotSupported(this.id+" parseOption () is not supported yet")}parseOptionChain(e,t,i){let s={};for(let r=0;r<e.length;r++){let a=e[r],o=void 0===t?void 0:this.safeString(a,t),n=this.safeCurrency(o),d=void 0===i?void 0:this.safeString(a,i),h=this.safeMarket(d,void 0,void 0,"option");s[h.symbol]=this.parseOption(a,n,h)}return s}parseMarginModes(e,t,i,s){let r={},a=void 0===s?"swap":s;for(let s=0;s<e.length;s++){let o=e[s],n=void 0===i?void 0:this.safeString(o,i),d=this.safeMarket(n,void 0,void 0,a);(void 0===t||this.inArray(d.symbol,t))&&(r[d.symbol]=this.parseMarginMode(o,d))}return r}parseMarginMode(e,t){throw new y.NotSupported(this.id+" parseMarginMode () is not supported yet")}parseLeverages(e,t,i,s){let r={},a=void 0===s?"swap":s;for(let s=0;s<e.length;s++){let o=e[s],n=void 0===i?void 0:this.safeString(o,i),d=this.safeMarket(n,void 0,void 0,a);(void 0===t||this.inArray(d.symbol,t))&&(r[d.symbol]=this.parseLeverage(o,d))}return r}parseLeverage(e,t){throw new y.NotSupported(this.id+" parseLeverage () is not supported yet")}parseConversions(e,t,i,s,r,a,o={}){let n,d,h=this.toArray(e),c=[];for(let e=0;e<h.length;e++){let t=h[e],r=void 0===i?void 0:this.safeString(t,i),a=void 0===s?void 0:this.safeString(t,s);void 0!==r&&(n=this.safeCurrency(r)),void 0!==a&&(d=this.safeCurrency(a));let l=this.extend(this.parseConversion(t,n,d),o);c.push(l)}let l=this.sortBy(c,"timestamp");if(void 0===t)return this.filterBySinceLimit(l,r,a);let u=this.safeCurrency(t);if(void 0===u)throw new y.ExchangeError(this.id+" parseConversions() could not resolve currency");let f=u.code,p=this.filterBy(l,"fromCurrency",f),m=this.filterBy(l,"toCurrency",f),g=this.arrayConcat(p,m);return this.filterBySinceLimit(g,r,a)}parseConversion(e,t,i){throw new y.NotSupported(this.id+" parseConversion () is not supported yet")}convertExpireDate(e){if(void 0!==e)return"20"+e.slice(0,2)+"-"+e.slice(2,4)+"-"+e.slice(4,6)+"T00:00:00.000Z"}convertExpireDateToMarketIdDate(e){let t;if(void 0===e)return;let i=e.slice(0,2),s=e.slice(2,4),r=e.slice(4,6);if("01"===s?t="JAN":"02"===s?t="FEB":"03"===s?t="MAR":"04"===s?t="APR":"05"===s?t="MAY":"06"===s?t="JUN":"07"===s?t="JUL":"08"===s?t="AUG":"09"===s?t="SEP":"10"===s?t="OCT":"11"===s?t="NOV":"12"===s&&(t="DEC"),void 0===t)throw new y.BadSymbol(this.id+" invalid expiry date "+e);return r+t+i}convertMarketIdExpireDate(e){if(void 0===e)return;let t=e;6===e.length&&(t="0"+e);let i=t.slice(0,2),s=t.slice(2,5),r=this.safeString({JAN:"01",FEB:"02",MAR:"03",APR:"04",MAY:"05",JUN:"06",JUL:"07",AUG:"08",SEP:"09",OCT:"10",NOV:"11",DEC:"12"},s),a=t.slice(5,7);if(void 0===r)throw new y.BadSymbol(this.id+" invalid expiry date "+e);return a+r+i}async loadMarketsAndSignIn(){await Promise.all([this.loadMarkets(),this.signIn()])}parseMarginModification(e,t){throw new y.NotSupported(this.id+" parseMarginModification() is not supported yet")}parseMarginModifications(e,t,i,s){let r=[];if(void 0===e)return r;for(let a=0;a<e.length;a++){let o=e[a],n=void 0===i?void 0:this.safeString(o,i),d=this.safeMarket(n,void 0,void 0,s);(void 0===t||this.inArray(d.symbol,t))&&r.push(this.parseMarginModification(o,d))}return r}async fetchTransfer(e,t,i={}){throw new y.NotSupported(this.id+" fetchTransfer () is not supported yet")}async fetchTransfers(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchTransfers () is not supported yet")}async unWatchOHLCV(e,t="1m",i={}){throw new y.NotSupported(this.id+" unWatchOHLCV () is not supported yet")}async withdrawWs(e,t,i,s,r={}){throw new y.NotSupported(this.id+" withdrawWs () is not supported yet")}async unWatchMyTrades(e,t={}){throw new y.NotSupported(this.id+" unWatchMyTrades () is not supported yet")}async fetchOrdersByStatusWs(e,t,i,s,r={}){throw new y.NotSupported(this.id+" fetchOrdersByStatusWs () is not supported yet")}async unWatchBidsAsks(e,t={}){throw new y.NotSupported(this.id+" unWatchBidsAsks () is not supported yet")}cleanUnsubscription(e,t,i,s=!1){if(void 0!==i&&i in e.subscriptions&&delete e.subscriptions[i],s){let i=Object.keys(e.subscriptions);for(let s=0;s<i.length;s++){let r=i[s];void 0!==r&&void 0!==t&&r.startsWith(t)&&delete e.subscriptions[r]}let s=Object.keys(e.futures);for(let i=0;i<s.length;i++){let r=s[i];if(void 0!==r&&void 0!==t&&r.startsWith(t)){let t=new y.UnsubscribeError(this.id+" "+r);e.reject(t,r)}}}else if(void 0!==t&&t in e.subscriptions&&delete e.subscriptions[t],void 0!==t&&t in e.futures){let i=new y.UnsubscribeError(this.id+" "+t);e.reject(i,t)}e.resolve(!0,i)}cleanCache(e){let t=this.safeString(e,"topic"),i=this.safeList(e,"symbols",[]),s=i.length;if("ohlcv"===t){let t=this.safeList(e,"symbolsAndTimeframes",[]);for(let e=0;e<t.length;e++){let i=t[e],s=this.safeString(i,0),r=this.safeString(i,1);if(void 0===s)throw new y.ArgumentsRequired(this.id+" cleanCache() requires a symbol argument");if(void 0===r)throw new y.ArgumentsRequired(this.id+" cleanCache() requires a timeframe argument");void 0!==this.ohlcvs&&s in this.ohlcvs&&r in this.ohlcvs[s]&&delete this.ohlcvs[s][r]}}else if(s>0)for(let e=0;e<i.length;e++){let s=i[e];"trades"===t?s in this.trades&&delete this.trades[s]:"orderbook"===t?s in this.orderbooks&&delete this.orderbooks[s]:"ticker"===t?s in this.tickers&&delete this.tickers[s]:"bidsasks"===t&&s in this.bidsasks&&delete this.bidsasks[s]}else if("myTrades"===t&&void 0!==this.myTrades)this.myTrades=void 0;else if("orders"===t&&void 0!==this.orders)this.orders=void 0;else if("positions"===t&&void 0!==this.positions){this.positions=void 0;let e=Object.values(this.clients);for(let t=0;t<e.length;t++){let i=e[t].futures;void 0!==i&&"fetchPositionsSnapshot"in i&&delete i.fetchPositionsSnapshot}}else if(("ticker"===t||"markPrice"===t)&&void 0!==this.tickers){let e=Object.keys(this.tickers);for(let t=0;t<e.length;t++){let i=e[t];i in this.tickers&&delete this.tickers[i]}}else if("bidsasks"===t&&void 0!==this.bidsasks){let e=Object.keys(this.bidsasks);for(let t=0;t<e.length;t++){let i=e[t];i in this.bidsasks&&delete this.bidsasks[i]}}}timeframeFromMilliseconds(e){return e<=0?"":e%6048e5==0?e/6048e5+"w":e%864e5==0?e/864e5+"d":e%36e5==0?e/36e5+"h":e%6e4==0?e/6e4+"m":e%1e3==0?e/1e3+"s":""}async isUTAEnabled(e={}){return!1}constructor(e={}){M(this,"options",void 0),M(this,"isSandboxModeEnabled",!1),M(this,"api",void 0),M(this,"certified",!1),M(this,"pro",!1),M(this,"countries",void 0),M(this,"proxy",void 0),M(this,"proxyUrl",void 0),M(this,"proxy_url",void 0),M(this,"proxyUrlCallback",void 0),M(this,"proxy_url_callback",void 0),M(this,"httpProxy",void 0),M(this,"http_proxy",void 0),M(this,"httpProxyCallback",void 0),M(this,"http_proxy_callback",void 0),M(this,"httpsProxy",void 0),M(this,"https_proxy",void 0),M(this,"httpsProxyCallback",void 0),M(this,"https_proxy_callback",void 0),M(this,"socksProxy",void 0),M(this,"socks_proxy",void 0),M(this,"socksProxyCallback",void 0),M(this,"socks_proxy_callback",void 0),M(this,"userAgent",void 0),M(this,"user_agent",void 0),M(this,"wsProxy",void 0),M(this,"ws_proxy",void 0),M(this,"wssProxy",void 0),M(this,"wss_proxy",void 0),M(this,"wsSocksProxy",void 0),M(this,"ws_socks_proxy",void 0),M(this,"userAgents",{chrome:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",chrome39:"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36",chrome100:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36"}),M(this,"headers",{}),M(this,"returnResponseHeaders",!1),M(this,"origin","*"),M(this,"MAX_VALUE",Number.MAX_VALUE),M(this,"agent",void 0),M(this,"httpAgent",void 0),M(this,"httpsAgent",void 0),M(this,"minFundingAddressLength",1),M(this,"substituteCommonCurrencyCodes",!0),M(this,"quoteJsonNumbers",!0),M(this,"number",Number),M(this,"handleContentTypeApplicationZip",!1),M(this,"reduceFees",!0),M(this,"fetchImplementation",void 0),M(this,"AbortError",void 0),M(this,"FetchError",void 0),M(this,"fetchImplementationLoading",void 0),M(this,"fetchIsNative",!1),M(this,"undiciModule",void 0),M(this,"zlibModule",void 0),M(this,"httpStatusTexts",{}),M(this,"fetchDispatcher",void 0),M(this,"validateServerSsl",!0),M(this,"validateClientSsl",!1),M(this,"timeout",1e4),M(this,"verbose",!1),M(this,"apiKey",void 0),M(this,"secret",void 0),M(this,"uid",void 0),M(this,"login",void 0),M(this,"password",void 0),M(this,"privateKey",void 0),M(this,"walletAddress",void 0),M(this,"token",void 0),M(this,"twofa",void 0),M(this,"accountId",void 0),M(this,"balance",{}),M(this,"liquidations",void 0),M(this,"orderbooks",{}),M(this,"tickers",{}),M(this,"fundingRates",{}),M(this,"bidsasks",{}),M(this,"orders",void 0),M(this,"triggerOrders",void 0),M(this,"trades",void 0),M(this,"transactions",{}),M(this,"ohlcvs",void 0),M(this,"myLiquidations",void 0),M(this,"myTrades",void 0),M(this,"positions",void 0),M(this,"urls",void 0),M(this,"requiresWeb3",!1),M(this,"precision",void 0),M(this,"enableLastJsonResponse",!1),M(this,"enableLastHttpResponse",!0),M(this,"enableLastResponseHeaders",!0),M(this,"last_http_response",void 0),M(this,"last_json_response",void 0),M(this,"last_response_headers",void 0),M(this,"last_request_headers",void 0),M(this,"last_request_body",void 0),M(this,"last_request_url",void 0),M(this,"last_request_path",void 0),M(this,"fetchHistoryCache",[]),M(this,"fetchHistoryCacheSize",0),M(this,"id","Exchange"),M(this,"markets",void 0),M(this,"has",void 0),M(this,"features",void 0),M(this,"status",void 0),M(this,"requiredCredentials",void 0),M(this,"rateLimit",2e3),M(this,"tokenBucket",void 0),M(this,"throttler",void 0),M(this,"enableRateLimit",!0),M(this,"rollingWindowSize",0),M(this,"rateLimiterAlgorithm","leakyBucket"),M(this,"httpExceptions",void 0),M(this,"limits",void 0),M(this,"fees",void 0),M(this,"markets_by_id",void 0),M(this,"symbols",[]),M(this,"ids",void 0),M(this,"currencies",{}),M(this,"baseCurrencies",void 0),M(this,"quoteCurrencies",void 0),M(this,"currencies_by_id",void 0),M(this,"codes",void 0),M(this,"reloadingMarkets",void 0),M(this,"marketsLoading",void 0),M(this,"accounts",void 0),M(this,"accountsById",void 0),M(this,"commonCurrencies",void 0),M(this,"hostname",void 0),M(this,"precisionMode",void 0),M(this,"paddingMode",void 0),M(this,"exceptions",{}),M(this,"timeframes",{}),M(this,"version",void 0),M(this,"name",void 0),M(this,"lastRestRequestTimestamp",void 0),M(this,"targetAccount",void 0),M(this,"httpProxyAgentModule",void 0),M(this,"httpsProxyAgentModule",void 0),M(this,"socksProxyAgentModule",void 0),M(this,"socksProxyAgentModuleChecked",!1),M(this,"proxyDictionaries",{}),M(this,"proxyDictionariesMaxSize",8),M(this,"proxiesModulesLoading",void 0),M(this,"alias",!1),M(this,"clients",{}),M(this,"newUpdates",!0),M(this,"streaming",{}),M(this,"sleep",tf),M(this,"deepExtend",E),M(this,"deepExtendSafe",E),M(this,"isNode",_),M(this,"extend",R),M(this,"clone",L),M(this,"unique",N),M(this,"indexBy",D),M(this,"indexBySafe",D),M(this,"roundTimeframe",ek),M(this,"sortBy",q),M(this,"sortBy2",F),M(this,"groupBy",G),M(this,"aggregate",H),M(this,"uuid",U),M(this,"unCamelCase",W),M(this,"precisionFromString",j),M(this,"capitalize",z),M(this,"now",Y),M(this,"decimalToPrecision",X),M(this,"safeValue",Q),M(this,"safeValue2",Z),M(this,"safeString",J),M(this,"safeString2",$),M(this,"safeFloat",eY),M(this,"safeFloat2",V),M(this,"seconds",ee),M(this,"milliseconds",et),M(this,"binaryToBase16",ei),M(this,"numberToBE",es),M(this,"base16ToBinary",er),M(this,"iso8601",ea),M(this,"omit",eo),M(this,"isJsonEncodedObject",en),M(this,"safeInteger",ed),M(this,"sum",eh),M(this,"omitZero",ec),M(this,"implodeParams",el),M(this,"extractParams",eu),M(this,"json",ef),M(this,"binaryConcat",ep),M(this,"hash",em),M(this,"arrayConcat",eg),M(this,"encode",ev),M(this,"urlencode",ey),M(this,"hmac",eb),M(this,"numberToString",ew),M(this,"parseTimeframe",eS),M(this,"safeInteger2",eO),M(this,"safeStringLower",eT),M(this,"parse8601",eP),M(this,"yyyymmdd",eI),M(this,"safeStringUpper",eA),M(this,"safeTimestamp",ex),M(this,"binaryConcatArray",eM),M(this,"ymdhms",e_),M(this,"yymmdd",eD),M(this,"stringToBase64",eC),M(this,"decode",eB),M(this,"uuid22",eE),M(this,"safeIntegerProduct2",eR),M(this,"safeIntegerProduct",eL),M(this,"binaryToBase58",eF),M(this,"base58ToBinary",eq),M(this,"base64ToBinary",eX),M(this,"safeTimestamp2",eV),M(this,"rawencode",eG),M(this,"keysort",eH),M(this,"sort",eU),M(this,"inArray",eW),M(this,"safeStringLower2",eN),M(this,"safeStringUpper2",eQ),M(this,"isEmpty",ej),M(this,"filterBy",eK),M(this,"uuid16",ez),M(this,"urlencodeWithArrayRepeat",eZ),M(this,"microseconds",eJ),M(this,"binaryToBase64",e$),M(this,"strip",e0),M(this,"toArray",e1),M(this,"safeFloatN",e2),M(this,"safeIntegerN",e3),M(this,"safeIntegerProductN",e5),M(this,"safeTimestampN",e4),M(this,"safeValueN",e6),M(this,"safeStringN",e8),M(this,"safeStringLowerN",e7),M(this,"safeStringUpperN",e9),M(this,"urlencodeNested",te),M(this,"parseDate",ti),M(this,"ymd",ts),M(this,"base64ToString",tr),M(this,"crc32",ta),M(this,"packb",to),M(this,"urlencodeBase64",tt),M(this,"readFile",tp),M(this,"writeFile",tm),M(this,"existsFile",tg),M(this,"getTempDir",tv),Object.assign(this,g),this.options=this.getDefaultOptions(),this.headers={},this.origin="*",this.minFundingAddressLength=1,this.substituteCommonCurrencyCodes=!0,this.quoteJsonNumbers=!0,this.number=Number,this.handleContentTypeApplicationZip=!1,this.reduceFees=!0,this.fetchImplementation=void 0,this.validateServerSsl=!0,this.validateClientSsl=!1,this.timeout=1e4,this.verbose=!1,this.balance={},this.bidsasks={},this.orderbooks={},this.tickers={},this.liquidations=void 0,this.orders=void 0,this.trades={},this.transactions={},this.ohlcvs={},this.myLiquidations=void 0,this.myTrades=void 0,this.positions=void 0,this.requiresWeb3=!1,this.lastRestRequestTimestamp=0,this.enableLastJsonResponse=!1,this.enableLastHttpResponse=!0,this.enableLastResponseHeaders=!0,this.last_json_response=void 0,this.last_request_body=void 0;const t=(e=this)=>{if(null!==e){let i=Object.getOwnPropertyNames(e);for(let e=0;e<i.length;e++){let t=i[e];this[W(t)]=this[t]}t(Object.getPrototypeOf(e))}};t();const i=Object.entries(this.describe()).concat(Object.entries(e));for(let e=0;e<i.length;e++){const[t,s]=i[e];null!=s&&Object.getPrototypeOf(s)===Object.prototype?this[t]=this.deepExtend(this[t],s):this[t]=s}const s=Object.keys(this.has);for(let e=0;e<s.length;e++){const t=s[e];this["has"+this.capitalize(t)]=void 0!==this.has[t]&&!1!==this.has[t]}void 0!==this.api&&this.defineRestApi(this.api,"request"),this.newUpdates=void 0===this.options.newUpdates||this.options.newUpdates,this.afterConstruct(),(this.safeBool(e,"sandbox",!1)||this.safeBool(e,"testnet",!1))&&this.setSandboxMode(!0),this.loadExchangeSpecificFiles()}}M(tk,"ccxtVersion","4.5.84");class tS extends tk{async closePosition(e,t,i={}){throw new y.NotSupported(this.id+" closePosition() is not supported yet")}async closeAllPositions(e={}){throw new y.NotSupported(this.id+" closeAllPositions() is not supported yet")}async editOrders(e,t={}){throw new y.NotSupported(this.id+" editOrders() is not supported yet")}async fetchCanceledAndClosedOrders(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchCanceledAndClosedOrders() is not supported yet")}async fetchPositionHistory(e,t,i,s={}){if(void 0!==this.has.fetchPositionsHistory&&!1!==this.has.fetchPositionsHistory)return await this.fetchPositionsHistory([e],t,i,s);throw new y.NotSupported(this.id+" fetchPositionHistory () is not supported yet")}async fetchPositionsHistory(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchPositionsHistory () is not supported yet")}async fetchPositionsRisk(e,t={}){throw new y.NotSupported(this.id+" fetchPositionsRisk() is not supported yet")}async fetchPositionsForSymbol(e,t={}){throw new y.NotSupported(this.id+" fetchPositionsForSymbol() is not supported yet")}async fetchPositionsForSymbolWs(e,t={}){throw new y.NotSupported(this.id+" fetchPositionsForSymbol() is not supported yet")}async watchPosition(e,t={}){throw new y.NotSupported(this.id+" watchPosition() is not supported yet")}async watchMyTradesForSymbols(e,t,i,s={}){throw new y.NotSupported(this.id+" watchMyTradesForSymbols() is not supported yet")}async watchTradesForSymbols(e,t,i,s={}){throw new y.NotSupported(this.id+" watchTradesForSymbols() is not supported yet")}async fetchBidsAsks(e,t={}){throw new y.NotSupported(this.id+" fetchBidsAsks() is not supported yet")}async fetchMarkPrice(e,t={}){if(void 0!==this.has.fetchMarkPrices&&!1!==this.has.fetchMarkPrices){await this.loadMarkets();let i=this.market(e).symbol,s=await this.fetchMarkPrices([i],t),r=this.safeDict(s,i);if(void 0!==r)return r;throw new y.NullResponse(this.id+" fetchMarkPrices() could not find a ticker for "+i)}throw new y.NotSupported(this.id+" fetchMarkPrices() is not supported yet")}async fetchMarkPrices(e,t={}){throw new y.NotSupported(this.id+" fetchMarkPrices() is not supported yet")}async watchBidsAsks(e,t={}){throw new y.NotSupported(this.id+" watchBidsAsks() is not supported yet")}async watchMarkPrice(e,t={}){throw new y.NotSupported(this.id+" watchMarkPrice () is not supported yet")}async watchMarkPrices(e,t={}){throw new y.NotSupported(this.id+" watchMarkPrices () is not supported yet")}async fetchL3OrderBook(e,t,i={}){throw new y.BadRequest(this.id+" fetchL3OrderBook() is not supported yet")}async watchOrderBookForSymbols(e,t,i={}){throw new y.NotSupported(this.id+" watchOrderBookForSymbols() is not supported yet")}async watchOrdersForSymbols(e,t,i,s={}){throw new y.NotSupported(this.id+" watchOrdersForSymbols() is not supported yet")}async cancelAllOrdersWs(e,t={}){throw new y.NotSupported(this.id+" cancelAllOrdersWs() is not supported yet")}async cancelOrderWs(e,t,i={}){throw new y.NotSupported(this.id+" cancelOrderWs() is not supported yet")}async cancelOrdersWs(e,t,i={}){throw new y.NotSupported(this.id+" cancelOrdersWs() is not supported yet")}async createLimitBuyOrderWs(e,t,i,s={}){return await this.createOrderWs(e,"limit","buy",t,i,s)}async createLimitOrderWs(e,t,i,s,r={}){return await this.createOrderWs(e,"limit",t,i,s,r)}async createLimitSellOrderWs(e,t,i,s={}){return await this.createOrderWs(e,"limit","sell",t,i,s)}async createMarketBuyOrderWs(e,t,i={}){return await this.createOrderWs(e,"market","buy",t,void 0,i)}async createMarketOrderWithCostWs(e,t,i,s={}){if(void 0!==this.has.createMarketOrderWithCostWs&&!1!==this.has.createMarketOrderWithCostWs||void 0!==this.has.createMarketBuyOrderWithCostWs&&!1!==this.has.createMarketBuyOrderWithCostWs&&void 0!==this.has.createMarketSellOrderWithCostWs&&!1!==this.has.createMarketSellOrderWithCostWs)return await this.createOrderWs(e,"market",t,i,1,s);throw new y.NotSupported(this.id+" createMarketOrderWithCostWs() is not supported yet")}async createMarketOrderWs(e,t,i,s,r={}){return await this.createOrderWs(e,"market",t,i,s,r)}async createMarketSellOrderWs(e,t,i={}){return await this.createOrderWs(e,"market","sell",t,void 0,i)}async createOrderWithTakeProfitAndStopLossWs(e,t,i,s,r,a,o,n={}){let d=this.setTakeProfitAndStopLossParams(e,t,i,s,r,a,o,n);if(void 0!==this.has.createOrderWithTakeProfitAndStopLossWs&&!1!==this.has.createOrderWithTakeProfitAndStopLossWs)return await this.createOrderWs(e,t,i,s,r,d);throw new y.NotSupported(this.id+" createOrderWithTakeProfitAndStopLossWs() is not supported yet")}async createOrderWs(e,t,i,s,r,a={}){throw new y.NotSupported(this.id+" createOrderWs() is not supported yet")}async createOrdersWs(e,t={}){throw new y.NotSupported(this.id+" createOrdersWs () is not supported yet")}async createPostOnlyOrderWs(e,t,i,s,r,a={}){if(void 0===this.has.createPostOnlyOrderWs||!1===this.has.createPostOnlyOrderWs)throw new y.NotSupported(this.id+" createPostOnlyOrderWs() is not supported yet");let o=this.extend(a,{postOnly:!0});return await this.createOrderWs(e,t,i,s,r,o)}async createReduceOnlyOrderWs(e,t,i,s,r,a={}){if(void 0===this.has.createReduceOnlyOrderWs||!1===this.has.createReduceOnlyOrderWs)throw new y.NotSupported(this.id+" createReduceOnlyOrderWs() is not supported yet");let o=this.extend(a,{reduceOnly:!0});return await this.createOrderWs(e,t,i,s,r,o)}async createStopLimitOrderWs(e,t,i,s,r,a={}){if(void 0===this.has.createStopLimitOrderWs||!1===this.has.createStopLimitOrderWs)throw new y.NotSupported(this.id+" createStopLimitOrderWs() is not supported yet");let o=this.extend(a,{stopPrice:r});return await this.createOrderWs(e,"limit",t,i,s,o)}async createStopLossOrderWs(e,t,i,s,r,a,o={}){if(void 0===a)throw new y.ArgumentsRequired(this.id+" createStopLossOrderWs() requires a stopLossPrice argument");let n=this.extend(o,{stopLossPrice:a});if(void 0!==this.has.createStopLossOrderWs&&!1!==this.has.createStopLossOrderWs)return await this.createOrderWs(e,t,i,s,r,n);throw new y.NotSupported(this.id+" createStopLossOrderWs() is not supported yet")}async createStopMarketOrderWs(e,t,i,s,r={}){if(void 0===this.has.createStopMarketOrderWs||!1===this.has.createStopMarketOrderWs)throw new y.NotSupported(this.id+" createStopMarketOrderWs() is not supported yet");let a=this.extend(r,{stopPrice:s});return await this.createOrderWs(e,"market",t,i,void 0,a)}async createStopOrderWs(e,t,i,s,r,a,o={}){if(void 0===this.has.createStopOrderWs||!1===this.has.createStopOrderWs)throw new y.NotSupported(this.id+" createStopOrderWs() is not supported yet");if(void 0===a)throw new y.ArgumentsRequired(this.id+" createStopOrderWs() requires a stopPrice argument");let n=this.extend(o,{stopPrice:a});return await this.createOrderWs(e,t,i,s,r,n)}async createTakeProfitOrderWs(e,t,i,s,r,a,o={}){if(void 0===a)throw new y.ArgumentsRequired(this.id+" createTakeProfitOrderWs() requires a takeProfitPrice argument");let n=this.extend(o,{takeProfitPrice:a});if(void 0!==this.has.createTakeProfitOrderWs&&!1!==this.has.createTakeProfitOrderWs)return await this.createOrderWs(e,t,i,s,r,n);throw new y.NotSupported(this.id+" createTakeProfitOrderWs() is not supported yet")}async createTrailingAmountOrderWs(e,t,i,s,r,a,o,n={}){if(void 0===a)throw new y.ArgumentsRequired(this.id+" createTrailingAmountOrderWs() requires a trailingAmount argument");if(n.trailingAmount=a,void 0!==o&&(n.trailingTriggerPrice=o),void 0!==this.has.createTrailingAmountOrderWs&&!1!==this.has.createTrailingAmountOrderWs)return await this.createOrderWs(e,t,i,s,r,n);throw new y.NotSupported(this.id+" createTrailingAmountOrderWs() is not supported yet")}async createTrailingPercentOrderWs(e,t,i,s,r,a,o,n={}){if(void 0===a)throw new y.ArgumentsRequired(this.id+" createTrailingPercentOrderWs() requires a trailingPercent argument");if(n.trailingPercent=a,void 0!==o&&(n.trailingTriggerPrice=o),void 0!==this.has.createTrailingPercentOrderWs&&!1!==this.has.createTrailingPercentOrderWs)return await this.createOrderWs(e,t,i,s,r,n);throw new y.NotSupported(this.id+" createTrailingPercentOrderWs() is not supported yet")}async createTriggerOrderWs(e,t,i,s,r,a,o={}){if(void 0===a)throw new y.ArgumentsRequired(this.id+" createTriggerOrderWs() requires a triggerPrice argument");let n=this.extend(o,{triggerPrice:a});if(void 0!==this.has.createTriggerOrderWs&&!1!==this.has.createTriggerOrderWs)return await this.createOrderWs(e,t,i,s,r,n);throw new y.NotSupported(this.id+" createTriggerOrderWs() is not supported yet")}async editOrderWs(e,t,i,s,r,a,o={}){return await this.cancelOrderWs(e,t),await this.createOrderWs(t,i,s,r,a,o)}async fetchClosedOrdersWs(e,t,i,s={}){if(void 0!==this.has.fetchOrdersWs&&!1!==this.has.fetchOrdersWs){let r=await this.fetchOrdersWs(e,t,i,s);return this.filterBy(r,"status","closed")}throw new y.NotSupported(this.id+" fetchClosedOrdersWs() is not supported yet")}async fetchMyTradesWs(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchMyTradesWs() is not supported yet")}async fetchOpenOrdersWs(e,t,i,s={}){if(void 0!==this.has.fetchOrdersWs&&!1!==this.has.fetchOrdersWs){let r=await this.fetchOrdersWs(e,t,i,s);return this.filterBy(r,"status","open")}throw new y.NotSupported(this.id+" fetchOpenOrdersWs() is not supported yet")}async fetchOrderBookWs(e,t,i={}){throw new y.NotSupported(this.id+" fetchOrderBookWs() is not supported yet")}async fetchOrderWs(e,t,i={}){throw new y.NotSupported(this.id+" fetchOrderWs() is not supported yet")}async fetchOrdersWs(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchOrdersWs() is not supported yet")}async fetchPositionWs(e,t={}){throw new y.NotSupported(this.id+" fetchPositionWs() is not supported yet")}async fetchPositionsWs(e,t={}){throw new y.NotSupported(this.id+" fetchPositions() is not supported yet")}async fetchTickerWs(e,t={}){if(void 0!==this.has.fetchTickersWs&&!1!==this.has.fetchTickersWs){await this.loadMarkets();let i=this.market(e).symbol,s=await this.fetchTickersWs([i],t),r=this.safeDict(s,i);if(void 0!==r)return r;throw new y.NullResponse(this.id+" fetchTickerWs() could not find a ticker for "+i)}throw new y.NotSupported(this.id+" fetchTickerWs() is not supported yet")}async fetchTickersWs(e,t={}){throw new y.NotSupported(this.id+" fetchTickersWs() is not supported yet")}async fetchTradesWs(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchTradesWs() is not supported yet")}async loadOrderBook(e,t,i,s,r={}){let a;if(!(i in this.orderbooks))return void e.reject(new y.ExchangeError(this.id+" loadOrderBook() orderbook is not initiated"),t);let o=this.handleOption("watchOrderBook","snapshotMaxRetries",3),n=0;try{let d=this.orderbooks[i];for(;n<o;){let a=d.cache,o=await this.fetchRestOrderBookSafe(i,s,r),h=this.getCacheIndex(o,a);if(h>=0){d.reset(o),this.handleBookDeltas(d,a.slice(h)),d.cache.length=0,e.resolve(d,t);return}n++}a=new y.ExchangeError(this.id+" nonce is behind the cache after "+o.toString()+" tries.")}catch(e){a=e}e.reject(a,t),void 0===e.error&&(e.error=a),e.close(),this.clients[e.url]===e&&delete this.clients[e.url],this.orderbooks[i]=this.orderBook()}async fetchTrades(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchTrades() is not supported yet")}async watchTrades(e,t,i,s={}){throw new y.NotSupported(this.id+" watchTrades() is not supported yet")}async fetchOrderBook(e,t,i={}){throw new y.NotSupported(this.id+" fetchOrderBook() is not supported yet")}async fetchRestOrderBookSafe(e,t,i={}){let s=this.handleOption("watchOrderBook","maxRetries",3);for(let r=0;r<s;r++)try{return await this.fetchOrderBook(e,t,i)}catch(e){if(r+1===s)throw e}}async watchOrderBook(e,t,i={}){throw new y.NotSupported(this.id+" watchOrderBook() is not supported yet")}async fetchOpenInterest(e,t={}){if(void 0!==this.has.fetchOpenInterests&&!1!==this.has.fetchOpenInterests){let i=await this.fetchOpenInterests([e],t);return this.safeDict(i,e)}throw new y.NotSupported(this.id+" fetchOpenInterest() is not supported yet")}async fetchL2OrderBook(e,t,i={}){let s=await this.fetchOrderBook(e,t,i);return this.extend(s,{asks:this.sortBy(this.aggregate(s.asks),0),bids:this.sortBy(this.aggregate(s.bids),0,!0)})}async editLimitBuyOrder(e,t,i,s,r={}){return await this.editLimitOrder(e,t,"buy",i,s,r)}async editLimitSellOrder(e,t,i,s,r={}){return await this.editLimitOrder(e,t,"sell",i,s,r)}async editLimitOrder(e,t,i,s,r,a={}){return await this.editOrder(e,t,"limit",i,s,r,a)}async editOrder(e,t,i,s,r,a,o={}){return await this.cancelOrder(e,t),await this.createOrder(t,i,s,r,a,o)}async editOrderWithClientOrderId(e,t,i,s,r,a,o={}){let n=this.extend(o,{clientOrderId:e});return await this.editOrder("",t,i,s,r,a,n)}async fetchPosition(e,t={}){throw new y.NotSupported(this.id+" fetchPosition() is not supported yet")}async watchPositions(e,t,i,s={}){throw new y.NotSupported(this.id+" watchPositions() is not supported yet")}async watchPositionForSymbols(e,t,i,s={}){return await this.watchPositions(e,t,i,s)}async fetchPositions(e,t={}){throw new y.NotSupported(this.id+" fetchPositions() is not supported yet")}async fetchTicker(e,t={}){if(void 0!==this.has.fetchTickers&&!1!==this.has.fetchTickers){await this.loadMarkets();let i=this.market(e).symbol,s=await this.fetchTickers([i],t),r=this.safeDict(s,i);if(void 0!==r)return r;throw new y.NullResponse(this.id+" fetchTickers() could not find a ticker for "+i)}throw new y.NotSupported(this.id+" fetchTicker() is not supported yet")}async watchTicker(e,t={}){throw new y.NotSupported(this.id+" watchTicker() is not supported yet")}async fetchTickers(e,t={}){throw new y.NotSupported(this.id+" fetchTickers() is not supported yet")}async watchTickers(e,t={}){throw new y.NotSupported(this.id+" watchTickers() is not supported yet")}async fetchOrder(e,t,i={}){throw new y.NotSupported(this.id+" fetchOrder() is not supported yet")}async fetchOrderWithClientOrderId(e,t,i={}){let s=this.extend(i,{clientOrderId:e});return await this.fetchOrder("",t,s)}async fetchOrderStatus(e,t,i={}){return(await this.fetchOrder(e,t,i)).status}async fetchUnifiedOrder(e,t={}){return await this.fetchOrder(this.safeString(e,"id"),this.safeString(e,"symbol"),t)}async createOrder(e,t,i,s,r,a={}){throw new y.NotSupported(this.id+" createOrder() is not supported yet")}async createTrailingAmountOrder(e,t,i,s,r,a,o,n={}){if(void 0===a)throw new y.ArgumentsRequired(this.id+" createTrailingAmountOrder() requires a trailingAmount argument");if(n.trailingAmount=a,void 0!==o&&(n.trailingTriggerPrice=o),void 0!==this.has.createTrailingAmountOrder&&!1!==this.has.createTrailingAmountOrder)return await this.createOrder(e,t,i,s,r,n);throw new y.NotSupported(this.id+" createTrailingAmountOrder() is not supported yet")}async createTrailingPercentOrder(e,t,i,s,r,a,o,n={}){if(void 0===a)throw new y.ArgumentsRequired(this.id+" createTrailingPercentOrder() requires a trailingPercent argument");if(n.trailingPercent=a,void 0!==o&&(n.trailingTriggerPrice=o),void 0!==this.has.createTrailingPercentOrder&&!1!==this.has.createTrailingPercentOrder)return await this.createOrder(e,t,i,s,r,n);throw new y.NotSupported(this.id+" createTrailingPercentOrder() is not supported yet")}async createMarketOrderWithCost(e,t,i,s={}){if(void 0!==this.has.createMarketOrderWithCost&&!1!==this.has.createMarketOrderWithCost||void 0!==this.has.createMarketBuyOrderWithCost&&!1!==this.has.createMarketBuyOrderWithCost&&void 0!==this.has.createMarketSellOrderWithCost&&!1!==this.has.createMarketSellOrderWithCost)return await this.createOrder(e,"market",t,i,1,s);throw new y.NotSupported(this.id+" createMarketOrderWithCost() is not supported yet")}async createMarketBuyOrderWithCost(e,t,i={}){if(!0===this.options.createMarketBuyOrderRequiresPrice||void 0!==this.has.createMarketBuyOrderWithCost&&!1!==this.has.createMarketBuyOrderWithCost)return await this.createOrder(e,"market","buy",t,1,i);throw new y.NotSupported(this.id+" createMarketBuyOrderWithCost() is not supported yet")}async createMarketSellOrderWithCost(e,t,i={}){if(!0===this.options.createMarketSellOrderRequiresPrice||void 0!==this.has.createMarketSellOrderWithCost&&!1!==this.has.createMarketSellOrderWithCost)return await this.createOrder(e,"market","sell",t,1,i);throw new y.NotSupported(this.id+" createMarketSellOrderWithCost() is not supported yet")}async createTriggerOrder(e,t,i,s,r,a,o={}){if(void 0===a)throw new y.ArgumentsRequired(this.id+" createTriggerOrder() requires a triggerPrice argument");let n=this.extend(o,{triggerPrice:a});if(void 0!==this.has.createTriggerOrder&&!1!==this.has.createTriggerOrder)return await this.createOrder(e,t,i,s,r,n);throw new y.NotSupported(this.id+" createTriggerOrder() is not supported yet")}async createStopLossOrder(e,t,i,s,r,a,o={}){if(void 0===a)throw new y.ArgumentsRequired(this.id+" createStopLossOrder() requires a stopLossPrice argument");let n=this.extend(o,{stopLossPrice:a});if(void 0!==this.has.createStopLossOrder&&!1!==this.has.createStopLossOrder)return await this.createOrder(e,t,i,s,r,n);throw new y.NotSupported(this.id+" createStopLossOrder() is not supported yet")}async createTakeProfitOrder(e,t,i,s,r,a,o={}){if(void 0===a)throw new y.ArgumentsRequired(this.id+" createTakeProfitOrder() requires a takeProfitPrice argument");let n=this.extend(o,{takeProfitPrice:a});if(void 0!==this.has.createTakeProfitOrder&&!1!==this.has.createTakeProfitOrder)return await this.createOrder(e,t,i,s,r,n);throw new y.NotSupported(this.id+" createTakeProfitOrder() is not supported yet")}async createOrderWithTakeProfitAndStopLoss(e,t,i,s,r,a,o,n={}){let d=this.setTakeProfitAndStopLossParams(e,t,i,s,r,a,o,n);if(void 0!==this.has.createOrderWithTakeProfitAndStopLoss&&!1!==this.has.createOrderWithTakeProfitAndStopLoss)return await this.createOrder(e,t,i,s,r,d);throw new y.NotSupported(this.id+" createOrderWithTakeProfitAndStopLoss() is not supported yet")}async createOrders(e,t={}){throw new y.NotSupported(this.id+" createOrders() is not supported yet")}async cancelOrder(e,t,i={}){throw new y.NotSupported(this.id+" cancelOrder() is not supported yet")}async cancelOrderWithClientOrderId(e,t,i={}){let s=this.extend(i,{clientOrderId:e});return await this.cancelOrder("",t,s)}async cancelOrders(e,t,i={}){throw new y.NotSupported(this.id+" cancelOrders() is not supported yet")}async cancelOrdersWithClientOrderIds(e,t,i={}){let s=this.extend(i,{clientOrderIds:e});return await this.cancelOrders([],t,s)}async cancelAllOrders(e,t={}){throw new y.NotSupported(this.id+" cancelAllOrders() is not supported yet")}async cancelUnifiedOrder(e,t={}){return this.cancelOrder(this.safeString(e,"id"),this.safeString(e,"symbol"),t)}async fetchOrders(e,t,i,s={}){if(void 0!==this.has.fetchOpenOrders&&!1!==this.has.fetchOpenOrders&&void 0!==this.has.fetchClosedOrders&&!1!==this.has.fetchClosedOrders)throw new y.NotSupported(this.id+" fetchOrders() is not supported yet, consider using fetchOpenOrders() and fetchClosedOrders() instead");throw new y.NotSupported(this.id+" fetchOrders() is not supported yet")}async fetchOrderTrades(e,t,i,s,r={}){throw new y.NotSupported(this.id+" fetchOrderTrades() is not supported yet")}async watchOrders(e,t,i,s={}){throw new y.NotSupported(this.id+" watchOrders() is not supported yet")}async fetchOpenOrders(e,t,i,s={}){if(void 0!==this.has.fetchOrders&&!1!==this.has.fetchOrders){let r=await this.fetchOrders(e,t,i,s);return this.filterBy(r,"status","open")}throw new y.NotSupported(this.id+" fetchOpenOrders() is not supported yet")}async fetchClosedOrders(e,t,i,s={}){if(void 0!==this.has.fetchOrders&&!1!==this.has.fetchOrders){let r=await this.fetchOrders(e,t,i,s);return this.filterBy(r,"status","closed")}throw new y.NotSupported(this.id+" fetchClosedOrders() is not supported yet")}async fetchCanceledOrders(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchCanceledOrders() is not supported yet")}async fetchMyTrades(e,t,i,s={}){throw new y.NotSupported(this.id+" fetchMyTrades() is not supported yet")}async watchMyTrades(e,t,i,s={}){throw new y.NotSupported(this.id+" watchMyTrades() is not supported yet")}async createLimitOrder(e,t,i,s,r={}){return await this.createOrder(e,"limit",t,i,s,r)}async createMarketOrder(e,t,i,s,r={}){return await this.createOrder(e,"market",t,i,s,r)}async createLimitBuyOrder(e,t,i,s={}){return await this.createOrder(e,"limit","buy",t,i,s)}async createLimitSellOrder(e,t,i,s={}){return await this.createOrder(e,"limit","sell",t,i,s)}async createMarketBuyOrder(e,t,i={}){return await this.createOrder(e,"market","buy",t,void 0,i)}async createMarketSellOrder(e,t,i={}){return await this.createOrder(e,"market","sell",t,void 0,i)}async createPostOnlyOrder(e,t,i,s,r,a={}){if(void 0===this.has.createPostOnlyOrder||!1===this.has.createPostOnlyOrder)throw new y.NotSupported(this.id+" createPostOnlyOrder() is not supported yet");let o=this.extend(a,{postOnly:!0});return await this.createOrder(e,t,i,s,r,o)}async createReduceOnlyOrder(e,t,i,s,r,a={}){if(void 0===this.has.createReduceOnlyOrder||!1===this.has.createReduceOnlyOrder)throw new y.NotSupported(this.id+" createReduceOnlyOrder() is not supported yet");let o=this.extend(a,{reduceOnly:!0});return await this.createOrder(e,t,i,s,r,o)}async createStopOrder(e,t,i,s,r,a,o={}){if(void 0===this.has.createStopOrder||!1===this.has.createStopOrder)throw new y.NotSupported(this.id+" createStopOrder() is not supported yet");if(void 0===a)throw new y.ArgumentsRequired(this.id+" create_stop_order() requires a stopPrice argument");let n=this.extend(o,{stopPrice:a});return await this.createOrder(e,t,i,s,r,n)}async createStopLimitOrder(e,t,i,s,r,a={}){if(void 0===this.has.createStopLimitOrder||!1===this.has.createStopLimitOrder)throw new y.NotSupported(this.id+" createStopLimitOrder() is not supported yet");let o=this.extend(a,{stopPrice:r});return await this.createOrder(e,"limit",t,i,s,o)}async createStopMarketOrder(e,t,i,s,r={}){if(void 0===this.has.createStopMarketOrder||!1===this.has.createStopMarketOrder)throw new y.NotSupported(this.id+" createStopMarketOrder() is not supported yet");let a=this.extend(r,{stopPrice:s});return await this.createOrder(e,"market",t,i,void 0,a)}async fetchTradingFee(e,t={}){if(void 0===this.has.fetchTradingFees||!1===this.has.fetchTradingFees)throw new y.NotSupported(this.id+" fetchTradingFee() is not supported yet");let i=await this.fetchTradingFees(t);return this.safeDict(i,e)}}i.d(t,{TJ:()=>tk,k5:()=>tS})},4473(e,t,i){"use strict";var s=i(1453);function r(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}let a={empty_plan:"the plan contains no steps",route_unroutable:"the route carries an unroutableReason and must not be executed",partial_fill:"the route does not fill completely at the requested size",unknown_symbol:"the symbol is not listed on that venue",market_mismatch:"the venue market trades a different pair than the route hop says it does",invalid_step:"the step has a non-positive amount or price, or a side that is neither buy nor sell",amount_below_minimum:"the amount is below the market minimum",amount_above_maximum:"the amount is above the market maximum",cost_below_minimum:"the notional is below the market minimum cost",price_out_of_range:"the limit price falls outside the market price limits",notional_unvaluable:"the step cannot be valued in USD, so the notional cap cannot be enforced",notional_exceeds_cap:"the notional exceeds the per-trade USD cap",amount_precision:"the amount does not sit on the market amount precision",price_precision:"the limit price does not sit on the market price precision"},o=["sequential","parallel_within_hop","limit_protected","best_effort","atomic_ish"],n=["amountIn","amountOut","strategy","maxVenues","bridges","exchanges","balances","balanceMode","includeQuotes","includeFees","certified","requireFullFill","hopPenaltyBps","minLegNotional"];class d{stepLimitPrice(e){let t=this.numberAt(e,"limitPrice",0);return t>0?t:this.numberAt(e,"expectedPrice",0)}stepNotionalQuote(e){let t=this.numberAt(e,"notionalQuote",0);return t>0?t:this.numberAt(e,"amount",0)*this.numberAt(e,"expectedPrice",0)}numberAt(e,t,i){if(null==e)return i;let s=e[t];return null==s?i:"number"==typeof s?this.isFiniteNumber(s)?s:i:"string"==typeof s?this.parseNumber(s,i):i}isFiniteNumber(e){return e==e&&!(e>17976931348623157e292)&&!(e<-17976931348623157e292)}parseNumber(e,t){if(null==e)return t;let i=0;for(;i<e.length&&this.isRouterSpace(e[i]);)i+=1;let s=i;i<e.length&&("+"===e[i]||"-"===e[i])&&(i+=1);let r=0;for(;i<e.length&&e[i]>="0"&&e[i]<="9";)i+=1,r+=1;if(i<e.length&&"."===e[i])for(i+=1;i<e.length&&e[i]>="0"&&e[i]<="9";)i+=1,r+=1;if(0===r)return t;let a=i;if(i<e.length&&("e"===e[i]||"E"===e[i])){let t=i+1;t<e.length&&("+"===e[t]||"-"===e[t])&&(t+=1);let s=0;for(;t<e.length&&e[t]>="0"&&e[t]<="9";)t+=1,s+=1;s>0&&(a=t)}let o=Number(e.slice(s,a));return this.isFiniteNumber(o)?o:t}isRouterSpace(e){return" "===e||"	"===e||"\n"===e||"\r"===e||"\f"===e||"\v"===e}stringAt(e,t,i){if(null==e)return i;let s=e[t];return null==s?i:"string"==typeof s?s:i}boolAt(e,t,i){if(null==e)return i;let s=e[t];return null==s?i:"boolean"==typeof s?s:i}listAt(e,t){if(null==e)return[];let i=e[t];return null==i?[]:Array.isArray(i)?i:[]}dictAt(e,t){if(null==e)return{};let i=e[t];return null==i||"object"!=typeof i||Array.isArray(i)?{}:i}formatNumber(e){if(!isFinite(e))return"0";if(Math.abs(e)>=1e18)throw new s.BadRequest("OrderRouter: a number this large cannot be rendered identically in all six languages");let t=e.toFixed(12);if(t.indexOf(".")>=0){for(;t.length>0&&"0"===t[t.length-1];)t=t.slice(0,t.length-1);t.length>0&&"."===t[t.length-1]&&(t=t.slice(0,t.length-1))}return""===t||"-"===t||"-0"===t?"0":t}async fetchRoute(e,t,i={}){if(void 0===e||void 0===t||""===e||""===t)throw new s.ArgumentsRequired("fetchRoute requires fromAsset and toAsset");this.assertRouteAmounts(i,"fetchRoute");let r=Object.keys(this.venues);if(r.sort(),r.length>0){let e={},t=Object.keys(i);for(let s=0;s<t.length;s++)e[t[s]]=i[t[s]];(void 0===e.exchanges||null===e.exchanges)&&(e.exchanges=r.join(",")),this.trackBalances&&(void 0===e.balances||null===e.balances)&&(e.balances=await this.loadBalances()),i=e}let a=void 0!==i.balances&&null!==i.balances,o=this.stringAt(i,"requestId",""),n={};return n=a?await this.request(this.baseUrl+"/route","POST",this.routeBody(e,t,i),o):await this.request(this.baseUrl+"/route?"+this.routeQuery(e,t,i),"GET",{},o),a&&this.assertBalancesApplied(n,i),n.clientRequestedRequireFullFill=this.boolAt(i,"requireFullFill",!1),n.clientRequestedFrom=e.toUpperCase(),n.clientRequestedTo=t.toUpperCase(),n}assertRouteAmounts(e,t){if((void 0!==e.amountIn&&null!==e.amountIn)==(void 0!==e.amountOut&&null!==e.amountOut))throw new s.BadRequest(t+" requires exactly one of amountIn or amountOut")}streamUrl(e,t,i){if(void 0===e||void 0===t||""===e||""===t)throw new s.ArgumentsRequired("watchRoute requires fromAsset and toAsset");if(this.assertRouteAmounts(i,"watchRoute"),void 0!==i.balances&&null!==i.balances)throw new s.BadRequest("OrderRouter: /stream/route does not accept balances — a socket outlives the holdings it was opened with. Use fetchRoute");if(void 0!==i.balanceMode&&null!==i.balanceMode)throw new s.BadRequest("OrderRouter: /stream/route does not accept balanceMode, because it does not accept balances. Use fetchRoute");let r=Object.keys(this.venues);if(r.sort(),r.length>0&&void 0===i.exchanges){let e={},t=Object.keys(i);for(let s=0;s<t.length;s++)e[t[s]]=i[t[s]];e.exchanges=r.join(","),i=e}let a=this.routeQuery(e,t,i),o=this.baseUrl;return 0===o.indexOf("https://")?o="wss://"+o.slice(8):0===o.indexOf("http://")&&(o="ws://"+o.slice(7)),o+"/stream/route?"+a}streamHandshakeError(e){let t="Unexpected server response: ",i=e.indexOf(t);if(i>=0){let r=this.parseNumber(e.slice(i+t.length,i+t.length+3),0);if(401===r)return new s.AuthenticationError("OrderRouter: unauthorized");if(403===r)return new s.PermissionDenied("OrderRouter: the router resolved this client to a non-IPv4 address and refused it; reach it over IPv4");if(429===r)return new s.RateLimitExceeded("OrderRouter: rate limit exceeded")}return new s.ExchangeNotAvailable("OrderRouter: "+e)}streamCloseError(e,t){if(1008===e){let e=this.stringAt(t,"error","the router rejected the stream request");return new s.BadRequest("OrderRouter: "+e)}if(1013===e){let e=this.stringAt(t,"error","the router cache is cold");return new s.ExchangeNotAvailable("OrderRouter: "+e+this.coldCacheSuffix(t))}if(1e3!==e&&1005!==e&&0!==e)return new s.ExchangeNotAvailable("OrderRouter: the route stream closed with code "+e.toString())}assertBalancesApplied(e,t){if(!0===this.boolAt(t,"requireBalancesApplied",!0)&&""===this.stringAt(e,"balancesApplied","")&&!(this.numberAt(e,"balanceEntryCount",-1)>=0))throw new s.ExchangeError("OrderRouter did not echo balancesApplied: the balances were ignored, so this route is not funded-aware")}routeParamText(e){if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e)return this.formatNumber(e);if(Array.isArray(e))return e.join(",");if("string"==typeof e)return e;throw new s.BadRequest("OrderRouter: a route parameter must be a string, number, boolean or array; got "+typeof e)}routeQuery(e,t,i){let s="from="+encodeURIComponent(e.toUpperCase())+"&to="+encodeURIComponent(t.toUpperCase());for(let e=0;e<n.length;e++){let t=n[e],r=i[t];if(null==r)continue;let a="balances"===t?this.renderBalances(r):this.routeParamText(r);s=s+"&"+t+"="+encodeURIComponent(a)}return s}routeBody(e,t,i){let s={};s.from=e.toUpperCase(),s.to=t.toUpperCase();for(let e=0;e<n.length;e++){let t=n[e],r=i[t];null!=r&&("balances"===t?s[t]=this.renderBalances(r):"number"==typeof r||"boolean"==typeof r?s[t]=r:s[t]=this.routeParamText(r))}return s}retrySuffix(e){return""===e?"":", retry after "+e+"s"}coldCacheSuffix(e){let t=this.numberAt(e,"bookCount",0);if(t<=0)return"";let i=this.numberAt(e,"freshCount",0),s=this.numberAt(e,"minFreshBooksForReady",0);return" ("+this.formatNumber(i)+" of "+this.formatNumber(t)+" books fresh, "+this.formatNumber(s)+" needed)"}async request(e,t="GET",i={},r=""){let a={Accept:"application/json"};""!==this.apiKey&&(a["x-api-key"]=this.apiKey),""!==r&&r.length<=200&&(a["x-request-id"]=r);let o={method:t,headers:a};"POST"===t&&(a["Content-Type"]="application/json",o.body=JSON.stringify(i));let n=new AbortController,d=setTimeout(()=>n.abort(),this.timeoutMs);o.signal=n.signal;let h=0,c="",l="",u="";try{let t=await fetch(e,o);h=t.status;let i=t.headers.get("retry-after");null!=i&&(l=i);let s=t.headers.get("x-ratelimit-reset");null!=s&&(u=s),c=await t.text()}catch(t){let e=this.stringAt(t,"name",this.errorCodeOf(t));if("AbortError"===e||"TimeoutError"===e)throw new s.RequestTimeout("OrderRouter request timed out after "+this.timeoutMs.toString()+"ms");throw new s.ExchangeNotAvailable("OrderRouter request failed: "+t.message)}finally{clearTimeout(d)}let f={};try{f=JSON.parse(c)}catch(e){throw new s.ExchangeError("OrderRouter returned a non-JSON body")}if(h>=200&&h<300||(404===h||501===h)&&""!==this.stringAt(f,"unroutableReason",""))return f;let p=this.stringAt(f,"error","http status "+h.toString());if(400===h)throw new s.BadRequest("OrderRouter: "+p);if(401===h)throw new s.AuthenticationError("OrderRouter: "+p);if(403===h)throw new s.PermissionDenied("OrderRouter: "+p+" — the router resolved this client to a non-IPv4 address and refused it; reach it over IPv4");if(429===h){let e=""!==l?l:u;throw new s.RateLimitExceeded("OrderRouter: "+p+this.retrySuffix(e))}if(408===h||504===h)throw new s.RequestTimeout("OrderRouter: "+p);if(503===h){if(""!==this.stringAt(f,"status",""))return f;throw new s.ExchangeNotAvailable("OrderRouter: "+p+this.coldCacheSuffix(f)+this.retrySuffix(l))}throw new s.ExchangeError("OrderRouter: "+p)}async fetchHealth(){return await this.request(this.baseUrl+"/health","GET",{})}async fetchReadiness(){return await this.request(this.baseUrl+"/ready","GET",{})}async fetchVersion(){return await this.request(this.baseUrl+"/version","GET",{})}async fetchSymbols(){let e=await this.request(this.baseUrl+"/symbols","GET",{});return this.listAt(e,"symbols")}async fetchExchangesStatus(){let e=await this.request(this.baseUrl+"/exchanges/status","GET",{});return this.listAt(e,"exchanges")}async fetchCachedOrderBook(e,t){if(void 0===e||void 0===t||""===e||""===t)throw new s.ArgumentsRequired("fetchCachedOrderBook requires an exchangeId and a symbol");let i=this.baseUrl+"/orderbook/"+encodeURIComponent(e)+"/"+encodeURIComponent(t);return await this.request(i,"GET",{})}async watchRoute(e,t,i={},r){if(void 0===r)throw new s.ArgumentsRequired("watchRoute requires an onRoute callback");let a=this.streamUrl(e,t,i),o=this.stringAt(i,"requestId",""),n=await this.loadWebSocket(),d={};""!==this.apiKey&&(d["x-api-key"]=this.apiKey),""!==o&&o.length<=200&&(d["x-request-id"]=o);let h=new n(a,{headers:d}),c=e.toUpperCase(),l=t.toUpperCase(),u=this.boolAt(i,"requireFullFill",!1),f={},p={},m=!1;return await new Promise((e,t)=>{let i=setTimeout(()=>{if(i=void 0,!m){m=!0;try{h.close()}catch(e){}t(new s.RequestTimeout("OrderRouter stream did not open within "+this.timeoutMs.toString()+"ms"))}},this.timeoutMs),a=()=>{void 0!==i&&(clearTimeout(i),i=void 0)};h.onopen=()=>{a()},h.onmessage=i=>{let o;if(m)return;let n={};try{n=JSON.parse(i.data.toString())}catch(e){m=!0,a();try{h.close()}catch(e){}t(new s.ExchangeError("OrderRouter stream sent a non-JSON frame"));return}if(f=n,""===this.stringAt(n,"error","")){n.clientRequestedFrom=c,n.clientRequestedTo=l,n.clientRequestedRequireFullFill=u,p=n;try{o=r(n)}catch(e){m=!0,a();try{h.close()}catch(e){}t(e);return}if("stop"===o){m=!0,a();try{h.close(1e3)}catch(e){}e(p)}}},h.onerror=e=>{if(m)return;m=!0,a();let i=this.stringAt(e,"message","the route stream failed");t(this.streamHandshakeError(i))},h.onclose=i=>{if(a(),m)return;m=!0;let s=this.numberAt(i,"code",0),r=this.streamCloseError(s,f);void 0===r?e(p):t(r)}})}async loadWebSocket(){if(void 0!==this.webSocketImpl)return this.webSocketImpl;try{let e=await Promise.resolve().then(i.t.bind(i,1591,23));return this.webSocketImpl=void 0!==e.default?e.default:e,this.webSocketImpl}catch(e){throw new s.NotSupported("OrderRouter.watchRoute needs the ws package, which ccxt depends on but a browser bundle cannot provide — a browser WebSocket cannot send the x-api-key header the router requires. Use fetchRoute, or proxy the stream server-side")}}async loadBalances(e=!1){if(!this.trackBalances||0===Object.keys(this.venues).length)return"";if(this.balancesLoaded&&!e)return this.balancesCache;let t=this.balancesGeneration,i=await this.collectBalances(this.venues),s=this.stringAt(i,"balances","");return t===this.balancesGeneration&&(this.balancesCache=s,this.balancesLoaded=!0),s}invalidateBalances(){this.balancesLoaded=!1,this.balancesCache="",this.balancesGeneration=this.balancesGeneration+1}async collectBalances(e){let t=Object.keys(e);t.sort();let i=[],s=[];for(let r=0;r<t.length;r++){let a=t[r],o=e[a],n=await o.fetchBalance(),d=this.dictAt(n,"free");0===Object.keys(d).length&&(d=this.dictAt(n,"total"));let h=Object.keys(d);h.sort();for(let e=0;e<h.length;e++){let t=h[e],r=this.numberAt(d,t,0);if(!(r<=0)){if(r>=1e18){s.push({exchangeId:a,asset:t,amount:r,reason:"amount_out_of_range"});continue}i.push({exchangeId:a,asset:t,amount:r})}}}for(i.sort((e,t)=>e.amount!==t.amount?e.amount>t.amount?-1:1:e.exchangeId!==t.exchangeId?e.exchangeId<t.exchangeId?-1:1:e.asset<t.asset?-1:1);i.length>d.MAX_BALANCE_ENTRIES;){let e=i.pop();e.reason="entry_cap",s.push(e)}let r=this.joinBalances(i);for(;r.length>d.MAX_BALANCE_CHARS&&i.length>0;){let e=i.pop();e.reason="char_cap",s.push(e),r=this.joinBalances(i)}return{balances:r,dropped:s}}async fetchRouteWithBalances(e,t,i,s={}){0===Object.keys(i).length&&(i=this.venues);let r=await this.collectBalances(i),a=this.stringAt(r,"balances",""),o=this.listAt(r,"dropped"),n={},d=Object.keys(s);for(let e=0;e<d.length;e++)n[d[e]]=s[d[e]];n.balances=a;let h=await this.fetchRoute(e,t,n);return h.balancesUsed=a,h.balancesDropped=o,h}looksLikeOptions(e){let t=Object.keys(e);if(0===t.length)return!1;for(let i=0;i<t.length;i++){let s=e[t[i]];if(null!==s&&"object"==typeof s&&"function"==typeof s.createOrder)return!1}return!0}assertNoPlanShapingOptions(e){let t=["slippageBps","reconcileToleranceRatio"];for(let i=0;i<t.length;i++){let r=t[i];if(void 0!==e[r]&&null!==e[r])throw new s.BadRequest("OrderRouter: "+r+" shapes a plan and this plan is already built, so it cannot be applied — pass it to buildExecutionPlan, or hand execute the route instead of the plan")}}async marketsOf(e){let t={},i=Object.keys(e);i.sort();for(let s=0;s<i.length;s++){let r=i[s],a=e[r];0===Object.keys(this.dictAt(a,"markets")).length&&await a.loadMarkets(),t[r]=this.dictAt(a,"markets")}return t}renderBalances(e){if("string"==typeof e)return e;if(Array.isArray(e))return e.join(",");if(null===e||"object"!=typeof e)throw new s.BadRequest('OrderRouter: balances must be "[exchangeId.]ASSET:amount" entries, or a wallet like { mexc: { USDT: 100 } } or { USDT: 100 }');let t=[],i=Object.keys(e);i.sort();for(let s=0;s<i.length;s++){let r=i[s],a=e[r];if(null===a||"object"!=typeof a||Array.isArray(a)){let i=this.numberAt(e,r,0);i>0&&t.push({exchangeId:"",asset:r,amount:i})}else{let e=Object.keys(a);e.sort();for(let i=0;i<e.length;i++){let s=this.numberAt(a,e[i],0);s>0&&t.push({exchangeId:r,asset:e[i],amount:s})}}}return this.joinBalances(t)}joinBalances(e){let t="";for(let i=0;i<e.length;i++){let s=e[i];i>0&&(t+=",");let r=this.stringAt(s,"exchangeId","");t=t+(""===r?"":r+".")+s.asset+":"+this.formatNumber(s.amount)}return t}assertRouteChainIsCoherent(e,t){if(0===t.length)return;let i="";for(let r=0;r<t.length;r++){let a=t[r],o=this.stringAt(a,"side","").toLowerCase(),n=this.stringAt(a,"base","").toUpperCase(),d=this.stringAt(a,"quote","").toUpperCase();if(""===n||""===d||"buy"!==o&&"sell"!==o)throw new s.ExchangeError("OrderRouter: hop "+r.toString()+" does not name a market and a side");let h="buy"===o?d:n,c="buy"===o?n:d;if(r>0&&h!==i)throw new s.ExchangeError("OrderRouter: hop "+r.toString()+" spends "+h+" but the previous hop produced "+i);if(0===r){i=h;let t=this.stringAt(e,"clientRequestedFrom","");if(""!==t&&h!==t)throw new s.ExchangeError("OrderRouter: the route spends "+h+", not the requested "+t)}i=c}let r=this.stringAt(e,"clientRequestedTo","");if(""!==r&&i!==r)throw new s.ExchangeError("OrderRouter: the route produces "+i+", not the requested "+r)}buildExecutionPlan(e,t={}){let i=this.numberAt(t,"slippageBps",d.DEFAULT_SLIPPAGE_BPS),s=this.numberAt(t,"reconcileToleranceRatio",d.DEFAULT_RECONCILE_TOLERANCE),r=this.listAt(e,"hops");this.assertRouteChainIsCoherent(e,r);let a=[],o=0;for(let e=0;e<r.length;e++){let t=r[e],s=this.stringAt(t,"pair",""),n=this.stringAt(t,"side",""),d=this.stringAt(t,"base",""),h=this.stringAt(t,"quote",""),c=this.listAt(t,"legs");for(let t=0;t<c.length;t++){let r=c[t],l=this.numberAt(r,"amount",0),u=this.numberAt(r,"averagePrice",0),f=this.numberAt(r,"effectivePrice",u),p=0;p="buy"===n?u*(1+i/1e4):u*(1-i/1e4),a.push({stepIndex:o,hopIndex:e,legIndex:t,exchangeId:this.stringAt(r,"exchangeId",""),symbol:s,side:n,base:d,quote:h,amount:l,expectedPrice:u,effectivePrice:f,limitPrice:p,notionalQuote:l*u,expectedFeeCost:this.numberAt(r,"feeCost",0),balanceLimited:this.boolAt(r,"balanceLimited",!1)}),o+=1}}return{requestId:this.stringAt(e,"requestId",""),calculatedAt:this.numberAt(e,"calculatedAt",0),from:this.stringAt(e,"from",""),to:this.stringAt(e,"to",""),routingStrategy:this.stringAt(e,"strategy",""),exactSide:this.stringAt(e,"exactSide",""),amountIn:this.numberAt(e,"amountIn",0),amountOut:this.numberAt(e,"amountOut",0),fullyFillable:this.boolAt(e,"fullyFillable",!1),fillRatio:this.numberAt(e,"fillRatio",0),unroutableReason:this.stringAt(e,"unroutableReason",""),unroutableHopIndex:this.numberAt(e,"unroutableHopIndex",-1),requireFullFill:this.boolAt(e,"clientRequestedRequireFullFill",!1),hopCount:r.length,stepCount:a.length,slippageBps:i,reconcileToleranceRatio:s,steps:a}}checkExecutionPlanSafety(e,t,i={}){let s=[],r=this.numberAt(i,"maxNotionalUsd",this.maxNotionalUsd),a=r>0,o=this.dictAt(i,"usdRates"),n=this.stringAt(i,"precisionMode","tick_size"),h=this.listAt(e,"steps");if(0===h.length)return s.push(this.violation(-1,"","","empty_plan",!0,0,0)),s;if(""!==this.stringAt(e,"unroutableReason","")&&s.push(this.violation(-1,"","","route_unroutable",!0,0,0)),!this.boolAt(e,"fullyFillable",!1)){let t=this.boolAt(e,"requireFullFill",!1);s.push(this.violation(-1,"","","partial_fill",t,this.numberAt(e,"fillRatio",0),1))}for(let e=0;e<h.length;e++){let i=h[e],c=this.numberAt(i,"stepIndex",e),l=this.stringAt(i,"exchangeId",""),u=this.stringAt(i,"symbol",""),f=this.numberAt(i,"amount",0),p=this.numberAt(i,"expectedPrice",0),m=this.stepLimitPrice(i),g=this.stepNotionalQuote(i),v=this.stringAt(i,"side","");if(f<=0||p<=0||"buy"!==v&&"sell"!==v){s.push(this.violation(c,l,u,"invalid_step",!0,f,0));continue}let y=this.dictAt(t,l),b=this.dictAt(y,u);if(0===Object.keys(b).length){s.push(this.violation(c,l,u,"unknown_symbol",!0,0,0));continue}let w=this.stringAt(b,"base",""),k=this.stringAt(b,"quote",""),S=this.stringAt(i,"base",""),O=this.stringAt(i,"quote","");if(""!==w&&""!==S&&w!==S||""!==k&&""!==O&&k!==O){s.push(this.violation(c,l,u,"market_mismatch",!0,0,0));continue}let T=this.dictAt(b,"limits"),P=this.dictAt(T,"amount"),I=this.dictAt(T,"price"),A=this.dictAt(T,"cost"),x=this.numberAt(P,"min",0),M=this.numberAt(P,"max",0),_=this.numberAt(I,"min",0),C=this.numberAt(I,"max",0),B=this.numberAt(A,"min",0);x>0&&f<x&&s.push(this.violation(c,l,u,"amount_below_minimum",!0,f,x)),M>0&&f>M&&s.push(this.violation(c,l,u,"amount_above_maximum",!0,f,M)),B>0&&g<B&&s.push(this.violation(c,l,u,"cost_below_minimum",!0,g,B)),(_>0&&m<_||C>0&&m>C)&&s.push(this.violation(c,l,u,"price_out_of_range",!0,m,m<_?_:C));let E=this.dictAt(b,"precision"),R=this.numberAt(E,"amount",0),L=this.numberAt(E,"price",0);this.precisionViolated(f,R,n)&&s.push(this.violation(c,l,u,"amount_precision",!1,f,R)),this.precisionViolated(m,L,n)&&s.push(this.violation(c,l,u,"price_precision",!1,m,L));let N=p;if(m>N&&(N=m),a){let e=f*N,t=this.notionalUsd(i,e,o);t<=0?s.push(this.violation(c,l,u,"notional_unvaluable",!0,e,r)):t>r*(1+d.TOLERANCE)&&s.push(this.violation(c,l,u,"notional_exceeds_cap",!0,t,r))}}return s}violation(e,t,i,s,r,o,n){return{stepIndex:e,exchangeId:t,symbol:i,code:s,blocking:r,actual:o,limit:n,message:this.stringAt(a,s,s)}}notionalUsd(e,t,i){let s=this.stringAt(e,"quote",""),r=this.usdRateFor(s,i);if(r>0)return t*r;let a=this.stringAt(e,"base",""),o=this.usdRateFor(a,i);return o>0?this.numberAt(e,"amount",0)*o:0}usdRateFor(e,t){if(""===e)return 0;if("USD"===e)return 1;let i=this.numberAt(t,e,0);return i>0?i:0}precisionViolated(e,t,i){if(t<=0)return!1;let s=0;if("decimal_places"===i){let i=Math.pow(10,t);s=Math.round(e*i)/i}else s=Math.round(e/t)*t;let r=Math.abs(e)*d.TOLERANCE+1e-15;return Math.abs(s-e)>r}reconcileExecutionStep(e,t,i){let r=this.listAt(e,"steps");if(t<0||t>=r.length)throw new s.BadRequest("reconcileExecutionStep: stepIndex is out of range");let a=r[t],o=this.numberAt(a,"hopIndex",0),n=this.numberAt(e,"reconcileToleranceRatio",d.DEFAULT_RECONCILE_TOLERANCE),h=this.stepExpectedOut(a),c=[];if(h<=0)return{stepIndex:t,hopIndex:o,expectedOut:0,realisedOut:i,shortfall:0,shortfallRatio:0,scale:0,verdict:"halt",reason:"zero_expected_output",resizedSteps:c};let l=h-i;l<0&&(l=0);let u=l/h,f=0,p=0;for(let e=0;e<r.length;e++)if(this.numberAt(r[e],"hopIndex",0)===o&&(f+=this.stepExpectedOut(r[e]),this.numberAt(r[e],"stepIndex",-1)!==t&&this.hasNumberAt(r[e],"realisedOut"))){let t=this.stepExpectedOut(r[e])-this.numberAt(r[e],"realisedOut",0);t<0&&(t=0),p+=t}let m=1,g=1;f>0&&(m=(f-p)/f,g=(f-p-l)/f),m<=0&&(m=1,g=0);let v=g/m;v>1&&(v=1),v<0&&(v=0);for(let e=0;e<r.length;e++){let t=r[e];if(this.numberAt(t,"hopIndex",0)<=o)continue;let i=this.numberAt(t,"amount",0),s=i*v;c.push({stepIndex:this.numberAt(t,"stepIndex",e),previousAmount:i,amount:s,notionalQuote:s*this.numberAt(t,"expectedPrice",0)})}let y="proceed",b="within_tolerance";return i<=0?(y="halt",b="nothing_filled"):u>n*(1+d.TOLERANCE)&&(y="halt",b="shortfall_exceeds_tolerance"),{stepIndex:t,hopIndex:o,expectedOut:h,realisedOut:i,shortfall:l,shortfallRatio:u,scale:v,verdict:y,reason:b,resizedSteps:c}}stepExpectedOut(e){let t=this.numberAt(e,"amount",0);if("buy"===this.stringAt(e,"side",""))return t;let i=t*this.numberAt(e,"expectedPrice",0),s=this.numberAt(e,"expectedFeeCost",0);return s<=0||s>=i?i:i-s}buildUnwindPlan(e){let t=this.stringAt(e,"from",""),i=this.stringAt(e,"to",""),s=this.numberAt(e,"slippageBps",d.DEFAULT_SLIPPAGE_BPS),r=this.listAt(e,"steps"),a=[];for(let e=r.length-1;e>=0;e--){let t=r[e],i=this.stringAt(t,"exchangeId",""),s=this.stringAt(t,"outAsset",""),o=this.numberAt(t,"outAmount",0);""!==s&&o>0&&this.addPosition(a,i,s,o,t,!0);let n=this.stringAt(t,"inAsset",""),d=this.numberAt(t,"inAmount",0);""!==n&&d>0&&this.addPosition(a,i,n,-d,t,!1)}let o=[],n=[],h=0;for(let e=0;e<a.length;e++){let r=a[e],d=this.stringAt(r,"asset",""),c=this.numberAt(r,"amount",0),l=this.stringAt(r,"exchangeId","");if(c<=0||d===t)continue;h+=1;let u=this.dictAt(r,"source"),f=this.stringAt(u,"symbol",""),p=this.stringAt(u,"side",""),m=this.numberAt(u,"averagePrice",0);if(m<=0&&(m=this.numberAt(u,"expectedPrice",0)),""===f||"buy"!==p&&"sell"!==p){n.push({exchangeId:l,asset:d,amount:c,reason:"no_source_market"});continue}if(m<=0){n.push({exchangeId:l,asset:d,amount:c,reason:"no_price"});continue}let g="",v=0,y="",b="",w=this.stringAt(u,"inAsset","");"buy"===p?(g="sell",y=this.stringAt(u,"outAsset",""),b=this.stringAt(u,"inAsset","")):(g="buy",y=this.stringAt(u,"inAsset",""),b=this.stringAt(u,"outAsset",""));let k=0;k="buy"===g?m*(1+s/1e4):m*(1-s/1e4),v="buy"===g?c/k:c,o.push({stepIndex:o.length,exchangeId:l,symbol:f,side:g,base:y,quote:b,asset:d,counterAsset:w,amount:v,expectedPrice:m,limitPrice:k,notionalQuote:v*k,reachesFrom:w===t,isDestination:d===i})}return{from:t,to:i,halted:this.boolAt(e,"halted",!1),haltReason:this.stringAt(e,"haltReason",""),residualCount:h,requiresConfirmation:!0,automatic:!1,steps:o,unresolved:n}}addPosition(e,t,i,s,r,a){for(let o=0;o<e.length;o++){let n=e[o];if(n.exchangeId===t&&n.asset===i){n.amount=this.numberAt(n,"amount",0)+s,a&&0===Object.keys(this.dictAt(n,"source")).length&&(n.source=r);return}}e.push({exchangeId:t,asset:i,amount:s,source:a?r:{}})}planIdentity(e,t){let i=this.stringAt(t,"idempotencyKey","");return""!==i?i:this.stringAt(e,"requestId","")}hasExecutedPlan(e){return void 0!==this.executedPlanIdSet[e]}recordExecutedPlan(e){if(!this.hasExecutedPlan(e))for(this.executedPlanIds.push(e),this.executedPlanIdSet[e]=!0;this.executedPlanIds.length>d.MAX_EXECUTED_PLAN_IDS;){let e=this.executedPlanIds[0];this.executedPlanIds=this.executedPlanIds.slice(1),delete this.executedPlanIdSet[e]}}async execute(e,t={},i={}){this.looksLikeOptions(t)&&(i=t,t={}),0===Object.keys(t).length&&(t=this.venues),this.listAt(e,"steps").length>0&&this.assertNoPlanShapingOptions(i),0===this.listAt(e,"steps").length&&this.listAt(e,"hops").length>0&&(e=this.buildExecutionPlan(e,i));let r=this.stringAt(i,"strategy","sequential");if(0>o.indexOf(r))throw new s.BadRequest("OrderRouter: unknown execution strategy "+r);if(void 0!==i.live&&null!==i.live)throw new s.BadRequest("OrderRouter: options.live is gone — execute places orders, and a rehearsal is asked for with dryRun. Remove live, or pass dryRun to place nothing");let a=!0===i.dryRun,n=this.cloneSteps(e),d=this.emptyReport(e,r,a,n),h=this.planIdentity(e,i);d.planId=h;let c=this.numberAt(e,"calculatedAt",0),l=c>0?this.nowMs()-c:-1;d.planAgeMs=l;let u=this.numberAt(i,"maxPlanAgeMs",0);if(!a&&u>0){if(l<0)throw new s.ExchangeError("OrderRouter: refusing to execute, the plan carries no calculatedAt and maxPlanAgeMs was set");if(l>u)throw new s.ExchangeError("OrderRouter: refusing to execute a plan older than maxPlanAgeMs, recompute the route")}if(a)return d.wouldPlaceOrders=n.length,d;if(0===Object.keys(t).length)throw new s.ArgumentsRequired("OrderRouter.execute requires a venues dictionary when live");if(""===h)throw new s.BadRequest("OrderRouter: refusing to execute live without an identity, the plan carries no requestId — pass options.idempotencyKey");if(!0!==i.allowReexecution&&this.hasExecutedPlan(h))throw new s.BadRequest("OrderRouter: refusing to re-execute a plan this instance already executed, pass allowReexecution to override");let f=this.hopCountOf(n);if("best_effort"===r){if(f>1)throw new s.NotSupported("OrderRouter: best_effort refuses multi-hop routes");if(!0!==i.acknowledgeDispersion)throw new s.BadRequest("OrderRouter: best_effort requires acknowledgeDispersion");if(0>=this.numberAt(i,"maxOrders",0))throw new s.BadRequest("OrderRouter: best_effort requires a positive maxOrders")}if("limit_protected"===r&&this.hasNumberAt(i,"pollIntervalMs")&&0>=this.numberAt(i,"pollIntervalMs",0))throw new s.BadRequest("OrderRouter: pollIntervalMs must be positive, a resting order is polled on that clock");let p={},m=Object.keys(t);m.sort();for(let e=0;e<m.length;e++){let i=m[e],s=t[i];0===Object.keys(this.dictAt(s,"markets")).length&&await s.loadMarkets(),p[i]=this.dictAt(s,"markets")}let g=this.dictAt(i,"usdRates"),v={usdRates:g,maxNotionalUsd:this.numberAt(i,"maxNotionalUsd",this.maxNotionalUsd),precisionMode:this.stringAt(i,"precisionMode","tick_size")},y=this.checkExecutionPlanSafety(e,p,v),b="";for(let e=0;e<y.length;e++)this.boolAt(y[e],"blocking",!1)&&(""!==b&&(b+=", "),b+=this.stringAt(y[e],"code",""));if(""!==b){let e="";throw b.indexOf("notional_unvaluable")>=0&&0===Object.keys(g).length&&(e=" — maxNotionalUsd is set but options.usdRates is empty, and the cap cannot be evaluated without a USD price for the quote currency"),new s.ExchangeError("OrderRouter: refusing to execute, blocking safety violations: "+b+e)}"atomic_ish"===r&&await this.assertPrefunded(n,t),this.recordExecutedPlan(h),this.invalidateBalances();try{"parallel_within_hop"===r?await this.executeParallelWithinHop(d,n,t,i,g):"best_effort"===r?await this.executeBestEffort(d,n,t,i,g):await this.executeSequential(d,n,t,i,g,r)}finally{this.invalidateBalances()}return this.summariseReport(d,n),d}hopCountOf(e){let t=[];for(let i=0;i<e.length;i++){let s=this.numberAt(e[i],"hopIndex",0),r=!1;for(let e=0;e<t.length;e++)if(t[e]===s){r=!0;break}r||t.push(s)}return t.length}cloneSteps(e){let t=this.listAt(e,"steps"),i=[];for(let e=0;e<t.length;e++){let s=t[e];i.push({stepIndex:this.numberAt(s,"stepIndex",e),hopIndex:this.numberAt(s,"hopIndex",0),legIndex:this.numberAt(s,"legIndex",0),exchangeId:this.stringAt(s,"exchangeId",""),symbol:this.stringAt(s,"symbol",""),side:this.stringAt(s,"side",""),base:this.stringAt(s,"base",""),quote:this.stringAt(s,"quote",""),amount:this.numberAt(s,"amount",0),expectedPrice:this.numberAt(s,"expectedPrice",0),effectivePrice:this.numberAt(s,"effectivePrice",0),limitPrice:this.stepLimitPrice(s),notionalQuote:this.stepNotionalQuote(s),expectedFeeCost:this.numberAt(s,"expectedFeeCost",0)})}return i}emptyReport(e,t,i,s){let r=[];for(let e=0;e<s.length;e++){let t=s[e];r.push({stepIndex:this.numberAt(t,"stepIndex",e),hopIndex:this.numberAt(t,"hopIndex",0),legIndex:this.numberAt(t,"legIndex",0),exchangeId:this.stringAt(t,"exchangeId",""),symbol:this.stringAt(t,"symbol",""),side:this.stringAt(t,"side",""),status:"planned",requestedAmount:this.numberAt(t,"amount",0),filledAmount:0,averagePrice:0,expectedPrice:this.numberAt(t,"expectedPrice",0),cost:0,inAsset:"",inAmount:0,outAsset:"",outAmount:0,orderId:"",clientOrderId:"",errorCode:"",attempt:0})}return{planId:"",strategy:t,dryRun:i,live:!i,from:this.stringAt(e,"from",""),to:this.stringAt(e,"to",""),slippageBps:this.numberAt(e,"slippageBps",d.DEFAULT_SLIPPAGE_BPS),reconcileToleranceRatio:this.numberAt(e,"reconcileToleranceRatio",d.DEFAULT_RECONCILE_TOLERANCE),stepCount:s.length,wouldPlaceOrders:0,ordersPlaced:0,halted:!1,haltReason:"",haltStepIndex:-1,filledIn:0,filledOut:0,steps:r,openOrders:[],errors:[],reconciliations:[]}}async executeSequential(e,t,i,s,r,a){let o=this.listAt(e,"steps");for(let n=0;n<t.length;n++){let h=t[n],c=await this.placeStepWithRetry(h,i,s,r,a,e);o[n]=c;let l=this.stringAt(c,"status","");if("failed"===l||"outcome_unknown"===l){e.halted=!0,e.haltReason="failed"===l?"order_failed":"outcome_unknown",e.haltStepIndex=n,this.callOnStep(s,e,c,{},n,t.length),this.markRemainingSkipped(o,n+1);return}let u=this.reconcileExecutionStep({steps:t,reconcileToleranceRatio:this.numberAt(e,"reconcileToleranceRatio",d.DEFAULT_RECONCILE_TOLERANCE)},n,this.numberAt(c,"outAmount",0));if(e.reconciliations.push(u),"atomic_ish"!==a&&this.applyResize(t,u),"halt"===this.stringAt(u,"verdict","")){e.halted=!0,e.haltReason=this.stringAt(u,"reason",""),e.haltStepIndex=n,this.callOnStep(s,e,c,u,n,t.length),this.markRemainingSkipped(o,n+1);return}if("halt"===this.callOnStep(s,e,c,u,n,t.length)){e.halted=!0,e.haltReason="halted_by_on_step",e.haltStepIndex=n,this.markRemainingSkipped(o,n+1);return}}}async executeParallelWithinHop(e,t,i,s,r){let a=this.listAt(e,"steps"),o=0;for(;o<t.length;){let n=this.numberAt(t[o],"hopIndex",0),h=o;for(;h<t.length&&this.numberAt(t[h],"hopIndex",0)===n;)h+=1;let c=[],l=[],u=[];for(let e=o;e<h;e++){let i=this.stringAt(t[e],"exchangeId",""),s=-1;for(let e=0;e<l.length;e++)if(l[e]===i){s=e;break}-1===s?(l.push(i),u.push([e])):u[s].push(e)}for(let o=0;o<u.length;o++)c.push(this.placeVenueGroup(u[o],t,i,s,r,e,a));for(let e=0;e<c.length;e++)await c[e];for(let i=o;i<h;i++){let r=a[i],o=this.stringAt(r,"status","");if("failed"===o||"outcome_unknown"===o){e.halted=!0,e.haltReason="failed"===o?"order_failed":"outcome_unknown",e.haltStepIndex=i,this.callOnStep(s,e,r,{},i,t.length),this.markRemainingSkipped(a,h);return}let n=this.reconcileExecutionStep({steps:t,reconcileToleranceRatio:this.numberAt(e,"reconcileToleranceRatio",d.DEFAULT_RECONCILE_TOLERANCE)},i,this.numberAt(r,"outAmount",0));if(e.reconciliations.push(n),this.applyResize(t,n),"halt"===this.stringAt(n,"verdict","")){e.halted=!0,e.haltReason=this.stringAt(n,"reason",""),e.haltStepIndex=i,this.callOnStep(s,e,r,n,i,t.length),this.markRemainingSkipped(a,h);return}if("halt"===this.callOnStep(s,e,r,n,i,t.length)){e.halted=!0,e.haltReason="halted_by_on_step",e.haltStepIndex=i,this.markRemainingSkipped(a,h);return}}o=h}}async placeVenueGroup(e,t,i,s,r,a,o){for(let n=0;n<e.length;n++){let d=e[n];o[d]=await this.placeStepWithRetry(t[d],i,s,r,"parallel_within_hop",a)}}async executeBestEffort(e,t,i,s,r){let a=this.listAt(e,"steps"),o=this.numberAt(s,"maxOrders",0),n=0;for(let d=0;d<t.length;d++){if(n>=o){a[d].status="skipped",a[d].errorCode="max_orders_reached";continue}if(a[d]=await this.placeStepWithRetry(t[d],i,s,r,"best_effort",e),n+=1,"halt"===this.callOnStep(s,e,a[d],{},d,t.length)){e.halted=!0,e.haltReason="halted_by_on_step",e.haltStepIndex=d,this.markRemainingSkipped(a,d+1);return}}}async placeStepWithRetry(e,t,i,s,r,a){let o=this.numberAt(i,"retryFailedSteps",0),n=this.numberAt(i,"retryDelayMs",d.DEFAULT_RETRY_DELAY_MS),h=0,c={};for(;;){if(e.attempt=h,c=await this.placeStep(e,t,i,s,r,a),"failed"!==this.stringAt(c,"status","")||h>=o)return c;h+=1,n>0&&await this.sleep(n)}}callOnStep(e,t,i,s,r,a){if(void 0===e.onStep)return"";let o={planId:this.stringAt(t,"planId",""),stepIndex:r,hopIndex:this.numberAt(i,"hopIndex",0),legIndex:this.numberAt(i,"legIndex",0),exchangeId:this.stringAt(i,"exchangeId",""),symbol:this.stringAt(i,"symbol",""),side:this.stringAt(i,"side",""),status:this.stringAt(i,"status",""),requestedAmount:this.numberAt(i,"requestedAmount",0),filledAmount:this.numberAt(i,"filledAmount",0),outAsset:this.stringAt(i,"outAsset",""),outAmount:this.numberAt(i,"outAmount",0),orderId:this.stringAt(i,"orderId",""),clientOrderId:this.stringAt(i,"clientOrderId",""),errorCode:this.stringAt(i,"errorCode",""),attempt:this.numberAt(i,"attempt",0),reconciliation:s,ordersPlaced:this.numberAt(t,"ordersPlaced",0),halted:this.boolAt(t,"halted",!1),haltReason:this.stringAt(t,"haltReason",""),stepsTotal:a,stepsRemaining:a-(r+1)};try{let t=e.onStep(o);if("halt"===t)return"halt";return""}catch(e){return this.recordError(t,r,this.stringAt(i,"exchangeId",""),this.stringAt(i,"symbol",""),"on_step_hook_failed:"+this.errorCodeOf(e)),""}}async placeStep(e,t,i,s,r,a){let o=this.numberAt(e,"stepIndex",0),n=this.stringAt(e,"exchangeId",""),h=this.stringAt(e,"symbol",""),c=this.stringAt(e,"side",""),l={stepIndex:o,hopIndex:this.numberAt(e,"hopIndex",0),legIndex:this.numberAt(e,"legIndex",0),exchangeId:n,symbol:h,side:c,status:"failed",requestedAmount:this.numberAt(e,"amount",0),filledAmount:0,averagePrice:0,expectedPrice:this.numberAt(e,"expectedPrice",0),cost:0,inAsset:"",inAmount:0,outAsset:"",outAmount:0,orderId:"",clientOrderId:"",errorCode:"",placementAttempted:!1};try{let u=t[n];if(null==u)return l.errorCode="venue_missing",this.recordError(a,o,n,h,"venue_missing"),l;let f=this.parseNumber(u.amountToPrecision(h,this.numberAt(e,"amount",0)),0),p=this.parseNumber(u.priceToPrecision(h,this.stepLimitPrice(e)),0);if(!(f>0)||!(p>0))return l.errorCode="rounded_to_zero",this.recordError(a,o,n,h,"rounded_to_zero"),l;this.assertUnderCap(e,f,p,s,i);let m={},g=this.dictAt(i,"orderParams"),v=Object.keys(g);for(let e=0;e<v.length;e++)m[v[e]]=g[v[e]];l.attempt=this.numberAt(e,"attempt",0);let y={};y="limit_protected"===r?await this.placeProtectedLimit(u,e,h,c,f,p,m,i,a,l):await this.placeImmediateOrder(u,h,c,f,p,m,i,l),l.orderId=this.stringAt(y,"id",""),l.clientOrderId=this.stringAt(y,"clientOrderId",""),this.hasNumberAt(y,"filled")||""===l.orderId||(y=await this.refetchOrder(u,this.stringAt(l,"orderId",""),h,y));let b=!1;if("limit_protected"!==r&&"open"===this.stringAt(y,"status","")&&""!==l.orderId)try{await u.cancelOrder(this.stringAt(l,"orderId",""),h),y=await this.refetchOrder(u,this.stringAt(l,"orderId",""),h,y)}catch(e){b=!0}let w=this.hasNumberAt(y,"filled"),k=this.numberAt(y,"filled",0),S=this.hasNumberAt(y,"average")||this.hasNumberAt(y,"price"),O=this.numberAt(y,"average",0);O<=0&&(O=this.numberAt(y,"price",0)),O<=0&&(O=p);let T=this.hasNumberAt(y,"cost"),P=this.numberAt(y,"cost",0);P<=0&&(P=k*O),l.filledAmount=k,l.averagePrice=O,l.cost=P,l.filledKnown=w,l.averageKnown=S,l.costKnown=T,"buy"===c?(l.inAsset=this.stringAt(e,"quote",""),l.inAmount=P,l.outAsset=this.stringAt(e,"base",""),l.outAmount=k):(l.inAsset=this.stringAt(e,"base",""),l.inAmount=k,l.outAsset=this.stringAt(e,"quote",""),l.outAmount=P);let I=this.orderFeeInAsset(y,this.stringAt(l,"outAsset",""));if(l.feeCost=I,l.feeCurrency=this.stringAt(l,"outAsset",""),I>0){let e=this.numberAt(l,"outAmount",0)-I;e<0&&(e=0),l.grossOutAmount=this.numberAt(l,"outAmount",0),l.outAmount=e}if(!w)return l.status="outcome_unknown",this.recordOpenOrder(a,n,h,this.stringAt(l,"orderId",""),"fill_unconfirmed"),a.ordersPlaced=this.numberAt(a,"ordersPlaced",0)+1,l;return k<=0?l.status="unfilled":k>=f*(1-d.TOLERANCE)?l.status="filled":l.status="partial",b?(l.status="outcome_unknown",this.recordOpenOrder(a,n,h,this.stringAt(l,"orderId",""),"cancel_failed")):"open"===this.stringAt(y,"status","")&&(l.status="outcome_unknown",this.recordOpenOrder(a,n,h,this.stringAt(l,"orderId",""),"still_open")),a.ordersPlaced=this.numberAt(a,"ordersPlaced",0)+1,l}catch(t){l.status="failed",l.errorCode=this.errorCodeOf(t),this.recordError(a,o,n,h,l.errorCode);let e=this.stringAt(l,"orderId","");return""!==e?(l.status="outcome_unknown",this.recordOpenOrder(a,n,h,e,"outcome_unknown")):this.boolAt(l,"placementAttempted",!1)&&this.isOutcomeUnknownError(l.errorCode)&&(l.status="outcome_unknown",this.recordUnconfirmedPlacement(a,n,h,"placement_unconfirmed")),l}}recordUnconfirmedPlacement(e,t,i,s){let r=this.listAt(e,"openOrders");for(let e=0;e<r.length;e++)if(this.stringAt(r[e],"exchangeId","")===t&&this.stringAt(r[e],"symbol","")===i&&this.stringAt(r[e],"reason","")===s)return;e.openOrders.push({exchangeId:t,symbol:i,orderId:"",reason:s})}recordOpenOrder(e,t,i,s,r){if(""===s)return;let a=this.listAt(e,"openOrders");for(let e=0;e<a.length;e++)if(this.stringAt(a[e],"orderId","")===s&&this.stringAt(a[e],"exchangeId","")===t)return;e.openOrders.push({exchangeId:t,symbol:i,orderId:s,reason:r})}hasNumberAt(e,t){if(null==e)return!1;let i=e[t];return null!=i&&("number"==typeof i?this.isFiniteNumber(i):"string"==typeof i&&this.isFiniteNumber(this.parseNumber(i,NaN)))}async refetchOrder(e,t,i,s){try{let r=await e.fetchOrder(t,i);if(null==r)return s;return r}catch(e){return s}}orderFeeInAsset(e,t){if(""===t)return 0;let i=0,s=this.listAt(e,"fees"),r=!1;for(let e=0;e<s.length;e++){let a=s[e];this.stringAt(a,"currency","").toUpperCase()===t.toUpperCase()&&(i+=this.numberAt(a,"cost",0),r=!0)}if(!r){let s=this.dictAt(e,"fee");this.stringAt(s,"currency","").toUpperCase()===t.toUpperCase()&&(i+=this.numberAt(s,"cost",0),r=!0)}if(!r){let s=this.listAt(e,"trades");for(let e=0;e<s.length;e++){let r=this.dictAt(s[e],"fee");this.stringAt(r,"currency","").toUpperCase()===t.toUpperCase()&&(i+=this.numberAt(r,"cost",0))}}return!this.isFiniteNumber(i)||i<0?0:i}isOutcomeUnknownError(e){return"RequestTimeout"===e||"ExchangeNotAvailable"===e||"NetworkError"===e||"OnMaintenance"===e||"OperationFailed"===e||"BadResponse"===e||"NullResponse"===e}errorCodeOf(e){return null==e?"unknown_error":void 0!==e.constructor&&null!==e.constructor&&"string"==typeof e.constructor.name?e.constructor.name:"unknown_error"}async placeImmediateOrder(e,t,i,r,a,o,n,d){if(this.venueSupportsIoc(e)){o.timeInForce="IOC",d.placementAttempted=!0;let s=await e.createOrder(t,"limit",i,r,a,o);return d.orderId=this.stringAt(s,"id",""),s}if(!0!==n.allowMarketOrders)throw new s.NotSupported("OrderRouter: venue cannot do IOC and allowMarketOrders was not set");if(this.numberAt(n,"maxNotionalUsd",this.maxNotionalUsd)>0)throw new s.NotSupported("OrderRouter: allowMarketOrders cannot be honoured under a maxNotionalUsd cap, because a market order has no price to check");d.placementAttempted=!0;let h=await e.createOrder(t,"market",i,r,void 0,o);return d.orderId=this.stringAt(h,"id",""),h}async placeProtectedLimit(e,t,i,r,a,o,n,d,h,c){let l=this.numberAt(d,"orderTimeoutMs",2e4),u=this.numberAt(d,"pollIntervalMs",1e3);c.placementAttempted=!0;let f=await e.createOrder(i,"limit",r,a,o,n),p=this.stringAt(f,"id","");c.orderId=p;let m=0;for(;m<l;){if("closed"===this.stringAt(f,"status","")||"canceled"===this.stringAt(f,"status",""))return f;await this.sleep(u),m+=u,f=await e.fetchOrder(p,i)}let g=this.stringAt(f,"status","");if("closed"===g||"canceled"===g)return f;try{await e.cancelOrder(p,i)}catch(e){throw this.recordOpenOrder(h,this.stringAt(t,"exchangeId",""),i,p,"cancel_failed"),new s.ExchangeError("OrderRouter: cancelOrder failed and an order is left OPEN, refusing to proceed")}return await e.fetchOrder(p,i)}venueSupportsIoc(e){let t=this.dictAt(e,"features"),i=this.dictAt(t,"spot"),s=this.dictAt(i,"createOrder"),r=this.dictAt(s,"timeInForce");if(Object.keys(r).length>0)return this.boolAt(r,"IOC",!1);let a=this.listAt(s,"timeInForce");if(0===a.length)return!0;for(let e=0;e<a.length;e++)if("IOC"===a[e])return!0;return!1}assertUnderCap(e,t,i,r,a){let o=this.numberAt(a,"maxNotionalUsd",this.maxNotionalUsd);if(o<=0)return;let n={base:this.stringAt(e,"base",""),quote:this.stringAt(e,"quote",""),amount:t},h=this.notionalUsd(n,t*i,r);if(h<=0)throw new s.ExchangeError("OrderRouter: refusing to place an order that cannot be valued in USD");if(h>o*(1+d.TOLERANCE))throw new s.ExchangeError("OrderRouter: refusing to place an order above the per-trade USD notional cap")}async assertPrefunded(e,t){let i=[];for(let t=0;t<e.length;t++){let s=e[t],r=this.stringAt(s,"exchangeId",""),a=this.numberAt(s,"amount",0),o="",n=0;"buy"===this.stringAt(s,"side","")?(o=this.stringAt(s,"quote",""),n=a*this.stepLimitPrice(s)):(o=this.stringAt(s,"base",""),n=a);let d=!1;for(let e=0;e<i.length;e++)if(i[e].exchangeId===r&&i[e].asset===o){i[e].amount=this.numberAt(i[e],"amount",0)+n,d=!0;break}d||i.push({exchangeId:r,asset:o,amount:n})}let r={};for(let e=0;e<i.length;e++){let a=this.stringAt(i[e],"exchangeId","");void 0===r[a]&&(r[a]=await t[a].fetchBalance());let o=this.dictAt(r[a],"free"),n=this.stringAt(i[e],"asset","");if(this.numberAt(o,n,0)<this.numberAt(i[e],"amount",0))throw new s.InsufficientFunds("OrderRouter: atomic_ish requires the whole route pre-funded, and "+a+" is short of "+n)}}applyResize(e,t){let i=this.numberAt(t,"stepIndex",-1);for(let s=0;s<e.length;s++)if(this.numberAt(e[s],"stepIndex",-1)===i){e[s].realisedOut=this.numberAt(t,"realisedOut",0);break}let s=this.listAt(t,"resizedSteps");for(let t=0;t<s.length;t++){let i=s[t],r=this.numberAt(i,"stepIndex",-1);for(let t=0;t<e.length;t++)if(this.numberAt(e[t],"stepIndex",-1)===r){e[t].amount=this.numberAt(i,"amount",0),e[t].notionalQuote=this.numberAt(i,"notionalQuote",0);break}}}markRemainingSkipped(e,t){for(let i=t;i<e.length;i++)"planned"===this.stringAt(e[i],"status","")&&(e[i].status="skipped")}recordError(e,t,i,s,r){e.errors.push({stepIndex:t,exchangeId:i,symbol:s,code:r})}summariseReport(e,t){let i=this.listAt(e,"steps"),s=0;for(let e=0;e<t.length;e++){let i=this.numberAt(t[e],"hopIndex",0);i>s&&(s=i)}let r=0,a=0;for(let e=0;e<i.length;e++){let t=this.numberAt(i[e],"hopIndex",0);0===t&&(r+=this.numberAt(i[e],"inAmount",0)),t===s&&(a+=this.numberAt(i[e],"outAmount",0))}e.filledIn=r,e.filledOut=a}nowMs(){return Date.now()}sleep(e){return new Promise(t=>setTimeout(t,e))}constructor(e={}){r(this,"apiKey",void 0),r(this,"baseUrl",void 0),r(this,"venues",void 0),r(this,"balancesCache",void 0),r(this,"balancesLoaded",void 0),r(this,"balancesGeneration",void 0),r(this,"trackBalances",void 0),r(this,"timeoutMs",void 0),r(this,"maxNotionalUsd",void 0),r(this,"webSocketImpl",void 0),r(this,"executedPlanIds",void 0),r(this,"executedPlanIdSet",void 0),this.apiKey=this.stringAt(e,"apiKey","");let t=this.stringAt(e,"baseUrl",d.DEFAULT_BASE_URL);for(;t.length>0&&"/"===t[t.length-1];)t=t.slice(0,t.length-1);this.baseUrl=t,this.venues=this.dictAt(e,"venues"),this.balancesCache="",this.balancesLoaded=!1,this.balancesGeneration=0,this.trackBalances=this.boolAt(e,"trackBalances",!1),this.timeoutMs=this.numberAt(e,"timeoutMs",d.DEFAULT_TIMEOUT_MS);const i=this.numberAt(e,"maxNotionalUsd",d.NO_CAP);if(i<0)throw new s.BadRequest("OrderRouter maxNotionalUsd must not be negative; omit it, or pass 0, for no cap");this.maxNotionalUsd=i,this.executedPlanIds=[],this.executedPlanIdSet={}}}r(d,"DEFAULT_BASE_URL","https://docs.ccxt.com/router/api"),r(d,"DEFAULT_TIMEOUT_MS",3e4),r(d,"DEFAULT_SLIPPAGE_BPS",25),r(d,"DEFAULT_RECONCILE_TOLERANCE",.02),r(d,"DEFAULT_RETRY_DELAY_MS",1e3),r(d,"NO_CAP",0),r(d,"MAX_BALANCE_ENTRIES",64),r(d,"MAX_BALANCE_CHARS",4096),r(d,"MAX_EXECUTED_PLAN_IDS",1024),r(d,"TOLERANCE",1e-9),i.d(t,{G:()=>d})},7749(e,t,i){"use strict";function s(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}let r=BigInt(0),a=BigInt(-1),o=BigInt(10),n=[BigInt(1)];for(let e=1;e<=128;e++)n.push(n[e-1]*o);function d(e){return e<n.length?n[e]:o**BigInt(e)}class h{mul(e){return new h(this.integer*e.integer,this.decimals+e.decimals)}div(e,t=18){let i=t-this.decimals+e.decimals;return new h((0===i?this.integer:i<0?this.integer/d(-i):this.integer*d(i))/e.integer,t)}add(e){if(this.decimals===e.decimals)return new h(this.integer+e.integer,this.decimals);let t=this.decimals-e.decimals;return t>0?new h(e.integer*d(t)+this.integer,this.decimals):new h(this.integer*d(-t)+e.integer,e.decimals)}mod(e){let t=Math.max(-this.decimals+e.decimals,0),i=this.integer*d(t),s=Math.max(-e.decimals+this.decimals,0);return new h(i%(e.integer*d(s)),s+e.decimals)}sub(e){if(this.decimals===e.decimals)return new h(this.integer-e.integer,this.decimals);let t=this.decimals>e.decimals,i=t?e.integer:this.integer,s=t?this.integer:e.integer,r=t?this.decimals:e.decimals,a=i*d(r-(t?e.decimals:this.decimals));return new h(t?s-a:a-s,r)}abs(){return new h(this.integer<0?this.integer*a:this.integer,this.decimals)}neg(){return new h(-this.integer,this.decimals)}or(e){return new h(this.integer|e.integer,this.decimals)}min(e){return this.lt(e)?this:e}max(e){return this.gt(e)?this:e}compare(e){if(this.decimals===e.decimals)return this.integer===e.integer?0:this.integer<e.integer?-1:1;let t=this.decimals-e.decimals;if(t>0){let i=e.integer*d(t);return this.integer===i?0:this.integer<i?-1:1}let i=this.integer*d(-t);return i===e.integer?0:i<e.integer?-1:1}gt(e){return this.compare(e)>0}ge(e){return this.compare(e)>=0}lt(e){return 0>this.compare(e)}le(e){return 0>=this.compare(e)}reduceDigits(){let e,t=this.integer.toString(),i=t.length-1;if(0===i)return"0"===t&&(this.decimals=0),t;for(e=i;e>=0&&48===t.charCodeAt(e);e--);let s=i-e;if(0===s)return t;this.decimals-=s;let r=t.slice(0,e+1);return this.integer=BigInt(r),r}reduce(){return this.reduceDigits(),this}equals(e){return this.reduce(),e.reduce(),this.decimals===e.decimals&&this.integer===e.integer}toString(){let e=this.reduceDigits(),t="";45===e.charCodeAt(0)&&(t="-",e=e.slice(1));let i=this.decimals;if(i<=0)return t+e+"0".repeat(-i);if(e.length<=i)return t+"0."+e.padStart(i,"0");let s=e.length-i;return t+e.slice(0,s)+"."+e.slice(s)}static stringMul(e,t){if(void 0!==e&&void 0!==t)return new h(e).mul(new h(t)).toString()}static stringDiv(e,t,i=18){if(void 0===e||void 0===t)return;let s=new h(t);if(s.integer!==r)return new h(e).div(s,i).toString()}static stringAdd(e,t){if(void 0!==e&&void 0!==t)return new h(e).add(new h(t)).toString()}static stringSub(e,t){if(void 0!==e&&void 0!==t)return new h(e).sub(new h(t)).toString()}static stringAbs(e){if(void 0!==e)return new h(e).abs().toString()}static stringNeg(e){if(void 0!==e)return new h(e).neg().toString()}static stringMod(e,t){if(void 0!==e&&void 0!==t)return new h(e).mod(new h(t)).toString()}static stringOr(e,t){if(void 0!==e&&void 0!==t)return new h(e).or(new h(t)).toString()}static stringEquals(e,t){return void 0!==e&&void 0!==t&&new h(e).equals(new h(t))}static stringEq(e,t){return void 0!==e&&void 0!==t&&new h(e).equals(new h(t))}static stringMin(e,t){if(void 0!==e&&void 0!==t)return new h(e).min(new h(t)).toString()}static stringMax(e,t){if(void 0!==e&&void 0!==t)return new h(e).max(new h(t)).toString()}static stringGt(e,t){return void 0!==e&&void 0!==t&&new h(e).gt(new h(t))}static stringGe(e,t){return void 0!==e&&void 0!==t&&new h(e).ge(new h(t))}static stringLt(e,t){return void 0!==e&&void 0!==t&&new h(e).lt(new h(t))}static stringLe(e,t){return void 0!==e&&void 0!==t&&new h(e).le(new h(t))}constructor(e,t){if(s(this,"decimals",void 0),s(this,"integer",void 0),s(this,"base",void 0),void 0===t){let t=e,i=0,s=t.indexOf("e");-1===s&&(s=t.indexOf("E")),s>-1&&(i=parseInt(t.slice(s+1)),t=t.slice(0,s));const r=t.indexOf(".");r>-1?(this.decimals=t.length-r-1-i,this.integer=BigInt(t.slice(0,r)+t.slice(r+1))):(this.decimals=0-i,this.integer=BigInt(t))}else this.integer=e,this.decimals=t}}i.d(t,{Y:()=>h},{A:h})},1374(e,t,i){"use strict";var s=i(6039),r=i(7749),a=i(1453);function o(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class n extends s.TJ{describe(){return this.deepExtend(super.describe(),{has:{prediction:!0,approve:!1,redeem:!1,fetchEvent:!1,fetchEvents:!1,fetchOutcome:!1,fetchSettlements:!1,createOrder:!1,createOrders:!1,createLimitOrder:!1,createMarketOrder:!1,createMarketOrderWs:!1,createMarketBuyOrderWithCost:!1,cancelOrder:!1,cancelOrders:!1,cancelAllOrders:!1,editOrder:!1,fetchBalance:!1,fetchOrder:!1,fetchOrders:!1,fetchOrdersByIds:!1,fetchOrderTrades:!1,fetchOpenOrders:!1,fetchClosedOrders:!1,fetchCanceledOrders:!1,fetchMyTrades:!1,fetchPosition:!1,fetchPositions:!1,fetchAccounts:!1,fetchLedger:!1,fetchDeposits:!1,fetchWithdrawals:!1,fetchMarkets:!1,fetchCurrencies:!1,fetchTicker:!1,fetchTickers:!1,fetchOrderBook:!1,fetchL2OrderBook:!1,fetchOHLCV:!1,fetchTrades:!1,fetchStatus:!1,fetchTime:!1,fetchOpenInterest:!1,fetchTradingFee:!1,watchTicker:!1,watchTickers:!1,watchOrderBook:!1,watchTrades:!1,watchOrders:!1,watchMyTrades:!1,watchOHLCV:!1,watchPositions:!1}})}isPrediction(){return this.safeBool(this.has,"prediction",!1)}parseSearchQueries(e={}){let t=this.safeString(e,"query");return void 0!==t?[t]:this.safeList(e,"queries",[])}requireEventQuery(e={}){let t=this.safeString(e,"query"),i=this.safeList(e,"queries",[]),s=this.safeList(e,"tags",[]),r=this.safeString(e,"eventId"),o=this.safeString(e,"slug"),n=i.length,d=s.length;if(void 0!==t||n>0||d>0||void 0!==r||void 0!==o)return;let h=this.safeList(this.options,"eventScopeParams",[]),c=h.length,l="";for(let t=0;t<c;t++){let i=h[t];if(i in e)return;l=l+", "+i}throw new a.ArgumentsRequired(this.id+" fetchEvents() requires at least one of query, queries, tags, eventId, slug"+l+" to scope the search")}applyEventFetchParams(e,t={},i){this.setEvents(e);let s=e,r=this.safeString(t,"eventId"),a=this.safeString(t,"slug");if(void 0!==r||void 0!==a){let e=[];for(let t=0;t<s.length;t++){let i=s[t],o=void 0!==r&&this.safeString(i,"id")===r,n=void 0!==a&&this.safeString(i,"slug")===a;(o||n)&&e.push(i)}s=e}s=this.filterEventsByStatus(s,this.safeString(t,"status")),s=this.filterEventsByTags(s,this.safeList(t,"tags"));let o=0;void 0!==i&&(o=i.length),o>0&&(s=this.filterEventsBySearchIn(s,i,this.safeString(t,"searchIn")));let n=this.safeString(t,"sort");if(void 0!==n){let e;if("volume"===n?e="volume":"liquidity"===n?e="liquidity":"newest"===n&&(e="created"),void 0!==e){for(let t=0;t<s.length;t++)s[t][e]=this.safeNumber(s[t],e,0);s=this.sortBy(s,e,!0,0)}}let d=this.safeInteger(t,"limit");if(void 0!==d){let e=s.length,t=d;t>e&&(t=e),s=this.arraySlice(s,0,t)}return s}filterEventsByStatus(e,t){if(void 0===t||"all"===t)return e;let i="active"===t,s=[];for(let t=0;t<e.length;t++){let r=e[t],a=this.safeBool(r,"active");(void 0===a||a===i)&&s.push(r)}return s}filterEventsBySearchIn(e,t,i){let s=0;if(void 0!==t&&(s=t.length),void 0===i||void 0===t||0===s)return e;let r="title"===i||"both"===i,o="description"===i||"both"===i,n=[];for(let i=0;i<e.length;i++){let s=e[i],d=this.safeStringLower(s,"title",""),h=this.safeStringLower(s,"description",""),c=!1;for(let e=0;e<t.length;e++){let i=t[e].toLowerCase();if(void 0===d)throw new a.ExchangeError(this.id+" filterEventsBySearchIn() missing title");if(r&&d.indexOf(i)>=0){c=!0;break}if(void 0===h)throw new a.ExchangeError(this.id+" filterEventsBySearchIn() missing description");if(o&&h.indexOf(i)>=0){c=!0;break}}c&&n.push(s)}return n}normalizeTagKey(e){let t=e.toLowerCase(),i=this.stringToCharsArray(t),s="",r=!1;for(let e=0;e<i.length;e++){let t=i[e];"abcdefghijklmnopqrstuvwxyz0123456789".indexOf(t)>=0?(r&&""!==s&&(s+=" "),s+=t,r=!1):r=!0}return s}filterEventsByTags(e,t){if(void 0===t||0===t.length)return e;let i=[];for(let e=0;e<t.length;e++){let s=this.normalizeTagKey(t[e]);""!==s&&i.push(s)}let s=[];for(let t=0;t<e.length;t++){let r=e[t],a=this.safeList(r,"tags",[]),o=!1;for(let e=0;e<a.length;e++){let t,s=a[e];if(void 0!==(t="string"==typeof s?s:this.safeString2(s,"slug","title"))){let e=this.normalizeTagKey(t);for(let t=0;t<i.length;t++)if(e.indexOf(i[t])>=0){o=!0;break}}if(o)break}o&&s.push(r)}return s}async fetchEvents(e={}){throw new a.NotSupported(this.id+" fetchEvents() is not supported yet")}async fetchEvent(e,t={}){throw new a.NotSupported(this.id+" fetchEvent() is not supported yet")}setEvents(e){void 0===this.events&&(this.events={}),void 0===this.events_by_slug&&(this.events_by_slug={});for(let t=0;t<e.length;t++){let i=e[t],s=this.safeString(i,"id"),r=this.safeString(i,"slug"),a=this.safeString(i,"event");void 0!==s&&(this.events[s]=i),void 0!==a&&(this.events[a]=i),void 0!==r&&(this.events_by_slug[r]=i)}return this.events}eventsList(){if(void 0===this.events)return[];let e=[],t={},i=Object.keys(this.events);for(let s=0;s<i.length;s++){let r=this.events[i[s]],a=this.safeString2(r,"id","event",i[s]);a in t||(t[a]=!0,e.push(r))}return e}async loadEventsHelper(e=!1,t={}){if(!e&&void 0!==this.events&&null!==this.events)return this.events;let i=await this.fetchEvents(t);return this.setEvents(i)}async loadEvents(e=!1,t={}){return await this.loadEventsHelper(e,t)}getEvent(e){if(void 0!==this.events&&e in this.events)return this.events[e];if(void 0!==this.events_by_slug&&e in this.events_by_slug)return this.events_by_slug[e];throw new a.BadSymbol(this.id+" has no cached event "+e+" - call fetchEvents ({ 'query': ... }) first")}outcome(e){if(void 0===e)throw new a.ArgumentsRequired(this.id+" outcome() requires an outcomeSymbol argument");if(void 0===this.outcomes||this.isEmpty(this.outcomes))throw new a.ExchangeError(this.id+" outcomes not loaded - call loadOutcomes () or an outcome-addressed method first");if(e in this.outcomes)return this.outcomes[e];if(void 0!==this.outcomes_by_id&&e in this.outcomes_by_id)return this.outcomes_by_id[e];throw new a.BadSymbol(this.id+" does not have outcome "+e+" - pass a known outcome handle or outcomeId, or call fetchEvents ()/loadOutcomes () first")}hasOutcome(e){return void 0!==e&&(void 0!==this.outcomes&&e in this.outcomes||void 0!==this.outcomes_by_id&&e in this.outcomes_by_id)}safeOutcome(e,t){if(void 0!==e){if(void 0!==this.outcomes&&e in this.outcomes)return this.outcomes[e];if(void 0!==this.outcomes_by_id&&e in this.outcomes_by_id)return this.outcomes_by_id[e]}return void 0!==t?t:{outcome:e,outcomeId:e,market:void 0,label:void 0,event:void 0,info:{}}}safeOutcomeSymbol(e,t){return this.safeOutcome(e,t).outcome}shortenSlug(e){let t={"federal-reserve":"fed","interest-rates":"rates","interest-rate":"rate","basis-points":"bps","basis-point":"bp","executive-order":"eo","united-states":"us","united-kingdom":"uk","european-union":"eu","artificial-intelligence":"ai","republican-party":"gop","democratic-party":"dems","stock-market":"market","price-target":"pt","market-cap":"mcap",increase:"hike",decrease:"cut",higher:"up",lower:"down",greater:"gt",less:"lt",million:"M",billion:"B",trillion:"T",percent:"pct"},i=["will","the","a","an","after","before","in","at","by","of","there","be","to","or","and","for","on","its","that","this","from","with","as","is","are","was","were","?","how","many","who","what","when","where","which","much"],s=void 0===e?"":e.toLowerCase(),r=this.stringToCharsArray(s),a="",o=!0;for(let e=0;e<r.length;e++){let t=r[e];"abcdefghijklmnopqrstuvwxyz0123456789".indexOf(t)>=0?(a+=t,o=!1):o||(a+="-",o=!0)}let n=Object.keys(t);for(let e=0;e<n.length;e++){let i=n[e],s=this.safeString(t,i);void 0!==s&&(a=a.replaceAll(i,s))}let d=a.split("-"),h=[];for(let e=0;e<d.length;e++){let t=d[e];t.length>0&&!this.inArray(t,i)&&h.push(t)}return h.join("_").toUpperCase()}slugToMarketSymbol(e,t){let i=this.shortenSlug(t),s=this.shortenSlug(e);return void 0===s||""===s||s===i?i:s+"_"+i}slugToOutcomeSymbol(e,t,i){let s=(void 0===i?"":i).toUpperCase(),r=this.stringToCharsArray(s),a="",o=!1;for(let e=0;e<r.length;e++){let t=r[e];"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".indexOf(t)>=0?(o&&""!==a&&(a+="_"),a+=t,o=!1):o=!0}return""===a&&(a=s),this.slugToMarketSymbol(e,t)+":"+a}setMarkets(e,t){let i=this.toArray(e),s=[];for(let e=0;e<i.length;e++){let t=i[e],r=this.extend({},t);r.symbol=this.safeString2(t,"market","symbol"),s.push(r)}let r=super.setMarkets(s,t),a=Object.keys(r);for(let e=0;e<a.length;e++){let t=a[e];r[t]=this.omit(r[t],"symbol")}return this.populateOutcomes(),r}indexMarketOutcomes(e){void 0===this.outcomes&&(this.outcomes={}),void 0===this.outcomes_by_id&&(this.outcomes_by_id={});let t=this.safeList(e,"outcomes",[]);for(let e=0;e<t.length;e++){let i=t[e],s=this.safeString2(i,"outcome","symbol"),r=this.safeString2(i,"outcomeId","id");if(i.outcomeId=r,i.market=this.safeString2(i,"market","marketSymbol"),void 0!==s){let e=this.safeValue(this.outcomes,s);if(void 0!==e){let t=this.safeString(e,"outcomeId");if(void 0!==t&&void 0!==r&&t!==r){let e=r.length,t=r;e>6&&(t=r.slice(e-6)),s=s+"_"+t.toUpperCase()}}i.outcome=s,this.outcomes[s]=i}else i.outcome=s;void 0!==r&&(this.outcomes_by_id[r]=i)}}populateOutcomes(){if(this.outcomes={},this.outcomes_by_id={},void 0===this.markets)return;let e=Object.keys(this.markets);for(let t=0;t<e.length;t++)this.indexMarketOutcomes(this.markets[e[t]])}indexEventOutcomes(e){void 0===this.markets&&(this.markets=this.createSafeDictionary());let t=this.safeList(e,"markets",[]),i=t.length;for(let e=0;e<i;e++){let i=t[e],s=this.safeString2(i,"market","symbol");void 0!==s&&(this.markets[s]=i)}this.populateOutcomes()}async loadOutcomes(e,t=!1,i={}){if(void 0!==e){let i=[];for(let s=0;s<e.length;s++)(t||!this.hasOutcome(e[s]))&&i.push(e[s]);let s=i.length,r=void 0!==this.outcomes&&!this.isEmpty(this.outcomes),a=this.safeBool(this.options,"loadAllOutcomes",!1);if(s>0&&!0===a&&!r&&!t){await this.loadOutcomes();let e=[];for(let t=0;t<s;t++)this.hasOutcome(i[t])||e.push(i[t]);s=(i=e).length}return s>0&&await this.fetchOutcomes(i),this.outcomes}return(t||void 0===this.outcomes||this.isEmpty(this.outcomes))&&(await this.loadMarkets(t,i),this.populateOutcomes()),this.outcomes}async fetchOutcomes(e){for(let t=0;t<e.length;t++)await this.fetchOutcome(e[t]);return this.outcomes}async loadOutcome(e,t=!1){if(void 0===e)throw new a.ArgumentsRequired(this.id+" loadOutcome() requires an outcomeSymbol argument");if(!t){if(this.hasOutcome(e))return this.safeOutcome(e);let t=void 0!==this.outcomes&&!this.isEmpty(this.outcomes);if(!t&&void 0!==this.markets&&!this.isEmpty(this.markets)&&(this.populateOutcomes(),this.hasOutcome(e))||!0===this.safeBool(this.options,"loadAllOutcomes",!1)&&!t&&(await this.loadOutcomes(),this.hasOutcome(e)))return this.safeOutcome(e)}return await this.fetchOutcome(e)}outcomeSearchQuery(e){let t=e,i=e.indexOf(":");if(i>=0&&(t=e.slice(0,i)),0===t.indexOf("0x"))return;let s=t.toLowerCase().replaceAll("-","_").split("_"),r=[],a=!1;for(let e=0;e<s.length;e++){let t=s[e];if(0===t.length)continue;let i=!1,o=this.stringToCharsArray(t);for(let e=0;e<o.length;e++)if("abcdefghijklmnopqrstuvwxyz".indexOf(o[e])>=0){i=!0;break}i&&(r.push(t),a=!0)}if(0!==r.length&&a)return r.join(" ")}async fetchOutcome(e){let t=this.outcomeSearchQuery(e);if(void 0!==t&&this.safeBool(this.has,"fetchEvents",!1)){let i=this.safeInteger(this.options,"fetchOutcomeSearchLimit",10);try{await this.fetchEvents({query:t,limit:i})}catch(e){if(!(e instanceof a.BadSymbol))throw e}if(this.hasOutcome(e))return this.safeOutcome(e)}throw new a.BadSymbol(this.id+" could not resolve outcome "+e+" — call fetchEvents ({ 'query': ... }) first, or pass a known outcomeId")}async fetchTicker(e,t={}){throw new a.NotSupported(this.id+" fetchTicker() is not supported yet")}async fetchTickers(e,t={}){throw new a.NotSupported(this.id+" fetchTickers() is not supported yet")}async fetchOrderBook(e,t,i={}){throw new a.NotSupported(this.id+" fetchOrderBook() is not supported yet")}async fetchOHLCV(e,t="1m",i,s,r={}){return await super.fetchOHLCV(e,t,i,s,r)}async fetchTrades(e,t,i,s={}){throw new a.NotSupported(this.id+" fetchTrades() is not supported yet")}async createOrder(e,t,i,s,r,o={}){throw new a.NotSupported(this.id+" createOrder() is not supported yet")}async cancelOrder(e,t,i={}){throw new a.NotSupported(this.id+" cancelOrder() is not supported yet")}async watchTicker(e,t={}){throw new a.NotSupported(this.id+" watchTicker() is not supported yet")}async watchOrderBook(e,t,i={}){throw new a.NotSupported(this.id+" watchOrderBook() is not supported yet")}async watchTrades(e,t,i,s={}){throw new a.NotSupported(this.id+" watchTrades() is not supported yet")}async fetchOrders(e,t,i,s={}){throw new a.NotSupported(this.id+" fetchOrders() is not supported yet")}async fetchOpenOrders(e,t,i,s={}){throw new a.NotSupported(this.id+" fetchOpenOrders() is not supported yet")}async fetchClosedOrders(e,t,i,s={}){throw new a.NotSupported(this.id+" fetchClosedOrders() is not supported yet")}async fetchOrderTrades(e,t,i,s,r={}){throw new a.NotSupported(this.id+" fetchOrderTrades() is not supported yet")}async fetchMyTrades(e,t,i,s={}){throw new a.NotSupported(this.id+" fetchMyTrades() is not supported yet")}async fetchPosition(e,t={}){throw new a.NotSupported(this.id+" fetchPosition() is not supported yet")}async fetchPositions(e,t={}){throw new a.NotSupported(this.id+" fetchPositions() is not supported yet")}async fetchTradingFee(e,t={}){throw new a.NotSupported(this.id+" fetchTradingFee() is not supported yet")}async fetchOpenInterest(e,t={}){throw new a.NotSupported(this.id+" fetchOpenInterest() is not supported yet")}async createOrders(e,t={}){throw new a.NotSupported(this.id+" createOrders() is not supported yet")}async cancelOrders(e,t,i={}){throw new a.NotSupported(this.id+" cancelOrders() is not supported yet")}async createMarketBuyOrderWithCost(e,t,i={}){if(this.safeBool(this.options,"createMarketBuyOrderRequiresPrice",!1)||this.safeBool(this.has,"createMarketBuyOrderWithCost",!1))return await this.createOrder(e,"market","buy",t,1,i);throw new a.NotSupported(this.id+" createMarketBuyOrderWithCost() is not supported yet")}async createMarketSellOrderWithCost(e,t,i={}){if(this.safeBool(this.options,"createMarketSellOrderRequiresPrice",!1)||this.safeBool(this.has,"createMarketSellOrderWithCost",!1))return await this.createOrder(e,"market","sell",t,1,i);throw new a.NotSupported(this.id+" createMarketSellOrderWithCost() is not supported yet")}async watchTickers(e,t={}){throw new a.NotSupported(this.id+" watchTickers() is not supported yet")}async watchOrders(e,t,i,s={}){throw new a.NotSupported(this.id+" watchOrders() is not supported yet")}async watchMyTrades(e,t,i,s={}){throw new a.NotSupported(this.id+" watchMyTrades() is not supported yet")}async watchPositions(e,t,i,s={}){throw new a.NotSupported(this.id+" watchPositions() is not supported yet")}async fetchSettlements(e,t,i,s={}){throw new a.NotSupported(this.id+" fetchSettlements() is not supported yet")}safePredictionOrder(e,t){let i=this.omitZero(this.safeString(e,"amount")),s=this.safeString(e,"filled"),a=this.safeString(e,"remaining"),o=this.safeString(e,"cost"),n=this.omitZero(this.safeString(e,"average")),d=this.omitZero(this.safeString(e,"price")),h=this.safeString(e,"side"),c=this.safeString(e,"status"),l=this.safeInteger(e,"lastTradeTimestamp"),u=this.safeList(e,"trades",[]),f=this.parsePredictionTrades(u,t),p=f.length,m=[];if(p>0){void 0===s&&(s="0"),void 0===o&&(o="0");for(let e=0;e<p;e++){let t=f[e],i=this.safeString(t,"amount");void 0!==i&&(s=r.Y.stringAdd(s,i));let a=this.safeString(t,"cost");void 0!==a&&(o=r.Y.stringAdd(o,a)),void 0===h&&(h=this.safeString(t,"side"));let n=this.safeInteger(t,"timestamp");void 0!==n&&(void 0===l?l=n:n>l&&(l=n));let d=this.safeDict(t,"fee");void 0!==d&&m.push(d)}}if(void 0===s&&void 0!==i&&void 0!==a&&(s=r.Y.stringSub(i,a)),void 0===a&&void 0!==i&&void 0!==s&&(a=r.Y.stringSub(i,s)),void 0===i&&void 0!==s&&void 0!==a&&(i=r.Y.stringAdd(s,a)),void 0===n&&void 0!==s&&void 0!==o&&r.Y.stringGt(s,"0")&&(n=r.Y.stringDiv(o,s)),void 0===o&&void 0!==s){let e=void 0!==n?n:d;void 0!==e&&(o=r.Y.stringMul(s,e))}let g=this.safeDict(e,"fee"),v=m.length;if(void 0===g&&v>0){let e=this.reduceFeesByCurrency(m);e.length>0&&(g=e[0])}let y=this.safeString(e,"type"),b=this.safeString(e,"timeInForce"),w=this.safeBool(e,"postOnly");void 0===b?("market"===y&&(b="IOC"),!0===w&&(b="PO")):void 0===w&&(w="PO"===b);let k=this.safeInteger(e,"timestamp"),S=this.safeString(e,"datetime");return void 0===S&&(S=this.iso8601(k)),{id:this.safeString(e,"id"),clientOrderId:this.safeString(e,"clientOrderId"),timestamp:k,datetime:S,lastTradeTimestamp:l,lastUpdateTimestamp:this.safeInteger(e,"lastUpdateTimestamp"),status:c,type:y,timeInForce:b,side:h,price:this.parseNumber(d),average:this.parseNumber(n),amount:this.parseNumber(i),filled:this.parseNumber(s),remaining:this.parseNumber(a),cost:this.parseNumber(o),fee:g,reduceOnly:this.safeBool(e,"reduceOnly"),postOnly:w,trades:f,outcome:this.safeString(e,"outcome"),outcomeId:this.safeString(e,"outcomeId"),label:this.safeString(e,"label"),market:this.safeString(e,"market"),event:this.safeString(e,"event"),info:this.safeValue(e,"info",e)}}safePredictionTrade(e,t){let i=this.safeString(e,"price"),s=this.safeString(e,"amount"),a=this.safeString(e,"cost");void 0===a&&void 0!==i&&void 0!==s&&(a=r.Y.stringMul(i,s));let o=this.safeInteger(e,"timestamp"),n=this.safeString(e,"datetime");return void 0===n&&(n=this.iso8601(o)),{id:this.safeString(e,"id"),order:this.safeString(e,"order"),timestamp:o,datetime:n,type:this.safeString(e,"type"),side:this.safeString(e,"side"),takerOrMaker:this.safeString(e,"takerOrMaker"),price:this.parseNumber(i),amount:this.parseNumber(s),cost:this.parseNumber(a),fee:this.safeDict(e,"fee"),realizedPnl:this.safeNumber(e,"realizedPnl"),outcome:this.safeString(e,"outcome"),outcomeId:this.safeString(e,"outcomeId"),label:this.safeString(e,"label"),market:this.safeString(e,"market"),info:this.safeValue(e,"info",e)}}safePredictionTicker(e,t){let i=this.omitZero(this.safeString(e,"open")),s=this.omitZero(this.safeString2(e,"close","last")),a=this.omitZero(this.safeString2(e,"last","close")),o=this.safeString(e,"change"),n=this.omitZero(this.safeString(e,"percentage")),d=this.omitZero(this.safeString(e,"average"));void 0===o&&void 0!==i&&void 0!==s&&(o=r.Y.stringSub(s,i)),void 0===n&&void 0!==o&&void 0!==i&&r.Y.stringGt(i,"0")&&(n=r.Y.stringMul(r.Y.stringDiv(o,i),"100")),void 0===d&&void 0!==i&&void 0!==s&&(d=r.Y.stringDiv(r.Y.stringAdd(i,s),"2"));let h=this.safeInteger(e,"timestamp"),c=this.safeString(e,"datetime");return void 0===c&&(c=this.iso8601(h)),{timestamp:h,datetime:c,high:this.safeNumber(e,"high"),low:this.safeNumber(e,"low"),bid:this.parseNumber(this.omitZero(this.safeString(e,"bid"))),bidVolume:this.safeNumber(e,"bidVolume"),ask:this.parseNumber(this.omitZero(this.safeString(e,"ask"))),askVolume:this.safeNumber(e,"askVolume"),open:this.parseNumber(i),close:this.parseNumber(s),last:this.parseNumber(a),change:this.parseNumber(o),percentage:this.parseNumber(n),average:this.parseNumber(d),baseVolume:this.safeNumber(e,"baseVolume"),quoteVolume:this.safeNumber(e,"quoteVolume"),openInterest:this.safeNumber(e,"openInterest"),outcome:this.safeString(e,"outcome"),outcomeId:this.safeString(e,"outcomeId"),label:this.safeString(e,"label"),market:this.safeString(e,"market"),event:this.safeString(e,"event"),info:this.safeValue(e,"info",e)}}safePredictionPosition(e){let t=this.safeInteger(e,"timestamp"),i=this.safeString(e,"datetime");return void 0===i&&(i=this.iso8601(t)),{id:this.safeString(e,"id"),timestamp:t,datetime:i,contracts:this.safeNumber(e,"contracts"),contractSize:this.safeNumber(e,"contractSize"),side:this.safeString(e,"side"),notional:this.safeNumber(e,"notional"),unrealizedPnl:this.safeNumber(e,"unrealizedPnl"),realizedPnl:this.safeNumber(e,"realizedPnl"),collateral:this.safeNumber(e,"collateral"),entryPrice:this.safeNumber(e,"entryPrice"),markPrice:this.safeNumber(e,"markPrice"),lastPrice:this.safeNumber(e,"lastPrice"),percentage:this.safeNumber(e,"percentage"),resolved:this.safeBool(e,"resolved"),won:this.safeBool(e,"won"),settleFraction:this.safeNumber(e,"settleFraction"),payout:this.safeNumber(e,"payout"),outcome:this.safeString(e,"outcome"),outcomeId:this.safeString(e,"outcomeId"),label:this.safeString(e,"label"),market:this.safeString(e,"market"),event:this.safeString(e,"event"),info:this.safeValue(e,"info",e)}}safePredictionOrderBook(e,t){let i=this.safeString2(e,"outcome","symbol"),s={outcome:void 0===t?i:this.safeString(t,"outcome",i),outcomeId:void 0===t?this.safeString(e,"outcomeId"):this.safeString(t,"outcomeId"),market:void 0===t?this.safeString(e,"market"):this.safeString(t,"market")};return this.extend(this.omit(e,"symbol"),s)}parsePredictionTicker(e,t){throw new a.NotSupported(this.id+" parsePredictionTicker() is not supported yet")}parsePredictionOrder(e,t){throw new a.NotSupported(this.id+" parsePredictionOrder() is not supported yet")}parsePredictionTrade(e,t){throw new a.NotSupported(this.id+" parsePredictionTrade() is not supported yet")}parsePredictionPosition(e,t){throw new a.NotSupported(this.id+" parsePredictionPosition() is not supported yet")}parsePredictionOpenInterest(e,t){throw new a.NotSupported(this.id+" parsePredictionOpenInterest() is not supported yet")}parsePredictionTrades(e,t,i,s,r={}){let a=this.toArray(e),o=[];for(let e=0;e<a.length;e++){let i=this.parsePredictionTrade(a[e],t),s=this.extend(i,r);o.push(s)}o=this.sortBy2(o,"timestamp","id");let n=this.safeString(t,"outcome");return this.filterByOutcomeSinceLimit(o,n,i,s)}parsePredictionOrders(e,t,i,s,r={}){let a=this.toArray(e),o=[];for(let e=0;e<a.length;e++){let i=this.parsePredictionOrder(a[e],t),s=this.extend(i,r);o.push(s)}o=this.sortBy(o,"timestamp");let n=this.safeString(t,"outcome");return this.filterByOutcomeSinceLimit(o,n,i,s)}parsePredictionPositions(e,t={}){let i=this.toArray(e),s=[];for(let e=0;e<i.length;e++){let r=this.parsePredictionPosition(i[e]),a=this.extend(r,t);s.push(a)}return s}filterByOutcomeSinceLimit(e,t,i,s,r=!1){return this.filterByValueSinceLimit(e,"outcome",t,i,s,"timestamp",r)}filterByOutcomesSinceLimit(e,t,i,s,r=!1){let a=this.filterByArray(e,"outcome",t,!1);return this.filterBySinceLimit(a,i,s,"timestamp",r)}amountToPredictionPrecision(e,t){let i=this.outcome(e),s=this.safeString(i,"market");return this.amountToPrecision(s,t)}priceToPredictionPrecision(e,t){let i=this.outcome(e),s=this.safeString(i,"market");return this.priceToPrecision(s,t)}costToPredictionPrecision(e,t){let i=this.outcome(e),s=this.safeString(i,"market");return this.costToPrecision(s,t)}padHexToEven(e){return void 0===e?"":e.length%2!=0?"0"+e:e}padHexAddress(e){return void 0===e?"":"000000000000000000000000"+this.remove0xPrefix(e)}rlpEncodeBytes(e){if(void 0===e)return"";let t=this.parseToInt(e.length/2);if(0===t)return"80";if(1===t&&e<"80")return e;if(t<56)return this.intToBase16(128+t)+e;let i=this.intToBase16(t);i=this.padHexToEven(i);let s=this.parseToInt(i.length/2);return this.intToBase16(183+s)+i+e}rlpEncodeList(e){let t="";for(let i=0;i<e.length;i++)t+=e[i];let i=this.parseToInt(t.length/2);if(i<56)return this.intToBase16(192+i)+t;let s=this.intToBase16(i);s=this.padHexToEven(s);let r=this.parseToInt(s.length/2);return this.intToBase16(247+r)+s+t}intToRlpHex(e){if(void 0===e)throw new a.ArgumentsRequired(this.id+" intToRlpHex() requires a value argument");if(0===e)return"";let t=this.intToBase16(e);return this.padHexToEven(t)}hexToRlpBytes(e){if(void 0===e)return"";let t=this.remove0xPrefix(e),i=0,s=t.length;for(;i<s&&"0"===t.slice(i,i+1);)i+=1;return""===(t=t.slice(i))?"":t=this.padHexToEven(t)}signEvmTransaction(e,t){throw new a.NotSupported(this.id+" signEvmTransaction() must be overridden by the exchange")}async ethRpc(e,t,i){let s=await this.fetch(e,"POST",{"Content-Type":"application/json"},this.json({jsonrpc:"2.0",id:1,method:t,params:i})),r=this.safeValue(s,"error");if(void 0!==r)throw new a.ExchangeError(this.id+" rpc "+t+" error: "+this.json(r));return this.safeValue(s,"result")}async sendEvmTransaction(e,t,i,s,r,a,o){let n=await this.ethRpc(e,"eth_getTransactionCount",[i,"pending"]),d=await this.ethRpc(e,"eth_gasPrice",[]),h=this.signEvmTransaction({chainId:t,nonce:n,maxPriorityFeePerGas:d,maxFeePerGas:d,gasLimit:o,to:s,value:r,data:a},this.privateKey);return await this.ethRpc(e,"eth_sendRawTransaction",[h])}async waitForTransactionReceipt(e,t,i=6e4){let s=this.milliseconds();for(;this.milliseconds()-s<i;){let i=await this.ethRpc(e,"eth_getTransactionReceipt",[t]);if(null!=i)return i;await this.sleep(2e3)}throw new a.ExchangeError(this.id+" transaction "+t+" not mined within timeout")}constructor(...e){super(...e),o(this,"outcomes",void 0),o(this,"outcomes_by_id",void 0),o(this,"events",void 0),o(this,"events_by_slug",void 0)}}i.d(t,{A:()=>n})},1453(e,t,i){"use strict";i.r(t);class s extends Error{constructor(e){super(e),this.name="BaseError"}}class r extends s{constructor(e){super(e),this.name="ExchangeError"}}class a extends r{constructor(e){super(e),this.name="AuthenticationError"}}class o extends a{constructor(e){super(e),this.name="PermissionDenied"}}class n extends o{constructor(e){super(e),this.name="AccountNotEnabled"}}class d extends a{constructor(e){super(e),this.name="AccountSuspended"}}class h extends r{constructor(e){super(e),this.name="ArgumentsRequired"}}class c extends r{constructor(e){super(e),this.name="BadRequest"}}class l extends c{constructor(e){super(e),this.name="BadSymbol"}}class u extends r{constructor(e){super(e),this.name="OperationRejected"}}class f extends u{constructor(e){super(e),this.name="NoChange"}}class p extends f{constructor(e){super(e),this.name="MarginModeAlreadySet"}}class m extends u{constructor(e){super(e),this.name="MarketClosed"}}class g extends u{constructor(e){super(e),this.name="ManualInteractionNeeded"}}class v extends u{constructor(e){super(e),this.name="RestrictedLocation"}}class y extends r{constructor(e){super(e),this.name="InsufficientFunds"}}class b extends r{constructor(e){super(e),this.name="InvalidAddress"}}class w extends b{constructor(e){super(e),this.name="AddressPending"}}class k extends r{constructor(e){super(e),this.name="InvalidOrder"}}class S extends k{constructor(e){super(e),this.name="OrderNotFound"}}class O extends k{constructor(e){super(e),this.name="OrderNotCached"}}class T extends k{constructor(e){super(e),this.name="OrderImmediatelyFillable"}}class P extends k{constructor(e){super(e),this.name="OrderNotFillable"}}class I extends k{constructor(e){super(e),this.name="DuplicateOrderId"}}class A extends k{constructor(e){super(e),this.name="ContractUnavailable"}}class x extends r{constructor(e){super(e),this.name="NotSupported"}}class M extends r{constructor(e){super(e),this.name="InvalidProxySettings"}}class _ extends r{constructor(e){super(e),this.name="ExchangeClosedByUser"}}class C extends s{constructor(e){super(e),this.name="OperationFailed"}}class B extends C{constructor(e){super(e),this.name="NetworkError"}}class E extends B{constructor(e){super(e),this.name="DDoSProtection"}}class R extends B{constructor(e){super(e),this.name="RateLimitExceeded"}}class L extends B{constructor(e){super(e),this.name="ExchangeNotAvailable"}}class N extends L{constructor(e){super(e),this.name="OnMaintenance"}}class D extends B{constructor(e){super(e),this.name="InvalidNonce"}}class q extends D{constructor(e){super(e),this.name="ChecksumError"}}class F extends B{constructor(e){super(e),this.name="RequestTimeout"}}class V extends C{constructor(e){super(e),this.name="BadResponse"}}class G extends V{constructor(e){super(e),this.name="NullResponse"}}class H extends C{constructor(e){super(e),this.name="CancelPending"}}class U extends s{constructor(e){super(e),this.name="UnsubscribeError"}}i.d(t,{AccountNotEnabled:()=>n,AccountSuspended:()=>d,AddressPending:()=>w,ArgumentsRequired:()=>h,AuthenticationError:()=>a,BadRequest:()=>c,BadResponse:()=>V,BadSymbol:()=>l,BaseError:()=>s,CancelPending:()=>H,ChecksumError:()=>q,ContractUnavailable:()=>A,DDoSProtection:()=>E,DuplicateOrderId:()=>I,ExchangeClosedByUser:()=>_,ExchangeError:()=>r,ExchangeNotAvailable:()=>L,InsufficientFunds:()=>y,InvalidAddress:()=>b,InvalidNonce:()=>D,InvalidOrder:()=>k,InvalidProxySettings:()=>M,ManualInteractionNeeded:()=>g,MarginModeAlreadySet:()=>p,MarketClosed:()=>m,NetworkError:()=>B,NoChange:()=>f,NotSupported:()=>x,NullResponse:()=>G,OnMaintenance:()=>N,OperationFailed:()=>C,OperationRejected:()=>u,OrderImmediatelyFillable:()=>T,OrderNotCached:()=>O,OrderNotFillable:()=>P,OrderNotFound:()=>S,PermissionDenied:()=>o,RateLimitExceeded:()=>R,RequestTimeout:()=>F,RestrictedLocation:()=>v,UnsubscribeError:()=>U},{default:{BaseError:s,ExchangeError:r,AuthenticationError:a,PermissionDenied:o,AccountNotEnabled:n,AccountSuspended:d,ArgumentsRequired:h,BadRequest:c,BadSymbol:l,OperationRejected:u,NoChange:f,MarginModeAlreadySet:p,MarketClosed:m,ManualInteractionNeeded:g,RestrictedLocation:v,InsufficientFunds:y,InvalidAddress:b,AddressPending:w,InvalidOrder:k,OrderNotFound:S,OrderNotCached:O,OrderImmediatelyFillable:T,OrderNotFillable:P,DuplicateOrderId:I,ContractUnavailable:A,NotSupported:x,InvalidProxySettings:M,ExchangeClosedByUser:_,OperationFailed:C,NetworkError:B,DDoSProtection:E,RateLimitExceeded:R,ExchangeNotAvailable:L,OnMaintenance:N,InvalidNonce:D,ChecksumError:q,RequestTimeout:F,BadResponse:V,NullResponse:G,CancelPending:H,UnsubscribeError:U}})},1805(e,t,i){"use strict";i.r(t);var s=i(6519),r=i(2879),a=i(9637),o=i(7672),n=i(8405),d=i(7770),h=i(1093),c=i(6785),l=i(8280),u=i(5788),f=i(420);i.d(t,{DECIMAL_PLACES:()=>2,NO_PADDING:()=>5,PAD_WITH_ZERO:()=>6,ROUND:()=>1,ROUND_DOWN:()=>3,ROUND_UP:()=>2,SIGNIFICANT_DIGITS:()=>3,TICK_SIZE:()=>4,TRUNCATE:()=>0,Throttler:()=>l.x,TimedOut:()=>c.GA,aggregate:()=>u.QD,arrayConcat:()=>r.ax,asFloat:()=>o.Pf,asInteger:()=>o.JU,base16ToBinary:()=>d.FF,base58ToBinary:()=>d.Ry,base64ToBase64Url:()=>d.xg,base64ToBinary:()=>d.cg,base64ToString:()=>d.QM,binaryConcat:()=>d.qo,binaryConcatArray:()=>d.Vw,binaryToBase16:()=>d.t7,binaryToBase58:()=>d.bj,binaryToBase64:()=>d.sQ,binaryToString:()=>d.kn,capitalize:()=>a.ZH,clone:()=>r.o8,crc32:()=>h.QR,decimalToPrecision:()=>n.fq,decode:()=>d.D4,deepExtend:()=>r.zw,ecdsa:()=>h.h1,eddsa:()=>h.q4,encode:()=>d.lF,existsFile:()=>f.P8,extend:()=>r.X$,extractParams:()=>u.um,filePathToFileUrlForWindows:()=>f.Sk,filterBy:()=>r.WP,flatten:()=>r.Bq,getTempDir:()=>f.G4,groupBy:()=>r.$z,hasProps:()=>o.dl,hash:()=>h.tW,hmac:()=>h.w8,implodeParams:()=>u.Hp,inArray:()=>r.RV,index:()=>r.Pe,indexBy:()=>r.wQ,initFileSystem:()=>f.eK,isArray:()=>o.cy,isBrowser:()=>s.Bd,isBun:()=>s.Qg,isDeno:()=>s.N6,isDict:()=>o.Zm,isElectron:()=>s.b8,isEmpty:()=>r.Im,isInteger:()=>o.Fq,isJsonEncodedObject:()=>d.mC,isNode:()=>s.Ll,isNumber:()=>o.Et,isObject:()=>o.Gv,isString:()=>o.Kg,isStringCoercible:()=>o.KL,isWebWorker:()=>s.p7,isWindows:()=>s.uF,iso8601:()=>c.LC,json:()=>d.Pq,keys:()=>r.HP,keysort:()=>r.CA,mdy:()=>c.rE,merge:()=>r.h1,microseconds:()=>c.EZ,milliseconds:()=>c.Rz,now:()=>c.tB,numberToBE:()=>d.qE,numberToLE:()=>d.aN,numberToString:()=>n.um,omit:()=>r.cJ,omitZero:()=>n.Ye,ordered:()=>r.Sj,packb:()=>d.Am,parse8601:()=>c.Dj,parseDate:()=>c._U,parseTimeframe:()=>u.ce,pemToDer:()=>h.BL,pluck:()=>r.Ey,precisionConstants:()=>n.S2,precisionFromString:()=>n.Iu,prop:()=>o._w,rawencode:()=>d.rO,readFile:()=>f.TA,roundTimeframe:()=>u.jG,safeFloat:()=>o.w,safeFloat2:()=>o.Cw,safeFloatN:()=>o.Q7,safeInteger:()=>o.Y2,safeInteger2:()=>o.mU,safeIntegerN:()=>o.At,safeIntegerProduct:()=>o.lu,safeIntegerProduct2:()=>o.J0,safeIntegerProductN:()=>o.hO,safeString:()=>o.nr,safeString2:()=>o.d0,safeStringLower:()=>o.gw,safeStringLower2:()=>o.uS,safeStringLowerN:()=>o.I9,safeStringN:()=>o.Rc,safeStringUpper:()=>o.RH,safeStringUpper2:()=>o.F7,safeStringUpperN:()=>o.fu,safeTimestamp:()=>o.q0,safeTimestamp2:()=>o.ww,safeTimestampN:()=>o.Y_,safeValue:()=>o.pI,safeValue2:()=>o.Dj,safeValueN:()=>o.DR,seconds:()=>c.YA,selfIsDefined:()=>u.Se,setTimeout_safe:()=>c.k4,sleep:()=>c.yy,sort:()=>r.di,sortBy:()=>r.Ul,sortBy2:()=>r.sy,stringToBase64:()=>d.q3,stringToBinary:()=>d.wN,strip:()=>a.bB,sum:()=>r.cz,timeout:()=>c.wR,toArray:()=>r.$r,truncate:()=>n.xv,truncate_to_string:()=>n.NZ,unCamelCase:()=>a.Qd,unique:()=>r.Am,urlencode:()=>d.mu,urlencodeBase64:()=>d.LI,urlencodeNested:()=>d.Dy,urlencodeWithArrayRepeat:()=>d.ev,uuid:()=>a.uR,uuid16:()=>a.tg,uuid22:()=>a._n,uuidv1:()=>c.nm,values:()=>r.zu,vwap:()=>u.ru,writeFile:()=>f._h,ymd:()=>c.Th,ymdhms:()=>c.RR,yymmdd:()=>c.x_,yyyymmdd:()=>c.Rn})},1093(e,t,i){"use strict";var s=i(7474),r=i(7116),a=i(508),o=i(6885),n=i(2431),d=i(6724);let h=e=>"string"==typeof e?(0,a.AI)(e):e,c=e=>"string"==typeof e?(0,d.aT)(e):e,l={binary:e=>e,hex:r.uh.encode,base64:r.K3.encode},u={"1.3.132.0.10":o.bI,"1.2.840.10045.3.1.7":n.s9};function f(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");return r.K3.decode(t)}function p(e){let t=[],i=0;for(;i<e.length;){let s=e[i],r=function(e,t){let i=e[t];if(t+=1,128&i){let s=127&i;i=0;for(let r=0;r<s;r++)i=256*i+e[t],t+=1}return[i,t]}(e,i+=1),a=r[0];i=r[1];let o=e.slice(i,i+a);t.push({tag:s,content:o}),i+=a}return t}function m(e,t,i="hex"){let s=t(h(e));return l[i](s)}function g(e,t,i,r="hex"){let a=(0,s.w)(i,h(t),h(e));return l[r](a)}function v(e,t,i,s=null,a=!1){if(s&&(e=m(e,s,"hex")),"string"==typeof t&&t.length>64)if(t.startsWith("-----BEGIN EC PRIVATE KEY-----")){let e=p(f(t)),s=p(e[0].content);if(4===s.length){let e=s[2];if(void 0!==e&&160===e.tag&&e.content.length>0){let t=function(e){let t=[],i=e[0];t.push(Math.floor(i/40)),t.push(i%40);let s=0;for(let i=1;i<e.length;i++){let r=e[i];s=128*s+(127&r),(128&r)==0&&(t.push(s),s=0)}return t.join(".")}(p(e.content)[0].content);if(void 0===u[t])throw Error("Unsupported curve");i=u[t]}t=r.uh.encode(s[1].content)}else throw Error("Unsupported key format")}else throw Error("Unsupported key format");let o=c(e),n=c(t),h=i.Signature.fromBytes(i.sign(o,n,{lowS:!0,prehash:!1,format:"recovered"}),"recovered"),l=(BigInt(1)<<BigInt(8)*BigInt(31))-BigInt(1),g=i.Point.Fn.ORDER/BigInt(2),y=0;for(;a&&(h.r>g||h.r<=l||h.s<=l);)h=i.Signature.fromBytes(i.sign(o,n,{lowS:!0,prehash:!1,format:"recovered",extraEntropy:(0,d.z)(BigInt(y),32)}),"recovered"),y+=1;return{r:h.r.toString(16),s:h.s.toString(16),v:h.recovery}}function y(e,t,i){let s;32===t.length?s=h(t):"string"==typeof t&&(s=new Uint8Array(f(t).slice(16)));let a=i.sign(c(e),s);return r.K3.encode(a)}function b(e,t=!1){void 0===b.table&&(b.table="00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D".split(" ").map(e=>parseInt(e,16)));let i=-1;for(let t=0;t<e.length;t++)i=i>>>8^b.table[(i^e.charCodeAt(t))&255];let s=(-1^i)>>>0;return t&&s>=0x80000000?s-0x100000000:s}i.d(t,{BL:()=>f,QR:()=>b,h1:()=>v,q4:()=>y,tW:()=>m,w8:()=>g})},7770(e,t,i){"use strict";var s=i(7116),r=i(6724),a=i(8942);let o=e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase());function n(e,t={}){let i=[];for(let s of Object.keys(e))!function e(t,i,s,r){if(void 0!==i){if(null===i)return void s.push([t,""]);if(i instanceof Date||"object"!=typeof i)return void s.push([t,i instanceof Date?i.toISOString():String(i)]);if(Array.isArray(i)){for(let a=0;a<i.length;a++)void 0!==i[a]&&e(r.repeat?t:t+"["+a+"]",i[a],s,r);return}for(let a of Object.keys(i))e(t+"["+a+"]",i[a],s,r)}}(s,e[s],i,t);let s=!1===t.encode||t.encodeValuesOnly?e=>e:o,r=!1===t.encode?e=>e:o;return i.map(([e,t])=>s(e)+"="+r(t)).join("&")}let d=s.As.encode,h=s.As.decode,c=e=>s.K3.encode(s.As.decode(e)),l=s.K3.decode,u=s.K3.encode,f=s.uh.decode,p=s.uh.encode,m=s.tw.decode,g=s.tw.encode,v=r.Id,y=s.As.decode,b=s.As.encode;function w(e){return(0,a.l)(e)}function k(e,t=!0){let i=e.replace(/\+/g,"-").replace(/\//g,"_");return t&&(i=i.replace(/=+$/,"")),i}i.d(t,{Am:()=>w,xg:()=>k},{D4:b,Dy:e=>n(e||{},{encodeValuesOnly:!0}),FF:f,LI:e=>("string"==typeof e?c(e):u(e)).replace(/[=]+$/,"").replace(/\+/g,"-").replace(/\//g,"_"),Pq:(e,t)=>JSON.stringify(e),QM:e=>s.As.encode(s.K3.decode(e)),Ry:m,Vw:e=>(0,r.Id)(...e),aN:(e,t)=>(0,r.z)(BigInt(e),t),bj:g,cg:l,ev:e=>n(e||{},{repeat:!0}),kn:d,lF:y,mC:e=>"string"==typeof e&&("{"===e[0]||"["===e[0]),mu:(e,t=!1)=>n(e||{}),q3:c,qE:(e,t)=>(0,r.lq)(BigInt(e),t),qo:v,rO:(e,t=!1)=>n(e||{},{encode:!1}),sQ:u,t7:p,wN:h})},9759(e,t,i){"use strict";var s=i(6834);function r(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}let a=new TextEncoder,o=(1n<<256n)-1n,n=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),d=e=>(0,s.lY)(e);function h(e,t="value"){if(e instanceof Uint8Array)return e;if("string"==typeof e&&/^(0x)?[0-9a-fA-F]*$/.test(e)){let i=e.startsWith("0x")?e.slice(2):e;if(i.length%2)throw Error("invalid BytesLike "+t);let s=new Uint8Array(i.length/2);for(let e=0;e<s.length;e++)s[e]=parseInt(i.substr(2*e,2),16);return s}throw Error('invalid BytesLike value (argument="'+t+'")')}function c(e,t="value"){if("bigint"==typeof e)return e;if("number"==typeof e){if(!Number.isSafeInteger(e))throw Error('overflow (argument="'+t+'")');return BigInt(e)}if("string"==typeof e){if(/^-?\d+$/.test(e))return BigInt(e);if(/^-?0x[0-9a-fA-F]+$/.test(e))return e.startsWith("-")?-BigInt(e.slice(1)):BigInt(e)}if(e instanceof Uint8Array)return BigInt("0x"+(n(e)||"0"));throw Error('invalid BigNumberish value (argument="'+t+'")')}let l=e=>h((e<0n?e&o:e).toString(16).padStart(64,"0"));function u(e){if("string"!=typeof e||!/^(0x)?[0-9a-fA-F]{40}$/.test(e))throw Error('invalid address (argument="address")');let t=e.startsWith("0x")?e.slice(2):e;if(t!==t.toLowerCase()&&t!==t.toUpperCase()){let e=t.toLowerCase(),i=n(d(a.encode(e))),s="";for(let t=0;t<40;t++)s+=parseInt(i[t],16)>=8?e[t].toUpperCase():e[t];if(s!==t)throw Error('bad address checksum (argument="address")')}return t.toLowerCase()}let f=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),i=0;for(let s of e)t.set(s,i),i+=s.length;return t},p=e=>e.length%32==0?e:f([e,new Uint8Array(32-e.length%32)]),m=e=>"string"===e.kind||"bytes"===e.kind||"array"===e.kind&&(-1===e.len||m(e.inner))||"tuple"===e.kind&&e.comps.some(m);function g(e,t){return"0x"+n(function e(t,i){if(t.length!==i.length)throw Error("types/values length mismatch");let s=[],r=[],o=0;for(let n=0;n<t.length;n++){let d=function(t,i){switch(t.kind){case"uint":{let e=c(i);if(e<0n||e>=1n<<BigInt(t.bits))throw Error("value out-of-bounds");return l(e)}case"int":{let e=c(i),s=1n<<BigInt(t.bits-1);if(e<-s||e>=s)throw Error("value out-of-bounds");return l(e)}case"address":return l(BigInt("0x"+u(i)));case"bool":return l(i?1n:0n);case"fixedbytes":{let e=h(i);if(e.length!==t.n)throw Error("incorrect data length");return p(e)}case"bytes":{let e=h(i);return f([l(BigInt(e.length)),p(e)])}case"string":{let e=a.encode(i);return f([l(BigInt(e.length)),p(e)])}case"array":{if(-1!==t.len&&i.length!==t.len)throw Error("array length mismatch");let s=e(i.map(()=>t.inner),i);return -1===t.len?f([l(BigInt(i.length)),s]):s}case"tuple":return e(t.comps,i)}}(t[n],i[n]);m(t[n])?(s.push(null),r.push(d),o+=32):(s.push(d),r.push(null),o+=d.length)}let n=o,d=[];for(let e=0;e<t.length;e++){let t=s[e];t?d.push(t):(d.push(l(BigInt(n))),n+=r[e].length)}for(let e of r)e&&d.push(e);return f(d)}(e.map(function e(t){let i=(t=t.trim()).match(/^(.*)\[(\d*)\]$/);if(i)return{kind:"array",inner:e(i[1]),len:""===i[2]?-1:parseInt(i[2],10)};if(t.startsWith("tuple(")&&(t=t.slice(5)),t.startsWith("(")){let i=0,s="",r=[];for(let e of t.slice(1,-1))"("===e&&i++,")"===e&&i--,","===e&&0===i?(r.push(s),s=""):s+=e;return s&&r.push(s),{kind:"tuple",comps:r.map(e)}}let s=t.match(/^(u?int)(\d*)$/);if(s){let e=""===s[2]?256:parseInt(s[2],10);if(e%8||e<8||e>256)throw Error("invalid "+t);return{kind:s[1],bits:e}}if("address"===t)return{kind:"address"};if("bool"===t)return{kind:"bool"};if("string"===t)return{kind:"string"};if("bytes"===t)return{kind:"bytes"};let r=t.match(/^bytes(\d+)$/);if(r){let e=parseInt(r[1],10);if(e<1||e>32)throw Error("invalid "+t);return{kind:"fixedbytes",n:e}}throw Error("invalid type: "+t)}),t))}let v={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},y=["name","version","chainId","verifyingContract","salt"];class b{static from(e){return new b(e)}encodeType(e){let t=this.fullTypes[e];if(!t)throw Error("unknown type: "+e);return t}buildEncoder(e){let t=e.match(/^(.*)(\x5b(\d*)\x5d)$/);if(t){let e=this.getEncoder(t[1]);return i=>{let s;if(t[3]&&parseInt(t[3],10)!==i.length)throw Error("array length mismatch");return s=this.fullTypes[t[1]]?i.map(t=>d(h(e(t)))):i.map(t=>h(e(t))),"0x"+n(d(f(s)))}}let i=this.types[e];if(i){let t=d(a.encode(this.encodeType(e)));return e=>"0x"+n(f([t,...i.map(t=>{let i=this.getEncoder(t.type)(e[t.name]);return this.fullTypes[t.type]?d(h(i)):h(i)})]))}let s=e.match(/^(u?)int(\d*)$/);if(s){let t=parseInt(s[2]||"0",10);if(t%8||t>256||0===t)throw Error("invalid numeric width (EIP-712 requires explicit width)");let i=""===s[1];return s=>{let r=c(s,e);if(i){let i=1n<<BigInt(t-1);if(r<-i||r>=i)throw Error("value out-of-bounds for "+e)}else if(r<0n||r>=1n<<BigInt(t))throw Error("value out-of-bounds for "+e);return"0x"+n(l(r))}}let r=e.match(/^bytes(\d+)$/);if(r){let t=parseInt(r[1],10);if(0===t||t>32)throw Error("invalid bytes width");return i=>{let s=h(i);if(s.length!==t)throw Error("invalid length for "+e);return"0x"+n(p(s))}}switch(e){case"address":return e=>"0x"+n(l(BigInt("0x"+u(e))));case"bool":return e=>"0x"+n(l(e?1n:0n));case"bytes":return e=>"0x"+n(d(h(e)));case"string":return e=>"0x"+n(d(a.encode(e)))}throw Error("unknown type: "+e)}getEncoder(e){return e in this.encoderCache||(this.encoderCache[e]=this.buildEncoder(e)),this.encoderCache[e]}encodeData(e,t){return this.getEncoder(e)(t)}hashStruct(e,t){return"0x"+n(d(h(this.encodeData(e,t))))}static hashDomain(e){let t=[];for(let i of y)void 0!==e[i]&&null!==e[i]&&t.push({name:i,type:v[i]});for(let t of Object.keys(e))if(!(t in v))throw Error("invalid typed-data domain key: "+t);return b.from({EIP712Domain:t}).hashStruct("EIP712Domain",e)}static encode(e,t,i){let s=b.from(t);return"0x1901"+b.hashDomain(e).slice(2)+s.hashStruct(s.primaryType,i).slice(2)}constructor(e){for(const t of(r(this,"types",void 0),r(this,"primaryType",void 0),r(this,"fullTypes",void 0),r(this,"encoderCache",void 0),this.types={},Object.keys(e)))this.types[t]=e[t].map(e=>({name:e.name,type:e.type}));const t={},i={};for(const e of Object.keys(this.types))t[e]=new Set,i[e]=[];for(const e of Object.keys(this.types)){const s=new Set;for(const r of this.types[e]){if(s.has(r.name))throw Error("duplicated struct field "+r.name);s.add(r.name);const a=r.type.split("[")[0];if(a===e)throw Error("circular type reference to "+e);this.types[a]&&(i[a].push(e),t[e].add(a))}}const s=Object.keys(i).filter(e=>0===i[e].length);if(0===s.length)throw Error("missing primary type");if(s.length>1)throw Error("ambiguous primary types or unused types: "+s.map(e=>JSON.stringify(e)).join(", "));this.primaryType=s[0],this.fullTypes={};const a=(e,i)=>{if(!i.has(e))for(let s of(i.add(e),t[e]))a(s,i)};for(const e of Object.keys(this.types)){const t=new Set;a(e,t),t.delete(e);const i=[e,...Array.from(t).sort()];this.fullTypes[e]=i.map(e=>e+"("+this.types[e].map(e=>e.type+" "+e.name).join(",")+")").join("")}this.encoderCache={}}}i.d(t,{vg:()=>g,zl:()=>b})},2879(e,t,i){"use strict";var s=i(7672);let r=Object.keys,a=e=>(0,s.cy)(e)?e:Object.values(e),o=e=>new Set(a(e)),n=(...e)=>Object.assign({},...e),d=e=>(0,s.cy)(e)?Array.from(e):n(e),h=function(...e){let t=null,i=!1;for(let s of e)if(null!==s&&"object"==typeof s&&s.constructor===Object){if(null!==t&&i||(t={},i=!0),0===Object.keys(s).length)continue;for(let e in s){let i=s[e],r=t[e];null!==r&&"object"==typeof r&&r.constructor===Object&&null!==i&&"object"==typeof i&&i.constructor===Object?t[e]=h(r,i):t[e]=i}}else t=s,i=!1;return t};i.d(t,{},{$r:e=>null==e?[]:Object.values(e),$z:(e,t,i={})=>{if(void 0===e)return i;for(let s of a(e))if(t in s){let e=s[t];i[e]=i[e]||[],i[e].push(s)}return i},Am:e=>Array.from(o(e)),Bq:function e(t,i=[]){for(let r of t)(0,s.cy)(r)?e(r,i):i.push(r);return i},CA:(e,t={})=>{if(void 0===e)return t;for(let i of r(e).sort())t[i]=e[i];return t},Ey:(e,t)=>a(e).filter(e=>t in e).map(e=>e[t]),HP:r,Im:e=>null==e||(Array.isArray(e)?e.length<1:!!(0,s.Zm)(e)&&Object.keys(e).length<1),Pe:o,RV:(e,t)=>t.includes(e),Sj:e=>e,Ul:(e,t,i=!1,s=0,r=i?-1:1)=>e.slice().sort((e,i)=>{let a=t in e?e[t]:s,o=t in i?i[t]:s;return a<o?-r:a>o?r:0}),WP:(e,t,i,s=[])=>{if(void 0===e)return s;for(let r of a(e))r[t]===i&&s.push(r);return s},X$:n,ax:(e,t)=>e.concat(t),cJ:(e,...t)=>{if(void 0===e)return e;if(!Array.isArray(e)){let i=d(e);for(let e of t)if((0,s.cy)(e))for(let t of e)delete i[t];else delete i[e];return i}return e},cz:(...e)=>{let t=e.filter(s.Et);return t.length>0?t.reduce((e,t)=>e+t,0):void 0},di:e=>{let t=e.slice();return t.sort(),t},h1:(e,...t)=>{let i={},s=Object.assign({},...t),r=Object.keys(s);for(let t=0;t<r.length;t++){let a=r[t];void 0===e[a]&&(i[a]=s[a])}return Object.assign({},e,i)},o8:d,sy:(e,t,i,s=!1,r=s?-1:1)=>e.slice().sort((e,s)=>e[t]<s[t]?-r:e[t]>s[t]?r:e[i]<s[i]?-r:e[i]>s[i]?r:0),wQ:(e,t,i={})=>{if(void 0===e)return i;for(let s of a(e))t in s&&(i[s[t]]=s);return i},zu:a,zw:h})},420(e,t,i){"use strict";var s=i(6519);let r=null,a=null,o=null,n=null;async function d(){if(s.Ll){if(null===r)try{r=await import("node:fs")}catch(e){}if(null===a)try{a=await import("node:os")}catch(e){}if(null===o)try{o=await import("node:path")}catch(e){}if(null===n)try{n=await import("node:url")}catch(e){}}}function h(){if(s.Ll&&null!==a)try{let e=o.resolve(a.tmpdir()),t=o?o.sep:"/";return e.endsWith(t)?e:e+t}catch(e){return}}function c(e){if(null===o)throw Error("path module is not available");let t=o.resolve(e);if(!(t.startsWith(e)&&t.endsWith(".ccxtfile")||t.endsWith(".wasm")))throw Error("invalid file path: "+e)}function l(e,t="utf8"){if(s.Ll&&null!==r){c(e);try{if(null===t)return r.readFileSync(e);return r.readFileSync(e,t)}catch(e){return}}}function u(e,t,i="utf8"){if(!s.Ll||null===r)return!1;c(e);try{return r.writeFileSync(e,t,i),!0}catch(e){return!1}}function f(e){if(!s.Ll||null===r)return!1;c(e);try{return r.accessSync(e),!0}catch(e){return!1}}function p(e){return!s.Ll||!e||e.startsWith("file://")||null===a||null===n||"win32"!==a.platform()?e:/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?n.pathToFileURL(e).href:e}s.Ll&&d(),i.d(t,{G4:()=>h,P8:()=>f,Sk:()=>p,TA:()=>l,_h:()=>u,eK:()=>d})},5788(e,t,i){"use strict";var s=i(7672),r=i(1453);let a=e=>{let t;if(void 0===e)throw new r.NotSupported("timeframe is required");let i=(0,s.Pf)(e.slice(0,-1)),a=e.slice(-1);if("y"===a)t=31536e3;else if("M"===a)t=2592e3;else if("w"===a)t=604800;else if("d"===a)t=86400;else if("h"===a)t=3600;else if("m"===a)t=60;else if("s"===a)t=1;else throw new r.NotSupported("timeframe unit "+a+" is not supported");return i*t};function o(e,t){return void 0!==e&&void 0!==t&&e>0?t/e:void 0}function n(e){let t={};for(let i=0;i<e.length;i++){let[s,r]=e[i];r>0&&(t[s]=(t[s]||0)+r)}return Object.keys(t).map(e=>[parseFloat(e),parseFloat(t[e])])}function d(){let e=!1;try{e=void 0!==self}catch(t){e=!1}return e}i.d(t,{QD:()=>n,Se:()=>d,ru:()=>o},{Hp:(e,t)=>{if(void 0===e)return"";if(!Array.isArray(t)){let i=Object.keys(t);for(let s=0;s<i.length;s++){let r=i[s];Array.isArray(t[r])||(e=e.replace("{"+r+"}",t[r]))}}return e},ce:a,jG:(e,t,i=3)=>{let r=(0,s.Pf)(e.slice(0,-1)),o=e.slice(-1);if(("w"===o||"M"===o||"y"===o)&&r>=1&&Math.floor(r)===r){let e=new Date(t),s=t;if("w"===o){let t=e.getUTCDay(),a=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()-(t+6)%7),o=Date.UTC(1970,0,5),n=Math.floor(Math.floor((a-o)/6048e5)/r)*r;s=o+6048e5*n,2===i&&(s+=6048e5*r)}else if("M"===o){let t=Math.floor((12*e.getUTCFullYear()+e.getUTCMonth())/r)*r,a=Math.floor(t/12),o=t%12;s=Date.UTC(a,o,1),2===i&&(s=Date.UTC(a,o+r,1))}else{let t=Math.floor(e.getUTCFullYear()/r)*r;s=Date.UTC(t,0,1),2===i&&(s=Date.UTC(t+r,0,1))}return s}let n=1e3*a(e);return t-t%n+(2===i?n:0)},um:e=>{let t=/{([\w-]+)}/g,i=[],s=t.exec(e);for(;s;)i.push(s[1]),s=t.exec(e);return i}})},8942(e,t,i){"use strict";let s=new TextEncoder;function r(e){let t=new Uint8Array(128),i=0,r=e=>{if(i+e<=t.length)return;let s=2*t.length;for(;s<i+e;)s*=2;let r=new Uint8Array(s);r.set(t),t=r},a=e=>{r(1),t[i++]=e},o=e=>{r(e.length),t.set(e,i),i+=e.length},n=e=>{a(e>>>8&255),a(255&e)},d=e=>{n(e>>>16&65535),n(65535&e)},h=e=>{let t,i;e>=0?(t=e/0x100000000,i=e%0x100000000):(t=~(Math.abs(++e)/0x100000000),i=~(Math.abs(e)%0x100000000)),o([t>>>24,t>>>16,t>>>8,t,i>>>24,i>>>16,i>>>8,i])},c=(e,t,i,s,r,o)=>{e<=i?a(t|e):void 0!==s&&e<256?(a(s),a(e)):e<65536?(a(r),n(e)):(a(o),d(e))},l=e=>{switch(typeof e){case"undefined":a(192);break;case"boolean":a(e?195:194);break;case"number":if(isFinite(e)&&Math.floor(e)===e)if(e>=0&&e<=127)a(e);else if(e<0&&e>=-32)a(256+e);else if(e>0&&e<=255)a(204),a(e);else if(e>=-128&&e<=127)a(208),a(255&e);else if(e>0&&e<=65535)a(205),n(e);else if(e>=-32768&&e<=32767)a(209),n(65535&e);else if(e>0&&e<=0xffffffff)a(206),d(e);else if(e>=-0x80000000&&e<=0x7fffffff)a(210),d(e>>>0);else if(e>0&&e<=0xffffffffffffffff){let t,i;a(207),o([(t=e/0x100000000)>>>24,t>>>16,t>>>8,t,(i=e%0x100000000)>>>24,i>>>16,i>>>8,i])}else e>=-0x8000000000000000&&e<=0x8000000000000000?(a(211),h(e)):e>0?(a(207),o(new Uint8Array(8).fill(255))):(a(211),o([128,0,0,0,0,0,0,0]));else{let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e),a(203),o(new Uint8Array(t.buffer))}break;case"string":{let t=s.encode(e);c(t.length,160,31,217,218,219),o(t);break}case"object":if(null===e)a(192);else if(e instanceof Date){let t,i,s;t=e.getTime()/1e3,s=1e6*(i=e.getMilliseconds()),0===i&&t>=0&&t<0x100000000?(a(214),a(255),d(t)):t>=0&&t<0x400000000?o([215,255,s>>>22,s>>>14,s>>>6,s<<2>>>0|t/0x100000000,t>>>24,t>>>16,t>>>8,t]):(o([199,12,255,s>>>24,s>>>16,s>>>8,s]),h(t))}else if(Array.isArray(e))for(let t of(c(e.length,144,15,void 0,220,221),e))l(t);else if(e instanceof Uint8Array||e instanceof Uint8ClampedArray){let t=e.length;t<=15?(a(196),a(t)):t<=65535?(a(197),n(t)):(a(198),d(t)),o(e)}else if(ArrayBuffer.isView(e)){c(e.length,144,15,void 0,220,221);for(let t=0;t<e.length;t++)l(e[t])}else{let t=[];for(let i in e)void 0!==e[i]&&t.push(i);for(let i of(c(t.length,128,15,void 0,222,223),t))l(i),l(e[i])}break;default:throw Error("Invalid argument type: The type '"+typeof e+"' cannot be serialized.")}};return l(e),t.subarray(0,i)}i.d(t,{l:()=>r})},8405(e,t,i){"use strict";var s=i(7749);let r=2,a=5,o=(e,t)=>{if(!e)throw Error(t||"assertion failed")};function n(e){if(void 0===e)return;if("number"!=typeof e)return e.toString();let t=e.toString();if(0>t.indexOf("e"))return t;if(1>Math.abs(e)){let e=t.split("e-"),i=e[0].replace(".",""),s=parseInt(e[1]),r="-"===t[0];if(s)return(r?"-":"")+"0."+Array(s).join("0")+i.substring(r)}else{let e=t.split("e");if(e[1]){let t=parseInt(e[1]),i=e[0].split("."),s="";return i[1]&&(t-=i[1].length,s=i[1]),i[0]+s+Array(t+1).join("0")}}return t}let d=[],h=(e,t=0)=>{if(e=n(e),t>0){let i=d[t]||(d[t]=RegExp("([-]*\\d+\\.\\d{"+t+"})(\\d)")),[,s]=e.toString().match(i)||[null,e];return s.toString()}return parseInt(e).toString()};function c(e){if(void 0===e)return 0;let t=e.indexOf("e");if(t<0&&(t=e.indexOf("E")),t>=0)return 0-parseInt(e.slice(t+1));let i=-1,s=-1,r=-1,a=e.length;for(let t=0;t<a;t++){let a=e.charCodeAt(t);48!==a&&(r=t,46===a&&(i<0?i=t:s<0&&(s=t)))}return i<0?0:(s<0?r+1:s)-i-1}let l=(e,t,i,d=r,h=a)=>{if(o(void 0!==i,"numPrecisionDigits should not be undefined"),"string"==typeof i&&(i=parseFloat(i)),o(Number.isFinite(i),"numPrecisionDigits has an invalid number"),4===d?o(i>0,"negative or zero numPrecisionDigits can not be used with TICK_SIZE precisionMode"):o(Number.isInteger(i),"numPrecisionDigits must be an integer with DECIMAL_PLACES or SIGNIFICANT_DIGITS precisionMode"),o(1===t||0===t,"invalid roundingMode provided"),o(d===r||3===d||4===d,"invalid countingMode provided"),o(h===a||6===h,"invalid paddingMode provided"),i<0){let s=Math.pow(10,-i);if(1===t)return(s*parseFloat(l(e/s,t,0,d,h))).toString();if(0===t)return(e-e%s).toString()}if(4===d){let o=c(l(i,1,22,r,a));if(0===t){let t=n(i),r=n(e),a=s.Y.stringDiv(r,t,36);if(void 0===a)return"0";let d=a.indexOf("."),c=d<0?a:a.slice(0,d);(""===c||"-"===c)&&(c="0");let l=s.Y.stringMul(c,t);return"-0"===(l=6===h?((e,t)=>{if(t<=0){let t=e.indexOf(".");return t<0?e:e.slice(0,t)}let i=e.indexOf(".");return(i<0?e:e.slice(0,i))+"."+((i<0?"":e.slice(i+1))+"0".repeat(t)).slice(0,t)})(l,o):(e=>{if(0>e.indexOf("."))return e;let t=e.length;for(;t>0&&"0"===e[t-1];)t--;t>0&&"."===e[t-1]&&t--;let i=e.slice(0,t);return""===i?"0":i})(l))?"0":l}let d=e%i;return d=Number(l(d,1,8,r,a)),0!==c(l(d/i,1,Math.max(o,8),r,a))&&1===t&&(e>0?d>=i/2?e=e-d+i:e-=d:e=d>=i/2?Number(e)-d:Number(e)-d-i),l(e,1,o,r,h)}let u=n(e),f="-"===u[0],p=+!!f,m=u.length;for(var g=0;g<m&&"."!==u[g];g++);let v=new Uint8Array(m-p+ +!(g<u.length));v[0]=48;let y=v.length,b=-1,w=-1;for(var k=1,S=p;S<m;S++,k++){let e=u.charCodeAt(S);if(46===e)y=k--;else if(e<48||e>57)throw Error(`${u}: invalid number (contains an illegal character '${u[k-1]}')`);else v[k]=e,48!==e&&b<0&&(b=k)}b<0&&(b=1);let O=d===r?y:b,T=O+i;w=-1;let P=!0,I=f;for(let e=v.length-1,s=0;e>=0;e--){let r=v[e];0!==e?(r+=s,e>=O+i&&(r=1===t&&r>=53&&!(53===r&&s)?58:48),r>57?(r=48,s=1):s=0):s&&(r=49),v[e]=r,48!==r&&(P=!1,b=e,w=w<0?e+1:w)}3===d&&(T=(O=b)+i),P&&(I=!1);let A=b>=y||P?y-1:b,x=w<y?y:w,M=+!!I,_=M+(y-A),C=Math.max(x-y,0),B=x-A,E=Math.max((h===a?B:T-A)-B,0),R=_+1+C,L=R+E,N=I?"-":"";for(k=M,S=A;k<_;k++,S++)N+=String.fromCharCode(v[S]);for(C+E!==0&&(N+="."),k=_+1,S=y;k<R;k++,S++)N+=String.fromCharCode(v[S]);for(k=R;k<L;k++)N+="0";return N};function u(e){try{if(void 0===e||""===e||0===parseFloat(e))return;return e}catch(t){return e}}i.d(t,{Iu:()=>c,Ye:()=>u,um:()=>n},{NZ:h,S2:{ROUND:1,TRUNCATE:0,ROUND_UP:2,ROUND_DOWN:3,DECIMAL_PLACES:r,SIGNIFICANT_DIGITS:3,TICK_SIZE:4,NO_PADDING:a,PAD_WITH_ZERO:6},fq:(e,t,i,s=r,o=a)=>l(e,t,i,s,o),xv:(e,t=0)=>parseFloat(h(e,t))})},6519(e,t,i){"use strict";let s="u">typeof window,r="u">typeof process&&void 0!==process.versions&&void 0!==process.versions.electron,a="u">typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,o="u">typeof process&&"win32"===process.platform,n="u">typeof Deno,d="u">typeof process&&void 0!==process.versions&&void 0!==process.versions.bun,h=!(s||a||n);i.d(t,{},{Bd:s,Ll:h,N6:n,Qg:d,b8:r,p7:a,uF:o})},8748(e,t,i){"use strict";var s=i(178),r=i.n(s),a=i(7116),o=i(7770),n=i(1093),d=i(2431),h=i(7468);function c(e,t,i,s="pkcs1"){if(void 0===r()||void 0===r().createSign)throw Error("rsa is currently not supported in the browser");let a=i.create().constructor.name.toLowerCase().replace("_",""),o=r().createSign({sha256:"RSA-SHA256",sha384:"RSA-SHA384",sha512:"RSA-SHA512"}[a]);return(o.update(e),"pss"===s)?o.sign({key:t,padding:r().constants.RSA_PKCS1_PSS_PADDING,saltLength:r().constants.RSA_PSS_SALTLEN_DIGEST},"base64"):o.sign(t,"base64")}function l(e,t,i,s=!1,r={}){let u,f=(s?"RS":"HS")+8*i.outputLen;r.alg&&(f=r.alg.toUpperCase());let p=Object.assign({alg:f,typ:"JWT"},r);void 0!==p.iat&&(e.iat=p.iat,delete p.iat);let m=[(0,o.LI)(JSON.stringify(p)),(0,o.LI)(JSON.stringify(e))].join("."),g=f.slice(0,2);if("HS"===g)u=(0,o.LI)((0,n.w8)(m,t,i,"binary"));else if(s||"RS"===g)u=(0,o.LI)((0,o.cg)(c(m,a.As.encode(t),i)));else if("ES"===g){let e=(0,n.h1)(m,a.As.encode(t),d.s9,i),s=e.r.padStart(64,"0"),r=e.s.padStart(64,"0");u=(0,o.LI)((0,o.FF)(s+r))}else if("ED"===g){let e=(0,n.q4)(function(e){for(var t="",i=0;i<e.length;i++)t+=e.charCodeAt(i).toString(16);return t}(m),t,h.ev);u=(0,o.xg)(e)}return[m,u].join(".")}i.d(t,{a:()=>l,n:()=>c})},300(e,t,i){"use strict";var s=i(789);let r=(1n<<250n)-1n,a=(1n<<251n)-256n,o=new TextEncoder,n=e=>"0x"+BigInt(e).toString(16);function d(e){if(!/^[\x00-\x7F]*$/.test(e))throw Error(e+" is not an ASCII string");if(e.length>31)throw Error(e+" is too long");return"0x"+Array.from(e,e=>e.charCodeAt(0).toString(16)).join("")}function h(e){if("bigint"==typeof e||Number.isInteger(e))return e.toString();if("string"==typeof e){if(/^0x[0-9a-f]*$/i.test(e))return BigInt(e).toString();if(/^\d+$/.test(e))return e;if(e.length>31)throw Error(e+" is a long string > 31 chars.");return BigInt(d(e)).toString()}if("boolean"==typeof e)return e?"1":"0";throw Error(e+" can't be computed by felt()")}let c=e=>n((0,s.Dq)(o.encode(e))&r),l=e=>[...e,e.length].reduce((e,t)=>(0,s.NO)(BigInt(e),BigInt(t)),0).toString();function u(e){let t=[],i=e=>{if(Array.isArray(e))t.push(h(e.length)),e.forEach(i);else if(null!==e&&"object"==typeof e)for(let t of Object.keys(e))i(e[t]);else t.push(h(e))};return Array.isArray(e)?e.forEach(i):i(e),t}function f(e,t,i,s){let r=l(u(i));return n(BigInt(l([h("0x535441524b4e45545f434f4e54524143545f41444452455353"),s,e,t,r]))%a)}function p(e,t,i){let s=[c(function(e,t){let i=[],s=new Set,r=t=>{if(t=t.endsWith("*")?t.slice(0,-1):t,!s.has(t)&&e[t])for(let a of(s.add(t),i.push(t),e[t]))r(a.type)};r(t);let[a,...o]=i;return[a,...o.sort()].map(t=>t+"("+e[t].map(e=>e.name+":"+e.type).join(",")+")").join("")}(e,t))];for(let r of e[t]){if(void 0===i[r.name]||null===i[r.name])throw Error("Cannot encode data: missing data for '"+r.name+"'");s.push(function e(t,i,s){if(t[i])return p(t,i,s);if(i.endsWith("*"))return l(s.map(s=>e(t,i.slice(0,-1),s)));if("selector"===i)return/^0x[0-9a-f]*$/i.test(s)?s:c(s);if("bigint"==typeof s||"number"==typeof s)return n(s);if("string"==typeof s)try{return n(s)}catch(e){return n(d(s))}if("boolean"==typeof s)return n(+s);throw Error("Invalid BigNumberish: "+s)}(e,r.type,i[r.name]))}return l(s)}function m(e,t){if(!e.message||!e.primaryType||!e.types||!("StarkNetDomain"in e.types)||(e.domain.revision??"0")!=="0")throw Error("Typed data does not match JSON schema");return l([d("StarkNet Message"),p(e.types,"StarkNetDomain",e.domain),t,p(e.types,e.primaryType,e.message)])}i.d(t,{E:()=>m,Yo:()=>u,r4:()=>f},{BK:c,dl:e=>n((0,s.pd)(e.map(e=>BigInt(e))))})},9637(e,t,i){"use strict";let s=e=>e?(e^16*Math.random()>>e/4).toString(16):"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s),r=e=>e?(e^16*Math.random()>>e/4).toString(16):"1000001004008000".replace(/[018]/g,r),a=e=>e?(e^16*Math.random()>>e/4).toString(16):"1000000010004000800000".replace(/[018]/g,a);i.d(t,{},{Qd:e=>{let t={fetchOHLCVWs:"fetch_ohlcv_ws"};return t[e]?t[e]:e.match(/[A-Z]/)?e.replace(/[a-z0-9][A-Z]/g,e=>e[0]+"_"+e[1]).replace(/[A-Z0-9][A-Z0-9][a-z][^$]/g,e=>e[0]+"_"+e[1]+e[2]+e[3]).replace(/[a-z][0-9]$/g,e=>e[0]+"_"+e[1]).toLowerCase():e},ZH:e=>void 0===e?"":e.length?e.charAt(0).toUpperCase()+e.slice(1):e,_n:a,bB:e=>e.replace(/^\s+|\s+$/g,""),tg:r,uR:s})},8280(e,t,i){"use strict";var s=i(6785);function r(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class a{dequeue(){this.queue[this.queueHead]=void 0,this.queueHead+=1,this.queueHead===this.queue.length?(this.queue.length=0,this.queueHead=0):this.queueHead>=a.QUEUE_COMPACTION_THRESHOLD&&this.queueHead>=this.queue.length/2&&(this.queue=this.queue.slice(this.queueHead),this.queueHead=0)}async leakyBucketLoop(){let e=(0,s.tB)();for(;this.running;){let{resolver:t,cost:i}=this.queue[this.queueHead];if(this.config.tokens>=0)this.config.tokens-=i,t(),this.dequeue(),await Promise.resolve(),0===this.queue.length&&(this.running=!1);else{await (0,s.yy)(1e3*this.config.delay);let t=(0,s.tB)(),i=t-e;e=t;let r=this.config.tokens+this.config.refillRate*i;this.config.tokens=Math.min(r,this.config.capacity)}}}async rollingWindowLoop(){for(;this.running;){let{resolver:e,cost:t}=this.queue[this.queueHead],i=(0,s.tB)(),r=i-this.config.windowSize,a=0,o=this.timestamps.length;for(;a<o&&this.timestamps[a].timestamp<=r;)this.totalCost-=this.timestamps[a].cost,a+=1;if(a>0&&(this.timestamps.splice(0,a),0===this.timestamps.length&&(this.totalCost=0)),this.totalCost+t<=this.config.maxWeight)this.timestamps.push({timestamp:i,cost:t}),this.totalCost+=t,e(),this.dequeue(),await Promise.resolve(),0===this.queue.length&&(this.running=!1);else{let e=this.timestamps[0].timestamp+this.config.windowSize-i;e>0&&await (0,s.yy)(e)}}}async loop(){"leakyBucket"===this.config.algorithm?await this.leakyBucketLoop():await this.rollingWindowLoop()}throttle(e){let t,i=new Promise((e,i)=>{t=e});return e=void 0===e?this.config.cost:e,this.queue.push({resolver:t,cost:e}),this.running||(this.running=!0,this.loop()),i}constructor(e){r(this,"running",void 0),r(this,"queue",void 0),r(this,"queueHead",void 0),r(this,"config",void 0),r(this,"timestamps",void 0),r(this,"totalCost",void 0),this.config={refillRate:1,delay:.001,capacity:1,tokens:0,cost:1,algorithm:"leakyBucket",windowSize:6e4,maxWeight:void 0},Object.assign(this.config,e),"leakyBucket"!==this.config.algorithm&&(this.config.maxWeight=this.config.windowSize/this.config.rateLimit),this.queue=[],this.queueHead=0,this.running=!1,this.timestamps=[],this.totalCost=0}}r(a,"QUEUE_COMPACTION_THRESHOLD",1024),i.d(t,{x:()=>a})},6785(e,t,i){"use strict";let s=Date.now,r=()=>1e3*s(),a=setTimeout,o=(e,t,i=a,r=s()+t)=>{if(t>=0x7fffffff)throw Error("setTimeout() function was called with unrealistic value of "+t.toString());let n=()=>{},d=!0,h=i(()=>{d=!0;let t=r-s();t>0?n=o(e,t,i,r):e()},t);return function(){d&&(d=!1,clearTimeout(h)),n()}};class n extends Error{constructor(){const e="timed out";super(e),this.constructor=n,this.__proto__=n.prototype,this.message=e}}let d=[];for(let e=0;e<60;e++)d.push(e<10?"0"+e:""+e);let h=[];for(let e=0;e<1e3;e++)h.push(e<10?"00"+e:e<100?"0"+e:""+e);let c=e=>{if(!("string"!=typeof e||!e||e.match(/^[0-9]+$/))&&!(0>e.indexOf("-")||0>e.indexOf(":")))try{let t=e.indexOf("+")>=0||"Z"===e.slice(-1)||/-\d\d:?\d\d$/.test(e),i=Date.parse(t?e:(e+"Z").replace(/\s(\d\d):/,"T$1:"));if(Number.isNaN(i))return;return i}catch(e){return}},l=(e,t,i=!0)=>{t=t||"";let s=new Date(e),r=s.getUTCFullYear(),a=(i?r:r-2e3).toString(),o=s.getUTCMonth()+1,n=s.getUTCDate();return a+t+(o=o<10?"0"+o:o.toString())+t+(n=n<10?"0"+n:n.toString())},u=async(e,t)=>{let i=()=>{},s=new Promise(t=>i=o(t,e));try{return await Promise.race([t,s.then(()=>{throw new n})])}finally{i()}};i.d(t,{GA:()=>n},{Dj:c,EZ:r,LC:e=>{let t,i;if("number"==typeof e?t=Math.floor(e):"string"==typeof e&&e.match(/^[0-9]+$/)&&(t=parseInt(e,10)),void 0===t||Number.isNaN(t)||t<0||t>864e13)return;let s=Math.floor(t/1e3),r=t-1e3*s,a=s-86400*Math.floor(s/86400),o=(s-a)/86400+719468,n=Math.floor(o/146097),c=o-146097*n,l=Math.floor((c-Math.floor(c/1460)+Math.floor(c/36524)-Math.floor(c/146096))/365),u=c-(365*l+Math.floor(l/4)-Math.floor(l/100)),f=Math.floor((5*u+2)/153),p=u-Math.floor((153*f+2)/5)+1,m=f<10?f+3:f-9,g=l+400*n,v=m<=2?g+1:g;i=v>9999?"+"+(""+v).padStart(6,"0"):v>=1e3?""+v:(""+v).padStart(4,"0");let y=Math.floor(a/3600),b=a-3600*y,w=Math.floor(b/60);return i+"-"+d[m]+"-"+d[p]+"T"+d[y]+":"+d[w]+":"+d[b-60*w]+"."+h[r]+"Z"},RR:(e,t=" ")=>{let i=new Date(e),s=i.getUTCFullYear(),r=i.getUTCMonth()+1,a=i.getUTCDate(),o=i.getUTCHours(),n=i.getUTCMinutes(),d=i.getUTCSeconds();return s+"-"+(r=r<10?"0"+r:r)+"-"+(a=a<10?"0"+a:a)+t+(o=o<10?"0"+o:o)+":"+(n=n<10?"0"+n:n)+":"+(d=d<10?"0"+d:d)},Rn:(e,t="-")=>l(e,t,!0),Rz:s,Th:l,YA:()=>Math.floor(s()/1e3),_U:e=>{if("string"==typeof e&&e){if(e.indexOf("GMT")>=0)try{return Date.parse(e)}catch(e){return}return c(e)}},k4:o,nm:()=>{let e=(10*r()+122192928e9).toString(16);return e.slice(7,15)+e.slice(3,7)+"1"+e.slice(0,3)+"9696"+"ff".repeat(6)},rE:(e,t="-")=>{t=t||"";let i=new Date(e),s=i.getUTCFullYear().toString(),r=i.getUTCMonth()+1,a=i.getUTCDate();return(r=r<10?"0"+r:r.toString())+t+(a=a<10?"0"+a:a.toString())+t+s},tB:s,wR:u,x_:(e,t="")=>l(e,t,!1),yy:e=>new Promise(t=>o(t,e))})},6637(e,t,i){"use strict";var s=i(7116),r=i(8858),a=i(1093);function o(e){let t;e=e.replace(" ","");let i=("0000000000000000"+(((t=Math.floor(Math.round(new Date().getTime()/1e3)/30))<15.5?"0":"")+Math.round(t).toString(16))).slice(-16),o=(0,a.w8)(s.uh.decode(i),s.RG.decode(e),r.e8,"hex"),n=parseInt(o.substring(o.length-1),16),d=(parseInt(o.substr(2*n,8),16)&parseInt("7fffffff",16))+"";return d.substring(d.length-6,d.length)}i.d(t,{O:()=>o})},7672(e,t,i){"use strict";let s=Number.isFinite,r=Number.isInteger,a=Array.isArray,o=e=>null!=e,n=e=>"string"==typeof e,d=e=>null!=e&&"object"==typeof e,h=(e,t)=>{if(null!=t&&d(e)){let i=e[t];if(null!==i&&""!==i)return i}},c=(e,t,i)=>{if(d(e)){if(null!=t){let i=e[t];if(null!=i&&""!==i)return i}if(null!=i){let t=e[i];if(null!=t&&""!==t)return t}}},l=(e,t)=>{if(!d(e))return;let i=t.length;for(let s=0;s<i;s++){let i=t[s];if(null==i)continue;let r=e[i];if(null!=r&&""!==r)return r}},u=e=>n(e)&&0!==e.length?parseFloat(e):s(e)?e:NaN,f=e=>n(e)&&0!==e.length?Math.trunc(Number(e)):s(e)?Math.trunc(e):NaN;function p(e,t,i){let r=h(e,t);if(void 0===r)return i;let a=u(r);return s(a)?a:i}function m(e,t,i){let r=h(e,t);if(void 0===r)return i;let a=f(r);return s(a)?a:i}function g(e,t,i,r){let a=h(e,t);if(void 0===a)return r;let o=u(a)*i;return s(o)?Math.trunc(o):r}function v(e,t,i){let r=h(e,t);if(void 0===r)return i;let a=1e3*u(r);return s(a)?Math.trunc(a):i}function y(e,t,i){let s=h(e,t);return void 0!==s?s:i}function b(e,t,i){let s=h(e,t);return void 0===s?i:"string"==typeof s?s:Number.isFinite(s)?String(s):i}function w(e,t,i){let s=h(e,t);return void 0===s?i:"string"==typeof s?s.toLowerCase():Number.isFinite(s)?String(s).toLowerCase():i}function k(e,t,i){let s=h(e,t);return void 0===s?i:"string"==typeof s?s.toUpperCase():Number.isFinite(s)?String(s).toUpperCase():i}function S(e,t,i,r){let a=c(e,t,i);if(void 0===a)return r;let o=u(a);return s(o)?o:r}function O(e,t,i,r){let a=c(e,t,i);if(void 0===a)return r;let o=f(a);return s(o)?o:r}function T(e,t,i,r,a){let o=c(e,t,i);if(void 0===o)return a;let n=u(o)*r;return s(n)?Math.trunc(n):a}function P(e,t,i,r){let a=c(e,t,i);if(void 0===a)return r;let o=1e3*u(a);return s(o)?Math.trunc(o):r}function I(e,t,i,s){let r=c(e,t,i);return void 0!==r?r:s}function A(e,t,i,s){let r=c(e,t,i);return void 0===r?s:"string"==typeof r?r:Number.isFinite(r)?String(r):s}function x(e,t,i,s){let r=c(e,t,i);return void 0===r?s:"string"==typeof r?r.toLowerCase():Number.isFinite(r)?String(r).toLowerCase():s}function M(e,t,i,s){let r=c(e,t,i);return void 0===r?s:"string"==typeof r?r.toUpperCase():Number.isFinite(r)?String(r).toUpperCase():s}function _(e,t,i){let r=l(e,t);if(void 0===r)return i;let a=u(r);return s(a)?a:i}function C(e,t,i){if(void 0===e)return i;let r=l(e,t);if(void 0===r)return i;let a=f(r);return s(a)?a:i}function B(e,t,i,r){let a=l(e,t);if(void 0===a)return r;let o=u(a)*i;return s(o)?Math.trunc(o):r}function E(e,t,i){let r=l(e,t);if(void 0===r)return i;let a=1e3*u(r);return s(a)?Math.trunc(a):i}function R(e,t,i){if(void 0===e)return i;let s=l(e,t);return void 0!==s?s:i}function L(e,t,i){if(void 0===e)return i;let s=l(e,t);return void 0===s?i:"string"==typeof s?s:Number.isFinite(s)?String(s):i}function N(e,t,i){if(void 0===e)return i;let s=l(e,t);return void 0===s?i:"string"==typeof s?s.toLowerCase():Number.isFinite(s)?String(s).toLowerCase():i}function D(e,t,i){if(void 0===e)return i;let s=l(e,t);return void 0===s?i:"string"==typeof s?s.toUpperCase():Number.isFinite(s)?String(s).toUpperCase():i}i.d(t,{At:()=>C,Cw:()=>S,DR:()=>R,Dj:()=>I,F7:()=>M,I9:()=>N,J0:()=>T,Q7:()=>_,RH:()=>k,Rc:()=>L,Y2:()=>m,Y_:()=>E,d0:()=>A,fu:()=>D,gw:()=>w,hO:()=>B,lu:()=>g,mU:()=>O,nr:()=>b,pI:()=>y,q0:()=>v,uS:()=>x,w:()=>p,ww:()=>P},{Et:s,Fq:r,Gv:d,JU:f,KL:e=>o(e)&&e.toString||s(e),Kg:n,Pf:u,Zm:e=>d(e)&&Object.getPrototypeOf(e)===Object.prototype&&!a(e)&&!(e instanceof RegExp),_w:h,cy:a,dl:o})},1697(e,t,i){"use strict";class s extends Array{clear(){this.length=0}removeAt(e){let t=this.length-1,i=this[e];for(let i=e;i<t;i++)this[i]=this[i+1];return this.length=t,i}constructor(e){super(),Object.defineProperty(this,"maxSize",{__proto__:null,value:e,writable:!0})}}class r extends s{getLimit(e,t){let i;return(void 0===e?(i=this.allNewUpdates,this.clearAllUpdates=!0):(i=this.newUpdatesBySymbol[e],this.clearUpdatesBySymbol[e]=!0),void 0===i)?t:void 0!==t?Math.min(i,t):i}clear(){super.clear(),this.hashmap={},this.newUpdatesBySymbol={},this.seenUpdatesBySymbol={},this.seenUpdatesAll={},this.clearUpdatesBySymbol={},this.allNewUpdates=0,this.clearAllUpdates=!1}append(e){this.maxSize&&this.length===this.maxSize&&this.removeAt(0),this.push(e),this.clearAllUpdates&&(this.clearAllUpdates=!1,this.allNewUpdates=0,this.seenUpdatesAll={}),this.clearUpdatesBySymbol[e.symbol]&&(this.clearUpdatesBySymbol[e.symbol]=!1,this.newUpdatesBySymbol[e.symbol]=0),this.newUpdatesBySymbol[e.symbol]=(this.newUpdatesBySymbol[e.symbol]||0)+1,this.allNewUpdates=(this.allNewUpdates||0)+1}constructor(e){super(e),function(e,t,i){t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i}(this,"hashmap",{}),Object.defineProperty(this,"nestedNewUpdatesBySymbol",{__proto__:null,value:!1,writable:!0}),Object.defineProperty(this,"newUpdatesBySymbol",{__proto__:null,value:{},writable:!0}),Object.defineProperty(this,"seenUpdatesBySymbol",{__proto__:null,value:{},writable:!0}),Object.defineProperty(this,"seenUpdatesAll",{__proto__:null,value:{},writable:!0}),Object.defineProperty(this,"clearUpdatesBySymbol",{__proto__:null,value:{},writable:!0}),Object.defineProperty(this,"allNewUpdates",{__proto__:null,value:0,writable:!0}),Object.defineProperty(this,"clearAllUpdates",{__proto__:null,value:!1,writable:!0}),Object.defineProperty(this,"hashmap",{__proto__:null,value:{},writable:!0,enumerable:!1})}}class a extends s{getLimit(e,t){return(this.clearUpdates=!0,void 0===t)?this.newUpdates:Math.min(this.newUpdates,t)}clear(){super.clear(),this.hashmap={},this.sizeTracker.clear(),this.newUpdates=0,this.clearUpdates=!1}append(e){if(e[0]in this.hashmap){let t=this.hashmap[e[0]];if(t!==e){for(let i=0;i<e.length;i++)t[i]=e[i];t.length=e.length}}else{if(this.hashmap[e[0]]=e,this.maxSize&&this.length===this.maxSize){let e=this.removeAt(0);delete this.hashmap[e[0]]}this.push(e)}this.clearUpdates&&(this.clearUpdates=!1,this.sizeTracker.clear()),this.sizeTracker.add(e[0]),this.newUpdates=this.sizeTracker.size}constructor(e){super(e),Object.defineProperty(this,"hashmap",{__proto__:null,value:{},writable:!0}),Object.defineProperty(this,"sizeTracker",{__proto__:null,value:new Set,writable:!0}),Object.defineProperty(this,"newUpdates",{__proto__:null,value:0,writable:!0}),Object.defineProperty(this,"clearUpdates",{__proto__:null,value:!1,writable:!0})}}class o extends r{append(e){let t=e[this.keyField],i=this.hashmap[t]=this.hashmap[t]||{};if(e.id in i){let t=i[e.id];if(t!==e)for(let i in e)t[i]=e[i];let s=(e=t).id,r=e[this.keyField],a=this.keyField,o=this.length;for(let e=0;e<o;e++){let t=this[e];if(t.id===s&&t[a]===r){this.removeAt(e);break}}}else i[e.id]=e;if(this.maxSize&&this.length===this.maxSize){let e=this.removeAt(0),t=e[this.keyField];delete this.hashmap[t][e.id],0===Object.keys(this.hashmap[t]).length&&delete this.hashmap[t],void 0!==this.seenUpdatesBySymbol[t]&&(this.seenUpdatesBySymbol[t].delete(e.id)&&(this.newUpdatesBySymbol[t]=this.newUpdatesBySymbol[t]-1),0===this.seenUpdatesBySymbol[t].size&&delete this.seenUpdatesBySymbol[t]),void 0!==this.seenUpdatesAll[t]&&(this.seenUpdatesAll[t].delete(e.id)&&(this.allNewUpdates=this.allNewUpdates-1),0===this.seenUpdatesAll[t].size&&delete this.seenUpdatesAll[t])}this.push(e),this.clearAllUpdates&&(this.clearAllUpdates=!1,this.allNewUpdates=0,this.seenUpdatesAll={}),void 0===this.seenUpdatesBySymbol[t]&&(this.seenUpdatesBySymbol[t]=new Set),this.clearUpdatesBySymbol[t]&&(this.clearUpdatesBySymbol[t]=!1,this.seenUpdatesBySymbol[t].clear());let s=this.seenUpdatesBySymbol[t];s.add(e.id),this.newUpdatesBySymbol[t]=s.size,void 0===this.seenUpdatesAll[t]&&(this.seenUpdatesAll[t]=new Set);let r=this.seenUpdatesAll[t],a=r.size;r.add(e.id),this.allNewUpdates=(this.allNewUpdates||0)+(r.size-a)}constructor(e){super(e),this.nestedNewUpdatesBySymbol=!0,Object.defineProperty(this,"keyField",{__proto__:null,value:"symbol",writable:!0})}}class n extends o{constructor(e){super(e),this.keyField="outcome"}}class d extends r{append(e){let t=this.hashmap[e.symbol]=this.hashmap[e.symbol]||{};if(e.side in t){let i=t[e.side];if(i!==e)for(let t in e)i[t]=e[t];let s=(e=i).symbol,r=e.side,a=this.length;for(let e=0;e<a;e++){let t=this[e];if(t.symbol===s&&t.side===r){this.removeAt(e);break}}}else t[e.side]=e;this.push(e),this.clearAllUpdates&&(this.clearAllUpdates=!1,this.allNewUpdates=0,this.seenUpdatesAll={}),void 0===this.seenUpdatesBySymbol[e.symbol]&&(this.seenUpdatesBySymbol[e.symbol]=new Set),this.clearUpdatesBySymbol[e.symbol]&&(this.clearUpdatesBySymbol[e.symbol]=!1,this.seenUpdatesBySymbol[e.symbol].clear());let i=this.seenUpdatesBySymbol[e.symbol];i.add(e.side),this.newUpdatesBySymbol[e.symbol]=i.size,void 0===this.seenUpdatesAll[e.symbol]&&(this.seenUpdatesAll[e.symbol]=new Set);let s=this.seenUpdatesAll[e.symbol],r=s.size;s.add(e.side),this.allNewUpdates=(this.allNewUpdates||0)+(s.size-r)}constructor(){super(),this.nestedNewUpdatesBySymbol=!0,Object.defineProperty(this,"hashmap",{__proto__:null,value:{},writable:!0})}}i.d(t,{$0:()=>n,Hk:()=>d,I3:()=>r,Pt:()=>o,TG:()=>a})},3208(e,t,i){"use strict";let s,r;var a=i(1453),o=i(5560),n=i(6519),d=i(6785),h=i(7770),c=i(2879),l=i(7116);function u(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}n.Ll?import("node:zlib").then(e=>{s=e.gunzipSync,r=e.inflateRawSync}).catch(()=>{}):Promise.resolve().then(i.bind(i,9861)).then(e=>{s=e.gunzipSync,r=e.inflateSync}).catch(()=>{});let f=n.Ll&&!n.Qg,p=n.Qg&&void 0!==globalThis.WebSocket&&"function"==typeof globalThis.WebSocket.prototype.ping,m=f||p;class g{reusableFuture(e){return this.future(e)}future(e){e in this.futures||(this.futures[e]=(0,o.K)());let t=this.futures[e];return e in this.rejections&&(t.reject(this.rejections[e]),delete this.rejections[e]),t}resolve(e,t){return this.verbose&&void 0===t&&this.log(new Date,"resolve received undefined messageHash"),void 0!==t&&t in this.futures&&(this.futures[t].resolve(e),delete this.futures[t]),e}reject(e,t){if(t)t in this.futures?(this.futures[t].reject(e),delete this.futures[t]):this.rejections[t]=e;else{let t=Object.keys(this.futures);for(let i=0;i<t.length;i++)this.reject(e,t[i])}return e}log(...e){console.log(...e)}connect(e=0){throw new a.NotSupported("connect() not implemented yet")}isOpen(){throw new a.NotSupported("isOpen() not implemented yet")}reset(e){this.clearConnectionTimeout(),this.clearPingInterval(),this.reject(e)}onConnectionTimeout(){if(!this.isOpen()){let e=new a.RequestTimeout("Connection to "+this.url+" failed due to a connection timeout");this.onError(e),this.connection.close(1006)}}setConnectionTimeout(){if(this.connectionTimeout){let e=this.onConnectionTimeout.bind(this);this.connectionTimer=setTimeout(e,this.connectionTimeout)}}clearConnectionTimeout(){this.connectionTimer&&(this.connectionTimer=clearTimeout(this.connectionTimer))}setPingInterval(){if(this.keepAlive){let e=this.onPingInterval.bind(this);this.pingInterval=setInterval(e,this.keepAlive)}}clearPingInterval(){this.pingInterval&&(this.pingInterval=clearInterval(this.pingInterval))}onPingInterval(){if(this.keepAlive&&this.isOpen()){let e=(0,d.Rz)();if(this.lastPong=this.lastPong||e,this.lastPong+this.keepAlive*this.maxPingPongMisses<e)this.onError(new a.RequestTimeout("Connection to "+this.url+" timed out due to a ping-pong keepalive missing on time")),this.close();else{let t;this.ping&&(t=this.ping(this)),this.verbose&&this.log(new Date,"onPingInterval","|",this.url),t?this.send(t).catch(e=>{this.onError(e)}):m?this.connection.ping():this.lastPong=e}}}onOpen(){this.verbose&&this.log(new Date,"onOpen","|",this.url),this.connectionEstablished=(0,d.Rz)(),this.isConnected=!0,this.connected.resolve(this.url),this.clearConnectionTimeout(),this.setPingInterval(),this.onConnectedCallback(this)}onPing(){this.verbose&&this.log(new Date,"onPing","|",this.url)}onPong(){this.lastPong=(0,d.Rz)(),this.verbose&&this.log(new Date,"onPong","|",this.url)}onError(e){this.verbose&&this.log(new Date,"onError",e.message,"|",this.url),e instanceof a.BaseError||(e=new a.NetworkError(e.message)),this.error=e,this.reset(this.error),this.onErrorCallback(this,this.error)}onClose(e){this.verbose&&this.log(new Date,"onClose",e,"|",this.url),this.error||this.reset(new a.NetworkError("connection closed by remote server, closing code "+String(e.code))),this.error instanceof a.ExchangeClosedByUser&&this.reset(this.error),void 0!==this.disconnected&&this.disconnected.resolve(!0),this.onCloseCallback(this,e)}onUpgrade(e){this.verbose&&this.log(new Date,"onUpgrade","|",this.url)}async send(e){this.verbose&&this.log(new Date,"sending",e),e="string"==typeof e?e:JSON.stringify(e);let t=(0,o.K)();return f?this.connection.send(e,{},function(e){e?t.reject(e):t.resolve(null)}):(this.connection.send(e),t.resolve(null)),t}close(){throw new a.NotSupported("close() not implemented yet")}onMessage(e){let t,i=e.data;try{"string"!=typeof i&&(this.gunzip||this.inflate?(t=new Uint8Array(i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)),this.gunzip?t=s(t):this.inflate&&(t=r(t)),i=l.As.encode(t)):this.decompressBinary&&(i=i.toString()))}catch(e){this.onError(e),this.close();return}try{(0,h.mC)(i)&&(i=i.toString(),i=JSON.parse(i.replace(/:(\d{15,}),/g,':"$1",'))),this.verbose&&this.log(new Date,"onMessage",i)}catch(e){this.log(new Date,"onMessage JSON.parse",e,"|",this.url)}try{this.onMessageCallback(this,i)}catch(e){this.reject(e)}}constructor(e,t,i,s,r,a={}){u(this,"connected",void 0),u(this,"disconnected",void 0),u(this,"futures",void 0),u(this,"rejections",void 0),u(this,"keepAlive",void 0),u(this,"connection",void 0),u(this,"connectionTimeout",void 0),u(this,"verbose",!1),u(this,"connectionTimer",void 0),u(this,"lastPong",void 0),u(this,"maxPingPongMisses",void 0),u(this,"pingInterval",void 0),u(this,"connectionEstablished",void 0),u(this,"gunzip",void 0),u(this,"error",void 0),u(this,"inflate",void 0),u(this,"url",void 0),u(this,"isConnected",void 0),u(this,"onConnectedCallback",void 0),u(this,"onMessageCallback",void 0),u(this,"onErrorCallback",void 0),u(this,"onCloseCallback",void 0),u(this,"ping",void 0),u(this,"subscriptions",void 0),u(this,"throttle",void 0),u(this,"cookies",void 0),u(this,"decompressBinary",!0),Object.assign(this,(0,c.zw)({url:e,onMessageCallback:t,onErrorCallback:i,onCloseCallback:s,onConnectedCallback:r,verbose:!1,protocols:void 0,options:void 0,futures:{},subscriptions:{},rejections:{},connected:void 0,error:void 0,connectionStarted:void 0,connectionEstablished:void 0,isConnected:!1,connectionTimer:void 0,connectionTimeout:1e4,pingInterval:void 0,ping:void 0,keepAlive:3e4,maxPingPongMisses:2,connection:void 0,startedConnecting:!1,gunzip:!1,inflate:!1},a)),this.connected=(0,o.K)()}}i.d(t,{A:()=>g})},5560(e,t,i){"use strict";function s(){let e,t,i,s=new Promise((i,s)=>{e=i,t=s}),r=0,a=[],o=()=>{let e=a;a=[];for(let t=0;t<e.length;t++){let s=e[t];1===r?s.onFulfil(i):s.onReject(i)}};s.resolve=function(t){e(t),0===r&&(r=1,i=t,o())},s.reject=function(e){t(e),0===r&&(r=2,i=e,o())};let n=!1;return s.subscribe=function(e,t){if(n||(n=!0,s.catch(()=>{})),1===r)return e(i),()=>{};if(2===r)return t(i),()=>{};let o={onFulfil:e,onReject:t};return a.push(o),()=>{let e=a.indexOf(o);e>=0&&a.splice(e,1)}},s}s.race=e=>{let t=s(),i=[],r=!1,a=e=>t=>{if(!r){r=!0;for(let e=0;e<i.length;e++)i[e]();e(t)}},o=a(t.resolve),n=a(t.reject);for(let t=0;t<e.length&&(i.push((function(e){if(e&&"function"==typeof e.subscribe)return e;let t=s();return Promise.resolve(e).then(t.resolve,t.reject),t})(e[t]).subscribe(o,n)),!r);t++);return t},i.d(t,{K:()=>s})},1718(e,t,i){"use strict";var s=i(6785),r=i(2879),a=i(8133);function o(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class n{limit(){return this.asks.limit(),this.bids.limit(),this}update(e){return void 0!==e.nonce&&void 0!==this.nonce&&e.nonce<=this.nonce?this:(this.nonce=e.nonce,this.timestamp=e.timestamp,this.datetime=(0,s.LC)(this.timestamp),this.reset(e))}reset(e={}){if(this.asks.index.fill(Number.MAX_VALUE),this.asks.length=0,e.asks)for(let t=0;t<e.asks.length;t++)this.asks.storeArray(e.asks[t]);if(this.bids.index.fill(Number.MAX_VALUE),this.bids.length=0,e.bids)for(let t=0;t<e.bids.length;t++)this.bids.storeArray(e.bids[t]);return this.nonce=e.nonce,this.timestamp=e.timestamp,this.datetime=(0,s.LC)(this.timestamp),this.symbol=e.symbol,void 0!==e.outcome&&(this.outcome=e.outcome,this.outcomeId=e.outcomeId,this.market=e.market,delete this.symbol),this}copy(){let e={};void 0!==this.outcome?(e.outcome=this.outcome,e.outcomeId=this.outcomeId,e.market=this.market):e.symbol=this.symbol;let t=new this.constructor(e,this.asks.depth);return t.asks=this.asks.copy(),t.bids=this.bids.copy(),t.nonce=this.nonce,t.timestamp=this.timestamp,t.datetime=this.datetime,t}constructor(e={},t){o(this,"cache",[]),o(this,"asks",void 0),o(this,"bids",void 0),o(this,"timestamp",void 0),o(this,"datetime",void 0),o(this,"nonce",void 0),o(this,"symbol",void 0),Object.defineProperty(this,"cache",{__proto__:null,value:[],writable:!0,enumerable:!1}),t=t||Number.MAX_SAFE_INTEGER;const i=Object.entries((0,r.X$)({bids:[],asks:[],timestamp:void 0,datetime:void 0,nonce:void 0,symbol:void 0},e));for(let e=0;e<i.length;e++){const[t,s]=i[e];this[t]=s}"Array"===this.asks.constructor.name&&(this.asks=new a.$w(this.asks,t)),"Array"===this.bids.constructor.name&&(this.bids=new a.PB(this.bids,t)),this.timestamp&&(this.datetime=(0,s.LC)(this.timestamp))}}class d extends n{constructor(e={},t){super((0,r.X$)(e,{asks:new a.f_(e.asks||[],t),bids:new a.jR(e.bids||[],t)}))}}class h extends n{constructor(e={},t){super((0,r.X$)(e,{asks:new a.o5(e.asks||[],t),bids:new a.eB(e.bids||[],t)}))}}i.d(t,{gX:()=>n,if:()=>d,nS:()=>h})},8133(e,t,i){"use strict";function s(e,t){let i=0,s=e.length-1;for(;i<=s;){let r=i+s>>>1;e[r]-t<0?i=r+1:s=r-1}return i}function r(e,t){let i=e.length;e.push(e[i-1]);for(let s=i-1;s>t;s--)e[s]=e[s-1]}function a(e,t){let i=e.length;for(let s=t;s<i-1;s++)e[s]=e[s+1];e.pop()}let o=new Float64Array(Array(1024).fill(Number.MAX_VALUE));class n extends Array{storeArray(e){let t=e[0],i=e[1],o=this.side?-t:t,n=s(this.index,o);if(i){if(this.index[n]===o)this[n][1]=i;else if(this.index.copyWithin(n+1,n,this.index.length),this.index[n]=o,r(this,n),this[n]=e,this.length>this.index.length-1){let e=Array.from(this.index);e.length=2*this.length,e.fill(Number.MAX_VALUE,this.index.length),this.index=new Float64Array(e)}}else this.index[n]===o&&(this.index.copyWithin(n,n+1,this.index.length),this.index[this.length-1]=Number.MAX_VALUE,a(this,n))}store(e,t){this.storeArray([e,t])}limit(){if(this.length>this.depth){for(let e=this.depth;e<this.length;e++)this.index[e]=Number.MAX_VALUE;this.length=this.depth}}copy(){let e=new this.constructor([],this.depth);for(let t=0;t<this.length;t++)e.storeArray(this[t].slice());return e}constructor(e=[],t){super(),Object.defineProperty(this,"index",{__proto__:null,value:new Float64Array(o),writable:!0}),Object.defineProperty(this,"depth",{__proto__:null,value:t||Number.MAX_SAFE_INTEGER,writable:!0}),this.length=0;for(let t=0;t<e.length;t++)this.storeArray(e[t].slice())}}class d extends n{store(e,t){throw Error("CountedOrderBookSide.store() is not supported, use storeArray([price, size, count]) instead")}storeArray(e){let t=e[0],i=e[1],o=e[2],n=this.side?-t:t,d=s(this.index,n);if(i&&o){if(this.index[d]===n){let e=this[d];e[1]=i,e[2]=o}else if(this.index.copyWithin(d+1,d,this.index.length),this.index[d]=n,r(this,d),this[d]=e,this.length>this.index.length-1){let e=Array.from(this.index);e.length=2*this.length,e.fill(Number.MAX_VALUE,this.index.length),this.index=new Float64Array(e)}}else this.index[d]===n&&(this.index.copyWithin(d,d+1,this.index.length),this.index[this.length-1]=Number.MAX_VALUE,a(this,d))}}class h extends Array{store(e,t){throw Error("IndexedOrderBook.store() is not supported, use storeArray([price, size, id]) instead")}storeArray(e){let t,i=e[0],o=e[1],n=e[2];if(t=void 0!==i?this.side?-i:i:void 0,o){if(this.hashmap.has(n)){let i=this.hashmap.get(n);if(t=t||i,e[0]=Math.abs(t),t===i){let i=s(this.index,t);for(;i<this.length&&this[i][2]!==n;)i++;if(i<this.length){this.index[i]=t,this[i]=e;return}}else{let e=s(this.index,i);for(;e<this.length&&this[e][2]!==n;)e++;e<this.length&&(this.index.copyWithin(e,e+1,this.index.length),this.index[this.length-1]=Number.MAX_VALUE,a(this,e))}}this.hashmap.set(n,t);let i=s(this.index,t);for(;i<this.length&&this.index[i]===t&&this[i][2]<n;)i++;if(this.index.copyWithin(i+1,i,this.index.length),this.index[i]=t,r(this,i),this[i]=e,this.length>this.index.length-1){let e=Array.from(this.index);e.length=2*this.length,e.fill(Number.MAX_VALUE,this.index.length),this.index=new Float64Array(e)}}else if(this.hashmap.has(n)){let e=this.hashmap.get(n),t=s(this.index,e);for(;t<this.length&&this[t][2]!==n;)t++;t<this.length&&(this.index.copyWithin(t,t+1,this.index.length),this.index[this.length-1]=Number.MAX_VALUE,a(this,t)),this.hashmap.delete(n)}}limit(){if(this.length>this.depth){for(let e=this.depth;e<this.length;e++)this.hashmap.delete(this[e][2]),this.index[e]=Number.MAX_VALUE;this.length=this.depth}}copy(){let e=new this.constructor([],this.depth);for(let t=0;t<this.length;t++)e.storeArray(this[t].slice());return e}constructor(e=[],t=Number.MAX_SAFE_INTEGER){super(),Object.defineProperty(this,"hashmap",{__proto__:null,value:new Map,writable:!0}),Object.defineProperty(this,"index",{__proto__:null,value:new Float64Array(o),writable:!0}),Object.defineProperty(this,"depth",{__proto__:null,value:t||Number.MAX_SAFE_INTEGER,writable:!0}),this.length=0;for(let t=0;t<e.length;t++)this.storeArray(e[t].slice())}}class c extends n{get side(){return!1}}class l extends n{get side(){return!0}}class u extends d{get side(){return!1}}class f extends d{get side(){return!0}}class p extends h{get side(){return!1}}class m extends h{get side(){return!0}}i.d(t,{$w:()=>c,PB:()=>l,eB:()=>m,f_:()=>u,jR:()=>f,o5:()=>p})},8794(e,t,i){"use strict";var s=i(1591),r=i.n(s),a=i(3208),o=i(6519),n=i(5788),d=i(6785),h=i(5560),c=i(1453);function l(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}let u=o.Qg?globalThis.WebSocket:o.Ll||!(0,n.Se)()?r():self.WebSocket;class f extends a.A{createConnection(){this.verbose&&this.log(new Date,"connecting to",this.url),this.connectionStarted=(0,d.Rz)(),this.setConnectionTimeout();let e={};if(void 0!==this.cookies){let t="",i=Object.keys(this.cookies);for(let e=0;e<i.length;e++){let s=i[e],r=this.cookies[s];t+=s+"="+r,e<i.length-1&&(t+="; ")}e.Cookie=t,this.options.headers=Object.assign(this.options.headers||{},e)}if(o.Qg){let e={protocols:this.protocols};this.options&&this.options.headers&&(e.headers=this.options.headers),this.connection=new u(this.url,e),this.connection.binaryType="nodebuffer"}else o.Ll?(this.options=this.options||{},this.connection=new u(this.url,this.protocols,this.options),this.duplex=(0,s.createWebSocketStream)(this.connection,{readableObjectMode:!0,readableHighWaterMark:1024}),this.duplex.on("error",()=>{})):(this.connection=new u(this.url,this.protocols),this.connection.binaryType="arraybuffer");this.connection.onopen=this.onConnectionOpen.bind(this),(!o.Ll||o.Qg)&&(this.connection.onmessage=this.onMessage.bind(this)),this.connection.onerror=this.onError.bind(this),this.connection.onclose=this.onClose.bind(this),o.Qg?this.connection.addEventListener("pong",this.onPong.bind(this)):o.Ll&&this.connection.on("ping",this.onPing.bind(this)).on("pong",this.onPong.bind(this)).on("upgrade",this.onUpgrade.bind(this))}onConnectionOpen(){o.Ll&&!o.Qg&&this.deliverLoop(),this.onOpen()}async deliverLoop(){try{for await(let e of this.duplex)for(this.onMessage({data:e});this.duplex.readableLength>0;){let e=this.duplex.read();if(null===e)break;this.onMessage({data:e})}}catch(e){}}connect(e=0){return this.startedConnecting||(this.startedConnecting=!0,e?(0,d.yy)(e).then(this.createConnection.bind(this)):this.createConnection()),this.connected}isOpen(){return this.connection.readyState===u.OPEN}close(){return this.connection instanceof u?(void 0===this.disconnected&&(this.disconnected=(0,h.K)()),this.connection.close()):this.reset(void 0!==this.error?this.error:new c.ExchangeClosedByUser("connection closed by the user")),this.disconnected}constructor(...e){super(...e),l(this,"connectionStarted",void 0),l(this,"protocols",void 0),l(this,"options",void 0),l(this,"duplex",void 0),l(this,"startedConnecting",!1)}}i.d(t,{A:()=>f})},6192(e,t,i){"use strict";var s=i(3030);class r extends s.A{describe(){return this.deepExtend(super.describe(),{id:"bequant",name:"Bequant",pro:!0,countries:["MT"],has:{CORS:void 0,spot:!0,margin:void 0,swap:!1,future:void 0,option:void 0},urls:{logo:"https://github.com/user-attachments/assets/01e199a6-5c65-4b03-83ab-7f9827c140f9",api:{public:"https://api.bequant.io/api/3",private:"https://api.bequant.io/api/3"},www:"https://bequant.io",doc:["https://api.bequant.io/"],fees:["https://bequant.io/fees-and-limits"],referral:"https://bequant.io/referral/dd104e3bee7634ec"}})}}i.d(t,{A:()=>r})},3484(e,t,i){"use strict";var s=i(4721),r=i(3893),a=i(1453),o=i(8748),n=i(7749);class d extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bigone",name:"BigONE",countries:["CN"],version:"v3",rateLimit:20,has:{CORS:void 0,spot:!0,margin:!1,swap:!0,future:void 0,option:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createPostOnlyOrder:!0,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchFundingHistory:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchMarkets:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTransactionFees:!1,fetchVolatilityHistory:!1,fetchWithdrawals:!0,repayCrossMargin:!1,repayIsolatedMargin:!1,transfer:!0,withdraw:!0},timeframes:{"1m":"min1","5m":"min5","15m":"min15","30m":"min30","1h":"hour1","3h":"hour3","4h":"hour4","6h":"hour6","12h":"hour12","1d":"day1","1w":"week1","1M":"month1"},hostname:"big.one",urls:{logo:"https://github.com/user-attachments/assets/4e5cfd53-98cc-4b90-92cd-0d7b512653d1",api:{public:"https://{hostname}/api/v3",private:"https://{hostname}/api/v3/viewer",contractPublic:"https://{hostname}/api/contract/v2",contractPrivate:"https://{hostname}/api/contract/v2",webExchange:"https://{hostname}/api/"},www:"https://big.one",doc:"https://open.big.one/docs/api.html",fees:"https://bigone.zendesk.com/hc/en-us/articles/115001933374-BigONE-Fee-Policy",referral:"https://b1.run/users/new?code=D3LLBVFT"},api:{public:{get:{ping:{cost:1},asset_pairs:{cost:1},"asset_pairs/{asset_pair_name}/depth":{cost:1},"asset_pairs/{asset_pair_name}/trades":{cost:1},"asset_pairs/{asset_pair_name}/ticker":{cost:1},"asset_pairs/{asset_pair_name}/candles":{cost:1},"asset_pairs/tickers":{cost:1}}},private:{get:{accounts:{cost:1},"fund/accounts":{cost:1},"assets/{asset_symbol}/address":{cost:1},orders:{cost:1},"orders/{id}":{cost:1},"orders/multi":{cost:1},trades:{cost:1},withdrawals:{cost:1},deposits:{cost:1}},post:{orders:{cost:1},"orders/{id}/cancel":{cost:1},"orders/cancel":{cost:1},withdrawals:{cost:1},transfer:{cost:1}}},contractPublic:{get:{symbols:{cost:1},instruments:{cost:1},"depth@{symbol}/snapshot":{cost:1},"instruments/difference":{cost:1},"instruments/prices":{cost:1}}},contractPrivate:{get:{accounts:{cost:1},"orders/{id}":{cost:1},orders:{cost:1},"orders/opening":{cost:1},"orders/count":{cost:1},"orders/opening/count":{cost:1},trades:{cost:1},"trades/count":{cost:1}},post:{orders:{cost:1},"orders/batch":{cost:1}},put:{"positions/{symbol}/margin":{cost:1},"positions/{symbol}/risk-limit":{cost:1}},delete:{"orders/{id}":{cost:1},"orders/batch":{cost:1}}},webExchange:{get:{"v3/assets":{cost:1}}}},fees:{trading:{maker:this.parseNumber("0.001"),taker:this.parseNumber("0.001")},funding:{withdraw:{}}},options:{createOrder:{createMarketBuyOrderRequiresPrice:!0},accountsByType:{spot:"SPOT",fund:"FUND",funding:"FUND",future:"CONTRACT",swap:"CONTRACT"},transfer:{fillResponseFromRequest:!0},exchangeMillisecondsCorrection:-100,fetchCurrencies:{webApiEnable:!0,webApiRetries:5,webApiMuteFailure:!0},defaultNetwork:"ERC20",defaultNetworks:{USDT:"TRC20"},networks:{ABBC:"ABBC",ACA:"Acala",AE:"Aeternity",ALGO:"Algorand",APT:"Aptos",AR:"Arweave",ASTR:"Astar",AVAXC:"Avax",AVAXX:"AvaxChain",BEAM:"Beam",BEP20:"BinanceSmartChain",BITCI:"BitciChain",BTC:"Bitcoin",BCH:"BitcoinCash",BSV:"BitcoinSV",CELO:"Celo",CKKB:"CKB",ATOM:"Cosmos",CRC20:"CRO",DASH:"Dash",DOGE:"Dogecoin",XEC:"ECash",EOS:"EOS",ETH:"Ethereum",ETC:"EthereumClassic",ETHW:"EthereumPow",FTM:"Fantom",FIL:"Filecoin",FSN:"Fusion",GRIN:"Grin",ONE:"Harmony",HRC20:"Hecochain",HBAR:"Hedera",HNT:"Helium",ZEN:"Horizen",IOST:"IOST",IRIS:"IRIS",KLAY:"Klaytn",KSM:"Kusama",LTC:"Litecoin",XMR:"Monero",GLMR:"Moonbeam",NEAR:"Near",NEO:"Neo",NEON3:"NeoN3",OASIS:"Oasis",OKC:"Okexchain",ONT:"Ontology",OPTIMISM:"Optimism",DOT:"Polkadot",MATIC:"Polygon",QTUM:"Qtum",REI:"REI",XRP:"Ripple",SGB:"SGB",SDN:"Shiden",SOL:"Solana",XLM:"Stellar",TERA:"Tera",XTZ:"Tezos",TRC20:"Tron",VET:"Vechain",VSYS:"VSystems",WAX:"WAX",ZEC:"Zcash"}},features:{default:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!0,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!1,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyRequiresPrice:!0,marketBuyByCost:!0,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:200,daysBack:void 0,untilDays:void 0,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:200,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:{marginMode:!1,limit:200,daysBack:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:{marginMode:!1,limit:200,daysBack:void 0,daysBackCanceled:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOHLCV:{limit:500}},spot:{extends:"default"},forDerivatives:{extends:"default",createOrder:{triggerPriceType:{mark:!0,index:!0,last:!0}},fetchOrders:{daysBack:1e5,untilDays:1e5},fetchClosedOrders:{daysBack:1e5,untilDays:1e5}},swap:{linear:{extends:"forDerivatives"},inverse:{extends:"forDerivatives"}},future:{linear:void 0,inverse:void 0}},precisionMode:4,exceptions:{exact:{10001:a.BadRequest,10005:a.ExchangeError,"Amount's scale must greater than AssetPair's base scale":a.InvalidOrder,"Price mulit with amount should larger than AssetPair's min_quote_value":a.InvalidOrder,10007:a.BadRequest,10011:a.ExchangeError,10013:a.BadSymbol,10014:a.InsufficientFunds,10403:a.PermissionDenied,10429:a.RateLimitExceeded,40004:a.AuthenticationError,40103:a.AuthenticationError,40104:a.AuthenticationError,40301:a.PermissionDenied,40302:a.ExchangeError,40601:a.ExchangeError,40602:a.ExchangeError,40603:a.InsufficientFunds,40604:a.InvalidOrder,40605:a.InvalidOrder,40120:a.InvalidOrder,40121:a.InvalidOrder,60100:a.BadSymbol},broad:{}},commonCurrencies:{CRE:"Cybereits",FXT:"FXTTOKEN",FREE:"FreeRossDAO",MBN:"Mobilian Coin",ONE:"BigONE Token"}})}async fetchCurrencies(e={}){let t=await this.fetchWebEndpoint("fetchCurrencies","webExchangeGetV3Assets",!0);if(void 0===t)return{};let i=this.safeList(t,"data",[]);return this.parseCurrencies(i)}parseCurrency(e){let t,i=this.safeString(e,"symbol"),s=this.safeCurrencyCode(i),r=this.safeString(e,"name"),a={},o=this.safeList(e,"binding_gateways",[]),n=this.parsePrecision(this.safeString2(e,"withdrawal_scale","scale"));for(let e=0;e<o.length;e++){let t=o[e],i=this.safeString(t,"gateway_name"),r=this.networkIdToCode(i,s),n=this.safeBool(t,"is_deposit_enabled"),d=this.safeBool(t,"is_withdrawal_enabled"),h=this.safeString(t,"min_deposit_amount"),c=this.safeString(t,"min_withdrawal_amount"),l=this.safeString(t,"withdrawal_fee"),u=this.parsePrecision(this.safeString2(t,"withdrawal_scale","scale"));void 0!==r&&(a[r]={id:i,network:r,margin:void 0,deposit:n,withdraw:d,active:void 0,fee:this.parseNumber(l),precision:this.parseNumber(u),limits:{deposit:{min:h,max:void 0},withdraw:{min:c,max:void 0}},info:t})}let d=o.length;return t=this.safeBool(e,"is_fiat",!1)?"fiat":0===d?this.isLeveragedCurrency(i)?"leveraged":"other":"crypto",this.safeCurrencyStructure({id:i,code:s,info:e,name:r,type:t,active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,precision:this.parseNumber(n),limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}},networks:a})}async fetchMarkets(e={}){let t=[this.publicGetAssetPairs(e),this.contractPublicGetSymbols(e)],i=await Promise.all(t),s=this.safeDict(i,0),r=i[1],a=this.safeList(s,"data",[]),o=[];for(let e=0;e<a.length;e++){let t=a[e],i=this.safeDict(t,"base_asset",{}),s=this.safeDict(t,"quote_asset",{}),r=this.safeString(i,"symbol"),n=this.safeString(s,"symbol"),d=this.safeCurrencyCode(r),h=this.safeCurrencyCode(n);void 0!==d&&void 0!==h&&o.push(this.safeMarketStructure({id:this.safeString(t,"name"),uuid:this.safeString(t,"id"),symbol:d+"/"+h,base:d,quote:h,settle:void 0,baseId:r,quoteId:n,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:!0,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(t,"base_scale"))),price:this.parseNumber(this.parsePrecision(this.safeString(t,"quote_scale")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(t,"min_quote_value"),max:this.safeNumber(t,"max_quote_value")}},created:void 0,info:t}))}let n=this.toArray(r);for(let e=0;e<n.length;e++){let t=n[e],i=this.safeString(t,"baseCurrency"),s=this.safeString(t,"quoteCurrency"),r=this.safeString(t,"settleCurrency"),a=this.safeString(t,"symbol"),d=this.safeCurrencyCode(i),h=this.safeCurrencyCode(s);if(void 0===d||void 0===h)continue;let c=this.safeCurrencyCode(r),l=this.safeBool(t,"isInverse");o.push(this.safeMarketStructure({id:a,symbol:d+"/"+h+":"+c,base:d,quote:h,settle:c,baseId:i,quoteId:s,settleId:r,type:"swap",spot:!1,margin:!1,swap:!0,future:!1,option:!1,active:this.safeBool(t,"enable"),contract:!0,linear:!0!==l,inverse:l,contractSize:this.safeNumber(t,"multiplier"),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(t,"valuePrecision"))),price:this.parseNumber(this.parsePrecision(this.safeString(t,"pricePrecision")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:this.safeNumber(t,"priceMin"),max:this.safeNumber(t,"priceMax")},cost:{min:this.safeNumber(t,"initialMargin"),max:void 0}},info:t}))}return o}parseTicker(e,t){let i="swap";"asset_pair_name"in e&&(i="spot");let s=this.safeString2(e,"asset_pair_name","symbol"),r=this.safeSymbol(s,t,"-",i),a=this.safeString2(e,"close","latestPrice"),o=this.safeDict(e,"bid",{}),n=this.safeDict(e,"ask",{});return this.safeTicker({symbol:r,timestamp:void 0,datetime:void 0,high:this.safeString2(e,"high","last24hMaxPrice"),low:this.safeString2(e,"low","last24hMinPrice"),bid:this.safeString(o,"price"),bidVolume:this.safeString(o,"quantity"),ask:this.safeString(n,"price"),askVolume:this.safeString(n,"quantity"),vwap:void 0,open:this.safeString(e,"open"),close:a,last:a,previousClose:void 0,change:this.safeString(e,"daily_change"),percentage:void 0,average:void 0,baseVolume:this.safeString2(e,"volume","volume24h"),quoteVolume:this.safeString(e,"volume24hInUsd"),markPrice:this.safeString(e,"markPrice"),indexPrice:this.safeString(e,"indexPrice"),info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),[s,r]=this.handleMarketTypeAndParams("fetchTicker",i,t);if("spot"===s){let e={asset_pair_name:i.id},t=await this.publicGetAssetPairsAssetPairNameTicker(this.extend(e,r)),s=this.safeDict(t,"data",{});return this.parseTicker(s,i)}{let t=await this.fetchTickers([e],r);return this.safeDict(t,e)}}async fetchTickers(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.safeString(e,0);void 0!==r&&(i=this.market(r));let[a,o]=this.handleMarketTypeAndParams("fetchTickers",i,t),n={},d=this.marketSymbols(e);if("spot"===a){void 0!==d&&(n.pair_names=this.marketIds(d).join(","));let e=await this.publicGetAssetPairsTickers(this.extend(n,o));s=this.safeList(e,"data",[])}else{let e=await this.contractPublicGetInstruments(o);s=this.toArray(e)}let h=this.parseTickers(s,d);return this.filterByArrayTickers(h,"symbol",d)}async fetchTime(e={}){let t=await this.publicGetPing(e),i=this.safeDict(t,"data",{}),s=this.safeIntegerProduct(i,"Timestamp",1e-6);if(void 0===s)throw new a.ExchangeError(this.id+" fetchTime() missing timestamp");return s}async fetchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e);if(!0===r.contract){let e={symbol:r.id};return s=await this.contractPublicGetDepthSymbolSnapshot(this.extend(e,i)),this.parseContractOrderBook(s,r.symbol,t)}{let e={asset_pair_name:r.id};void 0!==t&&(e.limit=t),s=await this.publicGetAssetPairsAssetPairNameDepth(this.extend(e,i));let a=this.safeDict(s,"data",{});return this.parseOrderBook(a,r.symbol,void 0,"bids","asks","price","quantity")}}parseContractBidsAsks(e){let t=Object.keys(e),i=[];for(let s=0;s<t.length;s++){let r=t[s],a=e[r];i.push([this.parseNumber(r),this.parseNumber(a)])}return i}parseContractOrderBook(e,t,i){let s=this.safeDict(e,"bids"),r=this.safeDict(e,"asks"),a=this.parseContractBidsAsks(s),o=this.parseContractBidsAsks(r);return{symbol:t,bids:this.filterByLimit(this.sortBy(a,0,!0),i),asks:this.filterByLimit(this.sortBy(o,0),i),timestamp:void 0,datetime:void 0,nonce:void 0}}parseTrade(e,t){let i,s,r,a,o=this.parse8601(this.safeString2(e,"created_at","inserted_at")),n=this.safeString(e,"price"),d=this.safeString(e,"amount"),h=this.safeString(e,"asset_pair_name"),c=this.safeMarket(h,t,"-"),l=this.safeString(e,"side"),u=this.safeString(e,"taker_side");void 0!==u&&void 0!==l&&"SELF_TRADING"!==l&&(i=u===l?"taker":"maker"),void 0===l?l="ASK"===u?"sell":"buy":"BID"===l?l="buy":"ASK"===l&&(l="sell");let f=this.safeString(e,"maker_order_id"),p=this.safeString(e,"taker_order_id");void 0!==f?s=f:void 0!==p&&(s=p);let m={id:this.safeString(e,"id"),timestamp:o,datetime:this.iso8601(o),symbol:c.symbol,order:s,type:"limit",side:l,takerOrMaker:i,price:n,amount:d,cost:void 0,info:e};void 0!==i?"buy"===l?"maker"===i?(r=this.safeString(c,"base"),a=this.safeString(c,"quote")):(r=this.safeString(c,"quote"),a=this.safeString(c,"base")):"maker"===i?(r=this.safeString(c,"quote"),a=this.safeString(c,"base")):(r=this.safeString(c,"base"),a=this.safeString(c,"quote")):"SELF_TRADING"===l&&("BID"===u?(r=this.safeString(c,"quote"),a=this.safeString(c,"base")):"ASK"===u&&(r=this.safeString(c,"base"),a=this.safeString(c,"quote")));let g=this.safeString(e,"maker_fee"),v=this.safeString(e,"taker_fee");if(void 0!==g){let e=r;void 0!==v?m.fees=[{cost:g,currency:e},{cost:v,currency:a}]:m.fee={cost:g,currency:e}}else void 0!==v?m.fee={cost:v,currency:a}:m.fee=void 0;return this.safeTrade(m,c)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e);if(!0===r.contract)throw new a.NotSupported(this.id+" fetchTrades () can only fetch trades for spot markets");let o={asset_pair_name:r.id},n=await this.publicGetAssetPairsAssetPairNameTrades(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTrades(d,r,t,i)}parseOHLCV(e,t){return[this.parse8601(this.safeString(e,"time")),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e);if(!0===o.contract)throw new a.NotSupported(this.id+" fetchOHLCV () can only fetch ohlcvs for spot markets");let n=this.safeInteger(r,"until"),d=void 0!==n,h=void 0!==i,c=100;h&&d&&(c=500);let l=void 0===s?c:s,u={asset_pair_name:o.id,period:this.safeString(this.timeframes,t,t),limit:l};if(h){let e=this.parseTimeframe(t),s=this.sum(i,l*e*1e3);d?u.time=this.iso8601(Math.min(s,n+1)):u.time=this.iso8601(s)}else d&&(u.time=this.iso8601(n+1));let f=this.omit(r,"until"),p=await this.publicGetAssetPairsAssetPairNameCandles(this.extend(u,f)),m=this.safeList(p,"data",[]);return this.parseOHLCVs(m,o,t,i,l)}parseBalance(e){let t={info:e,timestamp:void 0,datetime:void 0},i=this.safeList(e,"data",[]);for(let e=0;e<i.length;e++){let s=this.safeDict(i,e),r=this.safeString(s,"asset_symbol"),a=this.safeCurrencyCode(r),o=this.account();o.total=this.safeString(s,"balance"),o.used=this.safeString(s,"locked_balance"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let i=this.safeString(e,"type",""),s=this.omit(e,"type");return t="funding"===i||"fund"===i?await this.privateGetFundAccounts(s):await this.privateGetAccounts(s),this.parseBalance(t)}parseType(e){return this.safeString({STOP_LIMIT:"limit",STOP_MARKET:"market",LIMIT:"limit",MARKET:"market"},e,e)}parseOrder(e,t){let i,s,r,a,o=this.safeString(e,"id"),d=this.safeString(e,"asset_pair_name"),h=this.safeSymbol(d,t,"-"),c=this.parse8601(this.safeString(e,"created_at")),l=this.safeString(e,"side");l="BID"===l?"buy":"sell";let u=this.safeString(e,"stop_price");n.Y.stringEq(u,"0")&&(u=void 0),!0===this.safeBool(e,"immediate_or_cancel")&&(i="IOC");let f=this.parseType(this.safeString(e,"type")),p=this.safeString(e,"price");return"market"===f&&"buy"===l?a=this.safeString(e,"filled_amount"):(s=this.safeString(e,"amount"),r=this.safeString(e,"filled_amount")),this.safeOrder({info:e,id:o,clientOrderId:this.safeString(e,"client_order_id"),timestamp:c,datetime:this.iso8601(c),lastTradeTimestamp:this.parse8601(this.safeString(e,"updated_at")),symbol:h,type:f,timeInForce:i,postOnly:this.safeBool(e,"post_only"),side:l,price:p,triggerPrice:u,amount:s,cost:a,average:this.safeString(e,"avg_deal_price"),filled:r,remaining:void 0,status:this.parseOrderStatus(this.safeString(e,"state")),fee:void 0,trades:void 0},t)}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new a.NotSupported(this.id+" createMarketBuyOrderWithCost() supports spot orders only");return i.createMarketBuyOrderRequiresPrice=!1,await this.createOrder(e,"market","buy",t,void 0,i)}async createOrder(e,t,i,s,r,o={}){let d,h;void 0===this.markets&&await this.loadMarkets();let c=this.market(e),l="buy"===i,u="ASK";l&&(u="BID");let f=t.toUpperCase(),p="LIMIT"===f,m=this.safeBool(o,"post_only",!1);[d,h]=this.handlePostOnly("MARKET"===f,!0===m,o);let g=this.safeStringN(h,["triggerPrice","stopPrice","stop_price"]),v={asset_pair_name:c.id,side:u,amount:this.amountToPrecision(e,s)};if(p||"STOP_LIMIT"===f)v.price=this.priceToPrecision(e,r),p&&("IOC"===this.safeString(h,"timeInForce")&&(v.immediate_or_cancel=!0),!0===d&&(v.post_only=!0)),v.amount=this.amountToPrecision(e,s);else if(l){let t;[t,h]=this.handleOptionBoolAndParams(h,"createOrder","createMarketBuyOrderRequiresPrice",!0);let i=this.safeNumber(h,"cost");if(h=this.omit(h,"cost"),t)if(void 0===r&&void 0===i)throw new a.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument");else{let t=this.numberToString(s),a=this.numberToString(r),o=this.parseToNumeric(n.Y.stringMul(t,a));v.amount=this.costToPrecision(e,void 0!==i?i:o)}else v.amount=this.costToPrecision(e,s)}else v.amount=this.amountToPrecision(e,s);void 0!==g&&(v.stop_price=this.priceToPrecision(e,g),v.operator=l?"GTE":"LTE",p?f="STOP_LIMIT":"MARKET"===f&&(f="STOP_MARKET")),v.type=f;let y=this.safeString(h,"clientOrderId");void 0!==y&&(v.client_order_id=y),h=this.omit(h,["stop_price","stopPrice","triggerPrice","timeInForce","clientOrderId"]);let b=await this.privatePostOrders(this.extend(v,h)),w=this.safeDict(b,"data",{});return this.parseOrder(w,c)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privatePostOrdersIdCancel(this.extend({id:e},i)),r=this.safeDict(s,"data",{});return this.parseOrder(r)}async cancelAllOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={asset_pair_name:this.market(e).id},s=await this.privatePostOrdersCancel(this.extend(i,t)),r=this.safeDict(s,"data",{}),a=this.safeList(r,"cancelled",[]),o=this.safeList(r,"failed",[]),n=[];for(let e=0;e<a.length;e++){let t=a[e];n.push(this.safeOrder({info:t,id:t,status:"canceled"}))}for(let e=0;e<o.length;e++){let t=o[e];n.push(this.safeOrder({info:t,id:t,status:"failed"}))}return n}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateGetOrdersId(this.extend({id:e},i)),r=this.safeDict(s,"data",{});return this.parseOrder(r)}async fetchOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={asset_pair_name:r.id};void 0!==i&&(o.limit=i);let n=await this.privateGetOrders(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseOrders(d,r,t,i)}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={asset_pair_name:r.id};void 0!==i&&(o.limit=i);let n=await this.privateGetTrades(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTrades(d,r,t,i)}parseOrderStatus(e){return this.safeString({PENDING:"open",FILLED:"closed",CANCELLED:"canceled"},e)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({state:"PENDING"},s))}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({state:"FILLED"},s))}nonce(){let e=1e6*this.safeInteger(this.options,"exchangeMillisecondsCorrection",0);return this.sum(1e3*this.microseconds(),e)}sign(e,t="public",i="GET",r={},n,d){let h,c=this.omit(r,this.extractParams(e)),l=this.safeString(this.urls.api,t);if(void 0===l)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let u=this.implodeHostname(l)+"/"+this.implodeParams(e,r),f={};if("public"===t||"webExchange"===t||"contractPublic"===t)Object.keys(c).length>0&&(u+="?"+this.urlencode(c));else{this.checkRequiredCredentials();let e=this.nonce().toString(),t={type:"OpenAPIV2",sub:this.apiKey,nonce:e};f.Authorization="Bearer "+(0,o.a)(t,this.encode(this.secret),s.sc),"GET"===i?Object.keys(c).length>0&&(u+="?"+this.urlencode(c)):"POST"===i&&(f["Content-Type"]="application/json",h=this.json(c))}return f["User-Agent"]="ccxt/"+this.id+"-"+this.version,{url:u,method:i,body:void 0===h?d:h,headers:f}}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={asset_symbol:this.currency(e).id},[s,r]=this.handleNetworkCodeAndParams(t),o=await this.privateGetAssetsAssetSymbolAddress(this.extend(i,r)),n=this.safeList(o,"data",[]);if(n.length<1)throw new a.ExchangeError(this.id+" fetchDepositAddress() returned empty address response");let d=this.indexBy(n,"chain"),h=this.selectNetworkIdFromRawNetworks(e,s,d),c=this.safeDict(d,h,{}),l=this.safeString(c,"value"),u=this.safeString(c,"memo");return this.checkAddress(l),{info:o,currency:e,network:this.networkIdToCode(h,e),address:l,tag:u}}parseTransactionStatus(e){return this.safeString({WITHHOLD:"ok",UNCONFIRMED:"pending",CONFIRMED:"ok",COMPLETED:"ok",PENDING:"pending"},e,e)}parseTransaction(e,t){let i=this.safeString(e,"asset_symbol"),s=this.safeCurrencyCode(i),r=this.safeString(e,"id"),a=this.safeNumber(e,"amount"),o=this.parseTransactionStatus(this.safeString(e,"state")),n=this.parse8601(this.safeString(e,"inserted_at")),d=this.parse8601(this.safeString2(e,"updated_at","completed_at")),h=this.safeString(e,"txid"),c=this.safeString(e,"target_address"),l=this.safeString(e,"memo"),u="deposit";"customer_id"in e&&(u="withdrawal");let f=this.safeBool(e,"is_internal");return{info:e,id:r,txid:h,timestamp:n,datetime:this.iso8601(n),network:void 0,addressFrom:void 0,address:void 0,addressTo:c,tagFrom:void 0,tag:l,tagTo:void 0,type:u,amount:a,currency:s,status:o,updated:d,fee:void 0,comment:void 0,internal:f}}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.asset_symbol=(r=this.currency(e)).id),void 0!==i&&(a.limit=i);let o=await this.privateGetDeposits(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTransactions(n,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.asset_symbol=(r=this.currency(e)).id),void 0!==i&&(a.limit=i);let o=await this.privateGetWithdrawals(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTransactions(n,r,t,i)}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(e),o=this.safeDict(this.options,"accountsByType",{}),n=this.safeString(o,i,i),d=this.safeString(o,s,s),h=this.safeString(r,"guid",this.uuid()),c={symbol:a.id,amount:this.currencyToPrecision(e,t),from:n,to:d,guid:h},l=await this.privatePostTransfer(this.extend(c,r)),u=this.parseTransfer(l,a),f=this.safeDict(this.options,"transfer",{});return!0===this.safeBool(f,"fillResponseFromRequest",!0)&&(u.fromAccount=i,u.toAccount=s,u.amount=t,u.id=h),u}parseTransfer(e,t){let i=this.safeString(e,"code");return{info:e,id:void 0,timestamp:void 0,datetime:void 0,currency:void 0,amount:void 0,fromAccount:void 0,toAccount:void 0,status:this.parseTransferStatus(i)}}parseTransferStatus(e){return this.safeString({0:"ok"},e,"failed")}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d={symbol:n.id,target_address:i,amount:this.currencyToPrecision(e,t)};void 0!==a&&(d.memo=a);let[h,c]=this.handleNetworkCodeAndParams(o);void 0!==h&&(d.gateway_name=this.networkCodeToId(h,this.safeString(n,"code")));let l=await this.privatePostWithdrawals(this.extend(d,c)),u=this.safeDict(l,"data",{});return this.parseTransaction(u,n)}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"code"),l=this.safeString(n,"message");if("0"!==c&&void 0!==c){let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,l,e),this.throwExactlyMatchedException(this.exceptions.exact,c,e),this.throwBroadlyMatchedException(this.exceptions.broad,l,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>d})},2222(e,t,i){"use strict";var s=i(4721),r=i(7468),a=i(5077),o=i(1453),n=i(7749),d=i(8748),h=i(1093);class c extends a.A{describe(){return this.deepExtend(super.describe(),{id:"binance",name:"Binance",countries:[],rateLimit:50,certified:!0,pro:!0,has:{CORS:void 0,spot:!0,margin:!0,swap:!0,future:!0,option:!0,addMargin:!0,borrowCrossMargin:!0,borrowIsolatedMargin:!0,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!1,closePosition:!1,createConvertTrade:!0,createDepositAddress:!1,createLimitBuyOrder:!0,createLimitSellOrder:!0,createMarketBuyOrder:!0,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!0,createMarketSellOrder:!0,createMarketSellOrderWithCost:!0,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!1,createPostOnlyOrder:!0,createReduceOnlyOrder:!0,createStopLimitOrder:!0,createStopLossOrder:!0,createStopMarketOrder:!1,createStopOrder:!0,createTakeProfitOrder:!0,createTrailingPercentOrder:!0,createTriggerOrder:!0,editOrder:!0,editOrders:!0,fetchAccounts:void 0,fetchADLRank:!0,fetchAllGreeks:!0,fetchBalance:!0,fetchBidsAsks:!0,fetchBorrowInterest:!0,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!0,fetchCanceledAndClosedOrders:"emulated",fetchCanceledOrders:"emulated",fetchClosedOrder:!1,fetchClosedOrders:"emulated",fetchConvertCurrencies:!0,fetchConvertQuote:!0,fetchConvertTrade:!0,fetchConvertTradeHistory:!0,fetchCrossBorrowRate:!0,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:!1,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!1,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!0,fetchFundingInterval:"emulated",fetchFundingIntervals:!0,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchGreeks:!0,fetchIndexOHLCV:!0,fetchIsolatedBorrowRate:"emulated",fetchIsolatedBorrowRates:!0,fetchL3OrderBook:!1,fetchLastPrices:!0,fetchLedger:!0,fetchLedgerEntry:!0,fetchLeverage:"emulated",fetchLeverages:!0,fetchLeverageTiers:!0,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!0,fetchMarginAdjustmentHistory:!0,fetchMarginMode:!0,fetchMarginModes:!0,fetchMarketLeverageTiers:"emulated",fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMarkPrice:!0,fetchMarkPrices:!0,fetchMyLiquidations:!0,fetchMySettlementHistory:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!0,fetchOpenOrder:!0,fetchOpenOrders:!0,fetchOption:!0,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrders:!0,fetchOrderTrades:!0,fetchPosition:!0,fetchPositionADLRank:!0,fetchPositionHistory:!1,fetchPositionMode:!0,fetchPositions:!0,fetchPositionsADLRank:!0,fetchPositionsHistory:!1,fetchPositionsRisk:!0,fetchPremiumIndexOHLCV:!0,fetchSettlementHistory:!0,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTradingLimits:"emulated",fetchTransactionFee:"emulated",fetchTransactionFees:!0,fetchTransactions:!1,fetchTransfer:!1,fetchTransfers:!0,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,fetchWithdrawAddresses:!1,fetchWithdrawal:!1,fetchWithdrawals:!0,fetchWithdrawalWhitelist:!1,reduceMargin:!0,repayCrossMargin:!0,repayIsolatedMargin:!0,sandbox:!0,setLeverage:!0,setMargin:!1,setMarginMode:!0,setPositionMode:!0,signIn:!1,transfer:!0,withdraw:!0},timeframes:{"1s":"1s","1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","8h":"8h","12h":"12h","1d":"1d","3d":"3d","1w":"1w","1M":"1M"},urls:{logo:"https://github.com/user-attachments/assets/e9419b93-ccb0-46aa-9bff-c883f096274b",test:{dapiPublic:"https://testnet.binancefuture.com/dapi/v1",dapiPrivate:"https://testnet.binancefuture.com/dapi/v1",dapiPrivateV2:"https://testnet.binancefuture.com/dapi/v2",fapiPublic:"https://testnet.binancefuture.com/fapi/v1",fapiPublicV2:"https://testnet.binancefuture.com/fapi/v2",fapiPublicV3:"https://testnet.binancefuture.com/fapi/v3",fapiPrivate:"https://testnet.binancefuture.com/fapi/v1",fapiPrivateV2:"https://testnet.binancefuture.com/fapi/v2",fapiPrivateV3:"https://testnet.binancefuture.com/fapi/v3",public:"https://testnet.binance.vision/api/v3",private:"https://testnet.binance.vision/api/v3",v1:"https://testnet.binance.vision/api/v1"},demo:{dapiPublic:"https://demo-dapi.binance.com/dapi/v1",dapiPrivate:"https://demo-dapi.binance.com/dapi/v1",dapiPrivateV2:"https://demo-dapi.binance.com/dapi/v2",fapiPublic:"https://demo-fapi.binance.com/fapi/v1",fapiPublicV2:"https://demo-fapi.binance.com/fapi/v2",fapiPublicV3:"https://demo-fapi.binance.com/fapi/v3",fapiPrivate:"https://demo-fapi.binance.com/fapi/v1",fapiPrivateV2:"https://demo-fapi.binance.com/fapi/v2",fapiPrivateV3:"https://demo-fapi.binance.com/fapi/v3",public:"https://demo-api.binance.com/api/v3",private:"https://demo-api.binance.com/api/v3",v1:"https://demo-api.binance.com/api/v1"},api:{sapi:"https://api.binance.com/sapi/v1",sapiV2:"https://api.binance.com/sapi/v2",sapiV3:"https://api.binance.com/sapi/v3",sapiV4:"https://api.binance.com/sapi/v4",dapiPublic:"https://dapi.binance.com/dapi/v1",dapiPrivate:"https://dapi.binance.com/dapi/v1",eapiPublic:"https://eapi.binance.com/eapi/v1",eapiPrivate:"https://eapi.binance.com/eapi/v1",dapiPrivateV2:"https://dapi.binance.com/dapi/v2",dapiData:"https://dapi.binance.com/futures/data",fapiPublic:"https://fapi.binance.com/fapi/v1",fapiPublicV2:"https://fapi.binance.com/fapi/v2",fapiPublicV3:"https://fapi.binance.com/fapi/v3",fapiPrivate:"https://fapi.binance.com/fapi/v1",fapiPrivateV2:"https://fapi.binance.com/fapi/v2",fapiPrivateV3:"https://fapi.binance.com/fapi/v3",fapiData:"https://fapi.binance.com/futures/data",public:"https://api.binance.com/api/v3",private:"https://api.binance.com/api/v3",v1:"https://api.binance.com/api/v1",papi:"https://papi.binance.com/papi/v1",papiV2:"https://papi.binance.com/papi/v2"},www:"https://www.binance.com",referral:{url:"https://accounts.binance.com/register?ref=CCXTCOM",discount:.1},doc:["https://developers.binance.com/en"],api_management:"https://www.binance.com/en/usercenter/settings/api-management",fees:"https://www.binance.com/en/fee/schedule"},api:{sapi:{get:{"copyTrading/futures/userStatus":{cost:2},"copyTrading/futures/leadSymbol":{cost:2},"system/status":{cost:.1},accountSnapshot:{cost:240},"account/info":{cost:.1},"margin/asset":{cost:1},"margin/pair":{cost:1},"margin/allAssets":{cost:.1},"margin/allPairs":{cost:.1},"margin/priceIndex":{cost:1},"spot/delist-schedule":{cost:10},"asset/assetDividend":{cost:1},"asset/dribblet":{cost:.1},"asset/transfer":{cost:.1},"asset/assetDetail":{cost:.1},"asset/tradeFee":{cost:.1},"asset/ledger-transfer/cloud-mining/queryByPage":{cost:4.0002},"asset/convert-transfer/queryByPage":{cost:.033335},"asset/wallet/balance":{cost:6},"asset/custody/transfer-history":{cost:6},"margin/borrow-repay":{cost:1},"margin/loan":{cost:1},"margin/repay":{cost:1},"margin/account":{cost:1},"margin/transfer":{cost:.1},"margin/interestHistory":{cost:.1},"margin/forceLiquidationRec":{cost:.1},"margin/order":{cost:1},"margin/openOrders":{cost:1},"margin/allOrders":{cost:20},"margin/myTrades":{cost:1},"margin/maxBorrowable":{cost:5},"margin/maxTransferable":{cost:5},"margin/tradeCoeff":{cost:1},"margin/isolated/transfer":{cost:.1},"margin/isolated/account":{cost:1},"margin/isolated/pair":{cost:1},"margin/isolated/allPairs":{cost:1},"margin/isolated/accountLimit":{cost:.1},"margin/interestRateHistory":{cost:.1},"margin/orderList":{cost:1},"margin/allOrderList":{cost:20},"margin/openOrderList":{cost:1},"margin/crossMarginData":{cost:.1,noCoin:.5},"margin/isolatedMarginData":{cost:.1,noCoin:1},"margin/isolatedMarginTier":{cost:.1},"margin/rateLimit/order":{cost:2},"margin/dribblet":{cost:.1},"margin/dust":{cost:20.001},"margin/crossMarginCollateralRatio":{cost:10},"margin/exchange-small-liability":{cost:.6667},"margin/exchange-small-liability-history":{cost:.6667},"margin/next-hourly-interest-rate":{cost:.6667},"margin/capital-flow":{cost:10},"margin/delist-schedule":{cost:10},"margin/available-inventory":{cost:.3334},"margin/leverageBracket":{cost:.1},"loan/vip/loanable/data":{cost:40},"loan/vip/collateral/data":{cost:40},"loan/vip/request/data":{cost:2.6668},"loan/vip/request/interestRate":{cost:2.6668},"loan/income":{cost:40.002},"loan/ongoing/orders":{cost:40},"loan/ltv/adjustment/history":{cost:40},"loan/borrow/history":{cost:40},"loan/repay/history":{cost:40},"loan/loanable/data":{cost:40},"loan/collateral/data":{cost:40},"loan/repay/collateral/rate":{cost:600},"loan/flexible/ongoing/orders":{cost:30},"loan/flexible/borrow/history":{cost:40},"loan/flexible/repay/history":{cost:40},"loan/flexible/ltv/adjustment/history":{cost:40},"loan/vip/ongoing/orders":{cost:40},"loan/vip/repay/history":{cost:40},"loan/vip/collateral/account":{cost:600},"fiat/orders":{cost:600.03},"fiat/payments":{cost:.1},"futures/transfer":{cost:1},"futures/histDataLink":{cost:.1},"rebate/taxQuery":{cost:80.004},"capital/config/getall":{cost:1},"capital/deposit/address":{cost:1},"capital/deposit/address/list":{cost:1},"capital/deposit/hisrec":{cost:.1},"capital/deposit/subAddress":{cost:.1},"capital/deposit/subHisrec":{cost:.1},"capital/withdraw/history":{cost:2},"capital/withdraw/address/list":{cost:10},"capital/contract/convertible-coins":{cost:4.0002},"convert/tradeFlow":{cost:20.001},"convert/exchangeInfo":{cost:50},"convert/assetInfo":{cost:10},"convert/orderStatus":{cost:.6667},"convert/limit/queryOpenOrders":{cost:20.001},"account/status":{cost:.1},"account/apiTradingStatus":{cost:.1},"account/apiRestrictions/ipRestriction":{cost:.1},bnbBurn:{cost:.1},"sub-account/futures/account":{cost:1},"sub-account/futures/accountSummary":{cost:.1},"sub-account/futures/positionRisk":{cost:1},"sub-account/futures/internalTransfer":{cost:.1},"sub-account/list":{cost:.1},"sub-account/margin/account":{cost:1},"sub-account/margin/accountSummary":{cost:1},"sub-account/spotSummary":{cost:.1},"sub-account/status":{cost:1},"sub-account/sub/transfer/history":{cost:.1},"sub-account/transfer/subUserHistory":{cost:.1},"sub-account/universalTransfer":{cost:.1},"sub-account/apiRestrictions/ipRestriction/thirdPartyList":{cost:1},"sub-account/transaction-statistics":{cost:.40002},"sub-account/subAccountApi/ipRestriction":{cost:20.001},"managed-subaccount/asset":{cost:.1},"managed-subaccount/accountSnapshot":{cost:240},"managed-subaccount/queryTransLogForInvestor":{cost:.1},"managed-subaccount/queryTransLogForTradeParent":{cost:.40002},"managed-subaccount/fetch-future-asset":{cost:.40002},"managed-subaccount/marginAsset":{cost:.1},"managed-subaccount/info":{cost:.40002},"managed-subaccount/deposit/address":{cost:.006667},"managed-subaccount/query-trans-log":{cost:.40002},"lending/daily/product/list":{cost:.1},"lending/daily/userLeftQuota":{cost:.1},"lending/daily/userRedemptionQuota":{cost:.1},"lending/daily/token/position":{cost:.1},"lending/union/account":{cost:.1},"lending/union/purchaseRecord":{cost:.1},"lending/union/redemptionRecord":{cost:.1},"lending/union/interestHistory":{cost:.1},"lending/project/list":{cost:.1},"lending/project/position/list":{cost:.1},"eth-staking/eth/history/stakingHistory":{cost:15},"eth-staking/eth/history/redemptionHistory":{cost:15},"eth-staking/eth/history/rewardsHistory":{cost:15},"eth-staking/eth/quota":{cost:15},"eth-staking/eth/history/rateHistory":{cost:15},"eth-staking/account":{cost:15},"eth-staking/wbeth/history/wrapHistory":{cost:15},"eth-staking/wbeth/history/unwrapHistory":{cost:15},"eth-staking/eth/history/wbethRewardsHistory":{cost:15},"sol-staking/sol/history/stakingHistory":{cost:15},"sol-staking/sol/history/redemptionHistory":{cost:15},"sol-staking/sol/history/bnsolRewardsHistory":{cost:15},"sol-staking/sol/history/rateHistory":{cost:15},"sol-staking/account":{cost:15},"sol-staking/sol/quota":{cost:15},"mining/pub/algoList":{cost:.1},"mining/pub/coinList":{cost:.1},"mining/worker/detail":{cost:.5},"mining/worker/list":{cost:.5},"mining/payment/list":{cost:.5},"mining/statistics/user/status":{cost:.5},"mining/statistics/user/list":{cost:.5},"mining/payment/uid":{cost:.5},"bswap/pools":{cost:.1},"bswap/liquidity":{cost:.1,noPoolId:1},"bswap/liquidityOps":{cost:20.001},"bswap/quote":{cost:1.00005},"bswap/swap":{cost:20.001},"bswap/poolConfigure":{cost:1.00005},"bswap/addLiquidityPreview":{cost:1.00005},"bswap/removeLiquidityPreview":{cost:1.00005},"bswap/unclaimedRewards":{cost:6.667},"bswap/claimedHistory":{cost:6.667},"blvt/tokenInfo":{cost:.1},"blvt/subscribe/record":{cost:.1},"blvt/redeem/record":{cost:.1},"blvt/userLimit":{cost:.1},"apiReferral/ifNewUser":{cost:1},"apiReferral/customization":{cost:1},"apiReferral/userCustomization":{cost:1},"apiReferral/rebate/recentRecord":{cost:1},"apiReferral/rebate/historicalRecord":{cost:1},"apiReferral/kickback/recentRecord":{cost:1},"apiReferral/kickback/historicalRecord":{cost:1},"broker/subAccountApi":{cost:1},"broker/subAccount":{cost:1},"broker/subAccountApi/commission/futures":{cost:1},"broker/subAccountApi/commission/coinFutures":{cost:1},"broker/info":{cost:1},"broker/transfer":{cost:1},"broker/transfer/futures":{cost:1},"broker/rebate/recentRecord":{cost:1},"broker/rebate/historicalRecord":{cost:1},"broker/subAccount/bnbBurn/status":{cost:1},"broker/subAccount/depositHist":{cost:1},"broker/subAccount/spotSummary":{cost:1},"broker/subAccount/marginSummary":{cost:1},"broker/subAccount/futuresSummary":{cost:1},"broker/rebate/futures/recentRecord":{cost:1},"broker/subAccountApi/ipRestriction":{cost:1},"broker/universalTransfer":{cost:1},"account/apiRestrictions":{cost:.1},"c2c/orderMatch/listUserOrderHistory":{cost:.1},"nft/history/transactions":{cost:20.001},"nft/history/deposit":{cost:20.001},"nft/history/withdraw":{cost:20.001},"nft/user/getAsset":{cost:20.001},"pay/transactions":{cost:20.001},"giftcard/verify":{cost:.1},"giftcard/cryptography/rsa-public-key":{cost:.1},"giftcard/buyCode/token-limit":{cost:.1},"algo/spot/openOrders":{cost:.1},"algo/spot/historicalOrders":{cost:.1},"algo/spot/subOrders":{cost:.1},"algo/futures/openOrders":{cost:.1},"algo/futures/historicalOrders":{cost:.1},"algo/futures/subOrders":{cost:.1},"portfolio/account":{cost:.1},"portfolio/collateralRate":{cost:5},"portfolio/pmLoan":{cost:3.3335},"portfolio/interest-history":{cost:.6667},"portfolio/asset-index-price":{cost:.1},"portfolio/repay-futures-switch":{cost:3},"portfolio/margin-asset-leverage":{cost:5},"portfolio/balance":{cost:2},"portfolio/negative-balance-exchange-record":{cost:2},"portfolio/pmloan-history":{cost:5},"portfolio/earn-asset-balance":{cost:150},"portfolio/delta-mode":{cost:150},"portfolio/margin-call-level":{cost:150},"staking/productList":{cost:.1},"staking/position":{cost:.1},"staking/stakingRecord":{cost:.1},"staking/personalLeftQuota":{cost:.1},"lending/auto-invest/target-asset/list":{cost:.1},"lending/auto-invest/target-asset/roi/list":{cost:.1},"lending/auto-invest/all/asset":{cost:.1},"lending/auto-invest/source-asset/list":{cost:.1},"lending/auto-invest/plan/list":{cost:.1},"lending/auto-invest/plan/id":{cost:.1},"lending/auto-invest/history/list":{cost:.1},"lending/auto-invest/index/info":{cost:.1},"lending/auto-invest/index/user-summary":{cost:.1},"lending/auto-invest/one-off/status":{cost:.1},"lending/auto-invest/redeem/history":{cost:.1},"lending/auto-invest/rebalance/history":{cost:.1},"simple-earn/flexible/list":{cost:15},"simple-earn/locked/list":{cost:15},"simple-earn/flexible/personalLeftQuota":{cost:15},"simple-earn/locked/personalLeftQuota":{cost:15},"simple-earn/flexible/subscriptionPreview":{cost:15},"simple-earn/locked/subscriptionPreview":{cost:15},"simple-earn/flexible/history/rateHistory":{cost:15},"simple-earn/flexible/position":{cost:15},"simple-earn/locked/position":{cost:15},"simple-earn/account":{cost:15},"simple-earn/flexible/history/subscriptionRecord":{cost:15},"simple-earn/locked/history/subscriptionRecord":{cost:15},"simple-earn/flexible/history/redemptionRecord":{cost:15},"simple-earn/locked/history/redemptionRecord":{cost:15},"simple-earn/flexible/history/rewardsRecord":{cost:15},"simple-earn/locked/history/rewardsRecord":{cost:15},"simple-earn/flexible/history/collateralRecord":{cost:.1},"dci/product/list":{cost:.1},"dci/product/positions":{cost:.1},"dci/product/accounts":{cost:.1},"accumulator/product/list":{cost:.1},"accumulator/product/position/list":{cost:.1},"accumulator/product/sum-holding":{cost:.1},"equity/market/exchangeInfo":{cost:.1},"equity/market/tokenized-assets":{cost:.1},"equity/market/quote":{cost:.1},"equity/order/open-orders":{cost:.1},"equity/order/history":{cost:.1},"equity/order/detail":{cost:.1},"equity/trade/history":{cost:.1},"equity/tokenized/convert-status":{cost:.1},"equity/tokenized/history":{cost:.1}},post:{"asset/dust":{cost:.06667},"asset/dust-btc":{cost:.1},"asset/transfer":{cost:6.0003},"asset/get-funding-asset":{cost:.1},"asset/convert-transfer":{cost:.033335},"account/disableFastWithdrawSwitch":{cost:.1},"account/enableFastWithdrawSwitch":{cost:.1},"capital/withdraw/apply":{cost:4.0002},"capital/contract/convertible-coins":{cost:4.0002},"capital/deposit/credit-apply":{cost:.1},"margin/borrow-repay":{cost:20.001},"margin/transfer":{cost:4.0002},"margin/loan":{cost:20.001},"margin/repay":{cost:20.001},"margin/order":{cost:.040002},"margin/order/oco":{cost:.040002},"margin/dust":{cost:20.001},"margin/exchange-small-liability":{cost:20.001},"margin/isolated/transfer":{cost:4.0002},"margin/isolated/account":{cost:2.0001},"margin/max-leverage":{cost:300},bnbBurn:{cost:.1},"sub-account/virtualSubAccount":{cost:.1},"sub-account/margin/transfer":{cost:4.0002},"sub-account/margin/enable":{cost:.1},"sub-account/futures/enable":{cost:.1},"sub-account/futures/transfer":{cost:.1},"sub-account/futures/internalTransfer":{cost:.1},"sub-account/transfer/subToSub":{cost:.1},"sub-account/transfer/subToMaster":{cost:.1},"sub-account/universalTransfer":{cost:.1},"sub-account/options/enable":{cost:.1},"managed-subaccount/deposit":{cost:.1},"managed-subaccount/withdraw":{cost:.1},userDataStream:{cost:.1},"userDataStream/isolated":{cost:.1},userListenToken:{cost:.1},"futures/transfer":{cost:.1},"lending/customizedFixed/purchase":{cost:.1},"lending/daily/purchase":{cost:.1},"lending/daily/redeem":{cost:.1},"bswap/liquidityAdd":{cost:60},"bswap/liquidityRemove":{cost:60},"bswap/swap":{cost:60},"bswap/claimRewards":{cost:6.667},"blvt/subscribe":{cost:.1},"blvt/redeem":{cost:.1},"apiReferral/customization":{cost:1},"apiReferral/userCustomization":{cost:1},"apiReferral/rebate/historicalRecord":{cost:1},"apiReferral/kickback/historicalRecord":{cost:1},"broker/subAccount":{cost:1},"broker/subAccount/margin":{cost:1},"broker/subAccount/futures":{cost:1},"broker/subAccountApi":{cost:1},"broker/subAccountApi/permission":{cost:1},"broker/subAccountApi/commission":{cost:1},"broker/subAccountApi/commission/futures":{cost:1},"broker/subAccountApi/commission/coinFutures":{cost:1},"broker/transfer":{cost:1},"broker/transfer/futures":{cost:1},"broker/rebate/historicalRecord":{cost:1},"broker/subAccount/bnbBurn/spot":{cost:1},"broker/subAccount/bnbBurn/marginInterest":{cost:1},"broker/subAccount/blvt":{cost:1},"broker/subAccountApi/ipRestriction":{cost:1},"broker/subAccountApi/ipRestriction/ipList":{cost:1},"broker/universalTransfer":{cost:1},"broker/subAccountApi/permission/universalTransfer":{cost:1},"broker/subAccountApi/permission/vanillaOptions":{cost:1},"giftcard/createCode":{cost:.1},"giftcard/redeemCode":{cost:.1},"giftcard/buyCode":{cost:.1},"algo/spot/newOrderTwap":{cost:20.001},"algo/futures/newOrderVp":{cost:20.001},"algo/futures/newOrderTwap":{cost:20.001},"staking/purchase":{cost:.1},"staking/redeem":{cost:.1},"staking/setAutoStaking":{cost:.1},"eth-staking/eth/stake":{cost:15},"eth-staking/eth/redeem":{cost:15},"eth-staking/wbeth/wrap":{cost:15},"sol-staking/sol/stake":{cost:15},"sol-staking/sol/redeem":{cost:15},"mining/hash-transfer/config":{cost:.5},"mining/hash-transfer/config/cancel":{cost:.5},"portfolio/repay":{cost:20.001},"loan/vip/renew":{cost:40.002},"loan/vip/borrow":{cost:40.002},"loan/borrow":{cost:40.002},"loan/repay":{cost:40.002},"loan/adjust/ltv":{cost:40.002},"loan/customize/margin_call":{cost:40.002},"loan/flexible/repay":{cost:40.002},"loan/flexible/adjust/ltv":{cost:40.002},"loan/vip/repay":{cost:40.002},"convert/getQuote":{cost:1.3334},"convert/acceptQuote":{cost:3.3335},"convert/limit/placeOrder":{cost:3.3335},"convert/limit/cancelOrder":{cost:1.3334},"portfolio/auto-collection":{cost:150},"portfolio/asset-collection":{cost:6},"portfolio/bnb-transfer":{cost:150},"portfolio/repay-futures-switch":{cost:150},"portfolio/repay-futures-negative-balance":{cost:150},"portfolio/mint":{cost:20},"portfolio/redeem":{cost:20},"portfolio/earn-asset-transfer":{cost:150},"portfolio/delta-mode":{cost:150},"portfolio/margin-call-level":{cost:150},"lending/auto-invest/plan/add":{cost:.1},"lending/auto-invest/plan/edit":{cost:.1},"lending/auto-invest/plan/edit-status":{cost:.1},"lending/auto-invest/one-off":{cost:.1},"lending/auto-invest/redeem":{cost:.1},"simple-earn/flexible/subscribe":{cost:.1},"simple-earn/locked/subscribe":{cost:.1},"simple-earn/flexible/redeem":{cost:.1},"simple-earn/locked/redeem":{cost:.1},"simple-earn/flexible/setAutoSubscribe":{cost:15},"simple-earn/locked/setAutoSubscribe":{cost:15},"simple-earn/locked/setRedeemOption":{cost:5},"dci/product/subscribe":{cost:.1},"dci/product/auto_compound/edit":{cost:.1},"accumulator/product/subscribe":{cost:.1},"equity/order/place":{cost:.1},"equity/order/cancel":{cost:.1},"equity/order/cancel-all":{cost:.1},"equity/tokenized/mint":{cost:.1},"equity/tokenized/redeem":{cost:.1},"equity/account/disclaimer":{cost:.1},"equity/listenKey":{cost:.1}},put:{userDataStream:{cost:.1},"userDataStream/isolated":{cost:.1}},delete:{"portfolio/margin-call-level":{cost:150},"margin/openOrders":{cost:.1},"margin/order":{cost:.006667},"margin/orderList":{cost:.006667},"margin/isolated/account":{cost:2.0001},userDataStream:{cost:.1},"userDataStream/isolated":{cost:.1},"broker/subAccountApi":{cost:1},"broker/subAccountApi/ipRestriction/ipList":{cost:1},"algo/spot/order":{cost:.1},"algo/futures/order":{cost:.1},"sub-account/subAccountApi/ipRestriction/ipList":{cost:20.001}}},sapiV2:{get:{"eth-staking/account":{cost:15},"sub-account/futures/account":{cost:.1},"sub-account/futures/accountSummary":{cost:1},"sub-account/futures/positionRisk":{cost:.1},"loan/flexible/ongoing/orders":{cost:30},"loan/flexible/borrow/history":{cost:40},"loan/flexible/repay/history":{cost:40},"loan/flexible/ltv/adjustment/history":{cost:40},"loan/flexible/loanable/data":{cost:40},"loan/flexible/collateral/data":{cost:40},"portfolio/account":{cost:2}},post:{"eth-staking/eth/stake":{cost:15},"sub-account/subAccountApi/ipRestriction":{cost:20.001},"loan/flexible/borrow":{cost:40.002},"loan/flexible/repay":{cost:40.002},"loan/flexible/adjust/ltv":{cost:40.002}}},sapiV3:{get:{"sub-account/assets":{cost:.40002}},post:{"asset/getUserAsset":{cost:.5}}},sapiV4:{get:{"sub-account/assets":{cost:.40002}}},dapiPublic:{get:{ping:{cost:1},time:{cost:1},exchangeInfo:{cost:1},depth:{cost:2,byLimit:[[50,2],[100,5],[500,10],[1e3,20]]},trades:{cost:5},historicalTrades:{cost:200},aggTrades:{cost:20},premiumIndex:{cost:10},fundingRate:{cost:1},klines:{cost:1,byLimit:[[99,1],[499,2],[1e3,5],[1e4,10]]},continuousKlines:{cost:1,byLimit:[[99,1],[499,2],[1e3,5],[1e4,10]]},indexPriceKlines:{cost:1,byLimit:[[99,1],[499,2],[1e3,5],[1e4,10]]},markPriceKlines:{cost:1,byLimit:[[99,1],[499,2],[1e3,5],[1e4,10]]},premiumIndexKlines:{cost:1,byLimit:[[99,1],[499,2],[1e3,5],[1e4,10]]},"ticker/24hr":{cost:1,noSymbol:40},"ticker/price":{cost:1,noSymbol:2},"ticker/bookTicker":{cost:2,noSymbol:5},constituents:{cost:2},openInterest:{cost:1},fundingInfo:{cost:1}}},dapiData:{get:{"delivery-price":{cost:1},openInterestHist:{cost:1},topLongShortAccountRatio:{cost:1},topLongShortPositionRatio:{cost:1},globalLongShortAccountRatio:{cost:1},takerBuySellVol:{cost:1},basis:{cost:1}}},dapiPrivate:{get:{"positionSide/dual":{cost:30},orderAmendment:{cost:1},order:{cost:1},openOrder:{cost:1},openOrders:{cost:1,noSymbol:5},openAlgoOrders:{cost:1,noSymbol:40},algoOrder:{cost:1},allAlgoOrders:{cost:5},allOrders:{cost:5},balance:{cost:1},account:{cost:5},"positionMargin/history":{cost:1},positionRisk:{cost:1},userTrades:{cost:5},income:{cost:20},leverageBracket:{cost:2,noSymbol:2},forceOrders:{cost:20,noSymbol:50},adlQuantile:{cost:5},commissionRate:{cost:20},"income/asyn":{cost:5},"income/asyn/id":{cost:5},"trade/asyn":{cost:.5},"trade/asyn/id":{cost:.5},"order/asyn":{cost:.5},"order/asyn/id":{cost:.5},pmExchangeInfo:{cost:.5},pmAccountInfo:{cost:.5}},post:{"positionSide/dual":{cost:1},order:{cost:4},algoOrder:{cost:1},batchOrders:{cost:5},countdownCancelAll:{cost:10},leverage:{cost:1},marginType:{cost:1},positionMargin:{cost:1},listenKey:{cost:1}},put:{listenKey:{cost:1},order:{cost:1},batchOrders:{cost:5}},delete:{order:{cost:1},algoOrder:{cost:1},algoOpenOrders:{cost:1},allOpenOrders:{cost:1},batchOrders:{cost:5},listenKey:{cost:1}}},dapiPrivateV2:{get:{leverageBracket:{cost:1,noSymbol:2}}},fapiPublic:{get:{ping:{cost:1},time:{cost:1},exchangeInfo:{cost:1},depth:{cost:2,byLimit:[[50,2],[100,5],[500,10],[1e3,20]]},rpiDepth:{cost:20},trades:{cost:5},historicalTrades:{cost:200},aggTrades:{cost:20},klines:{cost:1,byLimit:[[99,1],[499,2],[1e3,5],[1e4,10]]},continuousKlines:{cost:1,byLimit:[[99,1],[499,2],[1e3,5],[1e4,10]]},markPriceKlines:{cost:1,byLimit:[[99,1],[499,2],[1e3,5],[1e4,10]]},indexPriceKlines:{cost:1,byLimit:[[99,1],[499,2],[1e3,5],[1e4,10]]},premiumIndexKlines:{cost:1,byLimit:[[99,1],[499,2],[1e3,5],[1e4,10]]},fundingRate:{cost:1},fundingInfo:{cost:1},premiumIndex:{cost:1},"ticker/24hr":{cost:1,noSymbol:40},"ticker/price":{cost:1,noSymbol:2},"ticker/bookTicker":{cost:2,noSymbol:5},openInterest:{cost:1},indexInfo:{cost:1},assetIndex:{cost:1,noSymbol:10},constituents:{cost:2},apiTradingStatus:{cost:1,noSymbol:10},lvtKlines:{cost:1},"convert/exchangeInfo":{cost:4},insuranceBalance:{cost:1},symbolAdlRisk:{cost:1},tradingSchedule:{cost:5}}},fapiData:{get:{"delivery-price":{cost:1},openInterestHist:{cost:1},topLongShortAccountRatio:{cost:1},topLongShortPositionRatio:{cost:1},globalLongShortAccountRatio:{cost:1},takerlongshortRatio:{cost:1},basis:{cost:1}}},fapiPrivate:{get:{forceOrders:{cost:20,noSymbol:50},allOrders:{cost:5},openOrder:{cost:1},openOrders:{cost:1,noSymbol:40},order:{cost:1},account:{cost:5},balance:{cost:5},leverageBracket:{cost:1},"positionMargin/history":{cost:1},positionRisk:{cost:5},"positionSide/dual":{cost:30},userTrades:{cost:5},income:{cost:30},commissionRate:{cost:20},"rateLimit/order":{cost:1},apiTradingStatus:{cost:1},multiAssetsMargin:{cost:30},"apiReferral/ifNewUser":{cost:1},"apiReferral/customization":{cost:1},"apiReferral/userCustomization":{cost:1},"apiReferral/traderNum":{cost:1},"apiReferral/overview":{cost:1},"apiReferral/tradeVol":{cost:1},"apiReferral/rebateVol":{cost:1},"apiReferral/traderSummary":{cost:1},adlQuantile:{cost:5},pmAccountInfo:{cost:5},orderAmendment:{cost:1},"income/asyn":{cost:1e3},"income/asyn/id":{cost:10},"order/asyn":{cost:1e3},"order/asyn/id":{cost:10},"trade/asyn":{cost:1e3},"trade/asyn/id":{cost:10},feeBurn:{cost:1},symbolConfig:{cost:5},accountConfig:{cost:5},"convert/orderStatus":{cost:5},algoOrder:{cost:1},openAlgoOrders:{cost:1,noSymbol:40},allAlgoOrders:{cost:5},"stock/contract":{cost:50}},post:{batchOrders:{cost:5},"positionSide/dual":{cost:1},positionMargin:{cost:1},marginType:{cost:1},order:{cost:4},"order/test":{cost:1},leverage:{cost:1},listenKey:{cost:1},countdownCancelAll:{cost:10},multiAssetsMargin:{cost:1},"apiReferral/customization":{cost:1},"apiReferral/userCustomization":{cost:1},feeBurn:{cost:1},"convert/getQuote":{cost:200},"convert/acceptQuote":{cost:20},algoOrder:{cost:1}},put:{listenKey:{cost:1},order:{cost:1},batchOrders:{cost:5}},delete:{batchOrders:{cost:1},order:{cost:1},allOpenOrders:{cost:1},listenKey:{cost:1},algoOrder:{cost:1},algoOpenOrders:{cost:1}}},fapiPublicV2:{get:{"ticker/price":{cost:0}}},fapiPrivateV2:{get:{account:{cost:1},balance:{cost:1},positionRisk:{cost:1}}},fapiPublicV3:{get:{}},fapiPrivateV3:{get:{account:{cost:1},balance:{cost:1},positionRisk:{cost:1}}},eapiPublic:{get:{ping:{cost:1},time:{cost:1},exchangeInfo:{cost:1},index:{cost:1},ticker:{cost:5},mark:{cost:5},depth:{cost:1},klines:{cost:1},trades:{cost:5},historicalTrades:{cost:20},exerciseHistory:{cost:3},openInterest:{cost:3}}},eapiPrivate:{get:{account:{cost:3},position:{cost:5},openOrders:{cost:1,noSymbol:40},historyOrders:{cost:3},userTrades:{cost:5},exerciseRecord:{cost:5},bill:{cost:1},"income/asyn":{cost:5},"income/asyn/id":{cost:5},marginAccount:{cost:3},mmp:{cost:1},countdownCancelAll:{cost:1},order:{cost:1},"block/order/orders":{cost:5},"block/order/execute":{cost:5},"block/user-trades":{cost:5},blockTrades:{cost:5},comission:{cost:5}},post:{order:{cost:1},batchOrders:{cost:5},listenKey:{cost:1},mmpSet:{cost:1},mmpReset:{cost:1},countdownCancelAll:{cost:1},countdownCancelAllHeartBeat:{cost:10},"block/order/create":{cost:5},"block/order/execute":{cost:5},"stock/contract":{cost:50}},put:{listenKey:{cost:1},"block/order/create":{cost:5}},delete:{order:{cost:1},batchOrders:{cost:1},allOpenOrders:{cost:1},allOpenOrdersByUnderlying:{cost:1},listenKey:{cost:1},"block/order/create":{cost:5}}},public:{get:{ping:{cost:.2},time:{cost:.2},depth:{cost:1,byLimit:[[100,1],[500,5],[1e3,10],[5e3,50]]},trades:{cost:2},aggTrades:{cost:.4},historicalTrades:{cost:2},klines:{cost:.4},uiKlines:{cost:.4},"ticker/24hr":{cost:.4,noSymbol:16},ticker:{cost:.4,noSymbol:16},"ticker/tradingDay":{cost:.8},"ticker/price":{cost:.4,noSymbol:.8},"ticker/bookTicker":{cost:.4,noSymbol:.8},exchangeInfo:{cost:4},executionRules:{cost:.4,noSymbol:8},avgPrice:{cost:.4},referencePrice:{cost:.4},"referencePrice/calculation":{cost:.4},historicalBlockTrades:{cost:5}},put:{userDataStream:{cost:.4}},post:{userDataStream:{cost:.4}},delete:{userDataStream:{cost:.4}}},private:{get:{allOrderList:{cost:4},openOrderList:{cost:1.2},orderList:{cost:.8},order:{cost:.8},openOrders:{cost:1.2,noSymbol:16},allOrders:{cost:4},account:{cost:4},myTrades:{cost:4},"rateLimit/order":{cost:8},myPreventedMatches:{cost:4},myAllocations:{cost:4},"account/commission":{cost:4}},post:{"order/oco":{cost:.2},"orderList/oco":{cost:.2},"orderList/oto":{cost:.2},"orderList/otoco":{cost:.2},"orderList/opo":{cost:.2},"orderList/opoco":{cost:.2},"sor/order":{cost:.2},"sor/order/test":{cost:.2},order:{cost:.2},"order/cancelReplace":{cost:.2},"order/test":{cost:.2}},delete:{openOrders:{cost:.2},orderList:{cost:.2},order:{cost:.2}}},papi:{get:{ping:{cost:.2},"um/order":{cost:1},"um/openOrder":{cost:1},"um/openOrders":{cost:1,noSymbol:40},"um/allOrders":{cost:5},"cm/order":{cost:1},"cm/openOrder":{cost:1},"cm/openOrders":{cost:1,noSymbol:40},"cm/allOrders":{cost:20},"um/conditional/openOrder":{cost:1},"um/conditional/openOrders":{cost:1,noSymbol:40},"um/conditional/orderHistory":{cost:1},"um/conditional/allOrders":{cost:1,noSymbol:40},"um/algo/algoOrder":{cost:1},"um/algo/openAlgoOrders":{cost:1},"um/algo/allAlgoOrders":{cost:5},"cm/conditional/openOrder":{cost:1},"cm/conditional/openOrders":{cost:1,noSymbol:40},"cm/conditional/orderHistory":{cost:1},"cm/conditional/allOrders":{cost:40},"margin/order":{cost:10},"margin/openOrders":{cost:5},"margin/allOrders":{cost:100},"margin/orderList":{cost:5},"margin/allOrderList":{cost:100},"margin/openOrderList":{cost:5},"margin/myTrades":{cost:5},balance:{cost:4},account:{cost:4},"margin/maxBorrowable":{cost:1},"margin/maxWithdraw":{cost:1},"um/positionRisk":{cost:1},"cm/positionRisk":{cost:.2},"um/positionSide/dual":{cost:6},"cm/positionSide/dual":{cost:6},"um/userTrades":{cost:5},"cm/userTrades":{cost:20},"um/leverageBracket":{cost:.2},"cm/leverageBracket":{cost:.2},"margin/forceOrders":{cost:1},"um/forceOrders":{cost:20,noSymbol:50},"cm/forceOrders":{cost:20,noSymbol:50},"um/apiTradingStatus":{cost:.2,noSymbol:2},"um/commissionRate":{cost:4},"cm/commissionRate":{cost:4},"margin/marginLoan":{cost:2},"margin/repayLoan":{cost:2},"margin/marginInterestHistory":{cost:.2},"portfolio/interest-history":{cost:10},"um/income":{cost:6},"cm/income":{cost:6},"um/account":{cost:1},"cm/account":{cost:1},"repay-futures-switch":{cost:6},"um/adlQuantile":{cost:5},"cm/adlQuantile":{cost:5},"um/trade/asyn":{cost:300},"um/trade/asyn/id":{cost:2},"um/order/asyn":{cost:300},"um/order/asyn/id":{cost:2},"um/income/asyn":{cost:300},"um/income/asyn/id":{cost:2},"um/orderAmendment":{cost:1},"cm/orderAmendment":{cost:1},"um/feeBurn":{cost:30},"um/accountConfig":{cost:1},"um/symbolConfig":{cost:1},"cm/accountConfig":{cost:1},"cm/symbolConfig":{cost:1},"rateLimit/order":{cost:1}},post:{"um/order":{cost:1},"um/conditional/order":{cost:1},"um/algo/order":{cost:1},"cm/order":{cost:1},"cm/conditional/order":{cost:1},"margin/order":{cost:1},marginLoan:{cost:100},repayLoan:{cost:100},"margin/order/oco":{cost:1},"um/leverage":{cost:.2},"cm/leverage":{cost:.2},"um/positionSide/dual":{cost:.2},"cm/positionSide/dual":{cost:.2},"auto-collection":{cost:150},"bnb-transfer":{cost:150},"repay-futures-switch":{cost:150},"repay-futures-negative-balance":{cost:150},listenKey:{cost:.2},"asset-collection":{cost:6},"margin/repay-debt":{cost:3e3},"um/feeBurn":{cost:1},"um/stock/contract":{cost:1}},put:{listenKey:{cost:.2},"um/order":{cost:1},"cm/order":{cost:1}},delete:{"um/order":{cost:1},"um/conditional/order":{cost:1},"um/allOpenOrders":{cost:1},"um/conditional/allOpenOrders":{cost:1},"um/algo/order":{cost:1},"um/algo/allOpenOrders":{cost:1},"cm/order":{cost:1},"cm/conditional/order":{cost:1},"cm/allOpenOrders":{cost:1},"cm/conditional/allOpenOrders":{cost:1},"margin/order":{cost:2},"margin/allOpenOrders":{cost:5},"margin/orderList":{cost:2},listenKey:{cost:.2}}},papiV2:{get:{"um/account":{cost:1}}}},fees:{trading:{feeSide:"get",tierBased:!1,percentage:!0,taker:this.parseNumber("0.001"),maker:this.parseNumber("0.001")},linear:{trading:{feeSide:"quote",tierBased:!0,percentage:!0,taker:this.parseNumber("0.000500"),maker:this.parseNumber("0.000200"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.000400")],[this.parseNumber("250"),this.parseNumber("0.000400")],[this.parseNumber("2500"),this.parseNumber("0.000350")],[this.parseNumber("7500"),this.parseNumber("0.000320")],[this.parseNumber("22500"),this.parseNumber("0.000300")],[this.parseNumber("50000"),this.parseNumber("0.000270")],[this.parseNumber("100000"),this.parseNumber("0.000250")],[this.parseNumber("200000"),this.parseNumber("0.000220")],[this.parseNumber("400000"),this.parseNumber("0.000200")],[this.parseNumber("750000"),this.parseNumber("0.000170")]],maker:[[this.parseNumber("0"),this.parseNumber("0.000200")],[this.parseNumber("250"),this.parseNumber("0.000160")],[this.parseNumber("2500"),this.parseNumber("0.000140")],[this.parseNumber("7500"),this.parseNumber("0.000120")],[this.parseNumber("22500"),this.parseNumber("0.000100")],[this.parseNumber("50000"),this.parseNumber("0.000080")],[this.parseNumber("100000"),this.parseNumber("0.000060")],[this.parseNumber("200000"),this.parseNumber("0.000040")],[this.parseNumber("400000"),this.parseNumber("0.000020")],[this.parseNumber("750000"),this.parseNumber("0")]]}}},inverse:{trading:{feeSide:"base",tierBased:!0,percentage:!0,taker:this.parseNumber("0.000500"),maker:this.parseNumber("0.000100"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.000500")],[this.parseNumber("250"),this.parseNumber("0.000450")],[this.parseNumber("2500"),this.parseNumber("0.000400")],[this.parseNumber("7500"),this.parseNumber("0.000300")],[this.parseNumber("22500"),this.parseNumber("0.000250")],[this.parseNumber("50000"),this.parseNumber("0.000240")],[this.parseNumber("100000"),this.parseNumber("0.000240")],[this.parseNumber("200000"),this.parseNumber("0.000240")],[this.parseNumber("400000"),this.parseNumber("0.000240")],[this.parseNumber("750000"),this.parseNumber("0.000240")]],maker:[[this.parseNumber("0"),this.parseNumber("0.000100")],[this.parseNumber("250"),this.parseNumber("0.000080")],[this.parseNumber("2500"),this.parseNumber("0.000050")],[this.parseNumber("7500"),this.parseNumber("0.0000030")],[this.parseNumber("22500"),this.parseNumber("0")],[this.parseNumber("50000"),this.parseNumber("-0.000050")],[this.parseNumber("100000"),this.parseNumber("-0.000060")],[this.parseNumber("200000"),this.parseNumber("-0.000070")],[this.parseNumber("400000"),this.parseNumber("-0.000080")],[this.parseNumber("750000"),this.parseNumber("-0.000090")]]}}},option:{}},currencies:{BNFCR:this.safeCurrencyStructure({id:"BNFCR",code:"BNFCR",precision:this.parseNumber("0.001")})},commonCurrencies:{BCC:"BCC",YOYO:"YOYOW"},precisionMode:4,options:{sandboxMode:!1,fetchMargins:!0,fetchMarkets:{types:["spot","linear","inverse"],loadAllOptions:!1},fetchCurrencies:!0,createOrder:{timeInForce:"GTC",warnOnSTPForInverse:!0,quoteOrderQty:!0},defaultType:"spot",defaultSubType:void 0,hasAlreadyAuthenticatedSuccessfully:!1,fetchOpenOrders:{warnWithoutSymbol:!0},currencyToPrecisionRoundingMode:0,setMarginMode:{throwMarginModeAlreadySet:!0},fetchPositions:{method:"positionRisk"},recvWindow:1e4,timeDifference:0,adjustForTimeDifference:!1,newOrderRespType:{market:"FULL",limit:"FULL"},broker:{spot:"x-TKT5PX2F",margin:"x-TKT5PX2F",future:"x-cvBPrNm9",delivery:"x-xcKtGhcu",swap:"x-cvBPrNm9",option:"x-xcKtGhcu",inverse:"x-xcKtGhcu"},accountsByType:{main:"MAIN",spot:"MAIN",funding:"FUNDING",margin:"MARGIN",cross:"MARGIN",future:"UMFUTURE",delivery:"CMFUTURE",linear:"UMFUTURE",swap:"UMFUTURE",inverse:"CMFUTURE",option:"OPTION"},accountsById:{MAIN:"spot",FUNDING:"funding",MARGIN:"margin",UMFUTURE:"linear",CMFUTURE:"inverse",OPTION:"option"},networks:{BTC:"BTC",BTCSEGWIT:"SEGWITBTC",BTCLIGHTNING:"LIGHTNING",ERC20:"ETH",ETH:"ETH",TRC20:"TRX",TRX:"TRX",BEP2:"BNB",BSC:"BSC",BEP20:"BSC",CHZ2:"CHZ2",XRP:"XRP",EOS:"EOS",DOGE:"DOGE",SOL:"SOL",SONIC:"SONIC",ARBITRUM:"ARBITRUM",AVAXC:"AVAXC",MATIC:"MATIC",BASE:"BASE",SUI:"SUI",OP:"OPTIMISM",OPTIMISM:"OPTIMISM",NEAR:"NEAR",APT:"APT",SCROLL:"SCROLL",KAVA:"KAVA",XLM:"XLM",RSK:"RSK",SEI:"SEI",TON:"TON",ADA:"ADA",ALGO:"ALGO",RUNE:"RUNE",OSMO:"OSMO",CELO:"CELO",HBAR:"HBAR",ZKSYNCERA:"ZKSYNCERA",KLAY:"KLAY",ACA:"ACA",STX:"STX",XTZ:"XTZ",METIS:"METIS",EGLD:"EGLD",ASTR:"ASTR",CFX:"CFX",SCRT:"SCRT",ONT:"ONT",ZEC:"ZEC",XMR:"XMR",BCH:"BCH",LTC:"LTC",TAO:"TAO",WLD:"WLD",ICP:"ICP",FLR:"FLR",COSMOS:"ATOM",ATOM:"ATOM",FIL:"FIL",INJ:"INJ",DASH:"DASH",VET:"VET",FET:"FET",TIA:"TIA",KAIA:"KAIA",DCR:"DCR",IOTA:"IOTA",THETA:"THETA",AR:"AR",DYDX:"DYDX",XEC:"XEC",QTUM:"QTUM",ENJ:"ENJ",RVN:"RVN",ZIL:"ZIL",BERA:"BERA","0G":"0G",MINA:"MINA",AXL:"AXL",ROSE:"ROSE",CKB:"CKB",DGB:"DGB",MOVE:"MOVE",XVG:"XVG",SC:"SC",LINEA:"LINEA",WAVES:"WAVES",MANTA:"MANTA"},networksById:{TRX:"TRC20",BSC:"BEP20",ETH:"ERC20",SOL:"SOL",OPTIMISM:"OP"},impliedNetworks:{ETH:{ERC20:"ETH"},TRX:{TRC20:"TRX"}},legalMoney:{MXN:!0,UGX:!0,SEK:!0,CHF:!0,VND:!0,AED:!0,DKK:!0,KZT:!0,HUF:!0,PEN:!0,PHP:!0,USD:!0,TRY:!0,EUR:!0,NGN:!0,PLN:!0,BRL:!0,ZAR:!0,KES:!0,ARS:!0,RUB:!0,AUD:!0,NOK:!0,CZK:!0,GBP:!0,UAH:!0,GHS:!0,HKD:!0,CAD:!0,INR:!0,JPY:!0,NZD:!0},legalMoneyCurrenciesById:{BUSD:"USD"},defaultWithdrawPrecision:1e-8,defaultFiatWithdrawPrecision:.01},features:{spot:{sandbox:!0,fetchCurrencies:{private:!0},createOrder:{marginMode:!0,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!0,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,selfTradePrevention:{EXPIRE_MAKER:!0,EXPIRE_TAKER:!0,EXPIRE_BOTH:!0,NONE:!0},trailing:!1,icebergAmount:!0},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:void 0,untilDays:1,symbolRequired:!0},fetchOrder:{marginMode:!0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!0,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!0,limit:1e3,daysBack:void 0,untilDays:1e4,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:{marginMode:!0,limit:1e3,daysBack:void 0,daysBackCanceled:void 0,untilDays:1e4,trigger:!1,trailing:!1,symbolRequired:!0},fetchOHLCV:{limit:1e3}},forDerivatives:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:{mark:!0,last:!0,index:!1},stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!0},hedged:!0,selfTradePrevention:!0,trailing:!0,iceberg:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!0},createOrders:{max:5},fetchMyTrades:{marginMode:!1,daysBack:void 0,limit:1e3,untilDays:7,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!0,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!0,limit:500,trigger:!0,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!0,limit:1e3,daysBack:90,untilDays:7,trigger:!0,trailing:!1,symbolRequired:!0},fetchClosedOrders:{marginMode:!0,limit:1e3,daysBack:90,daysBackCanceled:3,untilDays:7,trigger:!0,trailing:!1,symbolRequired:!0},fetchOHLCV:{limit:500}},swap:{linear:{extends:"forDerivatives",fetchOrders:{symbolRequired:!1}},inverse:{extends:"forDerivatives"}},future:{linear:{extends:"forDerivatives",fetchOrders:{symbolRequired:!1}},inverse:{extends:"forDerivatives"}}},exceptions:{spot:{exact:{"-1004":o.OperationFailed,"-1008":o.OperationFailed,"-1099":o.AuthenticationError,"-1108":o.BadRequest,"-1131":o.BadRequest,"-1134":o.BadRequest,"-1135":o.BadRequest,"-1145":o.BadRequest,"-1151":o.BadSymbol,"-2008":o.AuthenticationError,"-2016":o.OperationRejected,"-2021":o.BadResponse,"-2022":o.BadResponse,"-2026":o.InvalidOrder,"-3000":o.OperationFailed,"-3001":o.AuthenticationError,"-3002":o.BadSymbol,"-3003":o.BadRequest,"-3004":o.OperationRejected,"-3005":o.BadRequest,"-3006":o.BadRequest,"-3007":o.OperationFailed,"-3008":o.BadRequest,"-3009":o.OperationRejected,"-3010":o.BadRequest,"-3011":o.BadRequest,"-3012":o.OperationRejected,"-3013":o.BadRequest,"-3014":o.AccountSuspended,"-3015":o.BadRequest,"-3016":o.BadRequest,"-3017":o.OperationRejected,"-3018":o.AccountSuspended,"-3019":o.AccountSuspended,"-3020":o.BadRequest,"-3021":o.BadRequest,"-3022":o.AccountSuspended,"-3023":o.OperationRejected,"-3024":o.OperationRejected,"-3025":o.BadRequest,"-3026":o.BadRequest,"-3027":o.BadSymbol,"-3028":o.BadSymbol,"-3029":o.OperationFailed,"-3036":o.AccountSuspended,"-3037":o.OperationFailed,"-3038":o.BadRequest,"-3041":o.InsufficientFunds,"-3042":o.BadRequest,"-3043":o.PermissionDenied,"-3044":o.OperationFailed,"-3045":o.OperationRejected,"-3999":o.PermissionDenied,"-4000":o.ExchangeError,"-4001":o.BadRequest,"-4002":o.BadRequest,"-4003":o.BadRequest,"-4004":o.AuthenticationError,"-4005":o.RateLimitExceeded,"-4006":o.BadRequest,"-4007":o.PermissionDenied,"-4008":o.PermissionDenied,"-4009":o.ExchangeError,"-4010":o.PermissionDenied,"-4011":o.BadRequest,"-4012":o.PermissionDenied,"-4013":o.AuthenticationError,"-4014":o.OperationRejected,"-4015":o.PermissionDenied,"-4016":o.PermissionDenied,"-4017":o.PermissionDenied,"-4018":o.BadSymbol,"-4019":o.BadRequest,"-4020":o.ExchangeError,"-4021":o.BadRequest,"-4022":o.BadRequest,"-4023":o.OperationRejected,"-4024":o.InsufficientFunds,"-4025":o.InsufficientFunds,"-4026":o.InsufficientFunds,"-4027":o.OperationFailed,"-4028":o.BadRequest,"-4029":o.BadRequest,"-4030":o.BadResponse,"-4031":o.OperationFailed,"-4032":o.OperationRejected,"-4033":o.BadRequest,"-4034":o.OperationRejected,"-4035":o.PermissionDenied,"-4036":o.PermissionDenied,"-4037":o.OperationFailed,"-4038":o.OperationFailed,"-4039":o.PermissionDenied,"-4040":o.OperationRejected,"-4041":o.OperationFailed,"-4042":o.OperationRejected,"-4043":o.OperationRejected,"-4044":o.PermissionDenied,"-4045":o.OperationFailed,"-4046":o.AuthenticationError,"-4047":o.BadRequest,"-4048":o.ExchangeError,"-4049":o.ExchangeError,"-4050":o.ExchangeError,"-4051":o.ExchangeError,"-4052":o.ExchangeError,"-4053":o.ExchangeError,"-4054":o.ExchangeError,"-4055":o.ExchangeError,"-4056":o.ExchangeError,"-4057":o.ExchangeError,"-4058":o.ExchangeError,"-4059":o.ExchangeError,"-4060":o.OperationFailed,"-4061":o.ExchangeError,"-4062":o.ExchangeError,"-4063":o.ExchangeError,"-4064":o.ExchangeError,"-4065":o.ExchangeError,"-4066":o.ExchangeError,"-4067":o.ExchangeError,"-4068":o.ExchangeError,"-4069":o.ExchangeError,"-4070":o.ExchangeError,"-4071":o.ExchangeError,"-4072":o.ExchangeError,"-4073":o.ExchangeError,"-4074":o.ExchangeError,"-4075":o.ExchangeError,"-4076":o.ExchangeError,"-4077":o.ExchangeError,"-4078":o.ExchangeError,"-4079":o.ExchangeError,"-4080":o.ExchangeError,"-4081":o.ExchangeError,"-4082":o.ExchangeError,"-4083":o.ExchangeError,"-4084":o.ExchangeError,"-4085":o.ExchangeError,"-4086":o.ExchangeError,"-4087":o.ExchangeError,"-4088":o.ExchangeError,"-4089":o.ExchangeError,"-4091":o.ExchangeError,"-4092":o.ExchangeError,"-4093":o.ExchangeError,"-4094":o.ExchangeError,"-4095":o.ExchangeError,"-4096":o.ExchangeError,"-4097":o.ExchangeError,"-4098":o.ExchangeError,"-4099":o.ExchangeError,"-4101":o.ExchangeError,"-4102":o.ExchangeError,"-4103":o.ExchangeError,"-4104":o.ExchangeError,"-4105":o.ExchangeError,"-4106":o.ExchangeError,"-4107":o.ExchangeError,"-4108":o.ExchangeError,"-4109":o.ExchangeError,"-4110":o.ExchangeError,"-4112":o.ExchangeError,"-4113":o.ExchangeError,"-4114":o.ExchangeError,"-4115":o.ExchangeError,"-4116":o.ExchangeError,"-4117":o.ExchangeError,"-4118":o.ExchangeError,"-4119":o.ExchangeError,"-4120":o.ExchangeError,"-4121":o.ExchangeError,"-4122":o.ExchangeError,"-4123":o.ExchangeError,"-4124":o.ExchangeError,"-4125":o.ExchangeError,"-4126":o.ExchangeError,"-4127":o.ExchangeError,"-4128":o.ExchangeError,"-4129":o.ExchangeError,"-4130":o.ExchangeError,"-4131":o.ExchangeError,"-4132":o.ExchangeError,"-4133":o.ExchangeError,"-4134":o.ExchangeError,"-4135":o.ExchangeError,"-4136":o.ExchangeError,"-4137":o.ExchangeError,"-4138":o.ExchangeError,"-4139":o.ExchangeError,"-4141":o.ExchangeError,"-4142":o.ExchangeError,"-4143":o.ExchangeError,"-4144":o.ExchangeError,"-4145":o.ExchangeError,"-4146":o.ExchangeError,"-4147":o.ExchangeError,"-4148":o.ExchangeError,"-4149":o.ExchangeError,"-4150":o.ExchangeError,"-5001":o.BadRequest,"-5002":o.InsufficientFunds,"-5003":o.InsufficientFunds,"-5004":o.OperationRejected,"-5005":o.OperationRejected,"-5006":o.OperationRejected,"-5007":o.BadRequest,"-5008":o.OperationRejected,"-5009":o.BadSymbol,"-5010":o.OperationFailed,"-5011":o.BadRequest,"-5012":o.OperationFailed,"-5013":o.InsufficientFunds,"-5021":o.BadRequest,"-5022":o.BadRequest,"-6001":o.BadSymbol,"-6003":o.PermissionDenied,"-6004":o.BadRequest,"-6005":o.BadRequest,"-6006":o.BadRequest,"-6007":o.OperationRejected,"-6008":o.OperationRejected,"-6009":o.RateLimitExceeded,"-6011":o.OperationRejected,"-6012":o.InsufficientFunds,"-6013":o.BadResponse,"-6014":o.OperationRejected,"-6015":o.BadRequest,"-6016":o.BadRequest,"-6017":o.PermissionDenied,"-6018":o.InsufficientFunds,"-6019":o.OperationRejected,"-6020":o.BadRequest,"-7001":o.BadRequest,"-7002":o.BadRequest,"-10001":o.OperationFailed,"-10002":o.BadRequest,"-10005":o.BadResponse,"-10007":o.BadRequest,"-10008":o.BadRequest,"-10009":o.BadRequest,"-10010":o.BadRequest,"-10011":o.InsufficientFunds,"-10012":o.BadRequest,"-10013":o.InsufficientFunds,"-10015":o.OperationFailed,"-10016":o.OperationFailed,"-10017":o.OperationRejected,"-10018":o.BadRequest,"-10019":o.BadRequest,"-10020":o.BadRequest,"-10021":o.InvalidOrder,"-10022":o.BadRequest,"-10023":o.OperationFailed,"-10024":o.BadRequest,"-10025":o.OperationFailed,"-10026":o.BadRequest,"-10028":o.BadRequest,"-10029":o.OperationRejected,"-10030":o.OperationRejected,"-10031":o.OperationRejected,"-10032":o.OperationFailed,"-10034":o.OperationRejected,"-10039":o.OperationRejected,"-10040":o.OperationRejected,"-10041":o.OperationFailed,"-10042":o.BadSymbol,"-10043":o.OperationRejected,"-10044":o.OperationRejected,"-10045":o.OperationRejected,"-10046":o.OperationRejected,"-10047":o.PermissionDenied,"-11008":o.OperationRejected,"-12014":o.RateLimitExceeded,"-13000":o.OperationRejected,"-13001":o.OperationRejected,"-13002":o.OperationRejected,"-13003":o.PermissionDenied,"-13004":o.OperationRejected,"-13005":o.OperationRejected,"-13006":o.OperationRejected,"-13007":o.PermissionDenied,"-18002":o.OperationRejected,"-18003":o.OperationRejected,"-18004":o.OperationRejected,"-18005":o.PermissionDenied,"-18006":o.OperationRejected,"-18007":o.OperationRejected,"-21001":o.BadRequest,"-21002":o.BadRequest,"-21003":o.BadResponse,"-21004":o.OperationRejected,"-21005":o.InsufficientFunds,"-21006":o.OperationFailed,"-21007":o.OperationFailed,"-32603":o.BadRequest,400002:o.BadRequest,0x5f5e4eb:o.AuthenticationError,0xbebd13f:o.AuthenticationError}},linear:{exact:{"-1005":o.PermissionDenied,"-1008":o.OperationFailed,"-1011":o.PermissionDenied,"-1023":o.BadRequest,"-1099":o.AuthenticationError,"-1109":o.PermissionDenied,"-1110":o.BadRequest,"-1113":o.BadRequest,"-1122":o.BadRequest,"-1126":o.BadSymbol,"-1136":o.BadRequest,"-2012":o.OperationFailed,"-2016":o.OperationRejected,"-2017":o.PermissionDenied,"-2018":o.InsufficientFunds,"-2019":o.InsufficientFunds,"-2020":o.OperationFailed,"-2021":o.OrderImmediatelyFillable,"-2022":o.InvalidOrder,"-2023":o.OperationFailed,"-2024":o.InsufficientFunds,"-2025":o.OperationRejected,"-2026":o.InvalidOrder,"-2027":o.OperationRejected,"-2028":o.OperationRejected,"-4063":o.BadRequest,"-4064":o.BadRequest,"-4065":o.BadRequest,"-4066":o.BadRequest,"-4069":o.BadRequest,"-4070":o.BadRequest,"-4071":o.BadRequest,"-4072":o.OperationRejected,"-4073":o.BadRequest,"-4074":o.OperationRejected,"-4075":o.BadRequest,"-4076":o.OperationRejected,"-4077":o.OperationRejected,"-4078":o.OperationFailed,"-4079":o.BadRequest,"-4080":o.PermissionDenied,"-4081":o.BadRequest,"-4085":o.BadRequest,"-4087":o.PermissionDenied,"-4088":o.PermissionDenied,"-4114":o.BadRequest,"-4115":o.BadRequest,"-4116":o.InvalidOrder,"-4117":o.OperationRejected,"-4118":o.OperationRejected,"-4120":o.InvalidOrder,"-4131":o.OperationRejected,"-4140":o.BadRequest,"-4141":o.OperationRejected,"-4144":o.BadSymbol,"-4164":o.InvalidOrder,"-4136":o.InvalidOrder,"-4165":o.BadRequest,"-4167":o.BadRequest,"-4168":o.BadRequest,"-4169":o.OperationRejected,"-4170":o.OperationRejected,"-4171":o.OperationRejected,"-4172":o.OperationRejected,"-4183":o.BadRequest,"-4184":o.BadRequest,"-4192":o.PermissionDenied,"-4202":o.PermissionDenied,"-4203":o.PermissionDenied,"-4205":o.PermissionDenied,"-4206":o.PermissionDenied,"-4208":o.OperationRejected,"-4209":o.OperationRejected,"-4210":o.BadRequest,"-4211":o.BadRequest,"-4400":o.PermissionDenied,"-4401":o.PermissionDenied,"-4402":o.PermissionDenied,"-4403":o.PermissionDenied,"-5021":o.OrderNotFillable,"-5022":o.OrderNotFillable,"-5024":o.OperationRejected,"-5025":o.OperationRejected,"-5026":o.OperationRejected,"-5027":o.OperationRejected,"-5028":o.BadRequest,"-5037":o.BadRequest,"-5038":o.BadRequest,"-5039":o.BadRequest,"-4531":o.OperationRejected,"-5040":o.BadRequest,"-5041":o.OperationFailed,"-5047":o.InvalidOrder}},inverse:{exact:{"-1005":o.PermissionDenied,"-1011":o.PermissionDenied,"-1023":o.BadRequest,"-1109":o.AuthenticationError,"-1110":o.BadSymbol,"-1113":o.BadRequest,"-1128":o.BadRequest,"-1136":o.BadRequest,"-2016":o.OperationRejected,"-2018":o.InsufficientFunds,"-2019":o.InsufficientFunds,"-2020":o.OperationFailed,"-2021":o.OrderImmediatelyFillable,"-2022":o.InvalidOrder,"-2023":o.OperationFailed,"-2024":o.BadRequest,"-2025":o.OperationRejected,"-2026":o.InvalidOrder,"-2027":o.OperationRejected,"-2028":o.OperationRejected,"-4086":o.BadRequest,"-4087":o.BadSymbol,"-4088":o.BadRequest,"-4089":o.PermissionDenied,"-4090":o.PermissionDenied,"-4110":o.BadRequest,"-4111":o.BadRequest,"-4112":o.OperationRejected,"-4113":o.OperationRejected,"-4150":o.OperationRejected,"-4151":o.BadRequest,"-4152":o.BadRequest,"-4154":o.BadRequest,"-4155":o.BadRequest,"-4178":o.BadRequest,"-4188":o.BadRequest,"-4192":o.PermissionDenied,"-4194":o.PermissionDenied,"-4195":o.PermissionDenied,"-4120":o.InvalidOrder,"-4196":o.BadRequest,"-4197":o.OperationRejected,"-4198":o.OperationRejected,"-4199":o.BadRequest,"-4531":o.OperationRejected,"-4200":o.PermissionDenied,"-4201":o.PermissionDenied,"-4202":o.OperationRejected}},option:{exact:{"-1003":o.ExchangeError,"-1004":o.ExchangeError,"-1006":o.ExchangeError,"-1007":o.ExchangeError,"-1008":o.RateLimitExceeded,"-1010":o.ExchangeError,"-1013":o.ExchangeError,"-1108":o.ExchangeError,"-1112":o.ExchangeError,"-1114":o.ExchangeError,"-1128":o.BadSymbol,"-1129":o.BadSymbol,"-1131":o.BadRequest,"-2011":o.ExchangeError,"-2018":o.InsufficientFunds,"-2027":o.InsufficientFunds,"-3029":o.OperationFailed,"-4006":o.ExchangeError,"-4007":o.ExchangeError,"-4008":o.ExchangeError,"-4009":o.ExchangeError,"-4010":o.ExchangeError,"-4011":o.ExchangeError,"-4012":o.ExchangeError,"-4014":o.ExchangeError,"-4015":o.ExchangeError,"-4016":o.ExchangeError,"-4017":o.ExchangeError,"-4018":o.ExchangeError,"-4019":o.ExchangeError,"-4020":o.ExchangeError,"-4021":o.ExchangeError,"-4022":o.ExchangeError,"-4023":o.ExchangeError,"-4024":o.ExchangeError,"-4025":o.ExchangeError,"-4026":o.ExchangeError,"-4027":o.ExchangeError,"-4028":o.ExchangeError,"-4031":o.ExchangeError,"-4032":o.ExchangeError,"-4033":o.ExchangeError,"-4034":o.ExchangeError,"-4035":o.ExchangeError,"-4036":o.ExchangeError,"-4037":o.ExchangeError,"-4038":o.ExchangeError,"-4039":o.ExchangeError,"-4040":o.ExchangeError,"-4041":o.ExchangeError,"-4042":o.ExchangeError,"-4043":o.ExchangeError,"-4044":o.ExchangeError,"-4045":o.ExchangeError,"-4046":o.ExchangeError,"-4047":o.ExchangeError,"-4048":o.ExchangeError,"-4049":o.ExchangeError,"-4050":o.ExchangeError,"-4051":o.ExchangeError,"-4052":o.ExchangeError,"-4053":o.ExchangeError,"-4054":o.ExchangeError,"-4056":o.ExchangeError,"-4057":o.ExchangeError,"-4058":o.ExchangeError,"-4059":o.ExchangeError,"-4060":o.ExchangeError,"-4061":o.ExchangeError,"-4062":o.ExchangeError,"-4063":o.ExchangeError,"-4064":o.ExchangeError,"-4065":o.ExchangeError,"-4066":o.ExchangeError,"-4067":o.ExchangeError,"-4068":o.ExchangeError,"-4069":o.ExchangeError,"-4070":o.ExchangeError,"-4071":o.ExchangeError,"-4072":o.ExchangeError,"-4073":o.ExchangeError,"-4074":o.ExchangeError,"-4075":o.ExchangeError,"-4076":o.ExchangeError,"-4077":o.ExchangeError,"-4078":o.ExchangeError,"-4079":o.ExchangeError,"-4080":o.ExchangeError,"-4081":o.ExchangeError,"-4082":o.ExchangeError,"-4083":o.ExchangeError,"-4084":o.ExchangeError,"-4085":o.ExchangeError,"-4086":o.ExchangeError,"-4087":o.ExchangeError,"-4088":o.ExchangeError,"-4089":o.ExchangeError,"-4091":o.ExchangeError,"-4092":o.ExchangeError,"-4093":o.ExchangeError,"-4094":o.ExchangeError,"-4095":o.ExchangeError,"-4096":o.ExchangeError,"-4097":o.ExchangeError,"-4098":o.ExchangeError,"-4099":o.ExchangeError,"-4101":o.ExchangeError,"-4102":o.ExchangeError,"-4103":o.ExchangeError,"-4104":o.ExchangeError,"-4105":o.ExchangeError,"-4106":o.ExchangeError,"-4107":o.ExchangeError,"-4108":o.ExchangeError,"-4109":o.ExchangeError,"-4110":o.ExchangeError,"-4112":o.ExchangeError,"-4113":o.ExchangeError,"-4114":o.ExchangeError,"-4115":o.ExchangeError,"-4116":o.ExchangeError,"-4117":o.ExchangeError,"-4118":o.ExchangeError,"-4119":o.ExchangeError,"-4120":o.ExchangeError,"-4121":o.ExchangeError,"-4122":o.ExchangeError,"-4123":o.ExchangeError,"-4124":o.ExchangeError,"-4125":o.ExchangeError,"-4126":o.ExchangeError,"-4127":o.ExchangeError,"-4128":o.ExchangeError,"-4129":o.ExchangeError,"-4130":o.ExchangeError,"-4131":o.ExchangeError,"-4132":o.ExchangeError,"-4133":o.ExchangeError,"-4134":o.ExchangeError,"-4135":o.ExchangeError,"-4136":o.ExchangeError,"-4137":o.ExchangeError,"-4138":o.ExchangeError,"-4139":o.ExchangeError,"-4141":o.ExchangeError,"-4142":o.ExchangeError,"-4143":o.ExchangeError,"-4144":o.ExchangeError,"-4145":o.ExchangeError,"-4146":o.ExchangeError,"-4147":o.ExchangeError,"-4148":o.ExchangeError,"-4149":o.ExchangeError,"-4150":o.ExchangeError,"-20121":o.ExchangeError,"-20124":o.ExchangeError,"-20130":o.ExchangeError,"-20132":o.ExchangeError,"-20194":o.ExchangeError,"-20195":o.ExchangeError,"-20196":o.ExchangeError,"-20198":o.ExchangeError,"-20204":o.ExchangeError}},portfolioMargin:{exact:{"-1000":o.OperationFailed,"-1001":o.ExchangeError,"-1002":o.PermissionDenied,"-1003":o.RateLimitExceeded,"-1004":o.BadRequest,"-1005":o.PermissionDenied,"-1006":o.BadResponse,"-1007":o.BadResponse,"-1008":o.OperationFailed,"-1010":o.ExchangeError,"-1011":o.PermissionDenied,"-1013":o.ExchangeError,"-1014":o.InvalidOrder,"-1015":o.InvalidOrder,"-1016":o.NotSupported,"-1020":o.NotSupported,"-1021":o.BadRequest,"-1022":o.BadRequest,"-1023":o.BadRequest,"-1099":o.OperationFailed,"-1100":o.BadRequest,"-1101":o.BadRequest,"-1102":o.BadRequest,"-1103":o.BadRequest,"-1104":o.BadRequest,"-1105":o.BadRequest,"-1106":o.BadRequest,"-1108":o.BadRequest,"-1109":o.BadRequest,"-1110":o.BadSymbol,"-1111":o.BadRequest,"-1112":o.BadRequest,"-1113":o.BadRequest,"-1114":o.BadRequest,"-1115":o.BadRequest,"-1116":o.BadRequest,"-1117":o.BadRequest,"-1118":o.BadRequest,"-1119":o.BadRequest,"-1120":o.BadRequest,"-1121":o.BadSymbol,"-1125":o.BadRequest,"-1127":o.BadRequest,"-1128":o.BadRequest,"-1130":o.BadRequest,"-1131":o.BadRequest,"-1134":o.BadRequest,"-1136":o.BadRequest,"-1145":o.BadRequest,"-1151":o.BadRequest,"-2010":o.InvalidOrder,"-2011":o.OperationRejected,"-2013":o.OrderNotFound,"-2014":o.OperationRejected,"-2015":o.OperationRejected,"-2016":o.OperationFailed,"-2018":o.OperationFailed,"-2019":o.OperationFailed,"-2020":o.OrderNotFillable,"-2021":o.OrderImmediatelyFillable,"-2022":o.InvalidOrder,"-2023":o.OperationFailed,"-2024":o.OperationRejected,"-2025":o.OperationRejected,"-2026":o.InvalidOrder,"-2027":o.OperationRejected,"-2028":o.OperationRejected,"-4000":o.BadRequest,"-4001":o.BadRequest,"-4002":o.BadRequest,"-4003":o.BadRequest,"-4004":o.BadRequest,"-4005":o.BadRequest,"-4006":o.BadRequest,"-4007":o.BadRequest,"-4008":o.BadRequest,"-4009":o.BadRequest,"-4010":o.BadRequest,"-4011":o.BadRequest,"-4012":o.BadRequest,"-4013":o.BadRequest,"-4014":o.BadRequest,"-4015":o.BadRequest,"-4016":o.BadRequest,"-4017":o.BadRequest,"-4018":o.BadRequest,"-4019":o.BadRequest,"-4020":o.BadRequest,"-4021":o.BadRequest,"-4022":o.BadRequest,"-4023":o.BadRequest,"-4024":o.BadRequest,"-4025":o.BadRequest,"-4026":o.BadRequest,"-4027":o.BadRequest,"-4028":o.BadRequest,"-4029":o.BadRequest,"-4030":o.BadRequest,"-4031":o.BadRequest,"-4032":o.BadRequest,"-4033":o.BadRequest,"-4044":o.BadRequest,"-4045":o.BadRequest,"-4046":o.BadRequest,"-4047":o.BadRequest,"-4048":o.BadRequest,"-4049":o.BadRequest,"-4050":o.BadRequest,"-4051":o.BadRequest,"-4052":o.BadRequest,"-4053":o.BadRequest,"-4054":o.BadRequest,"-4055":o.BadRequest,"-4056":o.PermissionDenied,"-4057":o.PermissionDenied,"-4058":o.BadRequest,"-4059":o.BadRequest,"-4060":o.BadRequest,"-4061":o.InvalidOrder,"-4062":o.BadRequest,"-4063":o.BadRequest,"-4064":o.BadRequest,"-4065":o.BadRequest,"-4066":o.BadRequest,"-4067":o.BadRequest,"-4068":o.BadRequest,"-4069":o.BadRequest,"-4070":o.BadRequest,"-4071":o.BadRequest,"-4072":o.OperationRejected,"-4073":o.BadRequest,"-4074":o.BadRequest,"-4075":o.BadRequest,"-4076":o.OperationRejected,"-4077":o.OperationRejected,"-4078":o.OperationFailed,"-4079":o.BadRequest,"-4080":o.PermissionDenied,"-4081":o.BadRequest,"-4082":o.BadRequest,"-4083":o.BadRequest,"-4084":o.NotSupported,"-4085":o.BadRequest,"-4086":o.BadRequest,"-4087":o.PermissionDenied,"-4088":o.PermissionDenied,"-4104":o.BadRequest,"-4114":o.BadRequest,"-4115":o.BadRequest,"-4118":o.OperationRejected,"-4131":o.OperationRejected,"-4135":o.BadRequest,"-4137":o.BadRequest,"-4138":o.BadRequest,"-4139":o.BadRequest,"-4140":o.OrderImmediatelyFillable,"-4141":o.BadRequest,"-4142":o.OrderImmediatelyFillable,"-4144":o.BadSymbol,"-4161":o.OperationRejected,"-4164":o.InvalidOrder,"-4165":o.BadRequest,"-4183":o.InvalidOrder,"-4184":o.InvalidOrder,"-4408":o.InvalidOrder,"-5021":o.OrderNotFillable,"-5022":o.OrderNotFillable,"-5028":o.OperationFailed,"-5041":o.RateLimitExceeded}},exact:{"-1000":o.OperationFailed,"-1001":o.OperationFailed,"-1002":o.AuthenticationError,"-1003":o.RateLimitExceeded,"-1004":o.OperationRejected,"-1006":o.OperationFailed,"-1007":o.RequestTimeout,"-1010":o.OperationFailed,"-1013":o.BadRequest,"-1014":o.InvalidOrder,"-1015":o.RateLimitExceeded,"-1016":o.BadRequest,"-1020":o.BadRequest,"-1021":o.InvalidNonce,"-1022":o.AuthenticationError,"-1100":o.BadRequest,"-1101":o.BadRequest,"-1102":o.BadRequest,"-1103":o.BadRequest,"-1104":o.BadRequest,"-1105":o.BadRequest,"-1106":o.BadRequest,"-1108":o.BadSymbol,"-1111":o.BadRequest,"-1112":o.OperationFailed,"-1114":o.BadRequest,"-1115":o.BadRequest,"-1116":o.BadRequest,"-1117":o.BadRequest,"-1118":o.BadRequest,"-1119":o.BadRequest,"-1120":o.BadRequest,"-1121":o.BadSymbol,"-1125":o.AuthenticationError,"-1127":o.BadRequest,"-1128":o.BadRequest,"-1130":o.BadRequest,"-2010":o.InvalidOrder,"-2011":o.OrderNotFound,"-2013":o.OrderNotFound,"-2014":o.AuthenticationError,"-2015":o.AuthenticationError,"-4000":o.InvalidOrder,"-4001":o.BadRequest,"-4002":o.BadRequest,"-4003":o.BadRequest,"-4004":o.BadRequest,"-4005":o.BadRequest,"-4006":o.BadRequest,"-4007":o.BadRequest,"-4008":o.BadRequest,"-4009":o.BadRequest,"-4010":o.BadRequest,"-4011":o.BadRequest,"-4012":o.BadRequest,"-4013":o.BadRequest,"-4014":o.BadRequest,"-4015":o.BadRequest,"-4016":o.BadRequest,"-4017":o.BadRequest,"-4018":o.BadRequest,"-4019":o.OperationRejected,"-4020":o.BadRequest,"-4021":o.BadRequest,"-4022":o.BadRequest,"-4023":o.BadRequest,"-4024":o.BadRequest,"-4025":o.BadRequest,"-4026":o.BadRequest,"-4027":o.BadRequest,"-4028":o.BadRequest,"-4029":o.BadRequest,"-4030":o.BadRequest,"-4031":o.BadRequest,"-4032":o.OperationRejected,"-4033":o.BadRequest,"-4044":o.BadRequest,"-4045":o.OperationRejected,"-4046":o.OperationRejected,"-4047":o.OperationRejected,"-4048":o.OperationRejected,"-4049":o.BadRequest,"-4050":o.InsufficientFunds,"-4051":o.InsufficientFunds,"-4052":o.OperationRejected,"-4053":o.BadRequest,"-4054":o.OperationRejected,"-4055":o.BadRequest,"-4056":o.AuthenticationError,"-4057":o.AuthenticationError,"-4058":o.BadRequest,"-4059":o.OperationRejected,"-4060":o.BadRequest,"-4061":o.OperationRejected,"-4062":o.BadRequest,"-4067":o.OperationRejected,"-4068":o.OperationRejected,"-4082":o.BadRequest,"-4083":o.OperationRejected,"-4084":o.BadRequest,"-4086":o.BadRequest,"-4104":o.BadRequest,"-4135":o.BadRequest,"-4137":o.BadRequest,"-4138":o.BadRequest,"-4139":o.BadRequest,"-4142":o.OrderImmediatelyFillable,"-20121":o.BadSymbol,"-20124":o.BadRequest,"-20130":o.BadRequest,"-20132":o.BadRequest,"-20194":o.BadRequest,"-20195":o.BadRequest,"-20196":o.BadRequest,"-20198":o.OperationRejected,"-20204":o.BadRequest,"System is under maintenance.":o.OnMaintenance,"System abnormality":o.OperationFailed,"You are not authorized to execute this request.":o.PermissionDenied,"API key does not exist":o.AuthenticationError,"Order would trigger immediately.":o.OrderImmediatelyFillable,"Stop price would trigger immediately.":o.OrderImmediatelyFillable,"Order would immediately match and take.":o.OrderImmediatelyFillable,"Account has insufficient balance for requested action.":o.InsufficientFunds,"Rest API trading is not enabled.":o.PermissionDenied,"This account may not place or cancel orders.":o.PermissionDenied,"You don't have permission.":o.PermissionDenied,"Market is closed.":o.MarketClosed,"Too many requests. Please try again later.":o.RateLimitExceeded,"This action is disabled on this account.":o.AccountSuspended,"Limit orders require GTC for this phase.":o.BadRequest,"This type of sub-account exceeds the maximum number limit":o.OperationRejected,"This symbol is restricted for this account.":o.PermissionDenied,"This symbol is not permitted for this account.":o.PermissionDenied},broad:{"has no operation privilege":o.PermissionDenied,MAX_POSITION:o.BadRequest,PERCENT_PRICE_BY_SIDE:o.InvalidOrder,"This order type is not possible":o.BadRequest}},rollingWindowSize:6e4})}isInverse(e,t){return void 0===t?"delivery"===e:"inverse"===t}isLinear(e,t){return void 0===t?"future"===e||"swap"===e:"linear"===t}setSandboxMode(e){super.setSandboxMode(e),this.options.sandboxMode=e}createExpiredOptionMarket(e){let t,i="USDT",s=e.split("-"),r=e.split("/");t=e.indexOf("/")>-1?this.safeString(r,0):this.safeString(s,0);let a=this.safeString(s,1),o=this.safeInteger(s,2),n=this.safeString(s,2),d=this.safeString(s,3),h=this.convertExpireDate(a);return{id:t+"-"+a+"-"+n+"-"+d,symbol:t+"/"+i+":"+i+"-"+a+"-"+n+"-"+d,base:t,quote:i,baseId:t,quoteId:i,active:void 0,type:"option",linear:void 0,inverse:void 0,spot:!1,swap:!1,future:!1,option:!0,margin:!1,contract:!0,contractSize:void 0,expiry:this.parse8601(h),expiryDatetime:h,optionType:"C"===d?"call":"put",strike:o,settle:i,settleId:i,precision:{amount:void 0,price:void 0},limits:{amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},info:void 0}}market(e){if(void 0===e)throw new o.ArgumentsRequired(this.id+" market() requires a symbol argument");if(void 0===this.markets)throw new o.ExchangeError(this.id+" markets not loaded");let t=this.safeString(this.options,"defaultType"),i=this.safeString(this.options,"defaultSubType"),s="future"===t,r="delivery"===t;if("string"==typeof e){if(void 0!==this.markets&&e in this.markets){let t=this.markets[e];if(!((s||r)&&this.safeBool(t,"spot",!1)))return t;{let i=e+":"+(s?t.quote:t.base);if(void 0!==this.markets&&i in this.markets)return this.markets[i]}}else if(void 0!==this.markets_by_id&&e in this.markets_by_id){let a=this.markets_by_id[e];s?t="linear":r?t="inverse":void 0===t&&(t=i);for(let e=0;e<a.length;e++){let i=a[e];if(this.safeBool(i,t,!1))return i}return a[0]}else if(e.indexOf("/")>-1&&0>e.indexOf(":")){if(void 0!==t&&"spot"!==t){let[t,i]=e.split("/"),s=i;"USD"===i&&(s=t);let r=e+":"+s;if(void 0!==this.markets&&r in this.markets)return this.markets[r]}}else if(e.indexOf("-C")>-1||e.indexOf("-P")>-1)return this.createExpiredOptionMarket(e)}throw new o.BadSymbol(this.id+" does not have market symbol "+e)}safeMarket(e,t,i,s){return void 0!==e&&(e.indexOf("-C")>-1||e.indexOf("-P")>-1)&&(void 0===this.markets_by_id||!(e in this.markets_by_id))?this.createExpiredOptionMarket(e):super.safeMarket(e,t,i,s)}nonce(){let e=this.safeInteger(this.options,"timeDifference");if(void 0===e)throw new o.ExchangeError(this.id+' nonce() requires a numeric options["timeDifference"]');return this.milliseconds()-e}mintTokenizedAsset(e,t,i={}){let s={underlyingAsset:e,underlyingAssetAmount:t,timestamp:this.milliseconds()};return this.sapiPostEquityTokenizedRedeem(this.extend(s,i))}redeemTokenizedAsset(e,t,i={}){let s={tokenizedAsset:e,tokenizedAssetAmount:t,timestamp:this.milliseconds()};return this.sapiPostEquityTokenizedRedeem(this.extend(s,i))}tokenizedConvertStatus(e,t,i={}){let s={issuerRequestId:e,convertType:t,timestamp:this.milliseconds()};return this.sapiGetEquityTokenizedConvertStatus(this.extend(s,i))}tokenizedConvertHistory(e,t,i={}){let s={timestamp:this.milliseconds()};void 0!==e&&(s.startTime=e),void 0!==t&&(s.size=t);let[r,a]=this.handleUntilOption("endTime",s,i);return this.sapiGetEquityTokenizedHistory(this.extend(r,a))}enableDemoTrading(e){if(this.isSandboxModeEnabled)throw new o.NotSupported(this.id+" demo trading is not supported in the sandbox environment. Please check https://www.binance.com/en/support/faq/detail/9be58f73e5e14338809e3b705b9687dd to see the differences");if(e)this.urls.apiBackupDemoTrading=this.urls.api,this.urls.api=this.urls.demo;else if("apiBackupDemoTrading"in this.urls){this.urls.api=this.urls.apiBackupDemoTrading;let e=this.omit(this.urls,"apiBackupDemoTrading");this.urls=e}this.options.enableDemoTrading=e}async fetchTime(e={}){let t,i=this.safeString2(this.options,"fetchTime","defaultType","spot"),s=this.safeString(e,"type",i),r=this.omit(e,"type"),a=this.handleSubTypeAndParams("fetchTime",void 0,e)[0];return t=this.isLinear(s,a)?await this.fapiPublicGetTime(r):this.isInverse(s,a)?await this.dapiPublicGetTime(r):await this.publicGetTime(r),this.safeInteger(t,"serverTime")}async fetchCurrencies(e={}){let t;if(!0!==this.safeBool(this.options,"fetchCurrencies")||!this.checkRequiredCredentials(!1)||void 0!==this.safeValue(this.urls,"apiBackup")||this.safeBool(this.options,"enableDemoTrading",!1))return{};let i=[this.sapiGetCapitalConfigGetall(e)],s=this.safeBool(this.options,"fetchMargins",!1);!0===s&&i.push(this.sapiGetMarginAllPairs(e));let r=await Promise.all(i),a=r[0];if(!0===s){let e=r[1];t=this.indexBy(e,"assetName")}return this.parseCurrenciesCustom(a,t)}parseCurrenciesCustom(e,t){let i={};for(let s=0;s<e.length;s++){let r=this.parseCurrency(e[s]);if(void 0===r)throw new o.ExchangeError(this.id+" parseCurrenciesCustom() could not resolve parsed");let a=r.code;if(void 0===r)throw new o.ExchangeError(this.id+" parseCurrenciesCustom() could not resolve parsed");let n=this.safeDict(t,r.id);if(void 0===r)throw new o.ExchangeError(this.id+" parseCurrenciesCustom() could not resolve parsed");r.margin=this.safeBool(n,"isBorrowable"),i[a]=r}return i}parseCurrency(e){let t,i,s=this.safeString(e,"coin"),r=this.safeString(e,"name"),a=this.safeCurrencyCode(s),o=this.safeBool(e,"isLegalMoney"),n=this.safeList(e,"networkList",[]),d={},h={},c=!1;for(let e=0;e<n.length;e++){let i=n[e],s=this.safeString(i,"network"),r=this.networkIdToCode(s,a);c="ETF"===s;let l=this.safeNumber(i,"withdrawFee"),u=this.safeBool(i,"depositEnable"),f=this.safeBool(i,"withdrawEnable");void 0!==r&&(d[r]=l),(!0===this.safeBool(i,"isDefault")||void 0===t)&&(t=l);let p=this.omitZero(this.safeString2(i,"withdrawIntegerMultiple","withdrawInternalMin"));void 0===p&&!0===o&&(p=this.safeString(this.options,"defaultFiatWithdrawPrecision")),void 0!==r&&(h[r]={info:i,id:s,network:r,active:void 0,deposit:u,withdraw:f,fee:l,precision:this.parseNumber(p),limits:{withdraw:{min:this.safeNumber(i,"withdrawMin"),max:this.safeNumber(i,"withdrawMax")},deposit:{min:this.safeNumber(i,"depositDust"),max:void 0}}})}i=c?"other":!0===o?"fiat":"crypto";let l=this.safeBool(e,"trading");return this.safeCurrencyStructure({id:s,name:r,code:a,type:i,precision:void 0,info:e,active:l,deposit:void 0,withdraw:void 0,networks:h,fee:void 0,fees:d,limits:void 0})}async fetchMarkets(e={}){let t,i=[],s=["spot","linear","inverse"],r=this.safeDict(this.options,"fetchMarkets");t=void 0!==r?this.safeList(r,"types",s):this.safeList(this.options,"fetchMarkets",s),!0!==this.handleOption("fetchMarkets","loadAllOptions",!1)||this.inArray("option",t)||t.push("option");let a=this.safeBool(this.options,"sandboxMode",!1),n=!0===this.safeBool(this.options,"enableDemoTrading",!1)||!0===a,d=[];for(let e=0;e<t.length;e++){let i=t[e];("option"!==i||!0!==n)&&d.push(i)}let h=this.safeBool(this.options,"fetchMargins",!1);for(let t=0;t<d.length;t++){let s=d[t];if("spot"===s)i.push(this.publicGetExchangeInfo(e)),!0===h&&this.checkRequiredCredentials(!1)&&!0!==n&&(i.push(this.sapiGetMarginAllPairs(e)),i.push(this.sapiGetMarginIsolatedAllPairs(e)));else if("linear"===s)i.push(this.fapiPublicGetExchangeInfo(e));else if("inverse"===s)i.push(this.dapiPublicGetExchangeInfo(e));else if("option"===s)i.push(this.eapiPublicGetExchangeInfo(e));else if("stock"===s)!0!==n&&void 0!==this.apiKey&&""!==this.apiKey&&i.push(this.sapiGetEquityMarketExchangeInfo(e));else throw new o.ExchangeError(this.id+' fetchMarkets() this.options fetchMarkets "'+s+'" is not a supported market type')}let c=await Promise.all(i),l=[];this.options.crossMarginPairsData=[],this.options.isolatedMarginPairsData=[];for(let e=0;e<c.length;e++){let t=this.safeValue(c,e);if(!0===h&&Array.isArray(t)){let e=Object.keys(this.indexBy(t,"symbol"));0===this.options.crossMarginPairsData.length?this.options.crossMarginPairsData=e:this.options.isolatedMarginPairsData=e}else{let e=this.safeList2(t,"symbols","optionSymbols",[]);l=this.arrayConcat(l,e)}}this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference();let u=[];for(let e=0;e<l.length;e++){let t=this.parseMarket(l[e]);void 0!==t&&u.push(t)}return u}parseMarket(e){let t,i,s,r,a,n,d,h,c=!1,l=!1,u=!1,f=this.safeString(e,"underlying"),p=this.safeString(e,"symbol");if(void 0===p)throw new o.ExchangeError(this.id+" parseMarket() missing id");let m=p.split("-"),g=this.safeString(m,0),v=this.safeStringLower(e,"symbol"),y=this.safeString(e,"baseAsset",g),b=this.safeString(e,"quoteAsset"),w=!1;"tradability"in e&&(b="USDC",w=!0);let k=this.safeCurrencyCode(y),S=this.safeCurrencyCode(b);if(void 0===k||void 0===S)return;let O=this.safeString(e,"contractType"),T="contractType"in e,P=this.safeInteger2(e,"deliveryDate","expiryDate"),I=this.safeString(e,"marginAsset");"PERPETUAL"===O||41334048e5===P?(P=void 0,c=!0):void 0!==f?(T=!0,u=!0,void 0===I&&(I="USDT")):void 0!==P&&(l=!0);let A=this.safeCurrencyCode(I),x=!T,M=this.safeList(e,"filters",[]),_=this.indexBy(M,"filterType"),C=this.safeString2(e,"status","contractStatus"),B=this.fees,E=k+"/"+S;if(T){c?E=E+":"+A:l?E=E+":"+A+"-"+this.yymmdd(P):u&&(a=this.numberToString(this.parseToNumeric(this.safeString(e,"strikePrice"))),E=E+":"+A+"-"+this.yymmdd(P)+"-"+a+"-"+this.safeString(m,3)),t=this.safeNumber2(e,"contractSize","unit",this.parseNumber("1")),i=A===S,s=A===k,!0===i?r="linear":!0===s&&(r="inverse");let o="inverse";i&&(o="linear"),B=this.safeDict(this.fees,o,{})}let R="TRADING"===C;if(x){let t=this.safeList(e,"permissions",[]);for(let e=0;e<t.length;e++)if("TRD_GRP_003"===t[e]){R=!1;break}}let L=this.safeBool(e,"isMarginTradingAllowed",!1);x?n={cross:this.inArray(p,this.options.crossMarginPairsData),isolated:this.inArray(p,this.options.isolatedMarginPairsData)}:(!0===i||!0===s)&&(n={cross:!0,isolated:!0}),x?d="spot":c?d="swap":l?d="future":u&&(d="option",R=void 0),void 0!==a&&(h=this.parseToNumeric(a));let N=this.safeString(e,"tradability");void 0!==N&&"NONE"!==N&&(R=!0);let D={id:p,lowercaseId:v,symbol:E,base:k,quote:S,settle:A,baseId:y,quoteId:b,settleId:I,type:d,spot:x,margin:x&&L,marginModes:n,swap:c,future:l,option:u,stock:w,active:R,contract:T,linear:i,inverse:s,subType:r,taker:B.trading.taker,maker:B.trading.maker,contractSize:t,expiry:P,expiryDatetime:this.iso8601(P),strike:h,optionType:this.safeStringLower(e,"side"),precision:{amount:this.parseNumber(this.parsePrecision(this.safeString2(e,"quantityPrecision","quantityScale"))),price:this.parseNumber(this.parsePrecision(this.safeString2(e,"pricePrecision","priceScale"))),base:this.parseNumber(this.parsePrecision(this.safeString(e,"baseAssetPrecision"))),quote:this.parseNumber(this.parsePrecision(this.safeString(e,"quotePrecision")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(e,"minQty"),max:this.safeNumber(e,"maxQty")},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(e,"minNotional"),max:this.safeNumber(e,"maxNotional")}},info:e,created:this.safeInteger2(e,"onboardDate","listingTime")},q=this.safeNumber(e,"stepSize");if(void 0!==q&&(D.precision.amount=q),"PRICE_FILTER"in _){let e=this.safeDict(_,"PRICE_FILTER",{});D.limits.price={min:this.safeNumber(e,"minPrice"),max:this.safeNumber(e,"maxPrice")},D.precision.price=this.safeNumber(e,"tickSize")}if("LOT_SIZE"in _){let e=this.safeDict(_,"LOT_SIZE",{});D.precision.amount=this.safeNumber(e,"stepSize"),D.limits.amount={min:this.safeNumber(e,"minQty"),max:this.safeNumber(e,"maxQty")}}if("MARKET_LOT_SIZE"in _){let e=this.safeDict(_,"MARKET_LOT_SIZE",{});D.limits.market={min:this.safeNumber(e,"minQty"),max:this.safeNumber(e,"maxQty")}}if("MIN_NOTIONAL"in _||"NOTIONAL"in _){let e=this.safeDict2(_,"MIN_NOTIONAL","NOTIONAL",{});D.limits.cost.min=this.safeNumber2(e,"minNotional","notional"),D.limits.cost.max=this.safeNumber(e,"maxNotional")}return this.safeMarketStructure(D)}parseBalanceHelper(e){let t=this.account();t.used=this.safeString(e,"locked"),t.free=this.safeString(e,"free");let i=this.safeString(e,"interest"),s=this.safeString(e,"borrowed");return t.debt=n.Y.stringAdd(s,i),t}parseBalanceCustom(e,t,i,s=!1){let r,a={info:e},o="isolated"===i,d="margin"===t||"cross"===i;if(s)for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.account(),o=this.safeString(s,"asset"),h=this.safeCurrencyCode(o);if("linear"===t)r.free=this.safeString(s,"umWalletBalance"),r.used=this.safeString(s,"umUnrealizedPNL");else if("inverse"===t)r.free=this.safeString(s,"cmWalletBalance"),r.used=this.safeString(s,"cmUnrealizedPNL");else if(d){let e=this.safeString(s,"crossMarginBorrowed"),t=this.safeString(s,"crossMarginInterest");r.debt=n.Y.stringAdd(e,t),r.free=this.safeString(s,"crossMarginFree"),r.used=this.safeString(s,"crossMarginLocked"),r.total=this.safeString(s,"crossMarginAsset")}else{let e=this.safeString(s,"umUnrealizedPNL"),t=this.safeString(s,"cmUnrealizedPNL"),i=n.Y.stringAdd(e,t),a=this.safeString(s,"totalWalletBalance");r.total=n.Y.stringAdd(i,a)}void 0!==h&&(a[h]=r)}else if(!o&&("spot"===t||d)){r=this.safeInteger(e,"updateTime");let t=this.safeList2(e,"balances","userAssets",[]);for(let e=0;e<t.length;e++){let i=this.safeDict(t,e),s=this.safeString(i,"asset"),r=this.safeCurrencyCode(s),o=this.account();if(o.free=this.safeString(i,"free"),o.used=this.safeString(i,"locked"),d){let e=this.safeString(i,"borrowed"),t=this.safeString(i,"interest");o.debt=n.Y.stringAdd(e,t)}void 0!==r&&(a[r]=o)}}else if(o){let t=this.safeList(e,"assets",[]);for(let e=0;e<t.length;e++){let i=this.safeDict(t,e),s=this.safeDict(i,"baseAsset",{}),r=this.safeDict(i,"quoteAsset",{}),o=this.safeCurrencyCode(this.safeString(s,"asset")),n=this.safeCurrencyCode(this.safeString(r,"asset"));void 0!==o&&(a=this.mergeBalanceAccount(a,o,this.parseBalanceHelper(s))),void 0!==n&&(a=this.mergeBalanceAccount(a,n,this.parseBalanceHelper(r)))}}else if("savings"===t){let t=this.safeList(e,"positionAmountVos",[]);for(let e=0;e<t.length;e++){let i=this.safeDict(t,e),s=this.safeString(i,"asset"),r=this.safeCurrencyCode(s),o=this.account(),n=this.safeString(i,"amount");o.total=n,o.used=n,void 0!==r&&(a[r]=o)}}else if("funding"===t)for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s=this.account(),r=this.safeString(i,"asset"),o=this.safeCurrencyCode(r);s.free=this.safeString(i,"free");let d=this.safeString(i,"freeze"),h=this.safeString(i,"withdrawing"),c=this.safeString(i,"locked");s.used=n.Y.stringAdd(d,n.Y.stringAdd(c,h)),void 0!==o&&(a[o]=s)}else{let t=e;Array.isArray(e)||(t=this.safeList(e,"assets",[]));for(let e=0;e<t.length;e++){let i=this.safeDict(t,e);if(0===this.safeInteger(i,"updateTime"))continue;let s=this.safeString(i,"asset"),r=this.safeCurrencyCode(s),o=this.account();o.free=this.safeString(i,"availableBalance"),o.used=this.safeString(i,"initialMargin"),o.total=this.safeString2(i,"marginBalance","balance"),void 0!==r&&(a[r]=o)}}return a.timestamp=r,a.datetime=this.iso8601(r),this.safeBalance(a)}async fetchBalance(e={}){let t,i,s,r,a,o;void 0===this.markets&&await this.loadMarkets();let n=this.safeString2(this.options,"fetchBalance","defaultType","spot"),d=this.safeString(e,"type",n);[t,i]=this.handleSubTypeAndParams("fetchBalance",void 0,e),[s,i]=this.handleOptionBoolAndParams2(i,"fetchBalance","papi","portfolioMargin",!1),[r,a]=this.handleMarginModeAndParams("fetchBalance",i),a=this.omit(a,"type");let h={};if(s||"papi"===d)this.isLinear(d,t)?d="linear":this.isInverse(d,t)&&(d="inverse"),s=!0,o=await this.papiGetBalance(this.extend(h,a));else if(this.isLinear(d,t)){let e;d="linear",[e,i]=this.handleOptionBoolAndParams(i,"fetchBalance","useV2",!1),i=this.extend(h,a),o=e?await this.fapiPrivateV2GetAccount(i):await this.fapiPrivateV3GetAccount(i)}else if(this.isInverse(d,t))d="inverse",o=await this.dapiPrivateGetAccount(this.extend(h,a));else if("isolated"===r){let e=this.safeList(i,"symbols");if(a=this.omit(a,"symbols"),void 0!==e){let t="";if(Array.isArray(e)){let i=this.marketId(e[0]);void 0!==i&&(t=i);for(let i=1;i<e.length;i++){let s=e[i],r=this.marketId(s);void 0!==r&&(t+=","+r)}}else t=e;h.symbols=t}o=await this.sapiGetMarginIsolatedAccount(this.extend(h,a))}else o="margin"===d||"cross"===r?await this.sapiGetMarginAccount(this.extend(h,a)):"savings"===d?await this.sapiGetLendingUnionAccount(this.extend(h,a)):"funding"===d?await this.sapiPostAssetGetFundingAsset(this.extend(h,a)):await this.privateGetAccount(this.extend(h,a));return this.parseBalanceCustom(o,d,r,s)}async fetchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id};if(void 0!==t&&(a.limit=t),!0===r.option)s=await this.eapiPublicGetDepth(this.extend(a,i));else if(!0===r.linear){let e=this.safeBool(i,"rpi",!1),t=this.omit(i,"rpi");!0===e?(a.limit=1e3,s=await this.fapiPublicGetRpiDepth(this.extend(a,t))):s=await this.fapiPublicGetDepth(this.extend(a,t))}else s=!0===r.inverse?await this.dapiPublicGetDepth(this.extend(a,i)):await this.publicGetDepth(this.extend(a,i));let o=this.safeInteger(s,"T"),n=this.parseOrderBook(s,e,o);return n.nonce=this.safeInteger2(s,"lastUpdateId","u"),n}parseTicker(e,t){let i,s,r,a=this.safeInteger2(e,"closeTime","time");"time"in e&&(i="contract"),void 0===i&&(i="bidQty"in e?"spot":"contract");let o=this.safeString(e,"symbol"),d=this.safeSymbol(o,t,void 0,i),h=this.safeString(e,"lastPrice"),c=this.safeString(e,"weightedAvgPrice");return"baseVolume"in e?(s=this.safeString(e,"baseVolume"),r=n.Y.stringMul(s,c)):(s=this.safeString(e,"volume"),r=this.safeString2(e,"quoteVolume","amount")),this.safeTicker({symbol:d,timestamp:a,datetime:this.iso8601(a),high:this.safeString2(e,"highPrice","high"),low:this.safeString2(e,"lowPrice","low"),bid:this.safeString(e,"bidPrice"),bidVolume:this.safeString2(e,"bidQty","bidSize"),ask:this.safeString(e,"askPrice"),askVolume:this.safeString2(e,"askQty","askSize"),vwap:c,open:this.safeString2(e,"openPrice","open"),close:h,last:h,previousClose:this.safeString(e,"prevClosePrice"),change:this.safeString(e,"priceChange"),percentage:this.safeString(e,"priceChangePercent"),average:void 0,baseVolume:s,quoteVolume:r,markPrice:this.safeString(e,"markPrice"),indexPrice:this.safeString(e,"indexPrice"),info:e},t)}async fetchStatus(e={}){let t=await this.sapiGetSystemStatus(e),i=this.safeString(t,"status");return{status:this.safeString({0:"ok",1:"maintenance"},i,i),updated:void 0,eta:void 0,url:void 0,info:t}}async fetchTicker(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};if(!0===s.option)i=await this.eapiPublicGetTicker(this.extend(r,t));else if(!0===s.linear)i=await this.fapiPublicGetTicker24hr(this.extend(r,t));else if(!0===s.inverse)i=await this.dapiPublicGetTicker24hr(this.extend(r,t));else if(!0===this.safeBool(s,"stock",!1))i=await this.sapiGetEquityMarketQuote(this.extend(r,t));else{let e=this.safeBool(t,"rolling",!1),s=this.omit(t,"rolling");i=!0===e?await this.publicGetTicker(this.extend(r,s)):await this.publicGetTicker24hr(this.extend(r,s))}if(Array.isArray(i)){let e=this.safeDict(i,0,{});return this.parseTicker(e,s)}if(void 0===i)throw new o.NullResponse(this.id+" fetchTicker() returned empty response");return this.parseTicker(i,s)}checkNoStockSymbols(e,t){if(void 0!==e)for(let i=0;i<e.length;i++){let s=this.market(e[i]);if(!0===this.safeBool(s,"stock",!1))throw new o.NotSupported(this.id+" "+t+"() does not support tokenized stock symbols ("+e[i]+"), the equity quote endpoint accepts a single symbol per request, use fetchTicker() instead")}}async fetchBidsAsks(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!0,!0,!0);this.checkNoStockSymbols(s,"fetchBidsAsks");let r=this.getMarketFromSymbols(s),[a,n]=this.handleMarketTypeAndParams("fetchBidsAsks",r,t),[d,h]=this.handleSubTypeAndParams("fetchBidsAsks",r,n),c={};if(void 0!==s&&(this.isLinear(a,d)||this.isInverse(a,d))&&1===s.length&&(c.symbol=this.marketId(s[0])),"option"===a)i=await this.eapiPublicGetTicker(h);else if(this.isLinear(a,d))i=await this.fapiPublicGetTickerBookTicker(this.extend(c,h));else if(this.isInverse(a,d))i=await this.dapiPublicGetTickerBookTicker(this.extend(c,h));else if("spot"===a)void 0!==s&&(c.symbols=this.json(this.marketIds(s))),i=await this.publicGetTickerBookTicker(this.extend(c,h));else throw new o.NotSupported(this.id+" fetchBidsAsks() does not support "+a+" markets yet");return Array.isArray(i)||(i=[i]),this.parseTickers(i,s)}async fetchLastPrices(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!0,!0,!0),r=this.getMarketFromSymbols(s),[a,n]=this.handleMarketTypeAndParams("fetchLastPrices",r,t),[d,h]=this.handleSubTypeAndParams("fetchLastPrices",r,n);if(this.isLinear(a,d))i=await this.fapiPublicV2GetTickerPrice(h);else if(this.isInverse(a,d))i=await this.dapiPublicGetTickerPrice(h);else if("spot"===a)i=await this.publicGetTickerPrice(h);else throw new o.NotSupported(this.id+" fetchLastPrices() does not support "+a+" markets yet");return this.parseLastPrices(i,s)}parseLastPrice(e,t){let i=this.safeInteger(e,"time"),s="swap";void 0===i&&(s="spot");let r=this.safeString(e,"symbol");return{symbol:this.safeMarket(r,t,void 0,s).symbol,timestamp:i,datetime:this.iso8601(i),price:this.safeNumberOmitZero(e,"price"),side:void 0,info:e}}async fetchTickers(e,t={}){let i,s,r,a;void 0===this.markets&&await this.loadMarkets();let n=this.marketSymbols(e,void 0,!0,!0,!0);this.checkNoStockSymbols(n,"fetchTickers");let d=this.getMarketFromSymbols(n);if([i,s]=this.handleMarketTypeAndParams("fetchTickers",d,t),[r,s]=this.handleSubTypeAndParams("fetchTickers",d,s),this.isLinear(i,r))a=await this.fapiPublicGetTicker24hr(s);else if(this.isInverse(i,r))a=await this.dapiPublicGetTicker24hr(s);else if("spot"===i){let e=this.safeBool(s,"rolling",!1);if(s=this.omit(s,"rolling"),!0===e){n=this.marketSymbols(n);let e={symbols:this.json(this.marketIds(n))};return a=await this.publicGetTicker(this.extend(e,s)),this.parseTickersForRolling(a,n)}{let e={};void 0!==n&&(e.symbols=this.json(this.marketIds(n))),a=await this.publicGetTicker24hr(this.extend(e,s))}}else if("option"===i)a=await this.eapiPublicGetTicker(s);else throw new o.NotSupported(this.id+" fetchTickers() does not support "+i+" markets yet");return this.parseTickers(a,n)}parseTickersForRolling(e,t){let i=[];for(let t=0;t<e.length;t++){let s=this.safeString(e[t],"symbol"),r=this.safeMarket(s,void 0,void 0,"spot"),a=this.parseTicker(e[t]);a.symbol=r.symbol,i.push(a)}return this.filterByArray(i,"symbol",t)}async fetchMarkPrice(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),[r,a]=this.handleMarketTypeAndParams("fetchMarkPrice",s,t,"swap"),[n,d]=this.handleSubTypeAndParams("fetchMarkPrice",s,a,"linear"),h={symbol:s.id};if(!0===s.option)i=await this.eapiPublicGetMark(this.extend(h,d));else if(this.isLinear(r,n))i=await this.fapiPublicGetPremiumIndex(this.extend(h,d));else if(this.isInverse(r,n))i=await this.dapiPublicGetPremiumIndex(this.extend(h,d));else throw new o.NotSupported(this.id+" fetchMarkPrice() does not support "+r+" markets yet");if(Array.isArray(i))return this.parseTicker(this.safeDict(i,0,{}),s);if(void 0===i)throw new o.NullResponse(this.id+" fetchMarkPrice() returned empty response");return this.parseTicker(i,s)}async fetchMarkPrices(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!0,!0,!0),r=this.getMarketFromSymbols(s),[a,n]=this.handleMarketTypeAndParams("fetchMarkPrices",r,t,"swap"),[d,h]=this.handleSubTypeAndParams("fetchMarkPrices",r,n,"linear");if("option"===a)i=await this.eapiPublicGetMark(h);else if(this.isLinear(a,d))i=await this.fapiPublicGetPremiumIndex(h);else if(this.isInverse(a,d))i=await this.dapiPublicGetPremiumIndex(h);else throw new o.NotSupported(this.id+" fetchMarkPrices() does not support "+a+" markets yet");return this.parseTickers(i,s)}parseOHLCV(e,t){let i=this.safeBool(t,"inverse");return[this.safeInteger2(e,0,"openTime"),this.safeNumber2(e,1,"open"),this.safeNumber2(e,2,"high"),this.safeNumber2(e,3,"low"),this.safeNumber2(e,4,"close"),this.safeNumber2(e,!0===i?7:5,"volume")]}async fetchOHLCV(e,t="1m",i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(n)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,d,1e3);let h=this.market(e),c=this.safeString(d,"price"),l=this.safeInteger(d,"until"),u=this.omit(d,["price","until"]),f=s;void 0!==i&&void 0!==l&&void 0===s&&(f=1e3);let p=void 0===f?500:Math.min(f,1e3),m={interval:this.safeString(this.timeframes,t,t),limit:p},g=h.id;if(void 0===g)throw new o.ExchangeError(this.id+" fetchOHLCV() missing marketId");if("index"===c){let e=g.split("_");m.pair=this.safeString(e,0)}else m.symbol=g;if(void 0!==i&&(m.startTime=i,!0===h.inverse&&i>0)){let e=this.parseTimeframe(t),s=this.sum(i,p*e*1e3-1);m.endTime=Math.min(this.milliseconds(),s)}return void 0!==l&&(m.endTime=l),a=!0===h.option?await this.eapiPublicGetKlines(this.extend(m,u)):"mark"===c?!0===h.inverse?await this.dapiPublicGetMarkPriceKlines(this.extend(m,u)):await this.fapiPublicGetMarkPriceKlines(this.extend(m,u)):"index"===c?!0===h.inverse?await this.dapiPublicGetIndexPriceKlines(this.extend(m,u)):await this.fapiPublicGetIndexPriceKlines(this.extend(m,u)):"premiumIndex"===c?!0===h.inverse?await this.dapiPublicGetPremiumIndexKlines(this.extend(m,u)):await this.fapiPublicGetPremiumIndexKlines(this.extend(m,u)):!0===h.linear?await this.fapiPublicGetKlines(this.extend(m,u)):!0===h.inverse?await this.dapiPublicGetKlines(this.extend(m,u)):await this.publicGetKlines(this.extend(m,u)),this.parseOHLCVs(this.toArray(a),h,t,i,p)}parseTrade(e,t){let i,s,r;if("isDustTrade"in e)return this.parseDustTrade(e,t);let a=this.safeIntegerN(e,["T","time","executionAt"]),o=this.safeString2(e,"q","qty");o=this.safeString(e,"quantity",o);let d=this.safeString(e,"symbol"),h="contract";("isIsolated"in e||"M"in e||"orderListId"in e||"isMaker"in e)&&(h="spot");let c=this.safeMarket(d,t,void 0,h),l=c.symbol,u=this.safeBool2(e,"m","isBuyerMaker");if(void 0!==u?i=u?"sell":"buy":"side"in e?i=this.safeStringLower(e,"side"):"isBuyer"in e&&(i=this.safeBool(e,"isBuyer",!1)?"buy":"sell"),"commission"in e&&(r={cost:this.safeString(e,"commission"),currency:this.safeCurrencyCode(this.safeString(e,"commissionAsset"))}),"isMaker"in e&&(s=this.safeBool(e,"isMaker",!1)?"maker":"taker"),"maker"in e&&(s=this.safeBool(e,"maker",!1)?"maker":"taker"),"optionSide"in e||!0===c.option){let t=this.safeCurrencyCode(this.safeString(e,"quoteAsset","USDT"));s=this.safeStringLower(e,"liquidity"),"fee"in e&&(r={cost:this.safeString(e,"fee"),currency:t}),"buy"!==i&&"sell"!==i&&(i="1"===i?"buy":"sell"),"optionSide"in e&&"buy"!==i&&(o=n.Y.stringMul("-1",o))}let f=this.safeStringN(e,["quoteQty","baseQty","total"]);return!0===c.inverse&&(f=this.safeString(e,"baseQty",f)),this.safeTrade({info:e,timestamp:a,datetime:this.iso8601(a),symbol:l,id:this.safeStringN(e,["t","a","tradeId","id","executionId"]),order:this.safeString(e,"orderId"),type:this.safeStringLower2(e,"type","orderType"),side:i,takerOrMaker:s,price:this.safeString2(e,"p","price"),amount:o,cost:f,fee:r},c)}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,n]=this.handleOptionBoolAndParams(s,"fetchTrades","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchTrades",e,t,i,n);let d=this.market(e),h={symbol:d.id};if(!0!==d.option){void 0!==t&&(h.startTime=t,h.endTime=this.sum(t,36e5));let e=this.safeInteger(n,"until");void 0!==e&&(h.endTime=e)}let c=this.safeString(this.options,"fetchTradesMethod");if(c=this.safeString2(n,"fetchTradesMethod","method",c),void 0!==i){let e=!0===d.swap||!0===d.future,t=void 0!==c&&c.indexOf("GetHistoricalTrades")>=0;h.limit=!0===e?Math.min(i,t?500:1e3):i}let l=this.omit(n,["until","fetchTradesMethod"]);if(void 0===c&&(c=!0===d.option?"eapiPublicGetTrades":!0===d.linear?"fapiPublicGetAggTrades":!0===d.inverse?"dapiPublicGetAggTrades":"publicGetAggTrades"),"publicGetAggTrades"===c)r=await this.publicGetAggTrades(this.extend(h,l));else if("publicGetTrades"===c)r=await this.publicGetTrades(this.extend(h,l));else if("publicGetHistoricalTrades"===c)r=await this.publicGetHistoricalTrades(this.extend(h,l));else if("fapiPublicGetAggTrades"===c)r=await this.fapiPublicGetAggTrades(this.extend(h,l));else if("fapiPublicGetTrades"===c)r=await this.fapiPublicGetTrades(this.extend(h,l));else if("fapiPublicGetHistoricalTrades"===c)r=await this.fapiPublicGetHistoricalTrades(this.extend(h,l));else if("dapiPublicGetAggTrades"===c)r=await this.dapiPublicGetAggTrades(this.extend(h,l));else if("dapiPublicGetTrades"===c)r=await this.dapiPublicGetTrades(this.extend(h,l));else if("dapiPublicGetHistoricalTrades"===c)r=await this.dapiPublicGetHistoricalTrades(this.extend(h,l));else if("eapiPublicGetTrades"===c)r=await this.eapiPublicGetTrades(this.extend(h,l));else if("eapiPublicGetHistoricalTrades"===c)r=await this.eapiPublicGetHistoricalTrades(this.extend(h,l));else throw new o.NotSupported(this.id+" fetchTrades() does not support this method");let u=[];return void 0!==r&&(u=this.toArray(r)),this.parseTrades(u,d,t,i)}async editSpotOrder(e,t,i,s,r,a,n={}){void 0===this.markets&&await this.loadMarkets();let d=this.market(t);if(!0!==d.spot)throw new o.NotSupported(this.id+" editSpotOrder() does not support "+d.type+" orders");let h=this.editSpotOrderRequest(e,t,i,s,r,a,n),c=await this.privatePostOrderCancelReplace(h),l=this.safeDict(c,"newOrderResponse",{});return this.parseOrder(l,d)}editSpotOrderRequest(e,t,i,s,r,a,d={}){if(void 0===i)throw new o.ArgumentsRequired(this.id+" requires a type argument");if(void 0===s)throw new o.ArgumentsRequired(this.id+" requires a side argument");let h=this.market(t),c=this.safeStringN(d,["newClientOrderId","clientOrderId","origClientOrderId"]);if(void 0===s)throw new o.ArgumentsRequired(this.id+" editSpotOrderRequest() requires a side argument");let l={symbol:h.id,side:s.toUpperCase()},u=i.toUpperCase(),f=u;this.isPostOnly("MARKET"===u,"LIMIT_MAKER"===u,d)&&(f="LIMIT_MAKER");let p=this.safeNumber2(d,"stopPrice","triggerPrice");void 0!==p&&("MARKET"===f?f="STOP_LOSS":"LIMIT"===f&&(f="STOP_LOSS_LIMIT")),l.type=f;let m=this.safeList(h.info,"orderTypes",[]);if(!this.inArray(f,m))if(u!==f)throw new o.InvalidOrder(this.id+" triggerPrice parameter is not allowed for "+t+" "+i+" orders");else throw new o.InvalidOrder(this.id+" "+i+" is not a valid order type for the "+t+" market");void 0===c?l.newClientOrderId=this.generateClientOrderId(h):l.newClientOrderId=c,l.newOrderRespType=this.safeString(this.options.newOrderRespType,i,"RESULT");let g=!1,v=!1,y=!1,b=!1;if("MARKET"===f)if(!0===this.handleOption("createOrder","quoteOrderQty",!0)){let e=this.safeValue2(d,"quoteOrderQty","cost"),t=h.precision.price;if(void 0!==e)l.quoteOrderQty=this.decimalToPrecision(e,0,t,this.precisionMode);else if(void 0!==a){let e=this.numberToString(r),i=this.numberToString(a),s=n.Y.stringMul(e,i);l.quoteOrderQty=this.decimalToPrecision(s,0,t,this.precisionMode)}else b=!0}else b=!0;else"LIMIT"===f?(v=!0,g=!0,b=!0):"STOP_LOSS"===f||"TAKE_PROFIT"===f?(y=!0,b=!0):"STOP_LOSS_LIMIT"===f||"TAKE_PROFIT_LIMIT"===f?(b=!0,y=!0,v=!0,g=!0):"LIMIT_MAKER"===f&&(v=!0,b=!0);if(b&&(l.quantity=this.amountToPrecision(t,r)),v){if(void 0===a)throw new o.InvalidOrder(this.id+" editOrder() requires a price argument for a "+i+" order");l.price=this.priceToPrecision(t,a)}if(g&&void 0===this.safeString(d,"timeInForce")&&(l.timeInForce=this.handleOption("createOrder","timeInForce")),y)if(void 0===p)throw new o.InvalidOrder(this.id+" editOrder() requires a triggerPrice extra param for a "+i+" order");else l.stopPrice=this.priceToPrecision(t,p);l.cancelReplaceMode="STOP_ON_FAILURE",void 0===this.safeString2(d,"cancelNewClientOrderId","cancelOrigClientOrderId")&&(l.cancelOrderId=e);let w=d;"PO"===this.safeString(d,"timeInForce")&&(w=this.omit(d,["timeInForce"]));let k=this.omit(w,["quoteOrderQty","cost","stopPrice","newClientOrderId","clientOrderId","postOnly"]);return this.extend(l,k)}editContractOrderRequest(e,t,i,s,r,a,n={}){if(void 0===i)throw new o.ArgumentsRequired(this.id+" requires a type argument");if(void 0===s)throw new o.ArgumentsRequired(this.id+" requires a side argument");if(void 0===a&&!("priceMatch"in n))throw new o.ArgumentsRequired(this.id+" editOrder() and editOrderWs() require a price argument for swap orders");let d=this.market(t);if(!0!==d.contract)throw new o.NotSupported(this.id+" editContractOrder() does not support "+d.type+" orders");if(void 0===s)throw new o.ArgumentsRequired(this.id+" editContractOrder() requires a side argument");let h={symbol:d.id,side:s.toUpperCase(),orderId:e,quantity:this.amountToPrecision(t,r)},c=this.safeStringN(n,["newClientOrderId","clientOrderId","origClientOrderId"]);return void 0!==a&&(h.price=this.priceToPrecision(t,a)),void 0!==c&&(h.origClientOrderId=c),h}async editContractOrder(e,t,i,s,r,a,n={}){let d;void 0===this.markets&&await this.loadMarkets();let h=this.market(t),[c,l]=this.handleOptionBoolAndParams2(n,"editContractOrder","papi","portfolioMargin",!1),u=this.editContractOrderRequest(e,t,i,s,r,a,l);if(!0===h.linear?d=c?await this.papiPutUmOrder(this.extend(u,l)):await this.fapiPrivatePutOrder(this.extend(u,l)):!0===h.inverse&&(d=c?await this.papiPutCmOrder(this.extend(u,l)):await this.dapiPrivatePutOrder(this.extend(u,l))),void 0===d)throw new o.NullResponse(this.id+" parseOrder() returned empty response");return this.parseOrder(d,h)}async editOrder(e,t,i,s,r,a,n={}){void 0===this.markets&&await this.loadMarkets();let d=this.market(t);if(!0===d.option)throw new o.NotSupported(this.id+" editOrder() does not support "+d.type+" orders");return!0===d.spot?await this.editSpotOrder(e,t,i,s,r,a,n):await this.editContractOrder(e,t,i,s,r,a,n)}async editOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=[],r=[];for(let t=0;t<e.length;t++){let i,a=this.safeDict(e,t),n=this.safeString(a,"symbol");r.push(n);let d=this.safeString(a,"id"),h=this.safeString(a,"type"),c=this.safeString(a,"side"),l=this.safeValue(a,"amount"),u=this.safeValue(a,"price"),f=this.safeDict(a,"params",{});if([i,f]=this.handleOptionBoolAndParams2(f,"editOrders","papi","portfolioMargin",!1),i)throw new o.NotSupported(this.id+" editOrders() does not support portfolio margin orders");let p=this.editContractOrderRequest(d,n,h,c,l,u,f);s.push(p)}r=this.marketSymbols(r,void 0,!1,!0,!0);let a=this.market(r[0]);if(!0===a.spot||!0===a.option)throw new o.NotSupported(this.id+" editOrders() does not support "+a.type+" orders");let n={batchOrders:s};return n=this.extend(n,t),!0===a.linear?i=await this.fapiPrivatePutBatchOrders(n):!0===a.inverse&&(i=await this.dapiPrivatePutBatchOrders(n)),this.parseOrders(i)}parseOrderStatus(e){return this.safeString({NEW:"open",PARTIALLY_FILLED:"open",ACCEPTED:"open",TRIGGERING:"open",FILLED:"closed",TRIGGERED:"closed",FINISHED:"closed",CANCELED:"canceled",CANCELLED:"canceled",PENDING_CANCEL:"canceling",REJECTED:"rejected",EXPIRED:"expired",EXPIRED_IN_MATCH:"expired",S:"ok",F:"rejected"},e,e)}parseOrderTypeByMarket(e,t){let i={};return i=void 0!==t&&"spot"===t?{limit_maker:"limit",stop_loss_limit:"limit",stop_loss:"market",take_profit_limit:"limit",take_profit:"market"}:{limit_maker:"limit",stop:"limit",stop_market:"market",take_profit:"limit",take_profit_market:"market",trailing_stop_market:"market"},this.safeString(i,e,e)}parseOrder(e,t){let i,s,r=this.safeString(e,"code");if(void 0!==r){let i=this.safeString(e,"msg");if("200"!==r&&"success"!==i&&"The operation of cancel all open order is done."!==i)return this.safeOrder({info:e,status:"rejected"},t)}let a=this.parseOrderStatus(this.safeStringN(e,["status","strategyStatus","algoStatus"])),o=this.safeString(e,"symbol"),d="spot";("positionSide"in e||"cumQuote"in e)&&(d="contract");let h=this.safeMarket(o,t,void 0,d),c=h.symbol,l=this.safeString2(e,"executedQty","filledQty","0"),u=this.safeIntegerN(e,["time","createTime","workingTime","transactTime","updateTime","createdAt"]);if("transactTime"in e||"updateTime"in e||"updatedAt"in e){let t=this.safeIntegerN(e,["updateTime","transactTime","updatedAt"]);"open"===a?n.Y.stringGt(l,"0")&&(i=t):"closed"===a&&(i=t)}let f=this.safeIntegerN(e,["transactTime","updateTime","updatedAt"]),p=this.safeString2(e,"avgPrice","avgFilledPrice"),m=this.safeString2(e,"price","limitPrice"),g=this.safeStringN(e,["origQty","quantity","qty"]),v=this.safeString2(e,"cummulativeQuoteQty","cumQuote");!0===h.inverse&&(v=this.safeString(e,"cumBase",v));let y=this.safeStringLower2(e,"type","orderType"),b=this.safeStringLower(e,"side"),w=this.safeList2(e,"fills","trades",[]),k=this.safeString(e,"timeInForce");"GTX"===k&&(k="PO");let S="limit_maker"===y||"PO"===k,O=this.safeString2(e,"stopPrice","triggerPrice"),T=this.parseNumber(this.omitZero(O)),P=this.inArray(y,["take_profit","take_profit_market","take_profit_limit"])?T:void 0,I=this.safeNumber(e,"fee");return void 0!==I&&(s={currency:this.safeString2(e,"quoteAsset","quote"),cost:I,rate:void 0}),this.safeOrder({info:e,id:this.safeStringN(e,["strategyId","orderId","algoId"]),clientOrderId:this.safeStringN(e,["clientOrderId","newClientStrategyId","clientAlgoId"]),timestamp:u,datetime:this.iso8601(u),lastTradeTimestamp:i,lastUpdateTimestamp:f,symbol:c,type:this.parseOrderTypeByMarket(y,d),timeInForce:k,postOnly:S,reduceOnly:this.safeBool(e,"reduceOnly"),side:b,price:m,triggerPrice:T,takeProfitPrice:P,amount:g,cost:v,average:p,filled:l,remaining:void 0,status:a,fee:s,trades:w},h)}async createOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=[],r=[];for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),a=this.safeString(i,"symbol");r.push(a);let n=this.safeString(i,"type"),d=this.safeString(i,"side"),h=this.safeValue(i,"amount"),c=this.safeValue(i,"price"),l=this.safeDict(i,"params",{}),u=this.market(a);if(!0===u.linear&&!0!==u.option&&this.isConditionalOrder(l))throw new o.NotSupported(this.id+" createOrders() does not support conditional order types for linear markets, use createOrder() instead");let f=this.createOrderRequest(a,n,d,h,c,this.extend(l,{isAlgoOrder:!1}));s.push(f)}r=this.marketSymbols(r,void 0,!1,!0,!0);let a=this.market(r[0]);if(!0===a.spot)throw new o.NotSupported(this.id+" createOrders() does not support "+a.type+" orders");let n={batchOrders:s};return n=this.extend(n,t),i=!0===a.linear?await this.fapiPrivatePostBatchOrders(n):!0===a.option?await this.eapiPrivatePostBatchOrders(n):await this.dapiPrivatePostBatchOrders(n),this.parseOrders(i)}async createOrder(e,t,i,s,r,a={}){let n;void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h=this.safeString(a,"type",d.type),c=this.safeString(a,"marginMode"),l=this.safeBool2(this.options,"papi","portfolioMargin",!1),u=this.safeBool2(a,"papi","portfolioMargin",l),f=this.isConditionalOrder(a),p=(!0===d.swap||!0===d.future)&&f&&!u,m=this.safeBool2(a,"sor","SOR",!1),g=this.safeBool(a,"test",!1),v=this.safeBool(d,"stock",!1),y=this.omit(a,["sor","SOR","test"]),b=this.createOrderRequest(e,t,i,s,r,this.extend(y,{isAlgoOrder:p}));if(!0===d.option?n=await this.eapiPrivatePostOrder(b):!0===m?n=!0===g?await this.privatePostSorOrderTest(b):await this.privatePostSorOrder(b):!0===d.linear?!0===u?n=f?await this.papiPostUmConditionalOrder(b):await this.papiPostUmOrder(b):f?(b.algoType="CONDITIONAL",n=await this.fapiPrivatePostAlgoOrder(b)):n=await this.fapiPrivatePostOrder(b):!0===d.inverse?!0===u?n=f?await this.papiPostCmConditionalOrder(b):await this.papiPostCmOrder(b):f?(b.algoType="CONDITIONAL",n=await this.dapiPrivatePostAlgoOrder(b)):n=await this.dapiPrivatePostOrder(b):n="margin"===h||void 0!==c||!0===u?!0===u?await this.papiPostMarginOrder(b):await this.sapiPostMarginOrder(b):!0===v?await this.sapiPostEquityOrderPlace(b):!0===g?await this.privatePostOrderTest(b):await this.privatePostOrder(b),void 0===n)throw new o.NullResponse(this.id+" parseOrder() returned empty response");return this.parseOrder(n,d)}generateClientOrderId(e,t){let i;if(void 0!==e)i=!0===e.option?"option":!0===e.linear?!0===e.swap?"swap":"future":!0===e.inverse?"inverse":"spot";else if(void 0!==t)i=t.indexOf("sapi")>-1||"private"===t?"spot":t.indexOf("dapi")>-1?"inverse":t.indexOf("eapi")>-1?"option":"future";else{let e=this.safeString(this.options,"defaultType","spot"),t=this.safeString(this.options,"defaultSubType");i=e,"delivery"===e?i="inverse":"inverse"===t&&("swap"===e||"future"===e)&&(i="inverse")}let s="x-xcKtGhcu";"spot"===i||"margin"===i?s="x-TKT5PX2F":("future"===i||"swap"===i)&&(s="x-cvBPrNm9");let r=this.safeDict(this.options,"broker",{});return this.safeString(r,i,s)+this.uuid22()}isConditionalOrder(e={}){return void 0!==this.safeStringN(e,["triggerPrice","stopPrice","stopLossPrice","takeProfitPrice","trailingPercent","callbackRate","trailingDelta"])}createOrderRequest(e,t,i,s,r,a={}){let d,h;if(void 0===t)throw new o.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new o.ArgumentsRequired(this.id+" requires a side argument");let c=this.market(e),l=this.safeString(a,"type",c.type),u=this.safeBool(c,"stock",!1),f=this.safeBool(a,"isAlgoOrder",!1),p=this.omit(a,"isAlgoOrder"),m=this.safeStringN(p,["clientAlgoId","newClientOrderId","clientOrderId"]),g=t.toUpperCase(),v="MARKET"===g,y="LIMIT"===g,b=i.toUpperCase(),w={symbol:c.id,side:b},[k,S]=this.handleOptionBoolAndParams2(p,"createOrder","papi","portfolioMargin",!1),[O,T]=this.handleMarginModeAndParams("createOrder",S),P=["type","newClientOrderId","clientOrderId","postOnly","stopLossPrice","takeProfitPrice","stopPrice","triggerPrice","trailingTriggerPrice","activationPrice","trailingPercent","quoteOrderQty","cost","test","hedged","icebergAmount"],I=this.safeBool(T,"reduceOnly",!1);!0===I&&("margin"===l||!0!==c.contract&&void 0!==O)&&(P.push("reduceOnly"),w.sideEffectType="AUTO_REPAY");let A=this.safeString2(T,"triggerPrice","stopPrice"),x=this.safeString(T,"stopLossPrice",A),M=this.safeString(T,"takeProfitPrice"),_=this.safeString(T,"trailingDelta"),C=this.safeString2(T,"trailingTriggerPrice","activationPrice"),B=this.safeStringN(T,["trailingPercent","callbackRate","trailingDelta"]),E=this.safeString(T,"priceMatch"),R=void 0!==B,L=void 0!==x||void 0!==_,N=void 0!==M,D=void 0!==A,q=k&&(D||R||L||N),F=!0,V=t.toUpperCase();if(R)if(!0===c.swap||!0===c.future)V="TRAILING_STOP_MARKET",w.callbackRate=B,void 0!==C&&(w[f?"activatePrice":"activationPrice"]=this.priceToPrecision(e,C));else{if("STOP_LOSS"!==V&&"TAKE_PROFIT"!==V&&"STOP_LOSS_LIMIT"!==V&&"TAKE_PROFIT_LIMIT"!==V){let t=this.safeString(T,"stopLossOrTakeProfit");if(P.push("stopLossOrTakeProfit"),"stopLoss"!==t&&"takeProfit"!==t)throw new o.InvalidOrder(this.id+e+" trailingPercent orders require a stopLossOrTakeProfit parameter of either stopLoss or takeProfit");v?"stopLoss"===t?V="STOP_LOSS":"takeProfit"===t&&(V="TAKE_PROFIT"):"stopLoss"===t?V="STOP_LOSS_LIMIT":"takeProfit"===t&&(V="TAKE_PROFIT_LIMIT")}("STOP_LOSS"===V||"TAKE_PROFIT"===V)&&(F=!1),void 0!==C&&(d=this.priceToPrecision(e,C)),w.trailingDelta=n.Y.stringMul(B,"100")}else L?(d=x,v?V=!0===c.contract?"STOP_MARKET":"STOP_LOSS":y&&(V=!0===c.contract?"STOP":"STOP_LOSS_LIMIT")):N&&(d=M,v?V=!0===c.contract?"TAKE_PROFIT_MARKET":"TAKE_PROFIT":y&&(V=!0===c.contract?"TAKE_PROFIT":"TAKE_PROFIT_LIMIT"));if(!0===c.option){if("market"===t)throw new o.InvalidOrder(this.id+" "+t+" is not a valid order type for the "+e+" market")}else{let i=this.safeList(c.info,"orderTypes",[]);if(!0===u&&(i=["LIMIT","MARKET"]),!this.inArray(V,i))if(g!==V)throw new o.InvalidOrder(this.id+" triggerPrice parameter is not allowed for "+e+" "+t+" orders");else throw new o.InvalidOrder(this.id+" "+t+" is not a valid order type for the "+e+" market")}let G="newClientOrderId";q&&(G="newClientStrategyId"),f?G="clientAlgoId":!0===u&&(G="clientOrderId"),void 0===m?w[G]=this.generateClientOrderId(c):w[G]=m,k?(h=this.isPostOnly(v,"LIMIT_MAKER"===g,T))&&(!0!==c.contract?V="LIMIT_MAKER":w.timeInForce="GTX"):(h=this.isPostOnly(v,"LIMIT_MAKER"===g,T),(!0===c.spot||"margin"===l)&&(h&&(V="LIMIT_MAKER"),"isolated"===O&&(w.isIsolated=!0))),"spot"!==l&&"margin"!==l||k||!0===u?!0!==u&&(w.newOrderRespType="RESULT"):w.newOrderRespType=this.safeString(this.options.newOrderRespType,t,"FULL");let H="type";q&&(H="strategyType"),!0===u&&(H="orderType"),w[H]=V;let U=this.safeBool(T,"closePosition",!1),W=!1,j=!1,K=!1,z=!1;if("MARKET"===V)if(!0===u)if("BUY"===b){let e,t=this.safeNumber(c.precision,"price"),i=this.safeString2(T,"quoteOrderQty","cost");if(void 0!==i)e=i;else if(void 0!==r){let t=this.numberToString(s),i=this.numberToString(r);e=n.Y.stringMul(t,i)}else e=this.numberToString(s);void 0===t?w.notional=e:w.notional=this.decimalToPrecision(e,0,t,this.precisionMode)}else void 0!==this.safeString(c.precision,"amount")?w.quantity=this.amountToPrecision(e,s):w.quantity=this.parseToNumeric(s);else if(!0===c.spot)if(!0===this.handleOption("createOrder","quoteOrderQty",!0)){let e=this.safeString2(T,"quoteOrderQty","cost"),t=this.safeNumber(c.precision,"price");if(void 0!==e)w.quoteOrderQty=this.decimalToPrecision(e,0,t,this.precisionMode);else if(void 0!==r){let e=this.numberToString(s),i=this.numberToString(r),a=n.Y.stringMul(e,i);w.quoteOrderQty=this.decimalToPrecision(a,0,t,this.precisionMode)}else z=!0}else z=!0;else z=!0;else if("LIMIT"===V)!0===u&&(w.tradingSession=this.safeString(T,"tradingSession","24H")),j=!0,W=!0,z=!0;else if("STOP_LOSS"===V||"TAKE_PROFIT"===V)K=!0,z=!0,(!0===c.linear||!0===c.inverse)&&F&&(j=!0);else if("STOP_LOSS_LIMIT"===V||"TAKE_PROFIT_LIMIT"===V)z=!0,K=!0,j=!0,W=!0;else if("LIMIT_MAKER"===V)j=!0,z=!0;else if("STOP"===V)z=!0,K=!0,j=!0;else if("STOP_MARKET"===V||"TAKE_PROFIT_MARKET"===V)!0!==U&&(z=!0),K=!0;else if("TRAILING_STOP_MARKET"===V&&(!0!==U&&(z=!0),void 0===B))throw new o.InvalidOrder(this.id+" createOrder() requires a trailingPercent param for a "+t+" order");if(z&&(void 0!==this.safeString(c.precision,"amount")?w.quantity=this.amountToPrecision(e,s):w.quantity=this.parseToNumeric(s)),j&&void 0===E){if(void 0===r)throw new o.InvalidOrder(this.id+" createOrder() requires a price argument for a "+t+" order");void 0!==this.safeString(c.precision,"price")?w.price=this.priceToPrecision(e,r):w.price=this.parseToNumeric(r)}if(K){if(!0===c.contract){if(void 0===d)throw new o.InvalidOrder(this.id+" createOrder() requires a triggerPrice extra param for a "+t+" order")}else if(void 0===_&&void 0===d&&void 0===B)throw new o.InvalidOrder(this.id+" createOrder() requires a triggerPrice, trailingDelta or trailingPercent param for a "+t+" order");void 0!==d&&(f?w.triggerPrice=this.priceToPrecision(e,d):w.stopPrice=this.priceToPrecision(e,d))}W&&void 0===this.safeString(T,"timeInForce")&&void 0===this.safeString(w,"timeInForce")&&(w.timeInForce=this.handleOption("createOrder","timeInForce")),!k&&!0===c.contract&&h&&(w.timeInForce="GTX"),"PO"===this.safeString(T,"timeInForce")&&P.push("timeInForce");let Y=this.safeBool(T,"hedged",!1);if(!0!==c.spot&&!0!==c.option&&!0===Y){let e=i;!0===I&&(P.push("reduceOnly"),e="buy"===i?"sell":"buy"),w.positionSide="buy"===e?"LONG":"SHORT"}let[X,Q]=this.handleOptionStringAndParams(T,"createOrder","selfTradePrevention");if(void 0!==X){let e=this.handleOption("createOrder","warnOnSTPForInverse");if(!0===c.inverse&&!0===e)throw new o.NotSupported(this.id+' createOrder() selfTradePrevention is not supported for inverse markets. selfTradePrevention for inverse markets is taken from linear market. To disable this warning set the .options["createOrder"]["warnOnSTPForInverse"] to false.');w.selfTradePreventionMode=X.toUpperCase()}let Z=this.safeNumber(T,"icebergAmount");void 0!==Z&&!0===c.spot&&(w.icebergQty=this.amountToPrecision(e,Z));let J=this.omit(Q,P);return this.extend(w,J)}async createMarketOrderWithCost(e,t,i,s={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new o.NotSupported(this.id+" createMarketOrderWithCost() supports spot orders only");return await this.createOrder(e,"market",t,i,void 0,this.extend({cost:i},s))}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new o.NotSupported(this.id+" createMarketBuyOrderWithCost() supports spot orders only");return await this.createOrder(e,"market","buy",t,void 0,this.extend({cost:t},i))}async createMarketSellOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new o.NotSupported(this.id+" createMarketSellOrderWithCost() supports spot orders only");return i.quoteOrderQty=t,await this.createOrder(e,"market","sell",t,void 0,i)}async fetchOrder(e,t,i={}){let s,r,a,n,d,h,c,l;void 0===this.markets&&await this.loadMarkets();let u={};if([r,a]=this.handleOptionBoolAndParams(i,"fetchOrder","stock",!1),void 0!==t)s=this.market(t),!0!==(r=this.safeBool(s,"stock",!1))&&(u.symbol=s.id);else throw new o.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");[n,a]=this.handleMarketTypeAndParams("fetchOrder",s,a,"spot"),[d,a]=this.handleSubTypeAndParams("fetchOrder",s,a),[h,a]=this.handleMarginModeAndParams("fetchOrder",a),[c,a]=this.handleOptionBoolAndParams2(a,"fetchOrder","papi","portfolioMargin",!1);let f=this.safeBoolN(a,["stop","trigger","conditional"]),p="option"===n,m=this.isLinear(n,d),g=this.isInverse(n,d),v=(m||g)&&!0===f&&!0!==c,y=this.safeStringN(a,["origClientOrderId","clientOrderId","clientAlgoId"]);if(void 0!==y?p?u.clientOrderId=y:!0===v?u.clientAlgoId=y:u.origClientOrderId=y:!0===v?u.algoId=e:u.orderId=e,a=this.omit(a,["clientOrderId","origClientOrderId","stop","trigger","conditional","clientAlgoId"]),p?l=await this.eapiPrivateGetOrder(this.extend(u,a)):m?l=c?await this.papiGetUmOrder(this.extend(u,a)):!0===f?await this.fapiPrivateGetAlgoOrder(this.extend(u,a)):await this.fapiPrivateGetOrder(this.extend(u,a)):g?l=c?await this.papiGetCmOrder(this.extend(u,a)):!0===f?await this.dapiPrivateGetAlgoOrder(this.extend(u,a)):await this.dapiPrivateGetOrder(this.extend(u,a)):"margin"===n||void 0!==h||c?c?l=await this.papiGetMarginOrder(this.extend(u,a)):("isolated"===h&&(u.isIsolated=!0),l=await this.sapiGetMarginOrder(this.extend(u,a))):l=!0===r?await this.sapiGetEquityOrderDetail(this.extend(u,a)):await this.privateGetOrder(this.extend(u,a)),void 0===l)throw new o.NullResponse(this.id+" parseOrder() returned empty response");return this.parseOrder(l,s)}async fetchOrders(e,t,i,s={}){let r,a,n,d,h,c,l,u;void 0===this.markets&&await this.loadMarkets();let f=!1;if([f,r]=this.handleOptionBoolAndParams(s,"fetchOrders","paginate",!1),f)return await this.fetchPaginatedCallDynamic("fetchOrders",e,t,i,r);let p={};[n,r]=this.handleOptionBoolAndParams(r,"fetchOrders","stock",!1),void 0!==e&&(a=this.market(e),n=this.safeBool(a,"stock",!1),p.symbol=a.id),[d,r]=this.handleMarketTypeAndParams("fetchOrders",a,r,"spot"),[h,r]=this.handleSubTypeAndParams("fetchOrders",a,r),[c,r]=this.handleMarginModeAndParams("fetchOrders",r),[l,r]=this.handleOptionBoolAndParams2(r,"fetchOrders","papi","portfolioMargin",!1);let m=this.safeBoolN(r,["stop","trigger","conditional"]),g="option"===d,v=this.isLinear(d,h),y=this.isInverse(d,h);if(void 0===e&&!(!0===n||v&&!0!==m&&!0!==l))throw new o.ArgumentsRequired(this.id+" fetchOrders() requires a symbol argument");let b=this.safeIntegerN(r,["until","till","endTime"]);r=this.omit(r,["stop","trigger","conditional","until","till","endTime"]),void 0!==t&&(p.startTime=t);let w=i;if(void 0!==i&&!0===n&&(w=Math.min(i,100)),void 0!==w&&(!0===n?p.size=w:p.limit=w),void 0!==b&&(p.endTime=b),!0===n&&(void 0===b&&(p.endTime=b=this.milliseconds()),void 0===t&&(p.startTime=b-6048e5)),g?u=await this.eapiPrivateGetHistoryOrders(this.extend(p,r)):v?u=l?!0===m?await this.papiGetUmConditionalAllOrders(this.extend(p,r)):await this.papiGetUmAllOrders(this.extend(p,r)):!0===m?await this.fapiPrivateGetAllAlgoOrders(this.extend(p,r)):await this.fapiPrivateGetAllOrders(this.extend(p,r)):y?u=l?!0===m?await this.papiGetCmConditionalAllOrders(this.extend(p,r)):await this.papiGetCmAllOrders(this.extend(p,r)):!0===m?await this.dapiPrivateGetAllAlgoOrders(this.extend(p,r)):await this.dapiPrivateGetAllOrders(this.extend(p,r)):l?u=await this.papiGetMarginAllOrders(this.extend(p,r)):"margin"===d||void 0!==c?("isolated"===c&&(p.isIsolated=!0),u=await this.sapiGetMarginAllOrders(this.extend(p,r))):u=!0===n?await this.sapiGetEquityOrderHistory(this.extend(p,r)):await this.privateGetAllOrders(this.extend(p,r)),!0===n){let e=this.safeList(u,"rows",[]);return this.parseOrders(e,a,t,w)}return this.parseOrders(u,a,t,w)}async fetchOpenOrders(e,t,i,s={}){let r,a,n,d,h,c,l,u;void 0===this.markets&&await this.loadMarkets();let f={};[n,d]=this.handleMarginModeAndParams("fetchOpenOrders",s),[h,d]=this.handleOptionBoolAndParams2(d,"fetchOpenOrders","papi","portfolioMargin",!1);let p=this.safeBoolN(d,["stop","trigger","conditional"]);if([c,d]=this.handleOptionBoolAndParams(d,"fetchOpenOrders","stock",!1),void 0!==e)r=this.market(e),!0!==(c=this.safeBool(r,"stock",!1))&&(f.symbol=r.id);else if(!c){let e=this.safeBool(this.options.fetchOpenOrders,"warnWithoutSymbol"),t=this.safeBool(this.options,"warnOnFetchOpenOrdersWithoutSymbol");if(!0===t||void 0===t&&!0===e)throw new o.ExchangeError(this.id+" fetchOpenOrders() WARNING: fetching open orders without specifying a symbol has stricter rate limits (10 times more for spot, 40 times more for other markets) compared to requesting with symbol argument. To acknowledge this warning, set "+this.id+'.options["fetchOpenOrders"]["warnWithoutSymbol"] = false to suppress this warning message.')}if([a,d]=this.handleMarketTypeAndParams("fetchOpenOrders",r,d,"spot"),[l,d]=this.handleSubTypeAndParams("fetchOpenOrders",r,d),d=this.omit(d,["stop","trigger","conditional"]),"option"===a)void 0!==t&&(f.startTime=t),void 0!==i&&(f.limit=i),u=await this.eapiPrivateGetOpenOrders(this.extend(f,d));else if(this.isLinear(a,l))u=h?!0===p?await this.papiGetUmConditionalOpenOrders(this.extend(f,d)):await this.papiGetUmOpenOrders(this.extend(f,d)):!0===p?await this.fapiPrivateGetOpenAlgoOrders(this.extend(f,d)):await this.fapiPrivateGetOpenOrders(this.extend(f,d));else if(this.isInverse(a,l))u=h?!0===p?await this.papiGetCmConditionalOpenOrders(this.extend(f,d)):await this.papiGetCmOpenOrders(this.extend(f,d)):!0===p?await this.dapiPrivateGetOpenAlgoOrders(this.extend(f,d)):await this.dapiPrivateGetOpenOrders(this.extend(f,d));else if("margin"===a||void 0!==n||h)if(h)u=await this.papiGetMarginOpenOrders(this.extend(f,d));else{if("isolated"===n&&(f.isIsolated=!0,void 0===e))throw new o.ArgumentsRequired(this.id+" fetchOpenOrders() requires a symbol argument for isolated markets");u=await this.sapiGetMarginOpenOrders(this.extend(f,d))}else u=!0===c?await this.sapiGetEquityOrderOpenOrders(this.extend(f,d)):await this.privateGetOpenOrders(this.extend(f,d));return this.parseOrders(u,r,t,i)}async fetchOpenOrder(e,t,i={}){let s;if(void 0===t)throw new o.ArgumentsRequired(this.id+" fetchOpenOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),a={symbol:r.id},[n,d]=this.handleOptionBoolAndParams2(i,"fetchOpenOrder","papi","portfolioMargin",!1),h=this.safeBoolN(d,["stop","trigger","conditional"]),c=this.omit(d,["stop","trigger","conditional"]);if(!0===h&&!n&&(!0===r.swap||!0===r.future))throw new o.NotSupported(this.id+" fetchOpenOrder() does not support conditional orders, use fetchOrder() or fetchOpenOrders() with the trigger param instead");let l="orderId";if(!0===(n&&h)&&(l="strategyId"),a[l]=e,!0===r.linear)s=n?!0===h?await this.papiGetUmConditionalOpenOrder(this.extend(a,c)):await this.papiGetUmOpenOrder(this.extend(a,c)):await this.fapiPrivateGetOpenOrder(this.extend(a,c));else if(!0===r.inverse)s=n?!0===h?await this.papiGetCmConditionalOpenOrder(this.extend(a,c)):await this.papiGetCmOpenOrder(this.extend(a,c)):await this.dapiPrivateGetOpenOrder(this.extend(a,c));else if(!0===r.option)throw new o.NotSupported(this.id+" fetchOpenOrder() does not support option markets");else if(!0===r.spot)throw new o.NotSupported(this.id+" fetchOpenOrder() does not support spot markets");if(void 0===s)throw new o.NullResponse(this.id+" parseOrder() returned empty response");return this.parseOrder(s,r)}async fetchClosedOrders(e,t,i,s={}){let r,a,n;if([a,n]=this.handleOptionBoolAndParams(s,"fetchClosedOrders","stock",!1),void 0!==e)r=this.market(e),a=this.safeBool(r,"stock",!1);else if(!a)throw new o.ArgumentsRequired(this.id+" fetchClosedOrders() requires a symbol argument");!0===a&&(n.stock=!0,n.orderStatus="FILLED");let d=await this.fetchOrders(e,t,void 0,n),h=this.filterBy(d,"status","closed");return this.filterBySinceLimit(h,t,i)}async fetchCanceledOrders(e,t,i,s={}){let r,a,n;if([a,n]=this.handleOptionBoolAndParams(s,"fetchCanceledOrders","stock",!1),void 0!==e)r=this.market(e),a=this.safeBool(r,"stock",!1);else if(!a)throw new o.ArgumentsRequired(this.id+" fetchCanceledOrders() requires a symbol argument");!0===a&&(n.stock=!0,n.orderStatus="CANCELED");let d=await this.fetchOrders(e,t,void 0,n),h=this.filterBy(d,"status","canceled");return this.filterBySinceLimit(h,t,i)}async fetchCanceledAndClosedOrders(e,t,i,s={}){let r,a,n;if([a,n]=this.handleOptionBoolAndParams(s,"fetchCanceledAndClosedOrders","stock",!1),void 0!==e)r=this.market(e),a=this.safeBool(r,"stock",!1);else if(!a)throw new o.ArgumentsRequired(this.id+" fetchCanceledAndClosedOrders() requires a symbol argument");!0===a&&(n.stock=!0,n.orderStatus="FILLED,CANCELED");let d=await this.fetchOrders(e,t,void 0,n),h=this.filterBy(d,"status","canceled"),c=this.filterBy(d,"status","closed"),l=this.arrayConcat(h,c),u=this.sortBy(l,"timestamp");return this.filterBySinceLimit(u,t,i)}async cancelOrder(e,t,i={}){let s,r,a,n,d,h,c,l;void 0===this.markets&&await this.loadMarkets();let u={};if([r,a]=this.handleOptionBoolAndParams(i,"cancelOrder","stock",!1),void 0!==t)s=this.market(t),!0!==(r=this.safeBool(s,"stock",!1))&&(u.symbol=s.id);else throw new o.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");[n,a]=this.handleMarketTypeAndParams("cancelOrder",s,a,"spot"),[d,a]=this.handleSubTypeAndParams("cancelOrder",s,a),[h,a]=this.handleMarginModeAndParams("cancelOrder",a),[c,a]=this.handleOptionBoolAndParams2(a,"cancelOrder","papi","portfolioMargin",!1);let f=this.safeBoolN(a,["stop","trigger","conditional"]),p="option"===n,m=this.isLinear(n,d),g=this.isInverse(n,d),v=void 0!==s&&(!0===s.swap||!0===s.future)&&!0===f&&!0!==c,y=this.safeStringN(a,["origClientOrderId","clientOrderId","newClientStrategyId","clientAlgoId"]);if(void 0!==y?p?u.clientOrderId=y:!0===v?u.clientAlgoId=y:c&&!0===f?u.newClientStrategyId=y:u.origClientOrderId=y:c&&!0===f?u.strategyId=e:!0===v?u.algoId=e:u.orderId=e,a=this.omit(a,["origClientOrderId","clientOrderId","newClientStrategyId","stop","trigger","conditional","clientAlgoId"]),p?l=await this.eapiPrivateDeleteOrder(this.extend(u,a)):m?l=c?!0===f?await this.papiDeleteUmConditionalOrder(this.extend(u,a)):await this.papiDeleteUmOrder(this.extend(u,a)):!0===f?await this.fapiPrivateDeleteAlgoOrder(this.extend(u,a)):await this.fapiPrivateDeleteOrder(this.extend(u,a)):g?l=c?!0===f?await this.papiDeleteCmConditionalOrder(this.extend(u,a)):await this.papiDeleteCmOrder(this.extend(u,a)):!0===f?await this.dapiPrivateDeleteAlgoOrder(this.extend(u,a)):await this.dapiPrivateDeleteOrder(this.extend(u,a)):"margin"===n||void 0!==h||c?c?l=await this.papiDeleteMarginOrder(this.extend(u,a)):("isolated"===h&&(u.isIsolated=!0),l=await this.sapiDeleteMarginOrder(this.extend(u,a))):l=!0===r?await this.sapiPostEquityOrderCancel(this.extend(u,a)):await this.privateDeleteOrder(this.extend(u,a)),void 0===l)throw new o.NullResponse(this.id+" parseOrder() returned empty response");return this.parseOrder(l,s)}async cancelAllOrders(e,t={}){let i,s,r,a,n,d,h,c;void 0===this.markets&&await this.loadMarkets();let l={};if([s,r]=this.handleOptionBoolAndParams(t,"cancelAllOrders","stock",!1),void 0!==e)i=this.market(e),!0!==(s=this.safeBool(i,"stock",!1))&&(l.symbol=i.id);else throw new o.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument");[a,r]=this.handleOptionBoolAndParams2(r,"cancelAllOrders","papi","portfolioMargin",!1);let u=this.safeBoolN(r,["stop","trigger","conditional"]);[n,r]=this.handleMarketTypeAndParams("cancelAllOrders",i,r,"spot"),[d,r]=this.handleSubTypeAndParams("cancelAllOrders",i,r);let f="option"===n,p=this.isLinear(n,d),m=this.isInverse(n,d);return r=this.omit(r,["stop","trigger","conditional"]),[h,r]=this.handleMarginModeAndParams("cancelAllOrders",r),(f?c=await this.eapiPrivateDeleteAllOpenOrders(this.extend(l,r)):p?c=a?!0===u?await this.papiDeleteUmConditionalAllOpenOrders(this.extend(l,r)):await this.papiDeleteUmAllOpenOrders(this.extend(l,r)):!0===u?await this.fapiPrivateDeleteAlgoOpenOrders(this.extend(l,r)):await this.fapiPrivateDeleteAllOpenOrders(this.extend(l,r)):m?c=a?!0===u?await this.papiDeleteCmConditionalAllOpenOrders(this.extend(l,r)):await this.papiDeleteCmAllOpenOrders(this.extend(l,r)):!0===u?await this.dapiPrivateDeleteAlgoOpenOrders(this.extend(l,r)):await this.dapiPrivateDeleteAllOpenOrders(this.extend(l,r)):"margin"===n||void 0!==h||a?a?c=await this.papiDeleteMarginAllOpenOrders(this.extend(l,r)):("isolated"===h&&(l.isIsolated=!0),c=await this.sapiDeleteMarginOpenOrders(this.extend(l,r))):c=!0===s?await this.sapiPostEquityOrderCancelAll(this.extend(l,r)):await this.privateDeleteOpenOrders(this.extend(l,r)),Array.isArray(c))?this.parseOrders(c,i):[this.safeOrder({info:c})]}async cancelOrders(e,t,i={}){let s;if(void 0===t)throw new o.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t);if(!0!==r.contract)throw new o.BadRequest(this.id+" cancelOrders is only supported for swap markets.");let a={symbol:r.id},n=this.safeList2(i,"origClientOrderIdList","clientOrderIds"),d=void 0!==n?this.omit(i,["clientOrderIds"]):i;return void 0!==n?a.origClientOrderIdList=n:a.orderidlist=e,!0===r.linear?s=await this.fapiPrivateDeleteBatchOrders(this.extend(a,d)):!0===r.inverse&&(s=await this.dapiPrivateDeleteBatchOrders(this.extend(a,d))),this.parseOrders(s,r)}async fetchOrderTrades(e,t,i,s,r={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" fetchOrderTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let a=this.market(t),n=this.safeString(r,"type",a.type),d=this.omit(r,"type");if("spot"!==n)throw new o.NotSupported(this.id+" fetchOrderTrades() supports spot markets only");return await this.fetchMyTrades(t,i,s,this.extend({orderId:e},d))}async fetchMyTrades(e,t,i,s={}){let r,a,n,d,h,c;void 0===this.markets&&await this.loadMarkets();let l=!1;if([l,r]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1),l)return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,r);let u={};if([h,r]=this.handleOptionBoolAndParams(r,"fetchMyTrades","stock",!1),void 0!==e&&(a=this.market(e),h=this.safeBool(a,"stock",!1),u.symbol=a.id),[n,r]=this.handleMarketTypeAndParams("fetchMyTrades",a,r),!0!==h&&"option"!==n&&void 0===e)throw new o.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");let f=this.safeInteger2(r,"until","endTime");if(void 0!==t){u.startTime=t;let e=this.milliseconds();e-t>=6048e5&&void 0===f&&this.safeBool(a,"linear",!1)&&(f=Math.min(void 0===(f=this.sum(t,6048e5))?0:f,e))}void 0!==f&&(u.endTime=f,r=this.omit(r,["endTime","until"]));let p="option"===n||this.safeBool(a,"contract",!1),m=i;void 0!==i&&p&&(m=Math.min(i,1e3));let g=m;if(void 0!==m&&!0===h&&(g=Math.min(m,100)),void 0!==g&&(!0===h?u.size=g:u.limit=g),"option"===n)c=await this.eapiPrivateGetUserTrades(this.extend(u,r));else{let e;[d,r]=this.handleMarginModeAndParams("fetchMyTrades",r),[e,r]=this.handleOptionBoolAndParams2(r,"fetchMyTrades","papi","portfolioMargin",!1),!0===h?(void 0===f&&(u.endTime=f=this.milliseconds()),void 0===t&&(u.startTime=f-6048e5),c=await this.sapiGetEquityTradeHistory(this.extend(u,r))):"spot"===n||"margin"===n?e?c=await this.papiGetMarginMyTrades(this.extend(u,r)):"margin"===n||void 0!==d?("isolated"===d&&(u.isIsolated=!0),c=await this.sapiGetMarginMyTrades(this.extend(u,r))):c=await this.privateGetMyTrades(this.extend(u,r)):this.safeBool(a,"linear",!1)?c=e?await this.papiGetUmUserTrades(this.extend(u,r)):await this.fapiPrivateGetUserTrades(this.extend(u,r)):this.safeBool(a,"inverse",!1)&&(c=e?await this.papiGetCmUserTrades(this.extend(u,r)):await this.dapiPrivateGetUserTrades(this.extend(u,r)))}let v=[];return void 0!==c&&(v=!0===h?this.safeList(c,"rows",[]):this.toArray(c)),this.parseTrades(v,a,t,g)}async fetchMyDustTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={};void 0!==t&&(r.startTime=t,r.endTime=this.sum(t,7776e6));let a=this.safeStringUpper(s,"type"),o=this.omit(s,"type");void 0!==a&&(r.accountType=a);let n=await this.sapiGetAssetDribblet(this.extend(r,o)),d=this.safeList(n,"userAssetDribblets",[]),h=this.safeInteger(n,"total",0),c=[];for(let e=0;e<h;e++){let t=this.safeList(d[e],"userAssetDribbletDetails",[]);for(let e=0;e<t.length;e++)t[e].isDustTrade=!0,c.push(t[e])}let l=this.parseTrades(c,void 0,t,i);return this.filterBySinceLimit(l,t,i)}parseDustTrade(e,t){let i,s,r,a,o,d=this.safeString(e,"transId"),h=this.safeInteger(e,"operateTime"),c=this.safeString(e,"fromAsset"),l=this.safeCurrencyCode(c),u=this.currency("BNB").code,f=u+"/"+l,p=!1;void 0!==this.markets&&f in this.markets&&(p=!0);let m=this.safeString(e,"serviceChargeAmount"),g={currency:u,cost:this.parseNumber(m)};p?(i=f,s=this.safeString(e,"transferedAmount"),r=this.safeString(e,"amount"),a="buy"):(i=l+"/"+u,s=this.safeString(e,"amount"),r=this.safeString(e,"transferedAmount"),a="sell"),void 0!==r&&void 0!==s&&""!==s&&(o=n.Y.stringDiv(r,s));let v=this.parseNumber(s),y=this.parseNumber(o),b=this.parseNumber(r);return{id:void 0,timestamp:h,datetime:this.iso8601(h),symbol:i,order:d,type:void 0,takerOrMaker:void 0,side:a,amount:v,price:y,cost:b,fee:g,info:e}}async fetchDeposits(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOptionBoolAndParams(s,"fetchDeposits","paginate",!1);if(n)return await this.fetchPaginatedCallDynamic("fetchDeposits",e,t,i,d);let h={},c=this.safeDict(this.options,"legalMoney",{}),l=this.safeBool(d,"fiat",!1),u=this.omit(d,"fiatOnly"),f=this.safeInteger(u,"until"),p=this.omit(u,"until");if(!0===l||void 0!==e&&e in c){void 0!==e&&(r=this.currency(e)),h.transactionType=0,void 0!==t&&(h.beginTime=t),void 0!==f&&(h.endTime=f);let i=await this.sapiGetFiatOrders(this.extend(h,p));a=this.safeList(i,"data",[])}else{if(void 0!==e&&(h.coin=(r=this.currency(e)).id),void 0!==t){h.startTime=t;let e=this.sum(t,7776e6);void 0!==f&&(e=Math.min(e,f)),h.endTime=e}void 0!==i&&(h.limit=i),a=await this.sapiGetCapitalDepositHisrec(this.extend(h,p))}if(void 0===a)throw new o.NullResponse(this.id+" method() returned empty response");let m=[];void 0!==a&&(m=this.toArray(a));for(let e=0;e<m.length;e++)m[e].type="deposit";return this.parseTransactions(m,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r,a,n;void 0===this.markets&&await this.loadMarkets();let d=!1;if([d,r]=this.handleOptionBoolAndParams(s,"fetchWithdrawals","paginate",!1),d)return await this.fetchPaginatedCallDynamic("fetchWithdrawals",e,t,i,r);let h=this.safeDict(this.options,"legalMoney",{}),c=this.safeBool(r,"fiat",!1);r=this.omit(r,"fiatOnly");let l={},u=this.safeInteger(r,"until");if(void 0!==u&&(r=this.omit(r,"until"),l.endTime=u),!0===c||void 0!==e&&e in h){void 0!==e&&(n=this.currency(e)),l.transactionType=1,void 0!==t&&(l.beginTime=t);let i=await this.sapiGetFiatOrders(this.extend(l,r));a=this.safeList(i,"data",[])}else void 0!==e&&(l.coin=(n=this.currency(e)).id),void 0!==t&&(l.startTime=t,l.endTime=this.sum(t,7776e6)),void 0!==i&&(l.limit=i),a=await this.sapiGetCapitalWithdrawHistory(this.extend(l,r));if(void 0===a)throw new o.NullResponse(this.id+" method() returned empty response");"string"==typeof a&&(a=this.parseJson(a));let f=[];void 0!==a&&(f=this.toArray(a));for(let e=0;e<f.length;e++)f[e].type="withdrawal";return this.parseTransactions(f,n,t,i)}parseTransactionStatusByType(e,t){if(void 0===t)return e;let i=this.safeDict({deposit:{0:"pending",1:"ok",6:"ok",Processing:"pending",Failed:"failed",Successful:"ok",Refunding:"canceled",Refunded:"canceled","Refund Failed":"failed"},withdrawal:{0:"pending",1:"canceled",2:"pending",3:"failed",4:"pending",5:"failed",6:"ok",Processing:"pending",Failed:"failed",Successful:"ok",Refunding:"canceled",Refunded:"canceled","Refund Failed":"failed"}},t,{});return this.safeString(i,e,e)}parseTransaction(e,t){let i,s,r,a=this.safeString2(e,"id","orderNo"),o=this.safeString(e,"address"),n=this.safeString(e,"addressTag");void 0!==n&&n.length<1&&(n=void 0);let d=this.safeString(e,"txId");void 0!==d&&d.indexOf("Internal transfer ")>=0&&(d=d.slice(18));let h=this.safeString2(e,"coin","fiatCurrency"),c=this.safeCurrencyCode(h,t);void 0===(i=this.safeInteger2(e,"insertTime","createTime"))&&(i=this.parse8601(this.safeString(e,"applyTime")));let l=this.safeInteger2(e,"successTime","updateTime"),u=this.safeString(e,"type");if(void 0===u){let t=this.safeString(e,"transactionType");void 0!==t&&(u="0"===t?"deposit":"withdrawal");let i=this.safeDict(this.options,"legalMoneyCurrenciesById");c=this.safeString(i,c,c)}let f=this.parseTransactionStatusByType(this.safeString(e,"status"),u),p=this.safeNumber(e,"amount"),m=this.safeNumber2(e,"transactionFee","totalFee");void 0!==m&&(s={currency:c,cost:m});let g=this.safeInteger(e,"transferType");void 0!==g&&(r=0!==g);let v=this.safeString(e,"network"),y=this.networkIdToCode(v,c);return{info:e,id:a,txid:d,timestamp:i,datetime:this.iso8601(i),network:y,address:o,addressTo:o,addressFrom:void 0,tag:n,tagTo:n,tagFrom:void 0,type:u,amount:p,currency:c,status:f,updated:l,internal:r,comment:void 0,fee:s}}parseTransferStatus(e){return this.safeString({CONFIRMED:"ok"},e,e)}parseTransfer(e,t){let i,s,r=this.safeString2(e,"tranId","transactionId"),a=this.safeString2(e,"asset","currency"),o=this.safeCurrencyCode(a,t),n=this.safeNumber(e,"amount"),d=this.safeString(e,"type"),h=this.safeDict(this.options,"accountsById",{});if(void 0!==d){let e=d.split("_");i=this.safeString(e,0),s=this.safeString(e,1),i=this.safeString(h,i,i),s=this.safeString(h,s,s)}if(void 0!==this.safeInteger(e,"walletType")){let t=this.safeDict(e,"payerInfo",{}),r=this.safeDict(e,"receiverInfo",{});i=this.safeString(t,"accountId"),s=this.safeString(r,"accountId")}let c=this.safeInteger2(e,"timestamp","transactionTime"),l=this.parseTransferStatus(this.safeString(e,"status"));return{info:e,id:r,timestamp:c,datetime:this.iso8601(c),currency:o,amount:n,fromAccount:i,toAccount:s,status:l}}parseIncome(e,t){let i=this.safeString(e,"symbol"),s=this.safeString(e,"asset"),r=this.safeInteger(e,"time");return{info:e,symbol:this.safeSymbol(i,t,void 0,"swap"),code:this.safeCurrencyCode(s),timestamp:r,datetime:this.iso8601(r),id:this.safeString(e,"tranId"),amount:this.safeNumber(e,"income")}}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(e),n={asset:a.id,amount:this.currencyToPrecision(e,t)};n.type=this.safeString(r,"type");let d=this.omit(r,"type");if(void 0===n.type){let e,t,r=this.safeString(d,"symbol");void 0!==r&&(e=this.market(r),d=this.omit(d,"symbol"));let a=this.convertTypeToAccount(i).toUpperCase(),h=this.convertTypeToAccount(s).toUpperCase();if(void 0!==e&&(t=e.id),"ISOLATED"===a&&void 0===r)throw new o.ArgumentsRequired(this.id+' transfer () requires params["symbol"] when fromAccount is '+i);if("ISOLATED"===h&&void 0===r)throw new o.ArgumentsRequired(this.id+' transfer () requires params["symbol"] when toAccount is '+s);let c=this.safeDict(this.options,"accountsById",{}),l=!(a in c),u=!(h in c);if(l&&void 0===e&&(t=a),u&&void 0===e&&(t=h),l||u){let e="UMFUTURE"===a||"CMFUTURE"===a,r="UMFUTURE"===h||"CMFUTURE"===h,d="MAIN"===a,c="MAIN"===h,f="FUNDING"===a||"FUNDING"===h,p="OPTION"===a||"OPTION"===h;if((l||u)&&(e||r||f||p))throw new o.BadRequest(this.id+" transfer () does not allow transfers between "+i+" and "+s);c&&l?(a="ISOLATED_MARGIN",n.fromSymbol=t):d&&u?(h="ISOLATED_MARGIN",n.toSymbol=t):l&&u?(n.fromSymbol=a,n.toSymbol=h,a="ISOLATEDMARGIN",h="ISOLATEDMARGIN"):(l&&(n.fromSymbol=t,a="ISOLATEDMARGIN"),u&&(n.toSymbol=t,h="ISOLATEDMARGIN")),n.type=a+"_"+h}else n.type=a+"_"+h}let h=await this.sapiPostAssetTransfer(this.extend(n,d));return this.parseTransfer(h,a)}async fetchTransfers(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let n=this.safeBool(s,"internal"),d=this.omit(s,"internal"),h=!1;if([h,d]=this.handleOptionBoolAndParams(d,"fetchTransfers","paginate",!1),h&&!0!==n)return await this.fetchPaginatedCallDynamic("fetchTransfers",e,t,i,d);void 0!==e&&(r=this.currency(e));let c={},l="limit";if(!0!==n){let e=this.safeString2(this.options,"fetchTransfers","defaultType","spot"),t=this.safeString(d,"fromAccount",e),i="future";"future"===t&&(i="spot");let s=this.safeString(d,"toAccount",i),r=this.safeString(d,"type"),a=this.safeDict(this.options,"accountsByType",{}),n=this.safeString(a,t),h=this.safeString(a,s);if(void 0===r){if(void 0===n){let e=Object.keys(a);throw new o.ExchangeError(this.id+" fromAccount parameter must be one of "+e.join(", "))}if(void 0===h){let e=Object.keys(a);throw new o.ExchangeError(this.id+" toAccount parameter must be one of "+e.join(", "))}r=n+"_"+h}c.type=r,l="size"}void 0!==i&&(c[l]=i),void 0!==t&&(c.startTime=t);let u=this.safeInteger(d,"until");void 0!==u&&(d=this.omit(d,"until"),c.endTime=u),a=!0===n?await this.sapiGetPayTransactions(this.extend(c,d)):await this.sapiGetAssetTransfer(this.extend(c,d));let f=this.safeList2(a,"rows","data",[]);return this.parseTransfers(f,r,t,i)}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={coin:i.id},[r,a]=this.handleNetworkCodeAndParams(t);void 0!==r&&(s.network=this.networkCodeToId(r,this.safeString(i,"code")));let o=await this.sapiGetCapitalDepositAddress(this.extend(s,a));return this.parseDepositAddress(o,i)}parseDepositAddress(e,t){let i=this.safeString(e,"url"),s=this.safeString(e,"address"),r=this.safeString(e,"currency"),a=this.safeCurrencyCode(r,t),o=this.getNetworkCodeByNetworkUrl(a,i),n=this.safeString(e,"tag","");return 0===n.length&&(n=void 0),this.checkAddress(s),{info:e,currency:a,network:o,address:s,tag:n}}async fetchTransactionFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.sapiGetCapitalConfigGetall(t),s={},r=this.toArray(i);for(let e=0;e<r.length;e++){let t=this.safeDict(r,e),i=this.safeString(t,"coin"),a=this.safeCurrencyCode(i),o=this.safeList(t,"networkList",[]);void 0!==a&&(s[a]={});for(let e=0;e<o.length;e++){let t=this.safeDict(o,e),i=this.safeString(t,"network"),r=this.safeCurrencyCode(i),n=this.safeNumber(t,"withdrawFee");void 0!==a&&void 0!==r&&(s[a][r]=n)}}return{withdraw:s,deposit:{},info:i}}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.sapiGetCapitalConfigGetall(t);return this.parseDepositWithdrawFees(i,e,"coin")}parseDepositWithdrawFee(e,t){let i=this.safeString(t,"code"),s=this.safeList(e,"networkList",[]),r=this.depositWithdrawFee(e);for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),a=this.safeString(t,"network"),o=this.networkIdToCode(a,i),n=this.safeNumber(t,"withdrawFee");!0===this.safeBool(t,"isDefault")&&(r.withdraw={fee:n,percentage:void 0}),void 0!==o&&(r.networks[o]={withdraw:{fee:n,percentage:void 0},deposit:{fee:void 0,percentage:void 0}})}return r}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d={coin:n.id,address:i};void 0!==a&&(d.addressTag=a);let[h,c]=this.handleNetworkCodeAndParams(o);void 0!==h&&(d.network=this.networkCodeToId(h,this.safeString(n,"code"))),d.amount=this.currencyToPrecision(n.code,t,h);let l=await this.sapiPostCapitalWithdrawApply(this.extend(d,c));return this.parseTransaction(l,n)}parseTradingFee(e,t){let i=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(i,t,void 0,"spot"),maker:this.safeNumber2(e,"makerCommission","makerCommissionRate"),taker:this.safeNumber2(e,"takerCommission","takerCommissionRate"),percentage:void 0,tierBased:void 0}}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.type,[r,a]=this.handleSubTypeAndParams("fetchTradingFee",i,t),[n,d]=this.handleOptionBoolAndParams2(a,"fetchTradingFee","papi","portfolioMargin",!1),h=this.isLinear(s,r),c=this.isInverse(s,r),l={symbol:i.id},u=h?n?await this.papiGetUmCommissionRate(this.extend(l,d)):await this.fapiPrivateGetCommissionRate(this.extend(l,d)):c?n?await this.papiGetCmCommissionRate(this.extend(l,d)):await this.dapiPrivateGetCommissionRate(this.extend(l,d)):await this.sapiGetAssetTradeFee(this.extend(l,d));if(Array.isArray(u)&&(u=this.safeDict(u,0,{})),void 0===u)throw new o.NullResponse(this.id+" parseTradingFee() returned empty response");return this.parseTradingFee(u,i)}async fetchTradingFees(e={}){let t;void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleMarketTypeAndParams("fetchTradingFees",void 0,e),[r,a]=this.handleSubTypeAndParams("fetchTradingFees",void 0,s,"linear"),n="spot"===i||"margin"===i,d=this.isLinear(i,r),h=this.isInverse(i,r);if(n?t=await this.sapiGetAssetTradeFee(a):d?t=await this.fapiPrivateGetAccountConfig(a):h&&(t=await this.dapiPrivateGetAccount(a)),n){let e={};if(void 0===t)throw new o.NullResponse(this.id+" method() returned empty response");let i=this.toArray(t);for(let t=0;t<i.length;t++){let s=this.parseTradingFee(i[t]),r=s.symbol;void 0!==r&&(e[r]=s)}return e}if(d){let e=this.markets;if(void 0===e)throw new o.ExchangeError(this.id+" markets not loaded");let i=Object.keys(e),s={},r=this.safeInteger(t,"feeTier"),a=this.fees.linear.trading.tiers,n=a.maker[r][1],d=a.taker[r][1];for(let t=0;t<i.length;t++){let a=i[t],o=e[a];this.safeBool(o,"linear",!1)&&(s[a]={info:{feeTier:r},symbol:a,maker:n,taker:d})}return s}if(h){let e=this.markets;if(void 0===e)throw new o.ExchangeError(this.id+" markets not loaded");let i=Object.keys(e),s={},r=this.safeInteger(t,"feeTier"),a=this.fees.inverse.trading.tiers,n=a.maker[r][1],d=a.taker[r][1];for(let t=0;t<i.length;t++){let a=i[t],o=e[a];this.safeBool(o,"inverse",!1)&&(s[a]={info:{feeTier:r},symbol:a,maker:n,taker:d})}return s}throw new o.NotSupported(this.id+" fetchTradingFees() is not supported for "+i+" markets")}async futuresTransfer(e,t,i,s={}){if(i<1||i>4)throw new o.ArgumentsRequired(this.id+" type must be between 1 and 4");void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),a={asset:r.id,amount:t,type:i},n=await this.sapiPostFuturesTransfer(this.extend(a,s));return this.parseTransfer(n,r)}async fetchFundingRate(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};if(!0===s.linear)i=await this.fapiPublicGetPremiumIndex(this.extend(r,t));else if(!0===s.inverse)i=await this.dapiPublicGetPremiumIndex(this.extend(r,t));else throw new o.NotSupported(this.id+" fetchFundingRate() supports linear and inverse contracts only");if(void 0===i)throw new o.NullResponse(this.id+" fetchFundingRate() returned empty response");return!0===s.inverse&&(i=i[0]),this.parseFundingRate(i,s)}async fetchFundingRateHistory(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let n={},[d,h]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(d)return await this.fetchPaginatedCallDeterministic("fetchFundingRateHistory",e,t,i,"8h",h);let c=this.safeString2(this.options,"fetchFundingRateHistory","defaultType","future"),l=this.safeString(h,"type",c);void 0!==e&&(n.symbol=(r=this.market(e)).id);let[u,f]=this.handleSubTypeAndParams("fetchFundingRateHistory",r,h,"linear"),p=this.omit(f,"type");void 0!==t&&(n.startTime=t);let m=this.safeInteger(p,"until"),g=this.safeInteger(p,"endTime",m),v=this.omit(p,["endTime","until"]);if(void 0!==g&&(n.endTime=g),void 0!==i&&(n.limit=i),this.isLinear(l,u))a=await this.fapiPublicGetFundingRate(this.extend(n,v));else if(this.isInverse(l,u))a=await this.dapiPublicGetFundingRate(this.extend(n,v));else throw new o.NotSupported(this.id+" fetchFundingRateHistory() is not supported for "+l+" markets");return this.parseFundingRateHistories(a,r,t,i)}parseFundingRateHistory(e,t){let i=this.safeInteger(e,"fundingTime");return{info:e,symbol:this.safeSymbol(this.safeString(e,"symbol"),void 0,void 0,"swap"),fundingRate:this.safeNumber(e,"fundingRate"),timestamp:i,datetime:this.iso8601(i)}}async fetchFundingRates(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e),r=this.safeString2(this.options,"fetchFundingRates","defaultType","future"),a=this.safeString(t,"type",r),[n,d]=this.handleSubTypeAndParams("fetchFundingRates",void 0,t,"linear"),h=this.omit(d,"type");if(this.isLinear(a,n))i=await this.fapiPublicGetPremiumIndex(h);else if(this.isInverse(a,n))i=await this.dapiPublicGetPremiumIndex(h);else throw new o.NotSupported(this.id+" fetchFundingRates() supports linear and inverse contracts only");return this.parseFundingRates(i,s)}parseFundingRate(e,t){let i,s=this.safeInteger(e,"time"),r=this.safeString(e,"symbol"),a=this.safeSymbol(r,t,void 0,"contract"),o=this.safeNumber(e,"markPrice"),n=this.safeNumber(e,"indexPrice"),d=this.safeNumber(e,"interestRate"),h=this.safeNumber(e,"estimatedSettlePrice"),c=this.safeNumber(e,"lastFundingRate"),l=this.safeInteger(e,"nextFundingTime"),u=this.safeString(e,"fundingIntervalHours");return void 0!==u&&(i=u+"h"),{info:e,symbol:a,markPrice:o,indexPrice:n,interestRate:d,estimatedSettlePrice:h,timestamp:s,datetime:this.iso8601(s),fundingRate:c,fundingTimestamp:l,fundingDatetime:this.iso8601(l),nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:i}}parseAccountPositions(e,t=!1){let i=this.safeList(e,"positions",[]),s=this.safeList(e,"assets",[]),r={};for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),i=this.safeString(t,"asset"),a=this.safeCurrencyCode(i),o=this.safeString(t,"crossWalletBalance"),d=this.safeString(t,"crossUnPnl");void 0!==a&&(r[a]={crossMargin:n.Y.stringAdd(o,d),crossWalletBalance:o})}let a=[];for(let e=0;e<i.length;e++){let s=i[e],o=this.safeString(s,"symbol"),n=this.safeMarket(o,void 0,void 0,"contract"),d=!0===n.linear?n.quote:n.base,h=this.safeString(s,"maintMargin"),c="0"!==h&&"0.00000000"!==h;if((!t||c)&&d in r){let e=this.parseAccountPosition(this.extend(s,{crossMargin:r[d].crossMargin,crossWalletBalance:r[d].crossWalletBalance}),n);a.push(e)}}return a}parseAccountPosition(e,t){let i,s,r,a,d,h,c,l,u,f,p=this.safeString(e,"symbol"),m=this.safeMarket(p,t,void 0,"contract"),g=this.safeString(m,"symbol"),v=this.omitZero(this.safeString(e,"leverage")),y=void 0!==v?parseInt(v):void 0,b=this.safeString(e,"initialMargin"),w=this.parseNumber(b);if(void 0!==v){if(i=n.Y.stringDiv("1",v,8),void 0===y)throw new o.ExchangeError(this.id+" method() missing leverage");this.isRoundNumber(1e3%y)||(i=n.Y.stringDiv(n.Y.stringAdd(i,"1e-8"),"1",8))}let k="notional"in e,S=this.safeString(e,"maintMargin"),O=this.parseNumber(S),T=this.safeString(e,"entryPrice"),P=this.parseNumber(T),I=this.safeString2(e,"notional","notionalValue"),A=n.Y.stringAbs(I),x=this.parseNumber(A),M=this.safeString(e,"positionAmt"),_=n.Y.stringAbs(M);if(void 0===M){let e=n.Y.stringMul(n.Y.stringMul(v,b),T),t=this.safeString(m,"contractSize");M=n.Y.stringDiv(e,t),_=n.Y.stringDiv(n.Y.stringAdd(M,"0.5"),"1",0)}let C=this.parseNumber(_),B=this.safeDict(this.options,"leverageBrackets",{}),E=this.safeList(B,g,[]);for(let e=0;e<E.length;e++){let t=E[e];if(n.Y.stringLt(A,t[0]))break;s=this.safeString(t,1)}let R=this.parseNumber(s),L=this.safeString(e,"unrealizedProfit"),N=this.parseNumber(L),D=this.safeInteger(e,"updateTime");0===D&&(D=void 0);let q=this.safeBool(e,"isolated");if(void 0===q){let t=this.safeString(e,"isolatedMargin");q=!n.Y.stringEq(t,"0")}q?(r="isolated",d=this.safeString(e,"isolatedWallet"),a=n.Y.stringAdd(d,L)):(r="cross",d=this.safeString(e,"crossWalletBalance"),a=this.safeString(e,"crossMargin"));let F=this.parseNumber(a),V=this.safeNumber(m,"contractSize"),G=this.numberToString(V);if(n.Y.stringEquals(I,"0"))P=void 0;else{if(c=n.Y.stringLt(I,"0")?"short":"long",h=this.parseNumber(n.Y.stringDiv(n.Y.stringAdd(n.Y.stringDiv(S,a),"5e-5"),"1",4)),l=this.parseNumber(n.Y.stringMul(n.Y.stringDiv(L,b,4),"100")),k){let e,t=T;"short"===c?e=n.Y.stringAdd("1",s):(e=n.Y.stringAdd("-1",s),t=n.Y.stringMul("-1",t));let i=n.Y.stringDiv(d,n.Y.stringMul(_,e)),r=n.Y.stringDiv(t,e);u=n.Y.stringAdd(i,r)}else{let e,t=T;"short"===c?e=n.Y.stringSub("1",s):(e=n.Y.stringSub("-1",s),t=n.Y.stringMul("-1",t));let i=n.Y.stringMul(_,G),r=n.Y.stringMul(i,e),a=n.Y.stringSub(n.Y.stringMul(n.Y.stringDiv("1",t),i),d);u=n.Y.stringDiv(r,a)}let e=this.precisionFromString(this.safeString(m.precision,"price")),t=(e+1).toString(),i=new n.Y("5e-"+t).toString(),r=n.Y.stringAdd(i,u),o=n.Y.stringDiv(r,"1",e);void 0!==o&&"-"===o[0]&&(o=void 0),f=this.parseNumber(o)}let H=this.safeString(e,"positionSide");return{info:e,id:void 0,symbol:g,timestamp:D,datetime:this.iso8601(D),initialMargin:w,initialMarginPercentage:this.parseNumber(i),maintenanceMargin:O,maintenanceMarginPercentage:R,entryPrice:P,notional:x,leverage:this.parseNumber(v),unrealizedPnl:N,contracts:C,contractSize:V,marginRatio:h,liquidationPrice:f,markPrice:void 0,collateral:F,marginMode:r,side:c,hedged:"BOTH"!==H,percentage:l}}parsePositionRisk(e,t){let i,s,r,a,o,d,h,c=this.safeString(e,"symbol"),l=this.safeMarket(c,t,void 0,"contract"),u=this.safeString(l,"symbol"),f=this.safeString(e,"isolatedMargin"),p=this.safeDict(this.options,"leverageBrackets",{}),m=this.safeList(p,u,[]),g=this.safeString2(e,"notional","notionalValue"),v=n.Y.stringAbs(g);for(let e=0;e<m.length;e++){let t=m[e];if(n.Y.stringLt(v,t[0]))break;i=this.safeString(t,1)}let y=this.parseNumber(v),b=n.Y.stringAbs(this.safeString(e,"positionAmt")),w=this.parseNumber(b),k=this.safeString(e,"unRealizedProfit"),S=this.parseNumber(k),O=this.omitZero(this.safeString(e,"liquidationPrice")),T=this.parseNumber(O),P=this.safeString(e,"marginType");void 0===P&&void 0!==f&&(P=n.Y.stringEq(f,"0")?"cross":"isolated"),n.Y.stringGt(g,"0")?r="long":n.Y.stringLt(g,"0")&&(r="short");let I=this.safeString(e,"entryPrice"),A=this.parseNumber(I),x=this.safeNumber(l,"contractSize"),M=this.numberToString(x),_="notional"in e;if("cross"===P){let e=this.safeDict(l,"precision",{}),t=this.safeString(e,"base"),a=this.safeString2(e,"quote","price");if(void 0!==t||void 0!==a)if(_){let t,a=I;"short"===r?(t=n.Y.stringAdd("1",i),a=n.Y.stringMul("-1",a)):t=n.Y.stringAdd("-1",i);let o=n.Y.stringMul(O,t),d=n.Y.stringAdd(o,a),h=this.precisionFromString(this.safeString2(e,"quote","price"));s=n.Y.stringDiv(n.Y.stringMul(d,b),"1",h)}else{let t,a=I;"short"===r?t=n.Y.stringSub("1",i):(t=n.Y.stringSub("-1",i),a=n.Y.stringMul("-1",a));let o=n.Y.stringMul(b,M),d=n.Y.stringSub(n.Y.stringDiv("1",a),n.Y.stringDiv(t,O)),h=this.precisionFromString(this.safeString(e,"base"));s=n.Y.stringDiv(n.Y.stringMul(o,d),"1",h)}}else s=this.safeString(e,"isolatedMargin");s=void 0===s?"0":s;let C=this.parseNumber(s),B=this.parseNumber(this.omitZero(this.safeString(e,"markPrice"))),E=this.safeInteger(e,"updateTime");0===E&&(E=void 0);let R=this.parseNumber(i),L=n.Y.stringMul(i,v);void 0===L&&(L=this.safeString(e,"maintMargin"));let N=this.parseNumber(L),D=this.omitZero(this.safeString(e,"leverage"));if(void 0!==D){let e=parseInt(D),t=this.isRoundNumber(1e3%e);o=n.Y.stringDiv("1",D,8),t||(o=n.Y.stringAdd(o,"1e-8"));let i=n.Y.stringMul(v,o);a=n.Y.stringDiv(i,"1",8)}else{a=this.safeString(e,"initialMargin");let t=n.Y.stringMul(a,"1");o=n.Y.stringDiv(t,v,8)}n.Y.stringEquals(s,"0")||(d=this.parseNumber(n.Y.stringDiv(n.Y.stringAdd(n.Y.stringDiv(L,s),"5e-5"),"1",4)),h=this.parseNumber(n.Y.stringMul(n.Y.stringDiv(k,a,4),"100")));let q=this.safeString(e,"positionSide");return this.safePosition({info:e,id:void 0,symbol:u,contracts:w,contractSize:x,unrealizedPnl:S,leverage:this.parseNumber(D),liquidationPrice:T,collateral:C,notional:y,markPrice:B,entryPrice:A,timestamp:E,initialMargin:this.parseNumber(a),initialMarginPercentage:this.parseNumber(o),maintenanceMargin:N,maintenanceMarginPercentage:R,marginRatio:d,datetime:this.iso8601(E),marginMode:P,side:r,hedged:"BOTH"!==q,percentage:h,stopLossPrice:void 0,takeProfitPrice:void 0})}async loadLeverageBrackets(e=!1,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===this.safeDict(this.options,"leverageBrackets")||e){let e,i,s,r,a=this.safeString(this.options,"defaultType","future"),n=this.safeString(t,"type",a),d=this.omit(t,"type");if([e,i]=this.handleSubTypeAndParams("loadLeverageBrackets",void 0,t,"linear"),[s,i]=this.handleOptionBoolAndParams2(i,"loadLeverageBrackets","papi","portfolioMargin",!1),this.isLinear(n,e))r=s?await this.papiGetUmLeverageBracket(d):await this.fapiPrivateGetLeverageBracket(d);else if(this.isInverse(n,e))r=s?await this.papiGetCmLeverageBracket(d):await this.dapiPrivateV2GetLeverageBracket(d);else throw new o.NotSupported(this.id+" loadLeverageBrackets() supports linear and inverse contracts only");if(this.options.leverageBrackets=this.createSafeDictionary(),void 0===r)throw new o.NullResponse(this.id+" loadLeverageBrackets() returned empty response");let h=this.toArray(r);for(let e=0;e<h.length;e++){let t=this.safeDict(h,e),i=this.safeString(t,"symbol"),s=this.safeSymbol(i,void 0,void 0,"contract"),r=this.safeList(t,"brackets",[]),a=[];for(let e=0;e<r.length;e++){let t=this.safeDict(r,e),i=this.safeString2(t,"notionalFloor","qtyFloor"),s=this.safeString(t,"maintMarginRatio");a.push([i,s])}this.options.leverageBrackets[s]=a}}return this.options.leverageBrackets}async fetchLeverageTiers(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleMarketTypeAndParams("fetchLeverageTiers",void 0,t),[a,n]=this.handleSubTypeAndParams("fetchLeverageTiers",void 0,r,"linear"),[d,h]=this.handleOptionBoolAndParams2(n,"fetchLeverageTiers","papi","portfolioMargin",!1);if(this.isLinear(s,a))i=d?await this.papiGetUmLeverageBracket(h):await this.fapiPrivateGetLeverageBracket(h);else if(this.isInverse(s,a))i=d?await this.papiGetCmLeverageBracket(h):await this.dapiPrivateV2GetLeverageBracket(h);else throw new o.NotSupported(this.id+" fetchLeverageTiers() supports linear and inverse contracts only");return this.parseLeverageTiers(i,e,"symbol")}parseMarketLeverageTiers(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t,void 0,"contract"),r=this.safeList(e,"brackets",[]),a=[];for(let e=0;e<r.length;e++){let t=r[e];a.push({tier:this.safeNumber(t,"bracket"),symbol:this.safeSymbol(i,s),currency:s.quote,minNotional:this.safeNumber2(t,"notionalFloor","qtyFloor"),maxNotional:this.safeNumber2(t,"notionalCap","qtyCap"),maintenanceMarginRate:this.safeNumber(t,"maintMarginRatio"),maxLeverage:this.safeNumber(t,"initialLeverage"),info:t})}return a}async fetchPosition(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.option)throw new o.NotSupported(this.id+" fetchPosition() supports option markets only");let s={symbol:i.id},r=await this.eapiPrivateGetPosition(this.extend(s,t));return this.parseOptionPosition(this.safeDict(r,0,{}),i)}async fetchOptionPositions(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e),r={};if(void 0!==s){let e;if(Array.isArray(s)){if(s.length>1)throw new o.BadRequest(this.id+" fetchPositions() symbols argument cannot contain more than 1 symbol");e=s[0]}else e=s;r.symbol=(i=this.market(e)).id}let a=await this.eapiPrivateGetPosition(this.extend(r,t)),n=[],d=this.toArray(a);for(let e=0;e<d.length;e++)n.push(this.parseOptionPosition(d[e],i));return this.filterByArrayPositions(n,"symbol",s)}parseOptionPosition(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t,void 0,"swap").symbol,r=this.safeStringLower(e,"side"),a=this.safeString(e,"quantity");"long"!==r&&(a=n.Y.stringMul("-1",a));let o=this.safeInteger(e,"time");return this.safePosition({info:e,id:void 0,symbol:s,entryPrice:this.safeNumber(e,"entryPrice"),markPrice:this.safeNumber(e,"markPrice"),notional:this.safeNumber(e,"markValue"),collateral:this.safeNumber(e,"positionCost"),unrealizedPnl:this.safeNumber(e,"unrealizedPNL"),side:r,contracts:this.parseNumber(a),contractSize:void 0,timestamp:o,datetime:this.iso8601(o),hedged:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,initialMargin:void 0,initialMarginPercentage:void 0,leverage:void 0,liquidationPrice:void 0,marginRatio:void 0,marginMode:void 0,percentage:void 0})}async fetchPositions(e,t={}){let i,s;if([i,s]=this.handleOptionStringAndParams(t,"fetchPositions","method"),void 0===i&&(i=void 0===this.safeDict(this.options,"fetchPositions")?this.safeString(this.options,"fetchPositions","positionRisk"):"positionRisk"),"positionRisk"===i)return await this.fetchPositionsRisk(e,s);if("account"===i)return await this.fetchAccountPositions(e,s);if("option"===i)return await this.fetchOptionPositions(e,s);throw new o.NotSupported(this.id+'.options["fetchPositions"]["method"] or params["method"] = "'+i+'" is invalid, please choose between "account", "positionRisk" and "option"')}async fetchAccountPositions(e,t={}){let i;if(void 0!==e&&!Array.isArray(e))throw new o.ArgumentsRequired(this.id+" fetchPositions() requires an array argument for symbols");void 0===this.markets&&await this.loadMarkets(),await this.loadLeverageBrackets(!1,t);let s=this.safeString(this.options,"defaultType","future"),r=this.safeString(t,"type",s),a=this.omit(t,"type"),[n,d]=this.handleSubTypeAndParams("fetchAccountPositions",void 0,a,"linear"),[h,c]=this.handleOptionBoolAndParams2(d,"fetchAccountPositions","papi","portfolioMargin",!1);if(this.isLinear(r,n))if(h)i=await this.papiV2GetUmAccount(c);else{let[e,t]=this.handleOptionBoolAndParams(c,"fetchAccountPositions","useV2",!1);i=e?await this.fapiPrivateV2GetAccount(t):await this.fapiPrivateV3GetAccount(t)}else if(this.isInverse(r,n))i=h?await this.papiGetCmAccount(c):await this.dapiPrivateGetAccount(c);else throw new o.NotSupported(this.id+" fetchPositions() supports linear and inverse contracts only");let l=this.handleOptionBoolAndParams(c,"fetchAccountPositions","filterClosed",!1)[0],u=this.parseAccountPositions(i,l),f=this.marketSymbols(e);return this.filterByArrayPositions(u,"symbol",f)}async fetchPositionsRisk(e,t={}){let i,s,r,a;if(void 0!==e&&!Array.isArray(e))throw new o.ArgumentsRequired(this.id+" fetchPositionsRisk() requires an array argument for symbols");void 0===this.markets&&await this.loadMarkets(),await this.loadLeverageBrackets(!1,t);let d={},h="future";h=this.safeString(this.options,"defaultType",h);let c=this.safeString(t,"type",h);if([i,s]=this.handleSubTypeAndParams("fetchPositionsRisk",void 0,t,"linear"),[r,s]=this.handleOptionBoolAndParams2(s,"fetchPositionsRisk","papi","portfolioMargin",!1),s=this.omit(s,"type"),this.isLinear(c,i))if(r)a=await this.papiGetUmPositionRisk(this.extend(d,s));else{let e;[e,s]=this.handleOptionBoolAndParams(s,"fetchPositionsRisk","useV2",!1),s=this.extend(d,s),a=e?await this.fapiPrivateV2GetPositionRisk(s):await this.fapiPrivateV3GetPositionRisk(s)}else if(this.isInverse(c,i))a=r?await this.papiGetCmPositionRisk(this.extend(d,s)):await this.dapiPrivateGetPositionRisk(this.extend(d,s));else throw new o.NotSupported(this.id+" fetchPositionsRisk() supports linear and inverse contracts only");let l=[];if(void 0===a)throw new o.NullResponse(this.id+" method() returned empty response");let u=this.toArray(a);for(let e=0;e<u.length;e++){let t=u[e],i=this.safeString(t,"entryPrice");n.Y.stringGt(i,"0")&&l.push(this.parsePositionRisk(t))}let f=this.marketSymbols(e);return this.filterByArrayPositions(l,"symbol",f)}async fetchFundingHistory(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let n={incomeType:"FUNDING_FEE"};if(void 0!==e&&(n.symbol=(r=this.market(e)).id,!0!==r.swap))throw new o.NotSupported(this.id+" fetchFundingHistory() supports swap contracts only");let[d,h]=this.handleSubTypeAndParams("fetchFundingHistory",r,s,"linear"),[c,l]=this.handleOptionBoolAndParams2(h,"fetchFundingHistory","papi","portfolioMargin",!1),[u,f]=this.handleUntilOption("endTime",n,l);void 0!==t&&(u.startTime=t),void 0!==i&&(u.limit=i);let p=this.safeString2(this.options,"fetchFundingHistory","defaultType","future"),m=this.safeString(f,"type",p),g=this.omit(f,"type");if(this.isLinear(m,d))a=c?await this.papiGetUmIncome(this.extend(u,g)):await this.fapiPrivateGetIncome(this.extend(u,g));else if(this.isInverse(m,d))a=c?await this.papiGetCmIncome(this.extend(u,g)):await this.dapiPrivateGetIncome(this.extend(u,g));else throw new o.NotSupported(this.id+" fetchFundingHistory() supports linear and inverse contracts only");return this.parseIncomes(a,r,t,i)}async setLeverage(e,t,i={}){let s;if(void 0===t)throw new o.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");if(e<1||e>125)throw new o.BadRequest(this.id+" leverage should be between 1 and 125");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),a={symbol:r.id,leverage:e},[n,d]=this.handleOptionBoolAndParams2(i,"setLeverage","papi","portfolioMargin",!1);if(!0===r.linear)s=n?await this.papiPostUmLeverage(this.extend(a,d)):await this.fapiPrivatePostLeverage(this.extend(a,d));else if(!0===r.inverse)s=n?await this.papiPostCmLeverage(this.extend(a,d)):await this.dapiPrivatePostLeverage(this.extend(a,d));else throw new o.NotSupported(this.id+" setLeverage() supports linear and inverse contracts only");if(void 0===s)throw new o.NullResponse(this.id+" setLeverage() returned empty response");return s}async setMarginMode(e,t,i={}){let s;if(void 0===t)throw new o.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");let r=e.toUpperCase();if("CROSS"===r&&(r="CROSSED"),"ISOLATED"!==r&&"CROSSED"!==r)throw new o.BadRequest(this.id+" marginMode must be either isolated or cross");void 0===this.markets&&await this.loadMarkets();let a=this.market(t),n={symbol:a.id,marginType:r};try{if(!0===a.linear)s=await this.fapiPrivatePostMarginType(this.extend(n,i));else if(!0===a.inverse)s=await this.dapiPrivatePostMarginType(this.extend(n,i));else throw new o.NotSupported(this.id+" setMarginMode() supports linear and inverse contracts only")}catch(e){if(e instanceof o.MarginModeAlreadySet){if(!0===this.handleOption("setMarginMode","throwMarginModeAlreadySet",!1))throw e;s={code:-4046,msg:"No need to change margin type."}}else throw e}if(void 0===s)throw new o.NullResponse(this.id+" setMarginMode() returned empty response");return s}async setPositionMode(e,t,i={}){let s,r;void 0!==t&&(s=this.market(t));let[a,n]=this.handleMarketTypeAndParams("setPositionMode",s,i),[d,h]=this.handleSubTypeAndParams("setPositionMode",s,n),[c,l]=this.handleOptionBoolAndParams2(h,"setPositionMode","papi","portfolioMargin",!1),u={dualSidePosition:e?"true":"false"};if(this.isInverse(a,d))r=c?await this.papiPostCmPositionSideDual(this.extend(u,l)):await this.dapiPrivatePostPositionSideDual(this.extend(u,l));else if(this.isLinear(a,d))r=c?await this.papiPostUmPositionSideDual(this.extend(u,l)):await this.fapiPrivatePostPositionSideDual(this.extend(u,l));else throw new o.BadRequest(this.id+" setPositionMode() supports linear and inverse contracts only");if(void 0===r)throw new o.NullResponse(this.id+" setPositionMode() returned empty response");return r}async fetchLeverages(e,t={}){let i;void 0===this.markets&&await this.loadMarkets(),await this.loadLeverageBrackets(!1,t);let[s,r]=this.handleMarketTypeAndParams("fetchLeverages",void 0,t),[a,n]=this.handleSubTypeAndParams("fetchLeverages",void 0,r,"linear"),[d,h]=this.handleOptionBoolAndParams2(n,"fetchLeverages","papi","portfolioMargin",!1);if(this.isLinear(s,a))i=d?await this.papiGetUmAccount(h):await this.fapiPrivateGetSymbolConfig(h);else if(this.isInverse(s,a))i=d?await this.papiGetCmAccount(h):await this.dapiPrivateGetAccount(h);else throw new o.NotSupported(this.id+" fetchLeverages() supports linear and inverse contracts only");let c=this.safeList(i,"positions",[]);return Array.isArray(i)&&(c=i),this.parseLeverages(c,e,"symbol")}parseLeverage(e,t){let i,s,r,a=this.safeString(e,"symbol"),o=this.safeBool(e,"isolated");void 0!==o&&(i=o?"isolated":"cross");let n=this.safeStringLower(e,"marginType");void 0!==n&&(i="crossed"===n?"cross":"isolated");let d=this.safeStringLower(e,"positionSide"),h=this.safeInteger(e,"leverage");return void 0===d||"both"===d?(s=h,r=h):"long"===d?s=h:"short"===d&&(r=h),{info:e,symbol:this.safeSymbol(a,t),marginMode:i,longLeverage:s,shortLeverage:r}}async fetchSettlementHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=void 0===e?void 0:this.market(e),[a,n]=this.handleMarketTypeAndParams("fetchSettlementHistory",r,s);if("option"!==a)throw new o.NotSupported(this.id+" fetchSettlementHistory() supports option markets only");let d={},h=void 0!==e?this.safeString(r,"symbol"):e;void 0!==e&&(d.underlying=this.safeString(r,"baseId","")+this.safeString(r,"quoteId","")),void 0!==t&&(d.startTime=t),void 0!==i&&(d.limit=i);let c=await this.eapiPublicGetExerciseHistory(this.extend(d,n)),l=this.parseSettlements(c,r),u=this.sortBy(l,"timestamp");return this.filterBySymbolSinceLimit(u,h,t,i)}async fetchMySettlementHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=void 0===e?void 0:this.market(e),[a,n]=this.handleMarketTypeAndParams("fetchMySettlementHistory",r,s);if("option"!==a)throw new o.NotSupported(this.id+" fetchMySettlementHistory() supports option markets only");let d={};void 0!==e&&(d.symbol=this.safeString(r,"id"));let h=void 0!==e?this.safeString(r,"symbol"):e;void 0!==t&&(d.startTime=t),void 0!==i&&(d.limit=i);let c=await this.eapiPrivateGetExerciseRecord(this.extend(d,n)),l=this.parseSettlements(c,r),u=this.sortBy(l,"timestamp");return this.filterBySymbolSinceLimit(u,h,t,i)}parseSettlement(e,t){let i=this.safeInteger2(e,"expiryDate","createDate"),s=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(s,t),price:this.safeNumber2(e,"realStrikePrice","exercisePrice"),timestamp:i,datetime:this.iso8601(i)}}parseSettlements(e,t){let i=[];for(let s=0;s<e.length;s++)i.push(this.parseSettlement(e[s],t));return i}async fetchLedgerEntry(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleMarketTypeAndParams("fetchLedgerEntry",void 0,i);if("option"!==s)throw new o.BadRequest(this.id+" fetchLedgerEntry() can only be used for type option");this.checkRequiredArgument("fetchLedgerEntry",t,"code");let a=this.currency(t),n={recordId:e,currency:a.id},d=await this.eapiPrivateGetBill(this.extend(n,r)),h=this.safeDict(d,0,d);return this.parseLedgerEntry(h,a)}async fetchLedger(e,t,i,s={}){let r,a,n,d,h,c;void 0===this.markets&&await this.loadMarkets();let l=!1;if([l,r]=this.handleOptionBoolAndParams(s,"fetchLedger","paginate",!1),l)return await this.fetchPaginatedCallDynamic("fetchLedger",e,t,i,r,void 0,!1);void 0!==e&&(d=this.currency(e));let u={};[a,r]=this.handleMarketTypeAndParams("fetchLedger",void 0,r),[n,r]=this.handleSubTypeAndParams("fetchLedger",void 0,r),void 0!==t&&(u.startTime=t),void 0!==i&&(u.limit=i);let f=this.safeInteger(r,"until");if(void 0!==f&&(r=this.omit(r,"until"),u.endTime=f),[h,r]=this.handleOptionBoolAndParams2(r,"fetchLedger","papi","portfolioMargin",!1),"option"===a){if(this.checkRequiredArgument("fetchLedger",e,"code"),void 0===d)throw new o.ExchangeError(this.id+" fetchLedger() could not resolve currency");u.currency=d.id,c=await this.eapiPrivateGetBill(this.extend(u,r))}else if(this.isLinear(a,n))c=h?await this.papiGetUmIncome(this.extend(u,r)):await this.fapiPrivateGetIncome(this.extend(u,r));else if(this.isInverse(a,n))c=h?await this.papiGetCmIncome(this.extend(u,r)):await this.dapiPrivateGetIncome(this.extend(u,r));else throw new o.NotSupported(this.id+" fetchLedger() supports contract wallets only");return this.parseLedger(c,d,t,i)}parseLedgerEntry(e,t){let i,s=this.safeString2(e,"amount","income");n.Y.stringLe(s,"0")?(i="out",s=n.Y.stringMul("-1",s)):i="in";let r=this.safeString(e,"asset"),a=this.safeCurrencyCode(r,t),o=this.safeCurrency(r,t),d=this.safeInteger2(e,"createDate","time"),h=this.safeString2(e,"type","incomeType");return this.safeLedgerEntry({info:e,id:this.safeString2(e,"id","tranId"),direction:i,account:void 0,referenceAccount:void 0,referenceId:this.safeString(e,"tradeId"),type:this.parseLedgerEntryType(h),currency:a,amount:this.parseNumber(s),timestamp:d,datetime:this.iso8601(d),before:void 0,after:void 0,status:void 0,fee:void 0},o)}parseLedgerEntryType(e){return this.safeString({FEE:"fee",FUNDING_FEE:"fee",SPECIAL_FUNDING_FEE:"fee",OPTIONS_PREMIUM_FEE:"fee",POSITION_LIMIT_INCREASE_FEE:"fee",CONTRACT:"trade",REALIZED_PNL:"trade",AUTO_EXCHANGE:"trade",TRANSFER:"transfer",CROSS_COLLATERAL_TRANSFER:"transfer",INTERNAL_TRANSFER:"transfer",STRATEGY_UMFUTURES_TRANSFER:"transfer",COIN_SWAP_DEPOSIT:"deposit",COIN_SWAP_WITHDRAW:"withdrawal",OPTIONS_SETTLE_PROFIT:"settlement",DELIVERED_SETTELMENT:"settlement",INSURANCE_CLEAR:"settlement",WELCOME_BONUS:"cashback",CONTEST_REWARD:"cashback",BFUSD_REWARD:"cashback",COMMISSION_REBATE:"rebate",API_REBATE:"rebate",FEE_RETURN:"rebate",REFERRAL_KICKBACK:"referral",COMMISSION:"commission"},e,e)}getNetworkCodeByNetworkUrl(e,t){let i;if(void 0===t)return;let s=this.currency(e),r=this.safeDict(s,"networks",{}),a=Object.keys(r);for(let e=0;e<a.length;e++){let s=a[e],o=this.safeDict(r[s],"info",{}),n=this.safeString(o,"contractAddressUrl"),d=this.getBaseDomainFromUrl(n);void 0!==n&&void 0!==d&&t.startsWith(d)&&(i=s)}return i}getBaseDomainFromUrl(e){if(void 0===e)return;let t=e.split("/"),i=this.safeString(t,0);if(void 0===i)return;let s=this.safeString(t,2);if(void 0!==s)return i+"//"+s+"/"}sign(e,t="public",i="GET",a={},n,c){let l,u;if(!(t in this.urls.api))throw new o.NotSupported(this.id+" does not have a testnet/sandbox URL for "+t+" endpoints");let f=this.safeString(this.urls.api,t);if(void 0===f)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let p=f;if(p+="/"+e,"historicalTrades"===e)if(void 0!==this.apiKey&&""!==this.apiKey)l={"X-MBX-APIKEY":this.apiKey};else throw new o.AuthenticationError(this.id+" historicalTrades endpoint requires `apiKey` credential");if("userDataStream"===e||"listenKey"===e||"userListenToken"===e)if(void 0!==this.apiKey&&""!==this.apiKey)l={"X-MBX-APIKEY":this.apiKey,"Content-Type":"application/x-www-form-urlencoded"},"GET"!==i&&(u=this.urlencode(a));else throw new o.AuthenticationError(this.id+" userDataStream endpoint requires `apiKey` credential");else if("private"===t||"eapiPrivate"===t||"sapi"===t&&"system/status"!==e||"sapiV2"===t||"sapiV3"===t||"sapiV4"===t||"dapiPrivate"===t||"dapiPrivateV2"===t||"fapiPrivate"===t||"fapiPrivateV2"===t||"fapiPrivateV3"===t||"papiV2"===t||"papi"===t&&"ping"!==e){let n,c;if(this.checkRequiredCredentials(),p.indexOf("testnet.binancefuture.com")>-1&&this.isSandboxModeEnabled&&!this.safeBool(this.options,"disableFuturesSandboxWarning",!1))throw new o.NotSupported(this.id+" testnet/sandbox mode is not supported for futures anymore, please check the deprecation announcement https://t.me/ccxt_announcements/92 and consider using the demo trading instead.");if("POST"===i&&("order"===e||"sor/order"===e)?void 0===this.safeString(a,"newClientOrderId")&&(a.newClientOrderId=this.generateClientOrderId(void 0,t)):"POST"===i&&"algoOrder"===e&&void 0===this.safeString(a,"clientAlgoId")&&(a.clientAlgoId=this.generateClientOrderId(void 0,t)),"batchOrders"===e&&("POST"===i||"PUT"===i)){let e=this.safeList(a,"batchOrders",[]),s=e;if("POST"===i&&("fapiPrivate"===t||"dapiPrivate"===t)){s=[];for(let i=0;i<e.length;i++){let r=e[i];void 0===this.safeString(r,"newClientOrderId")&&(r.newClientOrderId=this.generateClientOrderId(void 0,t)),s.push(r)}}a.batchOrders=this.json(s)}let f=this.safeInteger(this.options,"recvWindow"),m=this.extend({timestamp:this.nonce()},a);void 0!==f&&(m.recvWindow=f);let g=this.safeInteger(a,"recvWindow");if(void 0!==g&&(m.recvWindow=g),"sapi"===t&&"asset/dust"===e)n=this.urlencodeWithArrayRepeat(m);else if("batchOrders"===e||e.indexOf("sub-account")>=0||"capital/withdraw/apply"===e||e.indexOf("staking")>=0||e.indexOf("simple-earn")>=0)if("DELETE"===i&&"batchOrders"===e){let e=this.safeList(m,"orderidlist",[]),t=this.safeList2(m,"origclientorderidlist","origClientOrderIdList",[]);"symbol"in(m=this.omit(m,["orderidlist","origclientorderidlist","origClientOrderIdList"]))&&(m.symbol=this.encodeURIComponent(m.symbol)),n=this.rawencode(m);let i=e.length,s=t.length;if(i>0&&(n=n+"&orderidlist=%5B"+e.join("%2C")+"%5D"),s>0){let e=[];for(let i=0;i<s;i++)e.push("%22"+t[i]+"%22");n=n+"&origclientorderidlist=%5B"+e.join("%2C")+"%5D"}}else n=this.rawencode(m);else n=this.urlencode(m);c=this.secret.indexOf("PRIVATE KEY")>-1?this.secret.length>120?this.encodeURIComponent((0,d.n)(n,this.secret,s.sc)):this.encodeURIComponent((0,h.q4)(this.encode(n),this.secret,r.ev)):this.hmac(this.encode(n),this.encode(this.secret),s.sc),n+="&signature="+c,l={"X-MBX-APIKEY":this.apiKey},"GET"===i||"DELETE"===i?p+="?"+n:(u=n,l["Content-Type"]="application/x-www-form-urlencoded")}else Object.keys(a).length>0&&(p+="?"+this.urlencode(a));return{url:p,method:i,body:void 0!==u?u:c,headers:void 0!==l?l:n}}getExceptionsByUrl(e,t){let i;if(void 0===e)return{};let s=void 0!==this.hostname?this.hostname:"binance.com";if(e.startsWith("https://api."+s+"/")||e.startsWith("https://demo-api")||e.startsWith("https://testnet.binance.vision")?i="spot":e.startsWith("https://dapi."+s+"/")||e.startsWith("https://demo-dapi")||e.startsWith("https://testnet.binancefuture.com/dapi")?i="inverse":e.startsWith("https://fapi."+s+"/")||e.startsWith("https://demo-fapi")||e.startsWith("https://testnet.binancefuture.com/fapi")?i="linear":e.startsWith("https://eapi."+s+"/")?i="option":e.startsWith("https://papi."+s+"/")&&(i="portfolioMargin"),void 0!==i){let e=this.safeDict(this.exceptions,i,{});return this.safeDict(e,t,{})}return{}}handleErrors(e,t,i,s,r,a,d,h,c){let l;if(418===e||429===e)throw new o.DDoSProtection(this.id+" "+e.toString()+" "+t+" "+a);if(e>=400&&void 0!==a){if(a.indexOf("Price * QTY is zero or less")>=0)throw new o.InvalidOrder(this.id+" order cost = amount * price is zero or less "+a);if(a.indexOf("LOT_SIZE")>=0)throw new o.InvalidOrder(this.id+" order amount should be evenly divisible by lot size "+a);if(a.indexOf("PRICE_FILTER")>=0)throw new o.InvalidOrder(this.id+" order price is invalid, i.e. exceeds allowed price precision, exceeds min price or max price limits or is invalid value in general, use this.priceToPrecision (symbol, amount) "+a)}if(void 0===d)return;let u=this.safeBool(d,"success",!0);if(!0!==u){let e=this.safeString(d,"msg");if(void 0!==e)try{l=JSON.parse(e)}catch(e){l=void 0}}let f=void 0!==l?l:d,p=this.safeString(f,"msg");void 0!==p&&(this.throwExactlyMatchedException(this.getExceptionsByUrl(i,"exact"),p,this.id+" "+p),this.throwExactlyMatchedException(this.exceptions.exact,p,this.id+" "+p),this.throwBroadlyMatchedException(this.getExceptionsByUrl(i,"broad"),p,this.id+" "+p),this.throwBroadlyMatchedException(this.exceptions.broad,p,this.id+" "+p));let m=this.safeString(f,"code");if(void 0!==m){if("200"===m||n.Y.stringEquals(m,"0"))return;if("-2015"===m&&this.safeBool(this.options,"hasAlreadyAuthenticatedSuccessfully",!1))throw new o.DDoSProtection(this.id+" "+a);let e=this.id+" "+a;if("No need to change margin type."===p)throw new o.MarginModeAlreadySet(e);throw this.throwExactlyMatchedException(this.getExceptionsByUrl(i,"exact"),m,e),this.throwExactlyMatchedException(this.exceptions.exact,m,e),new o.ExchangeError(e)}if(!0!==u)throw new o.ExchangeError(this.id+" "+a);if(Array.isArray(f)&&1===f.length){let e=this.safeDict(f,0),t=this.safeString(e,"code");void 0!==t&&(this.throwExactlyMatchedException(this.getExceptionsByUrl(i,"exact"),t,this.id+" "+a),this.throwExactlyMatchedException(this.exceptions.exact,t,this.id+" "+a))}}calculateRateLimiterCost(e,t,i,s,r={}){if("noCoin"in r&&!("coin"in s))return r.noCoin;if("noSymbol"in r&&!("symbol"in s))return r.noSymbol;if("noPoolId"in r&&!("poolId"in s))return r.noPoolId;if("byLimit"in r&&"limit"in s){let e=s.limit,t=this.safeValue(r,"byLimit");for(let i=0;i<t.length;i++){let s=t[i];if(e<=s[0])return s[1]}}return this.safeValue(r,"cost",1)}async request(e,t="public",i="GET",s={},r,a,o={}){let n=await this.fetch2(e,t,i,s,r,a,o);return"private"===t&&(this.options.hasAlreadyAuthenticatedSuccessfully=!0),n}async modifyMarginHelper(e,t,i,s={}){let r,a,n=this.safeString(this.options,"defaultType","future");"spot"===n&&(n="future");let d=this.safeString(s,"type",n);if("margin"===d||"spot"===d)throw new o.NotSupported(this.id+" add / reduce margin only supported with type future or delivery");void 0===this.markets&&await this.loadMarkets();let h=this.market(e),c=this.amountToPrecision(e,t),l={type:i,symbol:h.id,amount:c};if(!0===h.linear?(a=this.safeString(h,"quote"),r=await this.fapiPrivatePostPositionMargin(this.extend(l,s))):(a=this.safeString(h,"base"),r=await this.dapiPrivatePostPositionMargin(this.extend(l,s))),void 0===r)throw new o.NullResponse(this.id+" parseMarginModification() returned empty response");return this.extend(this.parseMarginModification(r,h),{code:a})}parseMarginModification(e,t){let i=this.safeInteger(e,"type"),s=this.safeString(e,"code"),r=this.safeString(e,"symbol"),a=this.safeInteger(e,"time");return{info:e,symbol:this.safeMarket(r,t,void 0,"swap").symbol,type:1===i?"add":"reduce",marginMode:"isolated",amount:this.safeNumber(e,"amount"),code:this.safeString(e,"asset"),total:void 0,status:"200"===s||void 0===s?"ok":"failed",timestamp:a,datetime:this.iso8601(a)}}async reduceMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,2,i)}async addMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,1,i)}async fetchCrossBorrowRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={asset:this.currency(e).id},s=await this.sapiGetMarginInterestRateHistory(this.extend(i,t)),r=this.safeDict(s,0);return this.parseBorrowRate(r)}async fetchIsolatedBorrowRate(e,t={}){let i=await this.fetchIsolatedBorrowRates(this.extend({symbol:e},t));return this.safeDict(i,e)}async fetchIsolatedBorrowRates(e={}){void 0===this.markets&&await this.loadMarkets();let t={},i=this.safeString(e,"symbol"),s=this.omit(e,"symbol");void 0!==i&&(t.symbol=this.market(i).id);let r=await this.sapiGetMarginIsolatedMarginData(this.extend(t,s));return this.parseIsolatedBorrowRates(r)}async fetchBorrowRateHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=void 0===i?93:i;if(void 0!==i&&i>93)throw new o.BadRequest(this.id+" fetchBorrowRateHistory() limit parameter cannot exceed 92");let a={asset:this.currency(e).id,limit:r};void 0!==t&&(a.startTime=t,a.endTime=Math.min(this.sum(t,864e5*r)-1,this.milliseconds()));let n=await this.sapiGetMarginInterestRateHistory(this.extend(a,s));return this.parseBorrowRateHistory(n,e,t,r)}parseBorrowRate(e,t){let i=this.safeInteger(e,"timestamp"),s=this.safeString(e,"asset");return{currency:this.safeCurrencyCode(s,t),rate:this.safeNumber(e,"dailyInterestRate"),period:864e5,timestamp:i,datetime:this.iso8601(i),info:e}}parseIsolatedBorrowRate(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t,void 0,"spot"),r=this.safeList(e,"data"),a=this.safeDict(r,0),o=this.safeDict(r,1);return{info:e,symbol:this.safeString(s,"symbol"),base:this.safeString(a,"coin"),baseRate:this.safeNumber(a,"dailyInterest"),quote:this.safeString(o,"coin"),quoteRate:this.safeNumber(o,"dailyInterest"),period:864e5,timestamp:void 0,datetime:void 0}}async createGiftCode(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={token:this.currency(e).id,amount:t},r=await this.sapiPostGiftcardCreateCode(this.extend(s,i)),a=this.safeDict(r,"data"),o=this.safeString(a,"code");return{info:r,id:this.safeString(a,"referenceNo"),code:o,currency:e,amount:t}}async redeemGiftCode(e,t={}){return await this.sapiPostGiftcardRedeemCode(this.extend({code:e},t))}async verifyGiftCode(e,t={}){return await this.sapiGetGiftcardVerify(this.extend({referenceNo:e},t))}async fetchBorrowInterest(e,t,i,s,r={}){let a,o;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOptionBoolAndParams2(r,"fetchBorrowInterest","papi","portfolioMargin",!1),h={};void 0!==e&&(h.asset=this.currency(e).id),void 0!==i&&(h.startTime=i),void 0!==s&&(h.size=s);let[c,l]=this.handleUntilOption("endTime",h,d);n?o=await this.papiGetMarginMarginInterestHistory(this.extend(c,l)):(void 0!==t&&(c.isolatedSymbol=(a=this.market(t)).id),o=await this.sapiGetMarginInterestHistory(this.extend(c,l)));let u=this.safeList(o,"rows"),f=this.parseBorrowInterests(u,a);return this.filterByCurrencySinceLimit(f,e,i,s)}parseBorrowInterest(e,t){let i=this.safeString(e,"isolatedSymbol"),s=this.safeInteger(e,"interestAccuredTime"),r="isolated";return void 0===i&&(r="cross"),{info:e,symbol:i,currency:this.safeCurrencyCode(this.safeString(e,"asset")),interest:this.safeNumber(e,"interest"),interestRate:this.safeNumber(e,"interestRate"),amountBorrowed:this.safeNumber(e,"principal"),marginMode:r,timestamp:s,datetime:this.iso8601(s)}}async repayCrossMargin(e,t,i={}){let s,r,a;void 0===this.markets&&await this.loadMarkets();let o=this.currency(e),n={asset:o.id,amount:this.currencyToPrecision(e,t)};if([r,a]=this.handleOptionBoolAndParams2(i,"repayCrossMargin","papi","portfolioMargin",!1),r){let e;[e,a]=this.handleOptionStringAndParams2(a,"repayCrossMargin","repayCrossMarginMethod","method"),s="papiPostMarginRepayDebt"===e?await this.papiPostMarginRepayDebt(this.extend(n,a)):await this.papiPostRepayLoan(this.extend(n,a))}else n.isIsolated="FALSE",n.type="REPAY",s=await this.sapiPostMarginBorrowRepay(this.extend(n,a));return this.parseMarginLoan(s,o)}async repayIsolatedMargin(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.currency(t),a=this.market(e),o={asset:r.id,amount:this.currencyToPrecision(t,i),symbol:a.id,isIsolated:"TRUE",type:"REPAY"},n=await this.sapiPostMarginBorrowRepay(this.extend(o,s));return this.parseMarginLoan(n,r)}async borrowCrossMargin(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),a={asset:r.id,amount:this.currencyToPrecision(e,t)},[o,n]=this.handleOptionBoolAndParams2(i,"borrowCrossMargin","papi","portfolioMargin",!1);return o?s=await this.papiPostMarginLoan(this.extend(a,n)):(a.isIsolated="FALSE",a.type="BORROW",s=await this.sapiPostMarginBorrowRepay(this.extend(a,n))),this.parseMarginLoan(s,r)}async borrowIsolatedMargin(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.currency(t),a=this.market(e),o={asset:r.id,amount:this.currencyToPrecision(t,i),symbol:a.id,isIsolated:"TRUE",type:"BORROW"},n=await this.sapiPostMarginBorrowRepay(this.extend(o,s));return this.parseMarginLoan(n,r)}parseMarginLoan(e,t){let i=this.safeString(e,"asset"),s=this.safeInteger(e,"updateTime");return{id:this.safeString(e,"tranId"),currency:this.safeCurrencyCode(i,t),amount:this.safeNumber(e,"amount"),symbol:void 0,timestamp:s,datetime:this.iso8601(s),info:e}}async fetchOpenInterestHistory(e,t="5m",i,s,r={}){let a;if("1m"===t)throw new o.BadRequest(this.id+" fetchOpenInterestHistory cannot use the 1m timeframe");void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOptionBoolAndParams(r,"fetchOpenInterestHistory","paginate",!1);if(n)return await this.fetchPaginatedCallDeterministic("fetchOpenInterestHistory",e,i,s,t,d,500);let h=this.market(e),c={period:this.safeString(this.timeframes,t,t)};void 0!==s&&(c.limit=s);let l="pair";!0===h.linear&&(l="symbol"),c[l]=h.id,!0===h.inverse&&(c.contractType=this.safeString(d,"contractType","CURRENT_QUARTER")),void 0!==i&&(c.startTime=i);let u=this.safeInteger(d,"until"),f=this.safeInteger(d,"endTime",u),p=this.omit(d,["endTime","until"]);if(void 0!==f&&0!==f)c.endTime=f;else if(void 0!==i&&0!==i){let e=void 0===s?30:s,r=this.parseTimeframe(t);c.endTime=this.sum(i,r*e*1e3)}return a=!0===h.inverse?await this.dapiDataGetOpenInterestHist(this.extend(c,p)):await this.fapiDataGetOpenInterestHist(this.extend(c,p)),this.parseOpenInterestsHistory(a,h,i,s)}async fetchOpenInterest(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={};if(!0===s.option){if(r.underlyingAsset=s.baseId,void 0===s.expiry)throw new o.NotSupported(this.id+" fetchOpenInterest does not support "+e);r.expiration=this.yymmdd(s.expiry)}else r.symbol=s.id;if(i=!0===s.option?await this.eapiPublicGetOpenInterest(this.extend(r,t)):!0===s.inverse?await this.dapiPublicGetOpenInterest(this.extend(r,t)):await this.fapiPublicGetOpenInterest(this.extend(r,t)),!0!==s.option)return this.parseOpenInterest(i,s);{let e=s.symbol,t=this.parseOpenInterestsHistory(i,s);for(let i=0;i<t.length;i++){let s=this.safeDict(t,i);if(this.safeString(s,"symbol")===e)return s}throw new o.NullResponse(this.id+" fetchOpenInterest() could not find open interest for "+e)}}parseOpenInterest(e,t){let i=this.safeInteger2(e,"timestamp","time"),s=this.safeString(e,"symbol"),r=this.safeNumber2(e,"sumOpenInterest","openInterest"),a=this.safeNumber2(e,"sumOpenInterestValue","sumOpenInterestUsd"),o=this.safeBool(t,"inverse",!1)?void 0:r;return this.safeOpenInterest({symbol:this.safeSymbol(s,t,void 0,"contract"),baseVolume:o,quoteVolume:a,openInterestAmount:r,openInterestValue:a,timestamp:i,datetime:this.iso8601(i),info:e},t)}async fetchMyLiquidations(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOptionBoolAndParams(s,"fetchMyLiquidations","paginate",!1);if(n)return await this.fetchPaginatedCallIncremental("fetchMyLiquidations",e,t,i,d,"current",100);void 0!==e&&(r=this.market(e));let[h,c]=this.handleMarketTypeAndParams("fetchMyLiquidations",r,d),[l,u]=this.handleSubTypeAndParams("fetchMyLiquidations",r,c,"linear"),[f,p]=this.handleOptionBoolAndParams2(u,"fetchMyLiquidations","papi","portfolioMargin",!1),m={};if("spot"!==h&&(m.autoCloseType="LIQUIDATION"),void 0!==r){let e="symbol";!0===r.spot&&(e="isolatedSymbol"),f||(m[e]=r.id)}void 0!==t&&(m.startTime=t),void 0!==i&&("spot"===h?m.size=i:m.limit=i);let[g,v]=this.handleUntilOption("endTime",m,p);if("spot"===h)a=f?await this.papiGetMarginForceOrders(this.extend(g,v)):await this.sapiGetMarginForceLiquidationRec(this.extend(g,v));else if("linear"===l)a=f?await this.papiGetUmForceOrders(this.extend(g,v)):await this.fapiPrivateGetForceOrders(this.extend(g,v));else if("inverse"===l)a=f?await this.papiGetCmForceOrders(this.extend(g,v)):await this.dapiPrivateGetForceOrders(this.extend(g,v));else throw new o.NotSupported(this.id+" fetchMyLiquidations() does not support "+this.safeString(r,"type")+" markets");let y=[],b=this.safeList(a,"rows");return void 0!==b?y=b:Array.isArray(a)&&(y=a),this.parseLiquidations(y,r,t,i)}parseLiquidation(e,t){let i=this.safeString(e,"symbol"),s=this.safeInteger2(e,"updatedTime","updateTime");return this.safeLiquidation({info:e,symbol:this.safeSymbol(i,t),contracts:this.safeNumber(e,"executedQty"),contractSize:this.safeNumber(t,"contractSize"),price:this.safeNumber(e,"avgPrice"),side:this.safeStringLower(e,"side"),baseValue:this.safeNumber(e,"cumBase"),quoteValue:this.safeNumber(e,"cumQuote"),timestamp:s,datetime:this.iso8601(s)})}async fetchGreeks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.eapiPublicGetMark(this.extend(s,t));return this.parseGreeks(this.safeDict(r,0,{}),i)}async fetchAllGreeks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s={};void 0!==i&&1===i.length&&(s.symbol=this.market(i[0]).id);let r=await this.eapiPublicGetMark(this.extend(s,t));return this.parseAllGreeks(r,i)}parseGreeks(e,t){let i=this.safeString(e,"symbol");return{symbol:this.safeSymbol(i,t),timestamp:void 0,datetime:void 0,delta:this.safeNumber(e,"delta"),gamma:this.safeNumber(e,"gamma"),theta:this.safeNumber(e,"theta"),vega:this.safeNumber(e,"vega"),rho:void 0,bidSize:void 0,askSize:void 0,bidImpliedVolatility:this.safeNumber(e,"bidIV"),askImpliedVolatility:this.safeNumber(e,"askIV"),markImpliedVolatility:this.safeNumber(e,"markIV"),bidPrice:void 0,askPrice:void 0,markPrice:this.safeNumber(e,"markPrice"),lastPrice:void 0,underlyingPrice:void 0,info:e}}async fetchTradingLimits(e,t={}){let i=await this.fetchMarkets(),s={};for(let t=0;t<i.length;t++){let r=i[t],a=this.safeString(r,"symbol");if(void 0===r)throw new o.ExchangeError(this.id+" fetchTradingLimits() could not resolve market");(void 0===e||this.inArray(a,e))&&void 0!==a&&(s[a]=r.limits.amount)}return s}async fetchPositionMode(e,t={}){let i,s;void 0!==e&&(i=this.market(e));let[r,a]=this.handleSubTypeAndParams("fetchPositionMode",i,t);s="inverse"===r?await this.dapiPrivateGetPositionSideDual(a):await this.fapiPrivateGetPositionSideDual(a);let o=this.safeBool(s,"dualSidePosition");return{info:s,hedged:o}}async fetchMarginModes(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e);void 0!==r&&(i=this.market(r[0]));let[a,n]=this.handleSubTypeAndParams("fetchMarginMode",i,t);if("linear"===a)s=await this.fapiPrivateGetSymbolConfig(n);else if("inverse"===a)s=await this.dapiPrivateGetAccount(n);else throw new o.BadRequest(this.id+" fetchMarginModes () supports linear and inverse subTypes only");let d=this.safeList(s,"positions",[]);return Array.isArray(s)&&(d=s),this.parseMarginModes(d,r,"symbol","swap")}async fetchMarginMode(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),[r,a]=this.handleSubTypeAndParams("fetchMarginMode",s,t);if("linear"===r){let e={symbol:s.id};i=await this.fapiPrivateGetSymbolConfig(this.extend(e,a))}else if("inverse"===r){let t=await this.fetchMarginModes([e],a);return this.safeDict(t,e)}else throw new o.BadRequest(this.id+" fetchMarginMode () supports linear and inverse subTypes only");if(void 0===i)throw new o.NullResponse(this.id+" fetchMarginMode() returned empty response");return this.parseMarginMode(i[0],s)}parseMarginMode(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=this.safeBool(e,"isolated");void 0!==a&&(i=a?"isolated":"cross");let o=this.safeStringLower(e,"marginType");return void 0!==o&&(i="crossed"===o?"cross":"isolated"),{info:e,symbol:this.safeString(r,"symbol"),marginMode:i}}async fetchOption(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.eapiPublicGetTicker(this.extend(s,t)),a=this.safeDict(r,0,{});return this.parseOption(a,void 0,i)}parseOption(e,t,i){let s=this.safeString(e,"symbol");return{info:e,currency:void 0,symbol:this.safeMarket(s,i).symbol,timestamp:void 0,datetime:void 0,impliedVolatility:void 0,openInterest:void 0,bidPrice:this.safeNumber(e,"bidPrice"),askPrice:this.safeNumber(e,"askPrice"),midPrice:void 0,markPrice:void 0,lastPrice:this.safeNumber(e,"lastPrice"),underlyingPrice:this.safeNumber(e,"exercisePrice"),change:this.safeNumber(e,"priceChange"),percentage:this.safeNumber(e,"priceChangePercent"),baseVolume:this.safeNumber(e,"volume"),quoteVolume:void 0}}async fetchMarginAdjustmentHistory(e,t,i,s,r={}){let a;if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new o.ArgumentsRequired(this.id+" fetchMarginAdjustmentHistory () requires a symbol argument");let n=this.market(e),d=this.safeInteger(r,"until"),h=this.omit(r,"until"),c={symbol:n.id};if(void 0!==t&&(c.type="add"===t?1:2),void 0!==i&&(c.startTime=i),void 0!==s&&(c.limit=s),void 0!==d&&(c.endTime=d),!0===n.linear)a=await this.fapiPrivateGetPositionMarginHistory(this.extend(c,h));else if(!0===n.inverse)a=await this.dapiPrivateGetPositionMarginHistory(this.extend(c,h));else throw new o.BadRequest(this.id+" fetchMarginAdjustmentHistory () is not supported for markets of type "+n.type);if(void 0===a)throw new o.NullResponse(this.id+" parseMarginModifications() returned empty response");let l=this.parseMarginModifications(this.toArray(a));return this.filterBySymbolSinceLimit(l,e,i,s)}async fetchConvertCurrencies(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.sapiGetConvertAssetInfo(e),i={},s=this.toArray(t);for(let e=0;e<s.length;e++){let t=s[e],r=this.safeString(t,"asset"),a=this.safeCurrencyCode(r);void 0!==a&&(i[a]={info:t,id:r,code:a,networks:void 0,type:void 0,name:void 0,active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,precision:this.parseNumber(this.parsePrecision(this.safeString(t,"fraction"))),limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},created:void 0})}return i}async fetchConvertQuote(e,t,i,s={}){if(void 0===i)throw new o.ArgumentsRequired(this.id+" fetchConvertQuote() requires an amount argument");void 0===this.markets&&await this.loadMarkets();let r=await this.sapiPostConvertGetQuote(this.extend({fromAsset:e,toAsset:t,fromAmount:i},s)),a=this.currency(e),n=this.currency(t);if(void 0===r)throw new o.NullResponse(this.id+" parseConversion() returned empty response");return this.parseConversion(r,a,n)}async createConvertTrade(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let n={};if("BUSD"===t||"BUSD"===i){if(void 0===s)throw new o.ArgumentsRequired(this.id+" createConvertTrade() requires an amount argument");n.clientTranId=e,n.asset=t,n.targetAsset=i,n.amount=s,a=await this.sapiPostAssetConvertTransfer(this.extend(n,r))}else n.quoteId=e,a=await this.sapiPostConvertAcceptQuote(this.extend(n,r));let d=this.currency(t),h=this.currency(i);if(void 0===a)throw new o.NullResponse(this.id+" parseConversion() returned empty response");return this.parseConversion(a,d,h)}async fetchConvertTrade(e,t,i={}){let s,r,a;void 0===this.markets&&await this.loadMarkets();let n={};if("BUSD"===t){let r=this.milliseconds();void 0!==t&&(n.asset=this.currency(t).id),n.tranId=e,n.startTime=r-864e5,n.endTime=r,s=await this.sapiGetAssetConvertTransferQueryByPage(this.extend(n,i))}else n.orderId=e,s=await this.sapiGetConvertOrderStatus(this.extend(n,i));let d=s;if("BUSD"===t){let e=this.safeList(s,"rows",[]);d=this.safeDict(e,0,{})}let h=this.safeString2(d,"deductedAsset","fromAsset"),c=this.safeString2(d,"targetAsset","toAsset");if(void 0!==h&&(r=this.currency(h)),void 0!==c&&(a=this.currency(c)),void 0===d)throw new o.NullResponse(this.id+" parseConversion() returned empty response");return this.parseConversion(d,r,a)}async fetchConvertTradeHistory(e,t,i,s={}){let r,a,n,d;void 0===this.markets&&await this.loadMarkets();let h={},c=this.milliseconds();void 0!==t?h.startTime=t:h.startTime=c-2592e6;let l=this.safeInteger2(s,"endTime","until");void 0!==l?h.endTime=l:h.endTime=c;let u=this.omit(s,"until");if("BUSD"===e)h.asset=this.currency(e).id,void 0!==i&&(h.size=i),n="deductedAsset",d="targetAsset",a="rows",r=await this.sapiGetAssetConvertTransferQueryByPage(this.extend(h,u));else{if(h.endTime-h.startTime>2592e6)throw new o.BadRequest(this.id+" fetchConvertTradeHistory () the max interval between startTime and endTime is 30 days.");void 0!==i&&(h.limit=i),n="fromAsset",d="toAsset",a="list",r=await this.sapiGetConvertTradeFlow(this.extend(h,u))}let f=this.safeList(r,a,[]);return this.parseConversions(f,e,n,d,t,i)}parseConversion(e,t,i){let s=this.safeIntegerN(e,["time","validTimestamp","createTime"]),r=this.safeString2(e,"deductedAsset","fromAsset"),a=this.safeCurrencyCode(r,t),o=this.safeString2(e,"targetAsset","toAsset"),n=this.safeCurrencyCode(o,i);return{info:e,timestamp:s,datetime:this.iso8601(s),id:this.safeStringN(e,["tranId","orderId","quoteId"]),fromCurrency:a,fromAmount:this.safeNumber2(e,"deductedAmount","fromAmount"),toCurrency:n,toAmount:this.safeNumber2(e,"targetAmount","toAmount"),price:void 0,fee:void 0}}async fetchFundingIntervals(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e);void 0!==r&&(i=this.market(r[0]));let a="swap",[n,d]=this.handleSubTypeAndParams("fetchFundingIntervals",i,t,"linear");if(this.isLinear(a,n))s=await this.fapiPublicGetFundingInfo(d);else if(this.isInverse(a,n))s=await this.dapiPublicGetFundingInfo(d);else throw new o.NotSupported(this.id+" fetchFundingIntervals() supports linear and inverse swap contracts only");return this.parseFundingRates(s,r)}async fetchLongShortRatioHistory(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),[d,h]=this.handleUntilOption("endTime",{period:void 0===t?"1d":t},r);void 0!==i&&(d.startTime=i),void 0!==s&&(d.limit=s);let[c,l]=this.handleSubTypeAndParams("fetchLongShortRatioHistory",n,h);if("linear"===c)d.symbol=n.id,a=await this.fapiDataGetGlobalLongShortAccountRatio(this.extend(d,l));else if("inverse"===c)d.pair=n.info.pair,a=await this.dapiDataGetGlobalLongShortAccountRatio(this.extend(d,l));else throw new o.BadRequest(this.id+" fetchLongShortRatioHistory() supports linear and inverse subTypes only");return this.parseLongShortRatioHistory(a,n)}parseLongShortRatio(e,t){let i=this.safeString(e,"symbol"),s=this.safeIntegerOmitZero(e,"timestamp");return{info:e,symbol:this.safeSymbol(i,t,void 0,"contract"),timestamp:s,datetime:this.iso8601(s),timeframe:void 0,longShortRatio:this.safeNumber(e,"longShortRatio")}}async fetchADLRank(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id},[a,n]=this.handleSubTypeAndParams("fetchADLRank",s,t);if("linear"===a)i=await this.fapiPublicGetSymbolAdlRisk(this.extend(r,n));else throw new o.BadRequest(this.id+" fetchADLRank() supports linear subTypes only");if(void 0===i)throw new o.NullResponse(this.id+" parseADLRank() returned empty response");return this.parseADLRank(i,s)}async fetchPositionsADLRank(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!0,!0,!0),r=this.getMarketFromSymbols(s),[a,n]=this.handleSubTypeAndParams("fetchPositionsADLRank",r,t),[d,h]=this.handleOptionBoolAndParams2(n,"fetchPositionsADLRank","papi","portfolioMargin",!1);if("linear"===a)i=d?await this.papiGetUmAdlQuantile(h):await this.fapiPrivateGetAdlQuantile(h);else if("inverse"===a)i=d?await this.papiGetCmAdlQuantile(h):await this.dapiPrivateGetAdlQuantile(h);else throw new o.BadRequest(this.id+" fetchPositionsADLRank() supports linear and inverse subTypes only");let c=[];return void 0!==i&&(c=this.toArray(i)),this.parseADLRanks(c,s)}parseADLRank(e,t){let i,s=this.safeDict(e,"adlQuantile",{}),r=this.safeNumber(s,"LONG"),a=this.safeNumber(s,"SHORT"),o=this.safeNumber(s,"BOTH");void 0!==o?i=o:void 0!==r&&void 0!==a&&(i=r>a?r:a);let n=this.safeString(e,"symbol"),d=this.safeInteger2(e,"timestamp","updateTime");return{info:e,symbol:this.safeSymbol(n,t,void 0,"contract"),rank:i,rating:this.safeStringLower(e,"adlRisk"),percentage:void 0,timestamp:d,datetime:this.iso8601(d)}}}i.d(t,{A:()=>c})},5164(e,t,i){"use strict";var s=i(2222);class r extends s.A{describe(){return this.deepExtend(super.describe(),{id:"binancecoinm",name:"Binance COIN-M",urls:{logo:"https://github.com/user-attachments/assets/387cfc4e-5f33-48cd-8f5c-cd4854dabf0c",doc:["https://binance-docs.github.io/apidocs/delivery/en/","https://binance-docs.github.io/apidocs/spot/en","https://developers.binance.com/en"]},has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!0,option:void 0,createStopMarketOrder:!0},options:{fetchMarkets:{types:["inverse"]},defaultSubType:"inverse",leverageBrackets:void 0}})}async transferIn(e,t,i={}){return await this.futuresTransfer(e,t,3,i)}async transferOut(e,t,i={}){return await this.futuresTransfer(e,t,4,i)}}i.d(t,{A:()=>r})},3942(e,t,i){"use strict";var s=i(2222);class r extends s.A{describe(){return this.deepExtend(super.describe(),{id:"binanceus",name:"Binance US",countries:["US"],hostname:"binance.us",rateLimit:50,certified:!1,pro:!0,urls:{logo:"https://github.com/user-attachments/assets/a9667919-b632-4d52-a832-df89f8a35e8c",api:{web:"https://www.binance.us",public:"https://api.binance.us/api/v3",private:"https://api.binance.us/api/v3",sapi:"https://api.binance.us/sapi/v1",sapiV2:"https://api.binance.us/sapi/v2",sapiV3:"https://api.binance.us/sapi/v3"},www:"https://www.binance.us",referral:"https://www.binance.us/?ref=35005074",doc:"https://github.com/binance-us/binance-official-api-docs",fees:"https://www.binance.us/en/fee/schedule"},fees:{trading:{tierBased:!0,percentage:!0,taker:this.parseNumber("0.001"),maker:this.parseNumber("0.001")}},options:{fetchMarkets:{types:["spot"]},defaultType:"spot",fetchMargins:!1,quoteOrderQty:!1,fetchCurrencies:!1},has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,closeAllPositions:!1,closePosition:!1,createReduceOnlyOrder:!1,createStopLossOrder:!1,createTakeProfitOrder:!1,fetchAllGreeks:!1,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverageTiers:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarketLeverageTiers:!1,fetchMarkOHLCV:!1,fetchMarkPrice:!1,fetchMarkPrices:!1,fetchMySettlementHistory:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOption:!1,fetchOptionChain:!1,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1},api:{public:{get:{ping:{cost:1},time:{cost:1},exchangeInfo:{cost:10},trades:{cost:1},historicalTrades:{cost:5},aggTrades:{cost:1},depth:{cost:1,byLimit:[[100,1],[500,5],[1e3,10],[5e3,50]]},klines:{cost:1},"ticker/price":{cost:1,noSymbol:2},avgPrice:{cost:1},"ticker/bookTicker":{cost:1,noSymbol:2},"ticker/24hr":{cost:1,noSymbol:40},ticker:{cost:2,noSymbol:100},"ticker/tradingDay":{cost:4}}},private:{get:{account:{cost:10},"account/commission":{cost:20},"rateLimit/order":{cost:20},order:{cost:2},openOrders:{cost:3,noSymbol:40},myTrades:{cost:10},myPreventedMatches:{cost:10},myFilters:{cost:40},allOrders:{cost:10},orderList:{cost:2},allOrderList:{cost:10},openOrderList:{cost:3}},post:{order:{cost:1},"order/test":{cost:1},"order/cancelReplace":{cost:1},"order/oco":{cost:1}},delete:{order:{cost:1},openOrders:{cost:1},orderList:{cost:1}}},sapi:{get:{"system/status":{cost:1},"asset/assetDistributionHistory":{cost:1},"asset/query/trading-fee":{cost:1},"asset/query/trading-volume":{cost:1},"sub-account/spotSummary":{cost:1},"sub-account/status":{cost:1},"otc/coinPairs":{cost:1},"otc/orders/{orderId}":{cost:1},"otc/orders":{cost:1},"ocbs/orders":{cost:1},"capital/config/getall":{cost:1},"capital/withdraw/history":{cost:1},"fiatpayment/query/withdraw/history":{cost:1},"capital/deposit/address":{cost:1},"capital/deposit/hisrec":{cost:1},"fiatpayment/query/deposit/history":{cost:1},"capital/sub-account/deposit/address":{cost:1},"capital/sub-account/deposit/history":{cost:1},"asset/query/dust-logs":{cost:1},"asset/query/dust-assets":{cost:1},"marketing/referral/reward/history":{cost:1},"staking/asset":{cost:1},"staking/stakingBalance":{cost:1},"staking/history":{cost:1},"staking/stakingRewardsHistory":{cost:1},"custodian/balance":{cost:1},"custodian/supportedAssetList":{cost:1},"custodian/walletTransferHistory":{cost:1},"custodian/custodianTransferHistory":{cost:1},"custodian/openOrders":{cost:1},"custodian/order":{cost:1},"custodian/orderHistory":{cost:1},"custodian/tradeHistory":{cost:1},"custodian/settlementSetting":{cost:1},"custodian/settlementHistory":{cost:1},"cl/transferHistory":{cost:1},"apipartner/checkEligibility":{cost:1},"apipartner/rebateHistory":{cost:1}},post:{"otc/quotes":{cost:1},"otc/orders":{cost:1},"fiatpayment/withdraw/apply":{cost:1},"capital/withdraw/apply":{cost:1},"asset/dust":{cost:10},"staking/stake":{cost:1},"staking/unstake":{cost:1},"custodian/walletTransfer":{cost:1},"custodian/custodianTransfer":{cost:1},"custodian/undoTransfer":{cost:1},"custodian/order":{cost:1},"custodian/ocoOrder":{cost:1},"cl/transfer":{cost:1}},delete:{"custodian/cancelOrder":{cost:1},"custodian/cancelOrdersBySymbol":{cost:1},"custodian/cancelOcoOrder":{cost:1}}},sapiV2:{get:{"cl/account":{cost:10},"cl/alertHistory":{cost:1}}},sapiV3:{get:{accountStatus:{cost:1},apiTradingStatus:{cost:1},"sub-account/list":{cost:1},"sub-account/transfer/history":{cost:1},"sub-account/assets":{cost:1}},post:{"sub-account/transfer":{cost:1}}}},features:{swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}}})}}i.d(t,{A:()=>r})},4965(e,t,i){"use strict";var s=i(2222),r=i(1453);class a extends s.A{describe(){return this.deepExtend(super.describe(),{id:"binanceusdm",name:"Binance USDⓈ-M",urls:{logo:"https://github.com/user-attachments/assets/871cbea7-eebb-4b28-b260-c1c91df0487a",doc:["https://binance-docs.github.io/apidocs/futures/en/","https://binance-docs.github.io/apidocs/spot/en","https://developers.binance.com/en"]},has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!0,option:void 0,createStopMarketOrder:!0},options:{fetchMarkets:{types:["linear"]},defaultType:"swap",defaultSubType:"linear",leverageBrackets:void 0,marginTypes:{},marginModes:{}},exceptions:{exact:{"-5021":r.InvalidOrder,"-5022":r.InvalidOrder,"-5028":r.InvalidOrder}}})}async transferIn(e,t,i={}){return await this.futuresTransfer(e,t,1,i)}async transferOut(e,t,i={}){return await this.futuresTransfer(e,t,2,i)}}i.d(t,{A:()=>a})},5938(e,t,i){"use strict";var s=i(4721),r=i(130),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bingx",name:"BingX",countries:["US"],rateLimit:100,version:"v1",certified:!0,pro:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!0,future:!1,option:!1,addMargin:!0,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelAllOrdersAfter:!0,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!0,closePosition:!0,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!0,createMarketSellOrderWithCost:!0,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!0,createReduceOnlyOrder:!0,createStopLossOrder:!0,createStopOrder:!0,createTakeProfitOrder:!0,createTrailingAmountOrder:!0,createTrailingPercentOrder:!0,createTriggerOrder:!0,editOrder:!0,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCanceledAndClosedOrders:!0,fetchCanceledOrders:!0,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!0,fetchDeposits:!0,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!0,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchGreeks:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLeverage:!0,fetchLiquidations:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!0,fetchMarketLeverageTiers:!0,fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMarkPrice:!0,fetchMarkPrices:!0,fetchMyLiquidations:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!0,fetchPositionHistory:!0,fetchPositionMode:!0,fetchPositions:!0,fetchPositionsHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTransfers:!0,fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!0,repayCrossMargin:!1,repayIsolatedMargin:!1,sandbox:!0,setLeverage:!0,setMargin:!0,setMarginMode:!0,setPositionMode:!0,transfer:!0,withdraw:!0},hostname:"bingx.com",urls:{logo:"https://github-production-user-asset-6210df.s3.amazonaws.com/1294454/253675376-6983b72e-4999-4549-b177-33b374c195e3.jpg",api:{fund:"https://open-api.{hostname}/openApi",spot:"https://open-api.{hostname}/openApi",swap:"https://open-api.{hostname}/openApi",contract:"https://open-api.{hostname}/openApi",wallets:"https://open-api.{hostname}/openApi",user:"https://open-api.{hostname}/openApi",subAccount:"https://open-api.{hostname}/openApi",account:"https://open-api.{hostname}/openApi",copyTrading:"https://open-api.{hostname}/openApi",cswap:"https://open-api.{hostname}/openApi",api:"https://open-api.{hostname}/openApi"},test:{fund:"https://open-api-vst.{hostname}/openApi",spot:"https://open-api-vst.{hostname}/openApi",swap:"https://open-api-vst.{hostname}/openApi",contract:"https://open-api-vst.{hostname}/openApi",wallets:"https://open-api-vst.{hostname}/openApi",user:"https://open-api-vst.{hostname}/openApi",subAccount:"https://open-api-vst.{hostname}/openApi",account:"https://open-api-vst.{hostname}/openApi",copyTrading:"https://open-api-vst.{hostname}/openApi",cswap:"https://open-api-vst.{hostname}/openApi",api:"https://open-api-vst.{hostname}/openApi"},www:"https://bingx.com/",doc:"https://bingx-api.github.io/docs/",referral:"https://bingx.com/invite/OHETOM"},fees:{tierBased:!0,spot:{feeSide:"get",maker:this.parseNumber("0.001"),taker:this.parseNumber("0.001")},swap:{feeSide:"quote",maker:this.parseNumber("0.0002"),taker:this.parseNumber("0.0005")}},requiredCredentials:{apiKey:!0,secret:!0},api:{fund:{v1:{private:{get:{"account/balance":{cost:1}}}}},spot:{v1:{public:{get:{"server/time":{cost:1},"common/symbols":{cost:1},"market/trades":{cost:1},"market/depth":{cost:1},"market/kline":{cost:1},"ticker/24hr":{cost:1},"ticker/price":{cost:1},"ticker/bookTicker":{cost:1}}},private:{get:{"trade/query":{cost:1},"trade/openOrders":{cost:1},"trade/historyOrders":{cost:1},"trade/myTrades":{cost:2},"user/commissionRate":{cost:5},"account/balance":{cost:2},"oco/orderList":{cost:5},"oco/openOrderList":{cost:5},"oco/historyOrderList":{cost:5}},post:{"trade/order":{cost:2},"trade/cancel":{cost:2},"trade/batchOrders":{cost:5},"trade/order/cancelReplace":{cost:5},"trade/cancelOrders":{cost:5},"trade/cancelOpenOrders":{cost:5},"trade/cancelAllAfter":{cost:5},"oco/order":{cost:5},"oco/cancel":{cost:5}}}},v2:{public:{get:{"market/depth":{cost:1},"market/kline":{cost:1},"ticker/price":{cost:1},"quote/bookTicker":{cost:1},"quote/depth":{cost:1},"quote/historicalKlines":{cost:1},"quote/historicalTrades":{cost:1},"quote/klines":{cost:1},"quote/price":{cost:1},"quote/ticker":{cost:1},"quote/trades":{cost:1}}}},v3:{private:{get:{"get/asset/transfer":{cost:1},"asset/transfer":{cost:1},"capital/deposit/hisrec":{cost:1},"capital/withdraw/history":{cost:1}},post:{"post/asset/transfer":{cost:5}}}}},swap:{v1:{public:{get:{"ticker/price":{cost:1},"market/historicalTrades":{cost:1},"market/markPriceKlines":{cost:1},"trade/multiAssetsRules":{cost:1},tradingRules:{cost:1}}},private:{get:{"positionSide/dual":{cost:5},"trade/batchCancelReplace":{cost:5},"trade/fullOrder":{cost:2},maintMarginRatio:{cost:2},"trade/positionHistory":{cost:2},"positionMargin/history":{cost:2},"twap/openOrders":{cost:5},"twap/historyOrders":{cost:5},"twap/orderDetail":{cost:5},"trade/assetMode":{cost:5},"user/marginAssets":{cost:5}},post:{"trade/amend":{cost:2},"trade/cancelReplace":{cost:2},"positionSide/dual":{cost:5},"trade/batchCancelReplace":{cost:5},"trade/closePosition":{cost:2},"trade/getVst":{cost:5},"twap/order":{cost:5},"twap/cancelOrder":{cost:5},"trade/assetMode":{cost:5},"trade/reverse":{cost:5},"trade/autoAddMargin":{cost:5}}}},v2:{public:{get:{"server/time":{cost:1},"quote/contracts":{cost:1},"quote/price":{cost:1},"quote/depth":{cost:1},"quote/trades":{cost:1},"quote/premiumIndex":{cost:1},"quote/fundingRate":{cost:1},"quote/klines":{cost:1},"quote/openInterest":{cost:1},"quote/ticker":{cost:1},"quote/bookTicker":{cost:1}}},private:{get:{"user/balance":{cost:2},"user/positions":{cost:2},"user/income":{cost:2},"trade/openOrders":{cost:2},"trade/openOrder":{cost:2},"trade/order":{cost:2},"trade/marginType":{cost:5},"trade/leverage":{cost:2},"trade/forceOrders":{cost:1},"trade/allOrders":{cost:2},"trade/allFillOrders":{cost:2},"trade/fillHistory":{cost:2},"trade/positionHistory":{cost:2},"user/income/export":{cost:2},"user/commissionRate":{cost:2},"quote/bookTicker":{cost:1}},post:{"trade/getVst":{cost:5},"trade/order":{cost:2},"trade/batchOrders":{cost:2},"trade/closeAllPositions":{cost:2},"trade/cancelAllAfter":{cost:5},"trade/marginType":{cost:5},"trade/leverage":{cost:5},"trade/positionMargin":{cost:5},"trade/order/test":{cost:2}},delete:{"trade/order":{cost:2},"trade/batchOrders":{cost:2},"trade/allOpenOrders":{cost:2}}}},v3:{public:{get:{"quote/klines":{cost:1}}},private:{get:{"user/balance":{cost:2}}}}},cswap:{v1:{public:{get:{"market/contracts":{cost:1},"market/premiumIndex":{cost:1},"market/openInterest":{cost:1},"market/klines":{cost:1},"market/depth":{cost:1},"market/ticker":{cost:1}}},private:{get:{"trade/leverage":{cost:2},"trade/forceOrders":{cost:2},"trade/allFillOrders":{cost:2},"trade/openOrders":{cost:2},"trade/orderDetail":{cost:2},"trade/orderHistory":{cost:2},"trade/marginType":{cost:2},"user/commissionRate":{cost:2},"user/positions":{cost:2},"user/balance":{cost:2}},post:{"trade/order":{cost:2},"trade/leverage":{cost:2},"trade/allOpenOrders":{cost:2},"trade/closeAllPositions":{cost:2},"trade/marginType":{cost:2},"trade/positionMargin":{cost:2}},delete:{"trade/allOpenOrders":{cost:2},"trade/cancelOrder":{cost:2}}}},v2:{private:{post:{"trade/order":{cost:2}}}}},contract:{v1:{private:{get:{allPosition:{cost:2},allOrders:{cost:2},balance:{cost:2}}}}},wallets:{v1:{private:{get:{"capital/config/getall":{cost:5},"capital/deposit/address":{cost:5},"capital/innerTransfer/records":{cost:1},"capital/subAccount/deposit/address":{cost:5},"capital/deposit/subHisrec":{cost:2},"capital/subAccount/innerTransfer/records":{cost:1},"capital/deposit/riskRecords":{cost:5}},post:{"capital/withdraw/apply":{cost:5},"capital/innerTransfer/apply":{cost:5},"capital/subAccountInnerTransfer/apply":{cost:2},"capital/deposit/createSubAddress":{cost:2}}}}},subAccount:{v1:{private:{get:{list:{cost:10},assets:{cost:2},allAccountBalance:{cost:2}},post:{create:{cost:10},"apiKey/create":{cost:2},"apiKey/edit":{cost:2},"apiKey/del":{cost:2},updateStatus:{cost:10}}}}},account:{v1:{private:{get:{uid:{cost:1},"apiKey/query":{cost:2},"account/apiPermissions":{cost:5},"account/apiRestrictions":{cost:5},allAccountBalance:{cost:2}},post:{"innerTransfer/authorizeSubAccount":{cost:1}}}},transfer:{v1:{private:{get:{"subAccount/asset/transferHistory":{cost:1}},post:{"subAccount/transferAsset/supportCoins":{cost:1},"subAccount/transferAsset":{cost:1}}}}}},user:{auth:{private:{post:{userDataStream:{cost:2}},put:{userDataStream:{cost:2}},delete:{userDataStream:{cost:2}}}}},copyTrading:{v1:{private:{get:{"swap/trace/currentTrack":{cost:2},"PFutures/traderDetail":{cost:2},"PFutures/profitHistorySummarys":{cost:2},"PFutures/profitDetail":{cost:2},"PFutures/tradingPairs":{cost:2},"spot/traderDetail":{cost:2},"spot/profitHistorySummarys":{cost:2},"spot/profitDetail":{cost:2},"spot/historyOrder":{cost:2}},post:{"swap/trace/closeTrackOrder":{cost:2},"swap/trace/setTPSL":{cost:2},"PFutures/setCommission":{cost:2},"spot/trader/sellOrder":{cost:10}}}}},api:{v3:{private:{get:{"asset/transfer":{cost:1},"asset/transferRecord":{cost:5},"capital/deposit/hisrec":{cost:1},"capital/withdraw/history":{cost:1}},post:{"post/asset/transfer":{cost:1}}}},asset:{v1:{private:{post:{transfer:{cost:5}}},public:{get:{"transfer/supportCoins":{cost:5}}}}}},agent:{v1:{private:{get:{"account/inviteAccountList":{cost:5},"reward/commissionDataList":{cost:5},"account/inviteRelationCheck":{cost:5},"asset/depositDetailList":{cost:5},"reward/third/commissionDataList":{cost:5},"asset/partnerData":{cost:5},"commissionDataList/referralCode":{cost:5},"account/superiorCheck":{cost:5}}}}},wealth:{v1:{private:{get:{"product/dual-currency/pre-order":{cost:2},"product/dual-currency/position":{cost:2},"product/dual-currency/order-records":{cost:2}},post:{"product/dual-currency/invest-asset-list":{cost:2},"product/dual-currency/order":{cost:2}}}}}},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","12h":"12h","1d":"1d","3d":"3d","1w":"1w","1M":"1M"},precisionMode:4,exceptions:{exact:{400:a.BadRequest,401:a.AuthenticationError,403:a.PermissionDenied,404:a.BadRequest,429:a.DDoSProtection,418:a.PermissionDenied,500:a.ExchangeError,504:a.ExchangeError,100001:a.AuthenticationError,100004:a.PermissionDenied,100412:a.AuthenticationError,100413:a.AuthenticationError,100202:a.InsufficientFunds,100204:a.BadRequest,100400:a.BadRequest,100410:a.OperationFailed,100421:a.BadSymbol,100440:a.ExchangeError,100500:a.OperationFailed,100503:a.ExchangeError,80001:a.BadRequest,80012:a.InsufficientFunds,80014:a.BadRequest,80016:a.OrderNotFound,80017:a.OrderNotFound,100414:a.AccountSuspended,100419:a.PermissionDenied,100437:a.BadRequest,101204:a.InsufficientFunds,110425:a.InvalidOrder,100490:a.BadSymbol,101481:a.DuplicateOrderId,109201:a.DuplicateOrderId,109400:a.BadRequest,109418:a.BadSymbol,109421:a.OrderNotFound,109425:a.BadSymbol,109500:a.OperationFailed,110500:a.OperationFailed,"Insufficient assets":a.InsufficientFunds,"illegal transferType":a.BadRequest},broad:{}},commonCurrencies:{SNOW:"Snowman",OMNI:"OmniCat",NAP:"$NAP",TRUMP:"TRUMPMAGA",TRUMPSOL:"TRUMP"},options:{defaultType:"spot",fetchOHLCV:{timeZone:0},accountsByType:{funding:"fund",spot:"spot",future:"stdFutures",swap:"USDTMPerp",linear:"USDTMPerp",inverse:"coinMPerp"},accountsById:{fund:"funding",spot:"spot",stdFutures:"future",USDTMPerp:"linear",coinMPerp:"inverse"},recvWindow:5e3,broker:"CCXT",defaultNetworks:{ETH:"ETH",USDT:"ERC20",USDC:"ERC20",BTC:"BTC",LTC:"LTC"},networks:{ARBITRUM:"ARB",MATIC:"POLYGON",ZKSYNC:"ZKSYNCERA",AVAXC:"AVAX-C",HBAR:"HEDERA"}},features:{defaultForLinear:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:{last:!0,mark:!0,index:!0},triggerDirection:!1,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:{triggerPriceType:{last:!0,mark:!0,index:!0},price:!0},timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!0,trailing:!0,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,iceberg:!1},createOrders:{max:5},fetchMyTrades:{marginMode:!1,limit:512,daysBack:30,untilDays:30,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:1e3,daysBack:2e4,untilDays:7,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:1e3,daysBack:void 0,daysBackCanceled:void 0,untilDays:7,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:1440}},defaultForInverse:{extends:"defaultForLinear",sandbox:!1,createOrders:void 0,fetchOHLCV:{limit:1e3},fetchMyTrades:{limit:1e3,daysBack:void 0,untilDays:void 0},fetchOrders:void 0},spot:{extends:"defaultForLinear",sandbox:!1,fetchCurrencies:{private:!0},createOrder:{marketBuyByCost:!0,triggerPriceType:void 0,attachedStopLossTakeProfit:void 0,trailing:!1},fetchMyTrades:{limit:1e3,daysBack:1,untilDays:1},fetchOrders:void 0,fetchClosedOrders:{limit:100,untilDays:void 0}},swap:{linear:{extends:"defaultForLinear"},inverse:{extends:"defaultForInverse"}}},rollingWindowSize:2e3})}async fetchTime(e={}){let t=await this.swapV2PublicGetServerTime(e),i=this.safeDict(t,"data");return this.safeInteger(i,"serverTime")}async fetchCurrencies(e={}){if(!this.checkRequiredCredentials(!1)||!0===this.safeBool(this.options,"sandboxMode",!1))return{};let t=await this.walletsV1PrivateGetCapitalConfigGetall(e),i=this.safeList(t,"data",[]);return this.parseCurrencies(i)}parseCurrency(e){let t=this.safeString(e,"coin"),i=this.safeCurrencyCode(t),s=this.safeString(e,"name"),r=this.safeList(e,"networkList"),a={};for(let e=0;e<r.length;e++){let t=r[e],s=this.safeString(t,"network"),o=this.networkIdToCode(s,i),n={withdraw:{min:this.safeNumber(t,"withdrawMin"),max:this.safeNumber(t,"withdrawMax")},deposit:{min:this.safeNumber(t,"depositMin"),max:void 0}},d=this.parseNumber(this.parsePrecision(this.safeString(t,"withdrawPrecision")));void 0!==o&&(a[o]={info:t,id:s,network:o,fee:this.safeNumber(t,"withdrawFee"),active:void 0,deposit:this.safeBool(t,"depositEnable"),withdraw:this.safeBool(t,"withdrawEnable"),precision:d,limits:n})}return this.safeCurrencyStructure({info:e,code:i,id:t,precision:void 0,name:s,active:void 0,deposit:void 0,withdraw:void 0,networks:a,fee:void 0,limits:void 0,type:"crypto"})}async fetchSpotMarkets(e){let t=await this.spotV1PublicGetCommonSymbols(e),i=this.safeDict(t,"data"),s=this.safeList(i,"symbols",[]);return this.parseMarkets(s)}async fetchSwapMarkets(e){let t=await this.swapV2PublicGetQuoteContracts(e),i=this.safeList(t,"data",[]);return this.parseMarkets(i)}async fetchInverseSwapMarkets(e){let t=await this.cswapV1PublicGetMarketContracts(e),i=this.safeList(t,"data",[]);return this.parseMarkets(i)}parseMarket(e){let t,i,s=this.safeString(e,"symbol"),r=s.split("-"),a=r[0],o=r[1],n=this.safeCurrencyCode(a),d=this.safeCurrencyCode(o);if(void 0===n||void 0===d)return;let h=this.safeString(e,"currency"),c=!1,l=!0,u=this.safeNumber(e,"minTickSize");void 0!==u&&(h=a,c=!0,l=!1);let f=this.safeCurrencyCode(h),p=this.safeNumber(e,"tickSize");void 0===p&&(p=this.parseNumber(this.parsePrecision(this.safeString(e,"pricePrecision"))));let m=this.safeNumber(e,"stepSize");void 0===m&&(m=this.parseNumber(this.parsePrecision(this.safeString(e,"quantityPrecision"))));let g="spot";void 0!==f&&(g="swap");let v="spot"===g,y="swap"===g,b=n+"/"+d;void 0!==f&&(b+=":"+f);let w=this.safeDict(this.fees,g,{});y&&(t=c?u:this.parseNumber("1"));let k=!1;"true"===this.safeString(e,"apiStateOpen")&&"true"===this.safeString(e,"apiStateClose")||this.safeBool(e,"apiStateSell",!1)&&this.safeBool(e,"apiStateBuy",!1)&&"1"===this.safeString(e,"status")?k=!0:c&&"1"===this.safeString(e,"status")&&(k=!0);let S=v?void 0:c,O=v?void 0:l;v||(i=this.safeNumber2(e,"minQty","tradeMinQuantity"));let T=this.safeInteger(e,"timeOnline");return 0===T&&(T=void 0),this.safeMarketStructure({id:s,symbol:b,base:n,quote:d,settle:f,baseId:a,quoteId:o,settleId:h,type:g,spot:v,margin:!1,swap:y,future:!1,option:!1,active:k,contract:y,linear:O,inverse:S,taker:this.safeNumber(w,"taker"),maker:this.safeNumber(w,"maker"),feeSide:this.safeString(w,"feeSide"),contractSize:t,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:m,price:p},limits:{leverage:{min:void 0,max:void 0},amount:{min:i,max:void 0},price:{min:void 0,max:void 0},cost:{min:this.safeNumberN(e,["minNotional","tradeMinUSDT","minTradeValue"]),max:this.safeNumber(e,"maxNotional")}},created:T,info:e})}async fetchMarkets(e={}){let t=[this.fetchSwapMarkets(e)];!0!==this.safeBool(this.options,"sandboxMode",!1)&&(t.push(this.fetchInverseSwapMarkets(e)),t.push(this.fetchSpotMarkets(e)));let i=await Promise.all(t),s=this.safeList(i,0,[]),r=this.safeList(i,1,[]),a=this.safeList(i,2,[]),o=this.arrayConcat(s,r);return this.arrayConcat(a,o)}async fetchOHLCV(e,t="1m",i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=!0===o.inverse?1e3:1440,[d,h]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(d)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,h,n);let c={symbol:o.id};c.interval=this.safeString(this.timeframes,t,t);let l=void 0===s?500:Math.min(s,n);void 0!==i&&(c.startTime=Math.max(i-1,0)),void 0!==s&&(c.limit=l);let u=this.safeInteger2(h,"until","endTime"),f=void 0!==u?this.omit(h,["until"]):h;if(void 0!==u)c.endTime=u;else if(!0===o.inverse&&void 0!==i){let e=1e3*this.parseTimeframe(t);c.endTime=this.sum(i,e*l)}if(!0===o.spot){let[e,t]=this.handleOptionIntegerAndParams(f,"fetchOHLCV","timeZone",0);void 0!==e&&(c.timeZone=e),a=await this.spotV1PublicGetMarketKline(this.extend(c,t))}else if(!0===o.inverse)a=await this.cswapV1PublicGetMarketKlines(this.extend(c,f));else{let e=this.safeString(f,"price"),t=this.omit(f,"price");a="mark"===e?await this.swapV1PublicGetMarketMarkPriceKlines(this.extend(c,t)):await this.swapV3PublicGetQuoteKlines(this.extend(c,t))}let p=this.safeValue(a,"data",[]);return Array.isArray(p)||(p=[p]),this.parseOHLCVs(p,o,t,i,s)}parseOHLCV(e,t){return Array.isArray(e)?[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]:[this.safeInteger2(e,"time","closeTime"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o=this.market(e);if(!0===o.inverse)throw new a.NotSupported(this.id+" fetchTrades() is not supported for inverse swap markets");let n={symbol:o.id},[d,h]=this.handleMarketTypeAndParams("fetchTrades",o,s);void 0!==i&&(n.limit=Math.min(i,"spot"===d?500:1e3)),r="spot"===d?await this.spotV1PublicGetMarketTrades(this.extend(n,h)):await this.swapV2PublicGetQuoteTrades(this.extend(n,h));let c=this.safeList(r,"data",[]);return this.parseTrades(c,o,t,i)}parseTrade(e,t){let i,s=this.safeIntegerN(e,["time","filledTm","T","tradeTime"]),r=this.safeString(e,"filledTm");void 0!==r&&(s=this.parse8601(r)),0===s&&(s=void 0);let a=this.safeString(e,"quoteQty"),n=this.safeStringN(e,["currency","N","commissionAsset"]),d=this.safeCurrencyCode(n),h=this.safeBool(e,"m"),c=this.safeString2(e,"s","symbol"),l=this.safeBoolN(e,["buyerMaker","isBuyerMaker","maker"]),u=!0===l||!0===h;(void 0!==l||void 0!==h)&&(i=u?"maker":"taker");let f=this.safeStringLower2(e,"side","S");void 0===f&&(void 0!==l||void 0!==h)&&(f=u?"sell":"buy",i="taker");let p=this.safeBool(e,"isBuyer");void 0!==p&&(f=p?"buy":"sell");let m=this.safeBool(e,"isMaker");void 0!==m&&(i=m?"maker":"taker");let g=this.safeStringN(e,["qty","amount","q"]);void 0!==t&&!0===t.swap&&"volume"in e&&(g=this.safeString(e,"volume"));let v=this.safeStringN(e,["price","p","tradePrice"]);if(void 0!==t&&!0===t.linear&&"TRADE"===this.safeString(e,"x")){let t=this.safeString(e,"l"),i=this.safeString(e,"L");void 0!==t&&void 0!==i&&(g=t,v=i)}return this.safeTrade({id:this.safeStringN(e,["id","t","fillId","tradeId"]),info:e,timestamp:s,datetime:this.iso8601(s),symbol:this.safeSymbol(c,t,"-"),order:this.safeString2(e,"orderId","i"),type:this.safeStringLower(e,"o"),side:this.parseOrderSide(f),takerOrMaker:i,price:v,amount:g,cost:a,fee:{cost:this.parseNumber(o.Y.stringAbs(this.safeString2(e,"commission","n"))),currency:d}},t)}async fetchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id},[o,n]=this.handleMarketTypeAndParams("fetchOrderBook",r,i);void 0!==t&&("spot"===o?a.limit=Math.min(t,1e3):a.limit=this.findNearestCeiling([5,10,20,50,100,500,1e3],t)),s="spot"===o?await this.spotV1PublicGetMarketDepth(this.extend(a,n)):!0===r.inverse?await this.cswapV1PublicGetMarketDepth(this.extend(a,n)):await this.swapV2PublicGetQuoteDepth(this.extend(a,n));let d=this.safeDict(s,"data",{}),h=this.safeInteger(d,"lastUpdateId"),c=this.safeInteger2(d,"T","ts"),l=this.parseOrderBook(d,r.symbol,c,"bids","asks",0,1);return l.nonce=h,l}async fetchFundingRate(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id};if(i=!0===r.inverse?await this.cswapV1PublicGetMarketPremiumIndex(this.extend(a,t)):await this.swapV2PublicGetQuotePremiumIndex(this.extend(a,t)),!0===r.inverse){let e=this.safeList(i,"data",[]);s=this.safeDict(e,0,{})}else s=this.safeDict(i,"data",{});return this.parseFundingRate(s,r)}async fetchFundingRates(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,"swap",!0,!0,!0),r=this.getMarketFromSymbols(s),[a,o]=this.handleSubTypeAndParams("fetchFundingRates",r,t,"linear");i="inverse"===a?await this.cswapV1PublicGetMarketPremiumIndex(o):await this.swapV2PublicGetQuotePremiumIndex(o);let n=this.safeList(i,"data",[]);return this.parseFundingRates(n,s)}parseFundingRate(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeInteger(e,"nextFundingTime"),a=this.safeInteger(e,"updateTime"),o=this.safeString(e,"fundingIntervalHours");return void 0!==o&&(i=o+"h"),{info:e,symbol:this.safeSymbol(s,t,"-","swap"),markPrice:this.safeNumber(e,"markPrice"),indexPrice:this.safeNumber(e,"indexPrice"),interestRate:void 0,estimatedSettlePrice:void 0,timestamp:a,datetime:this.iso8601(a),fundingRate:this.safeNumber(e,"lastFundingRate"),fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:void 0,nextFundingTimestamp:r,nextFundingDatetime:this.iso8601(r),previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:i}}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e);if(!0===r.inverse)throw new a.NotSupported(this.id+" fetchFundingRateHistory() is not supported for inverse swap markets");let[o,n]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(o)return await this.fetchPaginatedCallDeterministic("fetchFundingRateHistory",e,t,i,"8h",n);let d={symbol:r.id};void 0!==t&&(d.startTime=t),void 0!==i&&(d.limit=Math.min(i,1e3));let[h,c]=this.handleUntilOption("endTime",d,n),l=await this.swapV2PublicGetQuoteFundingRate(this.extend(h,c)),u=this.safeList(l,"data",[]);return this.parseFundingRateHistories(u,r,t,i)}parseFundingRateHistory(e,t){let i=this.safeInteger(e,"fundingTime");return{info:e,symbol:this.safeSymbol(this.safeString(e,"symbol"),t,"-","swap"),fundingRate:this.safeNumber(e,"fundingRate"),timestamp:i,datetime:this.iso8601(i)}}async fetchFundingHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let[o,n]=this.handleSubTypeAndParams("fetchFundingHistory",r,s);if(void 0!==r?!0===r.inverse:"inverse"===o)throw new a.NotSupported(this.id+" fetchFundingHistory() is not supported for inverse swap markets");let[d,h]=this.handleOptionBoolAndParams(n,"fetchFundingHistory","paginate",!1);if(d)return await this.fetchPaginatedCallDeterministic("fetchFundingHistory",e,t,i,"24h",h);let c={incomeType:"FUNDING_FEE"};void 0!==r&&(c.symbol=r.id),void 0!==t&&(c.startTime=t),void 0!==i&&(c.limit=i);let l=this.safeInteger2(h,"until","endTime"),u=void 0!==l?this.omit(h,["until"]):h;void 0!==l&&(c.endTime=l);let f=await this.swapV2PrivateGetUserIncome(this.extend(c,u)),p=this.safeList(f,"data",[]);return this.parseIncomes(p,r,t,i)}parseIncome(e,t){let i=this.safeString(e,"symbol"),s=this.safeString(e,"asset"),r=this.safeInteger(e,"time");return{info:e,symbol:this.safeSymbol(i,t,void 0,"swap"),code:this.safeCurrencyCode(s),timestamp:r,datetime:this.iso8601(r),id:this.safeString(e,"tranId"),amount:this.safeNumber(e,"income"),type:"funding"}}async fetchOpenInterest(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};i=!0===s.inverse?await this.cswapV1PublicGetMarketOpenInterest(this.extend(r,t)):await this.swapV2PublicGetQuoteOpenInterest(this.extend(r,t));let a={};if(!0===s.inverse){let e=this.safeList(i,"data",[]);a=this.safeDict(e,0,{})}else a=this.safeDict(i,"data",{});return this.parseOpenInterest(a,s)}parseOpenInterest(e,t){let i=this.safeInteger2(e,"time","timestamp"),s=this.safeString(e,"symbol"),r=this.safeSymbol(s,t,"-","swap"),a=this.safeNumber(e,"openInterest"),o=!0===this.safeBool(t,"inverse",!1),n=o?a:void 0,d=o?void 0:a;return this.safeOpenInterest({symbol:r,baseVolume:void 0,quoteVolume:void 0,openInterestAmount:n,openInterestValue:d,timestamp:i,datetime:this.iso8601(i),info:e},t)}async fetchTicker(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};i=!0===s.spot?await this.spotV1PublicGetTicker24hr(this.extend(r,t)):!0===s.inverse?await this.cswapV1PublicGetMarketTicker(this.extend(r,t)):await this.swapV2PublicGetQuoteTicker(this.extend(r,t));let a=this.safeList(i,"data");if(void 0!==a){let e=this.safeDict(a,0,{});return this.parseTicker(e,s)}let o=this.safeDict(i,"data",{});return this.parseTicker(o,s)}async fetchTickers(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e);if(void 0!==r){let e=this.safeString(r,0);void 0!==e&&(s=this.market(e))}let[a,o]=this.handleMarketTypeAndParams("fetchTickers",s,t),[n,d]=this.handleSubTypeAndParams("fetchTickers",s,o);i="spot"===a?await this.spotV1PublicGetTicker24hr(d):"inverse"===n?await this.cswapV1PublicGetMarketTicker(d):await this.swapV2PublicGetQuoteTicker(d);let h=this.safeList(i,"data");return this.parseTickers(h,r)}async fetchMarkPrice(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),[r,a]=this.handleSubTypeAndParams("fetchMarkPrice",s,t,"linear"),o={symbol:s.id};return Array.isArray((i="inverse"===r?await this.cswapV1PublicGetMarketPremiumIndex(this.extend(o,a)):await this.swapV2PublicGetQuotePremiumIndex(this.extend(o,a))).data)?this.parseTicker(this.safeDict(i.data,0,{}),s):this.parseTicker(i.data,s)}async fetchMarkPrices(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e);if(void 0!==r){let e=this.safeString(r,0);void 0!==e&&(s=this.market(e))}let[a,o]=this.handleSubTypeAndParams("fetchMarkPrices",s,t,"linear");i="inverse"===a?await this.cswapV1PublicGetMarketPremiumIndex(o):await this.swapV2PublicGetQuotePremiumIndex(o);let n=this.safeList(i,"data");return this.parseTickers(n,r)}parseTicker(e,t){let i=this.safeString(e,"symbol"),s=this.safeString(e,"lastQty"),r="swap";void 0===s&&(r="spot");let a=this.safeMarket(i,t,void 0,r),o=a.symbol,n=this.safeString(e,"openPrice"),d=this.safeString(e,"highPrice"),h=this.safeString(e,"lowPrice"),c=this.safeString(e,"lastPrice"),l=this.safeString(e,"quoteVolume"),u=this.safeString(e,"volume"),f=this.safeString(e,"priceChangePercent");void 0!==f&&(f=f.replace("%",""));let p=this.safeString(e,"priceChange"),m=this.safeInteger(e,"closeTime");0===m&&(m=void 0);let g=this.iso8601(m),v=this.safeString(e,"bidPrice"),y=this.safeString(e,"bidQty"),b=this.safeString(e,"askPrice"),w=this.safeString(e,"askQty");return this.safeTicker({symbol:o,timestamp:m,datetime:g,high:d,low:h,bid:v,bidVolume:y,ask:b,askVolume:w,vwap:void 0,open:n,close:c,last:void 0,previousClose:void 0,change:p,percentage:f,average:void 0,baseVolume:u,quoteVolume:l,markPrice:this.safeString(e,"markPrice"),indexPrice:this.safeString(e,"indexPrice"),info:e},a)}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionBoolAndParams(e,"fetchBalance","standard",!1),[r,a]=this.handleSubTypeAndParams("fetchBalance",void 0,s),[o,n]=this.handleMarketTypeAndParams("fetchBalance",void 0,a);return t=i?await this.contractV1PrivateGetBalance(n):"funding"===o||"fund"===o?await this.fundV1PrivateGetAccountBalance(n):"spot"===o?await this.spotV1PrivateGetAccountBalance(n):"inverse"===r?await this.cswapV1PrivateGetUserBalance(n):await this.swapV3PrivateGetUserBalance(n),this.parseBalance(t)}parseBalance(e){let t={info:e},i=this.safeList(e,"data"),s=this.safeDict(i,0),r=this.safeDict(e,"data",{}),a=this.safeList2(r,"balances","assets",[]);if(void 0!==s)for(let e=0;e<i.length;e++){let s=this.safeDict(i,e),r=this.safeString(s,"asset");if(void 0===r)break;let a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString2(s,"availableMargin","availableBalance"),o.used=this.safeString(s,"usedMargin"),o.total=this.safeString(s,"maxWithdrawAmount"),void 0!==a&&(t[a]=o)}else for(let e=0;e<a.length;e++){let i=this.safeDict(a,e),s=this.safeString(i,"asset"),r=this.safeCurrencyCode(s),o=this.account();o.free=this.safeString(i,"free"),o.used=this.safeString(i,"locked"),void 0!==r&&(t[r]=o)}return this.safeBalance(t)}async fetchPositionHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={symbol:o.id};void 0!==i&&(n.pageSize=i),void 0!==t&&(n.startTs=t);let[d,h]=this.handleUntilOption("endTs",n,s);if(!0===o.linear)r=await this.swapV1PrivateGetTradePositionHistory(this.extend(d,h));else throw new a.NotSupported(this.id+" fetchPositionHistory() is not supported for inverse swap positions");let c=this.safeDict(r,"data",{}),l=this.safeList(c,"positionHistory",[]),u=this.parsePositions(l);return this.filterBySymbolSinceLimit(u,e,t,i)}async fetchPositions(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e),[r,a]=this.handleOptionBoolAndParams(t,"fetchPositions","standard",!1);if(r)i=await this.contractV1PrivateGetAllPosition(a);else{let e;if(void 0!==s){let t=this.safeString(s,0);void 0!==t&&(e=this.market(t))}let[t,r]=this.handleSubTypeAndParams("fetchPositions",e,a);i="inverse"===t?await this.cswapV1PrivateGetUserPositions(r):await this.swapV2PrivateGetUserPositions(r)}let o=this.safeList(i,"data",[]);return this.parsePositions(o,s)}async fetchPosition(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e);if(!0!==s.swap)throw new a.BadRequest(this.id+" fetchPosition() supports swap markets only");let r={symbol:s.id};i=!0===s.inverse?await this.cswapV1PrivateGetUserPositions(this.extend(r,t)):await this.swapV2PrivateGetUserPositions(this.extend(r,t));let o=this.safeList(i,"data",[]),n=this.safeDict(o,0,{});return this.parsePosition(n,s)}parsePosition(e,t){let i,s=this.safeString(e,"symbol","");s=s.replace("/","-");let r=this.safeBool(e,"isolated");void 0!==r&&(i=r?"isolated":"cross");let a=this.safeInteger(e,"openTime");return this.safePosition({info:e,id:this.safeString(e,"positionId"),symbol:this.safeSymbol(s,t,"-","swap"),notional:this.safeNumber(e,"positionValue"),marginMode:i,liquidationPrice:this.safeNumberOmitZero(e,"liquidationPrice"),entryPrice:this.safeNumber2(e,"avgPrice","entryPrice"),unrealizedPnl:this.safeNumber(e,"unrealizedProfit"),realizedPnl:this.safeNumber(e,"realisedProfit"),percentage:void 0,contracts:this.safeNumber(e,"positionAmt"),contractSize:void 0,markPrice:this.safeNumber(e,"markPrice"),lastPrice:void 0,side:this.safeStringLower(e,"positionSide"),hedged:void 0,timestamp:a,datetime:this.iso8601(a),lastUpdateTimestamp:this.safeInteger(e,"updateTime"),maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,collateral:void 0,initialMargin:this.safeNumber(e,"initialMargin"),initialMarginPercentage:void 0,leverage:this.safeNumber(e,"leverage"),marginRatio:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}async createMarketOrderWithCost(e,t,i,s={}){return s.quoteOrderQty=i,await this.createOrder(e,"market",t,i,void 0,s)}async createMarketBuyOrderWithCost(e,t,i={}){return i.quoteOrderQty=t,await this.createOrder(e,"market","buy",t,void 0,i)}async createMarketSellOrderWithCost(e,t,i={}){return i.quoteOrderQty=t,await this.createOrder(e,"market","sell",t,void 0,i)}createOrderRequest(e,t,i,s,r,n={}){let d;if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let h=this.market(e),c=this.safeString2(n,"cost","quoteOrderQty");if(!0===h.contract&&void 0!==c)throw new a.NotSupported(this.id+" createOrder() with cost or quoteOrderQty is not supported for contract markets");let[l,u]=this.handleMarketTypeAndParams("createOrder",h,n),f=t.toUpperCase(),p={symbol:h.id,type:f,side:i.toUpperCase()},m="MARKET"===f,g="spot"===l,v="TWAP"===f;if(v&&g)throw new a.BadSymbol(this.id+" createOrder() twap order supports swap contracts only");let y=this.safeString(u,"stopLossPrice"),b=this.safeString(u,"takeProfitPrice"),w=this.safeString2(u,"stopPrice","triggerPrice"),k=void 0!==w,S=void 0!==y,O=void 0!==b,T="clientOrderID";g&&(T="newClientOrderId");let P=this.safeString2(u,T,"clientOrderId");void 0!==P&&(p[T]=P);let I=this.safeStringUpper(u,"timeInForce"),[A,x]=this.handlePostOnly(m,"PostOnly"===I,u);if(!0===A||"PostOnly"===I?p.timeInForce="PostOnly":"IOC"===I?p.timeInForce="IOC":"GTC"===I&&(p.timeInForce="GTC"),g){if(d=this.omit(x,["cost","quoteOrderQty"]),void 0!==c)p.quoteOrderQty=this.parseToNumeric(this.costToPrecision(e,c));else if(m&&void 0!==r){let e=o.Y.stringMul(this.numberToString(s),this.numberToString(r));p.quoteOrderQty=this.parseToNumeric(e)}else p.quantity=this.parseToNumeric(this.amountToPrecision(e,s));if(m||(p.price=this.parseToNumeric(this.priceToPrecision(e,r))),void 0!==w){if(m&&"buy"===i&&void 0===this.safeString(p,"quoteOrderQty"))throw new a.ArgumentsRequired(this.id+" createOrder() requires the cost parameter (or the amount + price) for placing spot market-buy trigger orders");p.stopPrice=this.priceToPrecision(e,w),"LIMIT"===f?p.type="TRIGGER_LIMIT":"MARKET"===f&&(p.type="TRIGGER_MARKET")}else if(void 0!==y||void 0!==b){let t=b;void 0!==y&&(t=y),"LIMIT"===f?p.type="TAKE_STOP_LIMIT":"MARKET"===f&&(p.type="TAKE_STOP_MARKET"),p.stopPrice=this.parseToNumeric(this.priceToPrecision(e,t))}}else{if(v){let t={symbol:p.symbol,side:p.side,positionSide:"buy"===i?"LONG":"SHORT",triggerPrice:this.parseToNumeric(this.priceToPrecision(e,w)),totalAmount:this.parseToNumeric(this.amountToPrecision(e,s))};return this.extend(t,x)}"FOK"===I&&(p.timeInForce="FOK");let t=this.safeString(x,"trailingAmount"),a=this.safeString2(x,"trailingPercent","priceRate"),n=this.safeString(x,"trailingType","TRAILING_STOP_MARKET"),c=void 0!==t,l=void 0!==a,u=c||l,g=this.safeDict(x,"stopLoss"),T=this.safeDict(x,"takeProfit"),P=void 0!==g,A=void 0!==T,M=x;P&&(M=this.omit(x,"stopLoss"));let _=M;A&&(_=this.omit(M,"takeProfit")),"LIMIT"!==f&&"TRIGGER_LIMIT"!==f&&"STOP"!==f&&"TAKE_PROFIT"!==f||u||(p.price=this.parseToNumeric(this.priceToPrecision(e,r)));let C=this.safeBool(_,"reduceOnly",!1);if(k)p.stopPrice=this.parseToNumeric(this.priceToPrecision(e,w)),m||"TRIGGER_MARKET"===f?p.type="TRIGGER_MARKET":("LIMIT"===f||"TRIGGER_LIMIT"===f)&&(p.type="TRIGGER_LIMIT");else if(S||O)C=!0,S?(p.stopPrice=this.parseToNumeric(this.priceToPrecision(e,y)),m||"STOP_MARKET"===f?p.type="STOP_MARKET":("LIMIT"===f||"STOP"===f)&&(p.type="STOP")):O&&(p.stopPrice=this.parseToNumeric(this.priceToPrecision(e,b)),m||"TAKE_PROFIT_MARKET"===f?p.type="TAKE_PROFIT_MARKET":("LIMIT"===f||"TAKE_PROFIT"===f)&&(p.type="TAKE_PROFIT"));else if(u){if(p.type=n,c)p.price=this.parseToNumeric(t);else if(l){let e=o.Y.stringDiv(a,"100");p.priceRate=this.parseToNumeric(e)}}if(P||A){let t=this.numberToString(s);if(P){let i=this.safeString2(g,"triggerPrice","stopPrice"),s=this.safeString(g,"workingType","MARK_PRICE"),r=this.safeString(g,"type","STOP_MARKET"),a={stopPrice:this.parseToNumeric(this.priceToPrecision(e,i)),workingType:s,type:r},o=this.safeString(g,"price");void 0!==o&&(a.price=this.parseToNumeric(this.priceToPrecision(e,o)));let n=this.safeString(g,"quantity",t),d=this.parseToNumeric(n);!0!==h.inverse&&(d=this.parseToNumeric(this.amountToPrecision(e,n))),a.quantity=d,p.stopLoss=this.json(a)}if(A){let i=this.safeString2(T,"triggerPrice","stopPrice"),s=this.safeString(T,"workingType","MARK_PRICE"),r=this.safeString(T,"type","TAKE_PROFIT_MARKET"),a={stopPrice:this.parseToNumeric(this.priceToPrecision(e,i)),workingType:s,type:r},o=this.safeString(T,"price");void 0!==o&&(a.price=this.parseToNumeric(this.priceToPrecision(e,o)));let n=this.safeString(T,"quantity",t),d=this.parseToNumeric(n);!0!==h.inverse&&(d=this.parseToNumeric(this.amountToPrecision(e,n))),a.quantity=d,p.takeProfit=this.json(a)}}let B=this.safeBool(_,"hedged",!1);if(d=!0===B?this.omit(_,"reduceOnly"):_,p.positionSide=!0===B?!0===C?"buy"===i?"SHORT":"LONG":"buy"===i?"LONG":"SHORT":"BOTH",!0!==this.safeBool(d,"closePosition",!1)){let t=s;!0!==h.inverse&&(t=this.parseToNumeric(this.amountToPrecision(e,s))),p.quantity=t}}let M=this.omit(d,["hedged","triggerPrice","stopLossPrice","takeProfitPrice","trailingAmount","trailingPercent","trailingType","clientOrderId"]);return this.extend(p,M)}async createOrder(e,t,i,s,r,o={}){let n;void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h=this.safeBool(o,"test",!1);if(h&&(!0!==d.swap||!0===d.inverse))throw new a.NotSupported(this.id+" createOrder() only supports test orders for linear swap markets");let c=this.omit(o,"test"),l=this.createOrderRequest(e,t,i,s,r,c);"string"==typeof(n=!0===d.swap?!0===h?await this.swapV2PrivatePostTradeOrderTest(l):!0===d.inverse?await this.cswapV1PrivatePostTradeOrder(l):"twap"===t?await this.swapV1PrivatePostTwapOrder(l):await this.swapV2PrivatePostTradeOrder(l):await this.spotV1PrivatePostTradeOrder(l))&&(n=this.fixStringifiedJsonMembers(n),n=this.parseJson(n));let u=this.safeDict(n,"data",{}),f={};f=!0===d.swap?!0===d.inverse?n:this.safeDict(u,"order",u):u;let p=this.safeDict(f,"stopLoss"),m=this.safeString(f,"stopLoss");void 0===p&&void 0!==m&&0===m.indexOf("{")&&(f.stopLoss=this.parseJson(m));let g=this.safeString(f,"takeProfit");return void 0!==g&&0===g.indexOf("{")&&(f.takeProfit=this.parseJson(g)),this.parseOrder(f,d)}async createOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=[],r=[];for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),a=this.safeString(i,"symbol",""),o=this.safeString(i,"type");r.push(a);let n=this.safeString(i,"side"),d=this.safeNumber(i,"amount"),h=this.safeNumber(i,"price"),c=this.safeDict(i,"params",{}),l=this.createOrderRequest(a,o,n,d,h,c);s.push(l)}let o=this.marketSymbols(r,void 0,!1,!0,!0),n=o.length,d=this.market(o[0]);if(!0===d.inverse)throw new a.NotSupported(this.id+" createOrders() is not supported for inverse swap markets");let h={};if(!0===d.swap){if(n>5)throw new a.InvalidOrder(this.id+" createOrders() can not create more than 5 orders at once for swap markets");h.batchOrders=this.json(s),i=await this.swapV2PrivatePostTradeBatchOrders(h)}else!0===this.safeBool(t,"sync",!1)&&(h.sync=!0),h.data=this.json(s),i=await this.spotV1PrivatePostTradeBatchOrders(h);"string"==typeof i&&(i=this.fixStringifiedJsonMembers(i),i=this.parseJson(i));let c=this.safeDict(i,"data",{}),l=this.safeList(c,"orders",[]);return this.parseOrders(l,d)}parseOrderSide(e){return this.safeString({BUY:"buy",SELL:"sell",SHORT:"sell",LONG:"buy",ask:"sell",bid:"buy"},e,e)}parseOrderType(e){return this.safeString({trigger_market:"market",trigger_limit:"limit",stop_limit:"limit",stop_market:"market",take_profit_market:"market",stop:"limit"},e,e)}parseOrder(e,t){let i,s,r=this.safeDict2(e,"newOrderResponse","orderOpenResponse"),a=void 0!==r?r:e,n=this.safeString2(a,"positionSide","ps"),d="swap";void 0===n&&(d="spot");let h=this.safeString2(a,"symbol","s"),c=this.safeMarket(void 0===t?h:void 0,t,void 0,d),l=this.safeStringLower2(a,"side","S"),u=this.safeIntegerN(a,["time","transactTime","E","createdTime"]),f=this.safeInteger2(a,"updateTime","T"),p=this.safeStringUpperN(a,["status","X","orderStatus"]),m=this.safeString2(a,"feeAsset","N"),g=this.safeStringN(a,["fee","commission","n"]);void 0===m&&(m=!0===c.spot?"buy"===l?c.base:c.quote:!0===c.inverse?c.settle:c.quote);let v=this.safeValue(a,"stopLoss");void 0!==v&&""!==v&&(i=this.omitZero(this.safeString(v,"stopLoss"))),void 0!==v&&"number"!=typeof v&&""!==v&&("string"==typeof v&&(v=this.parseJson(v)),i=this.omitZero(this.safeString(v,"stopPrice")));let y=this.safeValue(a,"takeProfit");void 0!==y&&""!==y&&(s=this.omitZero(this.safeString(y,"takeProfit"))),void 0!==y&&"number"!=typeof y&&""!==y&&("string"==typeof y&&(y=this.parseJson(y)),s=this.omitZero(this.safeString(y,"stopPrice")));let b=this.safeStringLower2(a,"type","o"),w=this.omitZero(this.safeString2(a,"StopPrice","stopPrice")),k=w;return void 0!==w&&(b.indexOf("stop")>-1&&void 0===i&&(i=w,k=void 0),b.indexOf("take")>-1&&void 0===s&&(s=w,k=void 0)),this.safeOrder({info:e,id:this.safeStringN(a,["orderId","i","mainOrderId"]),clientOrderId:this.safeStringN(a,["clientOrderID","clientOrderId","origClientOrderId","c"]),symbol:this.safeSymbol(h,c,"-",d),timestamp:u,datetime:this.iso8601(u),lastTradeTimestamp:f,lastUpdateTimestamp:this.safeInteger(a,"updateTime"),type:this.parseOrderType(b),timeInForce:this.safeString(a,"timeInForce"),postOnly:void 0,side:this.parseOrderSide(l),price:this.safeString2(a,"price","p"),triggerPrice:k,stopLossPrice:i,takeProfitPrice:s,average:this.safeString2(a,"avgPrice","ap"),cost:this.safeString2(a,"cummulativeQuoteQty","Z"),amount:this.safeStringN(a,["origQty","q","quantity","totalAmount"]),filled:this.safeString2(a,"executedQty","z"),remaining:void 0,status:this.parseOrderStatus(p),fee:{currency:m,cost:o.Y.stringAbs(g)},trades:void 0,reduceOnly:this.safeBool2(a,"reduceOnly","ro")},c)}parseOrderStatus(e){return this.safeString({NEW:"open",PENDING:"open",PARTIALLY_FILLED:"open",RUNNING:"open",FILLED:"closed",CANCELED:"canceled",CANCELLED:"canceled",FAILED:"canceled"},e,e)}async cancelOrder(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets();let o=this.safeBool(i,"twap",!1),n=this.omit(i,"twap");if(!0===o)s=await this.swapV1PrivatePostTwapCancelOrder(this.extend({mainOrderId:e},n));else{if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");let i={symbol:(r=this.market(t)).id},o=this.safeString2(n,"clientOrderId","clientOrderID"),d=this.omit(n,["clientOrderId"]);void 0!==o?i.clientOrderID=o:i.orderId=e;let[h,c]=this.handleMarketTypeAndParams("cancelOrder",r,d),[l,u]=this.handleSubTypeAndParams("cancelOrder",r,c);s="spot"===h?await this.spotV1PrivatePostTradeCancel(this.extend(i,u)):"inverse"===l?await this.cswapV1PrivateDeleteTradeCancelOrder(this.extend(i,u)):await this.swapV2PrivateDeleteTradeOrder(this.extend(i,u))}let d=this.safeDict(s,"data",{}),h=this.safeDict(d,"order",d);return this.parseOrder(h,r)}async cancelAllOrders(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r={};void 0!==e&&(r.symbol=(s=this.market(e)).id);let[o,n]=this.handleMarketTypeAndParams("cancelAllOrders",s,t),[d,h]=this.handleSubTypeAndParams("cancelAllOrders",s,n);if("spot"===o)i=await this.spotV1PrivatePostTradeCancelOpenOrders(this.extend(r,h));else if("swap"===o)i="inverse"===d?await this.cswapV1PrivateDeleteTradeAllOpenOrders(this.extend(r,h)):await this.swapV2PrivateDeleteTradeAllOpenOrders(this.extend(r,h));else throw new a.BadRequest(this.id+" cancelAllOrders is only supported for spot and swap markets.");let c=this.safeDict(i,"data",{}),l=this.safeList2(c,"success","orders",[]);return this.parseOrders(l)}async cancelOrders(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t);if(!0===r.inverse)throw new a.NotSupported(this.id+" cancelOrders() is not supported for inverse swap markets");let o={symbol:r.id},n=this.safeList(i,"clientOrderIds"),d=this.omit(i,"clientOrderIds"),h=e,c=void 0!==n;c&&(h=n);let l=[];for(let e=0;e<h.length;e++){let t=h[e].toString();l.push(t)}if(!0===r.spot){let e="orderIds";c&&(e="clientOrderIDs"),o[e]=l.join(","),s=await this.spotV1PrivatePostTradeCancelOrders(this.extend(o,d))}else c?o.clientOrderIDList=this.json(l):o.orderIdList=l,s=await this.swapV2PrivateDeleteTradeBatchOrders(this.extend(o,d));let u=this.safeDict(s,"data",{}),f=this.safeList2(u,"success","orders",[]);return this.parseOrders(f)}async cancelAllOrdersAfter(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=e>0,r={type:s?"ACTIVATE":"CLOSE",timeOut:s?this.parseToInt(e/1e3):0},[o,n]=this.handleMarketTypeAndParams("cancelAllOrdersAfter",void 0,t),[d,h]=this.handleSubTypeAndParams("cancelAllOrdersAfter",void 0,n);if("swap"===o&&"inverse"===d)throw new a.NotSupported(this.id+" cancelAllOrdersAfter() is not supported for inverse swap markets");if("spot"===o)i=await this.spotV1PrivatePostTradeCancelAllAfter(this.extend(r,h));else if("swap"===o)i=await this.swapV2PrivatePostTradeCancelAllAfter(this.extend(r,h));else throw new a.NotSupported(this.id+" cancelAllOrdersAfter() is not supported for "+o+" markets");return i}async fetchOrder(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets();let o=this.safeBool(i,"twap",!1),n=this.omit(i,"twap");if(!0===o)s=await this.swapV1PrivateGetTwapOrderDetail(this.extend({mainOrderId:e},n));else{if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");let i={symbol:(r=this.market(t)).id,orderId:e},[o,d]=this.handleMarketTypeAndParams("fetchOrder",r,n),[h,c]=this.handleSubTypeAndParams("fetchOrder",r,d);s="spot"===o?await this.spotV1PrivateGetTradeQuery(this.extend(i,c)):"inverse"===h?await this.cswapV1PrivateGetTradeOrderDetail(this.extend(i,c)):await this.swapV2PrivateGetTradeOrder(this.extend(i,c))}let d=this.safeDict(s,"data",{}),h=this.safeDict(d,"order",d);return this.parseOrder(h,r)}async fetchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o={};void 0!==e&&(o.symbol=(r=this.market(e)).id);let[n,d]=this.handleMarketTypeAndParams("fetchOrders",r,s);if("swap"!==n)throw new a.NotSupported(this.id+" fetchOrders() is only supported for swap markets");void 0!==i&&(o.limit=i),void 0!==t&&(o.startTime=t);let[h,c]=this.handleUntilOption("endTime",o,d),l=await this.swapV1PrivateGetTradeFullOrder(this.extend(h,c)),u=this.safeDict(l,"data",{}),f=this.safeList(u,"orders",[]);return this.parseOrders(f,r,t,i)}async fetchOpenOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o={};void 0!==e&&(o.symbol=(a=this.market(e)).id);let[n,d]=this.handleMarketTypeAndParams("fetchOpenOrders",a,s),[h,c]=this.handleSubTypeAndParams("fetchOpenOrders",a,d);if("spot"===n)r=await this.spotV1PrivateGetTradeOpenOrders(this.extend(o,c));else{let e=this.safeBool(c,"twap",!1),t=this.omit(c,"twap");r=!0===e?await this.swapV1PrivateGetTwapOpenOrders(this.extend(o,t)):"inverse"===h?await this.cswapV1PrivateGetTradeOpenOrders(this.extend(o,t)):await this.swapV2PrivateGetTradeOpenOrders(this.extend(o,t))}let l=this.safeDict(r,"data",{}),u=this.safeList2(l,"orders","list",[]);return this.parseOrders(u,a,t,i)}async fetchClosedOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.fetchCanceledAndClosedOrders(e,t,i,s);return this.filterBy(r,"status","closed")}async fetchCanceledOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.fetchCanceledAndClosedOrders(e,t,i,s);return this.filterBy(r,"status","canceled")}async fetchCanceledAndClosedOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o={};void 0!==e&&(o.symbol=(a=this.market(e)).id);let[n,d]=this.handleMarketTypeAndParams("fetchCanceledAndClosedOrders",a,s),[h,c]=this.handleSubTypeAndParams("fetchCanceledAndClosedOrders",a,d),[l,u]=this.handleOptionBoolAndParams(c,"fetchCanceledAndClosedOrders","standard",!1);if(l)r=await this.contractV1PrivateGetAllOrders(this.extend(o,u));else if("spot"===n){void 0!==t&&(o.startTime=t);let e=this.safeInteger2(u,"until","till");void 0!==e&&(o.endTime=e);let s=this.omit(u,["until","till"]);void 0!==i&&(o.pageSize=i),r=await this.spotV1PrivateGetTradeHistoryOrders(this.extend(o,s))}else{let e=this.safeBool(u,"twap",!1),s=this.omit(u,"twap");if(!0===e){o.pageIndex=1,o.pageSize=void 0===i?100:i,o.startTime=void 0===t?1:t;let e=this.safeInteger(s,"until",this.milliseconds()),a=this.omit(s,"until");o.endTime=e,r=await this.swapV1PrivateGetTwapHistoryOrders(this.extend(o,a))}else r="inverse"===h?await this.cswapV1PrivateGetTradeOrderHistory(this.extend(o,s)):await this.swapV2PrivateGetTradeAllOrders(this.extend(o,s))}let f=this.safeDict(r,"data",{}),p=this.safeList2(f,"orders","list",[]);return this.parseOrders(p,a,t,i)}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(e),o=this.safeDict(this.options,"accountsByType",{}),[n,d]=this.handleSubTypeAndParams("transfer",void 0,r),h=this.safeString(o,i,i),c=this.safeString(o,s,s);"swap"===h&&(h="inverse"===n?"coinMPerp":"USDTMPerp"),"swap"===c&&(c="inverse"===n?"coinMPerp":"USDTMPerp");let l={fromAccount:h,toAccount:c,asset:a.id,amount:this.currencyToPrecision(e,t)},u=await this.apiAssetV1PrivatePostTransfer(this.extend(l,d)),f=this.safeDict(u,"data",{}),p=this.safeInteger(u,"timestamp");return{info:u,id:this.safeString2(f,"transferId","tranId"),timestamp:p,datetime:this.iso8601(p),currency:e,amount:t,fromAccount:i,toAccount:s,status:void 0}}async fetchTransfers(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o={};void 0!==e&&(r=this.currency(e));let n=this.safeDict(this.options,"accountsByType",{}),d=this.safeString(s,"fromAccount"),h=this.safeString(s,"toAccount"),c=this.safeString(s,"transferId"),l=this.safeString(n,d,d),u=this.safeString(n,h,h);if(void 0===c&&(void 0===l||void 0===u))throw new a.ExchangeError(this.id+' fetchTransfers() requires params["transferId"] or both params["fromAccount"] and params["toAccount"]');void 0!==d&&(o.fromAccount=l),void 0!==h&&(o.toAccount=u);let[f,p]=this.handleOptionBoolAndParams(s,"fetchTransfers","paginate",!1);if(f)return await this.fetchPaginatedCallDynamic("fetchTransfers",e,t,i,p,100);let m=this.omit(p,["fromAccount","toAccount"]);void 0!==t&&(o.startTime=t),void 0!==i&&(o.pageSize=Math.min(i,100));let[g,v]=this.handleUntilOption("endTime",o,m),y=await this.apiV3PrivateGetAssetTransferRecord(this.extend(g,v)),b=this.safeList(y,"rows",[]);return this.parseTransfers(b,r,t,i)}parseTransfer(e,t){let i=this.safeString(e,"transferId"),s=this.safeInteger(e,"timestamp"),r=this.safeString(e,"asset"),a=this.safeCurrencyCode(r,t),o=this.safeString(e,"status"),n=this.safeDict(this.options,"accountsById",{}),d=this.safeString(e,"fromAccount"),h=this.safeString(e,"toAccount"),c=this.safeString(n,d,d),l=this.safeString(n,h,h);return{info:e,id:i,timestamp:s,datetime:this.iso8601(s),currency:a,amount:this.safeNumber(e,"amount"),fromAccount:c,toAccount:l,status:this.parseTransferStatus(o)}}parseTransferStatus(e){return this.safeString({CONFIRMED:"ok"},e,e)}async fetchDepositAddressesByNetwork(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s=this.safeInteger(this.options,"recvWindow"),r=this.safeInteger(t,"recvWindow",s),a={coin:i.id,offset:0,limit:1e3,recvWindow:r},o=await this.walletsV1PrivateGetCapitalDepositAddress(this.extend(a,t)),n=this.safeList(this.safeDict(o,"data"),"data"),d=this.parseDepositAddresses(n,[i.code],!1);return this.indexBy(d,"network")}async fetchDepositAddress(e,t={}){let i=this.safeString(t,"network"),s=this.omit(t,["network"]),r=await this.fetchDepositAddressesByNetwork(e,s);if(void 0!==i)return this.safeDict(r,i);{let t=this.safeDict(this.options,"defaultNetworks"),i=this.safeString(t,e);if(void 0!==i)return this.safeDict(r,i);{let e=Object.keys(r),t=this.safeString(e,0);return this.safeDict(r,t)}}}parseDepositAddress(e,t){let i=this.safeString(e,"tag"),s=this.safeString(e,"coin"),r=this.safeCurrency(s,t).code,a=this.safeString2(e,"addressWithPrefix","address"),o=this.safeString(e,"network"),n=this.networkIdToCode(o,r);return void 0!==a&&!(a.startsWith("0x")||a.startsWith("0X"))&&this.inArray(n,["BEP20","BSC","ERC20","ETH","HECO","MATIC","POLYGON","ARBITRUM","ARB","OPTIMISM","AVAXC","BASE","FTM","LINEA","ZKSYNC","OPBNB"])&&(a="0x"+a),this.checkAddress(a),{info:e,currency:r,network:n,address:a,tag:i}}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.coin=(r=this.currency(e)).id),void 0!==t&&(a.startTime=t),void 0!==i&&(a.limit=Math.min(i,1e3));let[o,n]=this.handleUntilOption("endTime",a,s),d=await this.spotV3PrivateGetCapitalDepositHisrec(this.extend(o,n));return this.parseTransactions(d,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.coin=(r=this.currency(e)).id),void 0!==t&&(a.startTime=t),void 0!==i&&(a.limit=Math.min(i,1e3));let[o,n]=this.handleUntilOption("endTime",a,s),d=await this.spotV3PrivateGetCapitalWithdrawHistory(this.extend(o,n));return this.parseTransactions(d,r,t,i)}parseTransaction(e,t){let i=this.safeDict(e,"data"),s=void 0===i?void 0:this.safeString(i,"id"),r=this.safeString(e,"id",s),a=this.safeString(e,"address"),o=this.safeString(e,"addressTag"),n=this.safeInteger2(e,"insertTime","timestamp"),d=this.iso8601(n);void 0===n&&(d=this.safeString(e,"applyTime"),n=this.parse8601(d));let h=this.safeString(e,"network"),c=this.safeString(e,"coin"),l=this.safeCurrencyCode(c,t);void 0!==l&&void 0!==h&&l!==h&&l.indexOf(h)>=0&&void 0!==h&&(l=l.replace(h,""));let u=this.safeString(e,"transferType"),f="withdrawal";return"0"===u&&(f="deposit"),{info:e,id:r,txid:this.safeString(e,"txId"),type:f,currency:l,network:this.networkIdToCode(h,l),amount:this.safeNumber(e,"amount"),status:this.parseTransactionStatus(this.safeString(e,"status")),timestamp:n,datetime:d,address:a,addressFrom:void 0,addressTo:a,tag:o,tagFrom:o,tagTo:void 0,updated:void 0,comment:this.safeString(e,"info"),fee:{currency:l,cost:this.safeNumber(e,"transactionFee"),rate:void 0},internal:void 0}}parseTransactionStatus(e){return this.safeString({0:"pending",1:"ok",10:"pending",20:"rejected",30:"ok",40:"rejected",50:"ok",60:"pending",70:"rejected",2:"pending",3:"rejected",4:"pending",5:"rejected",6:"ok"},e,e)}async setMarginMode(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t);if("swap"!==s.type)throw new a.BadSymbol(this.id+" setMarginMode() supports swap contracts only");let r=e.toUpperCase(),o="CROSS"===r?"CROSSED":r;if("ISOLATED"!==o&&"CROSSED"!==o)throw new a.BadRequest(this.id+" setMarginMode() marginMode argument should be isolated or cross");let n={symbol:s.id,marginType:o},[d,h]=this.handleSubTypeAndParams("setMarginMode",s,i);return"inverse"===d?await this.cswapV1PrivatePostTradeMarginType(this.extend(n,h)):await this.swapV2PrivatePostTradeMarginType(this.extend(n,h))}async addMargin(e,t,i={}){return await this.setMargin(e,t,this.extend({type:1},i))}async reduceMargin(e,t,i={}){return await this.setMargin(e,t,this.extend({type:2},i))}async setMargin(e,t,i={}){let s=this.safeInteger(i,"type");if(void 0===s||!this.inArray(s,[1,2]))throw new a.ArgumentsRequired(this.id+" setMargin() requires a type parameter either 1 (increase margin) or 2 (decrease margin)");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={symbol:r.id,amount:this.amountToPrecision(r.symbol,t),type:s},n=await this.swapV2PrivatePostTradePositionMargin(this.extend(o,i));return this.parseMarginModification(n,r)}parseMarginModification(e,t){let i=this.safeString(e,"type");return{info:e,symbol:this.safeString(t,"symbol"),type:"1"===i?"add":"reduce",marginMode:"isolated",amount:this.safeNumber(e,"amount"),total:this.safeNumber(e,"margin"),code:this.safeString(t,"settle"),status:void 0,timestamp:void 0,datetime:void 0}}async fetchLeverage(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};i=!0===s.inverse?await this.cswapV1PrivateGetTradeLeverage(this.extend(r,t)):await this.swapV2PrivateGetTradeLeverage(this.extend(r,t));let a=this.safeDict(i,"data",{});return this.parseLeverage(a,s)}parseLeverage(e,t){let i=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(i,t),marginMode:void 0,longLeverage:this.safeInteger(e,"longLeverage"),shortLeverage:this.safeInteger(e,"shortLeverage")}}async setLeverage(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");let s=this.safeStringUpper(i,"side");this.checkRequiredArgument("setLeverage",s,"side",["LONG","SHORT","BOTH"]);let r=this.omit(i,"side");void 0===this.markets&&await this.loadMarkets();let o=this.market(t),n={symbol:o.id,side:s,leverage:e};return!0===o.inverse?await this.cswapV1PrivatePostTradeLeverage(this.extend(n,r)):await this.swapV2PrivatePostTradeLeverage(this.extend(n,r))}async fetchMyTrades(e,t,i,s={}){let r,o,n;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h={},[c,l]=this.handleSubTypeAndParams("fetchMyTrades",d,s);if("inverse"===c){if(n=this.omit(l,"orderId"),void 0===this.safeString(l,"orderId"))throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires an orderId argument for inverse swap trades");o=await this.cswapV1PrivateGetTradeAllFillOrders(this.extend(h,l)),r=this.safeList(o,"data",[])}else{h.symbol=d.id;let e=this.milliseconds();if(void 0!==t){let e="startTs";!0===d.spot&&(e="startTime"),h[e]=t}else!0===d.swap&&(h.startTs=e-2592e6);let s=this.safeInteger(l,"until"),a=this.omit(l,"until");if(void 0!==s){let e="endTs";!0===d.spot&&(e="endTime"),h[e]=s}else!0===d.swap&&(h.endTs=e);if(!0===d.spot){void 0!==i&&(h.limit=i),n=a,o=await this.spotV1PrivateGetTradeMyTrades(this.extend(h,a));let e=this.safeDict(o,"data",{});r=this.safeList(e,"fills",[])}else{let e=this.safeStringUpper(a,"tradingUnit","CONT");n=this.omit(a,"tradingUnit"),h.tradingUnit=e,o=await this.swapV2PrivateGetTradeAllFillOrders(this.extend(h,n));let t=this.safeDict(o,"data",{});r=this.safeList(t,"fill_orders",[])}}return this.parseTrades(r,d,t,i,n)}parseDepositWithdrawFee(e,t){let i=this.safeDict(e,"networks",{}),s=Object.keys(i),r=s.length,a={info:i,withdraw:{fee:void 0,percentage:void 0},deposit:{fee:void 0,percentage:void 0},networks:{}};if(0!==r)for(let e=0;e<r;e++){let t=s[e],o=this.safeDict(i,t);a.networks[t]={deposit:{fee:void 0,percentage:void 0},withdraw:{fee:this.safeNumber(o,"fee"),percentage:!1}},1===r&&(a.withdraw.fee=this.safeNumber(o,"withdrawFee"),a.withdraw.percentage=!1)}return a}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.fetchCurrencies(t),s={},r=Object.keys(i);for(let t=0;t<r.length;t++){let a=r[t];if(void 0===e||this.inArray(a,e)){let e=this.safeDict(i,a);s[a]=this.parseDepositWithdrawFee(e)}}return s}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),[d,h]=this.handleOptionAndParams2(o,"withdraw","type","walletType",15),c=this.safeInteger({funding:1,fund:1,standard:2,perpetual:3,spot:15},d,15),l={coin:n.id,address:i,amount:this.currencyToPrecision(e,t),walletType:c},u=this.safeStringUpper(h,"network");void 0!==u&&(l.network=this.networkCodeToId(u,this.safeString(n,"code"))),void 0!==a&&(l.addressTag=a);let f=this.omit(h,["walletType","network"]),p=await this.walletsV1PrivatePostCapitalWithdrawApply(this.extend(l,f)),m=this.safeDict(p,"data");return this.parseTransaction(m)}parseParams(e){let t=this.clone(e),i=Object.keys(e),s=this.sort(i);for(let i=0;i<s.length;i++){let r=s[i],a=e[r];if(Array.isArray(a)){let e="[";for(let t=0;t<a.length;t++){let i=a[t];t>0&&(e+=","),e+=i.toString()}e+="]",t[r]=e}}return t}async fetchMyLiquidations(e,t,i,s={}){let r,a,o;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleUntilOption("endTime",{autoCloseType:"LIQUIDATION"},s);void 0!==e&&(n.symbol=(a=this.market(e)).id),void 0!==t&&(n.startTime=t),void 0!==i&&(n.limit=Math.min(i,100));let[h,c]=this.handleSubTypeAndParams("fetchMyLiquidations",a,d);if("inverse"===h)r=await this.cswapV1PrivateGetTradeForceOrders(this.extend(n,c)),o=this.safeList(r,"data",[]);else{r=await this.swapV2PrivateGetTradeForceOrders(this.extend(n,c));let e=this.safeDict(r,"data",{});o=this.safeList(e,"orders",[])}return this.parseLiquidations(o,a,t,i)}parseLiquidation(e,t){let i=this.safeString(e,"symbol"),s=this.safeInteger(e,"time"),r=this.safeString(e,"executedQty"),a=this.safeString(t,"contractSize"),n=this.safeString(e,"avgPrice"),d=o.Y.stringMul(r,a),h=o.Y.stringMul(d,n);return this.safeLiquidation({info:e,symbol:this.safeSymbol(i,t),contracts:this.parseNumber(r),contractSize:this.parseNumber(a),price:this.parseNumber(n),baseValue:this.parseNumber(d),quoteValue:this.parseNumber(h),timestamp:s,datetime:this.iso8601(s)})}async closePosition(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o=this.safeString(i,"positionId"),n={};if(void 0!==o){if(!0!==r.swap||!0===r.inverse)throw new a.NotSupported(this.id+" closePosition() with a positionId is only supported for linear swap markets");s=await this.swapV1PrivatePostTradeClosePosition(this.extend(n,i))}else n.symbol=r.id,s=!0===r.inverse?await this.cswapV1PrivatePostTradeCloseAllPositions(this.extend(n,i)):await this.swapV2PrivatePostTradeCloseAllPositions(this.extend(n,i));let d=this.safeDict(s,"data",{});return this.parseOrder(d,r)}async closeAllPositions(e={}){let t;void 0===this.markets&&await this.loadMarkets();let i=this.safeInteger(this.options,"recvWindow"),s=this.safeInteger(e,"recvWindow",i),[r,o]=this.handleMarketTypeAndParams("closeAllPositions",void 0,e),[n,d]=this.handleSubTypeAndParams("closeAllPositions",void 0,o);if("margin"===r)throw new a.BadRequest(this.id+" closePositions () cannot be used for "+r+" markets");let h={recvWindow:s};t="inverse"===n?await this.cswapV1PrivatePostTradeCloseAllPositions(this.extend(h,d)):await this.swapV2PrivatePostTradeCloseAllPositions(this.extend(h,d));let c=this.safeDict(t,"data",{}),l=this.safeList(c,"success",[]),u=[];for(let e=0;e<l.length;e++){let t=this.parsePosition({positionId:l[e]});u.push(t)}return u}async fetchPositionMode(e,t={}){let i;void 0!==e&&(await this.loadMarkets(),i=this.market(e));let[s,r]=this.handleSubTypeAndParams("fetchPositionMode",i,t);if("inverse"===s||void 0!==i&&!0===i.inverse)throw new a.NotSupported(this.id+" fetchPositionMode() is not supported for inverse swap markets");let o=await this.swapV1PrivateGetPositionSideDual(r),n=this.safeDict(o,"data",{});return{info:o,hedged:"true"===this.safeString(n,"dualSidePosition")}}async setPositionMode(e,t,i={}){let s;void 0!==t&&(await this.loadMarkets(),s=this.market(t));let[r,o]=this.handleSubTypeAndParams("setPositionMode",s,i);if("inverse"===r||void 0!==s&&!0===s.inverse)throw new a.NotSupported(this.id+" setPositionMode() is not supported for inverse swap markets");return await this.swapV1PrivatePostPositionSideDual(this.extend({dualSidePosition:e?"true":"false"},o))}async editOrder(e,t,i,s,r,o,n={}){let d;void 0===this.markets&&await this.loadMarkets();let h=this.market(t);if(!0===h.inverse)throw new a.NotSupported(this.id+" editOrder() is not supported for inverse swap markets");let c=this.createOrderRequest(t,i,s,r,o,n);c.cancelOrderId=e,c.cancelReplaceMode="STOP_ON_FAILURE",d=!0===h.swap?await this.swapV1PrivatePostTradeCancelReplace(c):await this.spotV1PrivatePostTradeOrderCancelReplace(c);let l=this.safeDict(d,"data",{});return this.parseOrder(l,h)}async fetchMarginMode(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id},[a,o]=this.handleSubTypeAndParams("fetchMarginMode",s,t);i="inverse"===a?await this.cswapV1PrivateGetTradeMarginType(this.extend(r,o)):await this.swapV2PrivateGetTradeMarginType(this.extend(r,o));let n=this.safeDict(i,"data",{});return this.parseMarginMode(n,s)}parseMarginMode(e,t){let i=this.safeString(e,"symbol"),s=this.safeStringLower(e,"marginType");return"crossed"===s&&(s="cross"),{info:e,symbol:this.safeSymbol(i,t,"-","swap"),marginMode:s}}async fetchTradingFee(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id},a={};if(!0===s.spot)i=await this.spotV1PrivateGetUserCommissionRate(this.extend(r,t)),a=this.safeDict(i,"data",{});else if(!0===s.inverse)i=await this.cswapV1PrivateGetUserCommissionRate(t),a=this.safeDict(i,"data",{});else{i=await this.swapV2PrivateGetUserCommissionRate(t);let e=this.safeDict(i,"data",{});a=this.safeDict(e,"commission",{})}return this.parseTradingFee(a,s)}parseTradingFee(e,t){return{info:e,symbol:void 0!==t?t.symbol:void 0,maker:this.safeNumber(e,"makerCommissionRate"),taker:this.safeNumber(e,"takerCommissionRate"),percentage:!1,tierBased:!1}}customEncode(e){let t,i=Object.keys(e),s=this.sort(i);for(let i=0;i<s.length;i++){let r=s[i],a=e[r];if(Array.isArray(a)){let e;for(let t=0;t<a.length;t++){let i=a[t];"string"==typeof i?t>0?e+=',"'+i.toString()+'"':e='"'+i.toString()+'"':t>0?e+=","+i.toString():e=i.toString()}a="["+e+"]"}0===i?t=r+"="+a:t+="&"+r+"="+a}return t}async fetchMarketLeverageTiers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new a.BadRequest(this.id+" fetchMarketLeverageTiers() supports swap markets only");if(!0===i.inverse)throw new a.NotSupported(this.id+" fetchMarketLeverageTiers() is not supported for inverse swap markets");let s={symbol:i.id},r=await this.swapV1PrivateGetMaintMarginRatio(this.extend(s,t)),o=this.safeList(r,"data",[]);return this.parseMarketLeverageTiers(o,i)}parseMarketLeverageTiers(e,t){let i=[];for(let s=0;s<e.length;s++){let r=this.safeDict(e,s),a=this.safeString(r,"tier").split(" "),o=this.safeString(r,"symbol"),n=this.safeMarket(o,t,void 0,"swap");i.push({tier:this.safeNumber(a,1),symbol:this.safeSymbol(o,n),currency:this.safeString(n,"settle"),minNotional:this.safeNumber(r,"minPositionVal"),maxNotional:this.safeNumber(r,"maxPositionVal"),maintenanceMarginRate:this.safeNumber(r,"maintMarginRatio"),maxLeverage:void 0,info:r})}return i}sign(e,t="public",i="GET",r={},o,n){let d,h,c=t[0],l=t[1],u=t[2],f=this.safeBool(this.options,"sandboxMode",!1),p=this.implodeHostname(this.urls.api[c]);if(!0===f&&void 0===p)throw new a.NotSupported(this.id+" does not have a testnet/sandbox URL for "+c+" endpoints");let m=this.implodeParams(e,r),g="transfer"===l,v="asset"===l;(g||v)&&(c=g?"account/transfer":"api/asset",l=t[2],u=t[3]),this.inArray(m,["account/apiPermissions","account/apiRestrictions"])||("spot"===c&&"v3"===l?p+="/api":p+="/"+c),p+="/"+l+"/"+m;let y=this.omit(r,this.extractParams(m));y.timestamp=this.nonce();let b=this.keysort(y);if("public"===u)Object.keys(b).length>0&&(p+="?"+this.urlencode(b));else if("private"===u){let e,t;this.checkRequiredCredentials();let r=("subAccount"===c||"account/transfer"===c)&&"POST"===i;r?t=this.customEncode(b):(e=this.parseParams(b),t=this.rawencode(e,!0));let a=void 0===t?"":t,o=this.hmac(this.encode(a),this.encode(this.secret),s.sc);d={"X-BX-APIKEY":this.apiKey,"X-SOURCE-KEY":this.safeString(this.options,"broker","CCXT")},r?(d["Content-Type"]="application/json",b.signature=o,h=this.json(b)):p+="?"+this.urlencode(e,!0)+"&signature="+o}return{url:p,method:i,body:void 0!==h?h:n,headers:void 0!==d?d:o}}nonce(){return this.milliseconds()}setSandboxMode(e){super.setSandboxMode(e),this.options.sandboxMode=e}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"code"),l=this.safeString(n,"msg"),u=this.safeString(n,"transferErrorMsg");if(void 0!==u||void 0!==c&&"0"!==c){void 0!==u&&(l=u);let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,l,e),this.throwExactlyMatchedException(this.exceptions.exact,c,e),this.throwBroadlyMatchedException(this.exceptions.broad,l,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>n})},4984(e,t,i){"use strict";var s=i(4721),r=i(927),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bit2c",name:"Bit2C",countries:["IL"],rateLimit:3e3,pro:!1,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!1,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createReduceOnlyOrder:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchTransfer:!1,fetchTransfers:!1,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,ws:!1},urls:{logo:"https://github.com/user-attachments/assets/db0bce50-6842-4c09-a1d5-0c87d22118aa",api:{rest:"https://bit2c.co.il"},www:"https://www.bit2c.co.il",referral:"https://bit2c.co.il/Aff/63bfed10-e359-420c-ab5a-ad368dab0baf",doc:["https://www.bit2c.co.il/home/api","https://github.com/OferE/bit2c"]},api:{public:{get:{"Exchanges/{pair}/Ticker":{cost:1},"Exchanges/{pair}/orderbook":{cost:1},"Exchanges/{pair}/orderbook-top":{cost:1},"Exchanges/{pair}/trades":{cost:1},"Exchanges/{pair}/lasttrades":{cost:1}}},private:{post:{"Merchant/CreateCheckout":{cost:1},"Funds/AddCoinFundsRequest":{cost:1},"Funds/WithdrawCoin":{cost:1},"Order/AddFund":{cost:1},"Order/AddOrder":{cost:1},"Order/GetById":{cost:1},"Order/AddOrderMarketPriceBuy":{cost:1},"Order/AddOrderMarketPriceSell":{cost:1},"Order/CancelOrder":{cost:1},"Order/AddCoinFundsRequest":{cost:1},"Order/AddStopOrder":{cost:1},"Payment/GetMyId":{cost:1},"Payment/Send":{cost:1},"Payment/Pay":{cost:1}},get:{"Account/Balance":{cost:1},"Account/Balance/v2":{cost:1},"Order/MyOrders":{cost:1},"Order/GetById":{cost:1},"Order/AccountHistory":{cost:1},"Order/OrderHistory":{cost:1},"Order/HistoryByOrderId":{cost:1}}}},markets:{"BTC/NIS":this.safeMarketStructure({id:"BtcNis",symbol:"BTC/NIS",base:"BTC",quote:"NIS",baseId:"Btc",quoteId:"Nis",type:"spot",spot:!0}),"ETH/NIS":this.safeMarketStructure({id:"EthNis",symbol:"ETH/NIS",base:"ETH",quote:"NIS",baseId:"Eth",quoteId:"Nis",type:"spot",spot:!0}),"LTC/NIS":this.safeMarketStructure({id:"LtcNis",symbol:"LTC/NIS",base:"LTC",quote:"NIS",baseId:"Ltc",quoteId:"Nis",type:"spot",spot:!0}),"USDC/NIS":this.safeMarketStructure({id:"UsdcNis",symbol:"USDC/NIS",base:"USDC",quote:"NIS",baseId:"Usdc",quoteId:"Nis",type:"spot",spot:!0})},fees:{trading:{tierBased:!0,percentage:!0,maker:this.parseNumber("0.025"),taker:this.parseNumber("0.03"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.03")],[this.parseNumber("20000"),this.parseNumber("0.0275")],[this.parseNumber("50000"),this.parseNumber("0.025")],[this.parseNumber("75000"),this.parseNumber("0.0225")],[this.parseNumber("100000"),this.parseNumber("0.02")],[this.parseNumber("250000"),this.parseNumber("0.015")],[this.parseNumber("500000"),this.parseNumber("0.0125")],[this.parseNumber("750000"),this.parseNumber("0.01")],[this.parseNumber("1000000"),this.parseNumber("0.008")],[this.parseNumber("2000000"),this.parseNumber("0.006")],[this.parseNumber("3000000"),this.parseNumber("0.004")],[this.parseNumber("4000000"),this.parseNumber("0.002")]],maker:[[this.parseNumber("0"),this.parseNumber("0.025")],[this.parseNumber("20000"),this.parseNumber("0.0225")],[this.parseNumber("50000"),this.parseNumber("0.02")],[this.parseNumber("75000"),this.parseNumber("0.0175")],[this.parseNumber("100000"),this.parseNumber("0.015")],[this.parseNumber("250000"),this.parseNumber("0.01")],[this.parseNumber("500000"),this.parseNumber("0.0075")],[this.parseNumber("750000"),this.parseNumber("0.005")],[this.parseNumber("1000000"),this.parseNumber("0.004")],[this.parseNumber("2000000"),this.parseNumber("0.003")],[this.parseNumber("3000000"),this.parseNumber("0.002")],[this.parseNumber("4000000"),this.parseNumber("0.001")]]}}},options:{fetchTrades:{method:"public_get_exchanges_pair_trades"}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!1,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:30,untilDays:30,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:void 0},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},precisionMode:4,exceptions:{exact:{"Please provide valid APIkey":a.AuthenticationError,"No order found.":a.OrderNotFound},broad:{"Please provide valid nonce":a.InvalidNonce,"please approve new terms of use on site":a.PermissionDenied}}})}parseBalance(e){let t={info:e,timestamp:void 0,datetime:void 0},i=Object.keys(this.currencies);for(let s=0;s<i.length;s++){let r=i[s],a=this.account(),o=this.currency(r).id.toUpperCase();o in e&&(a.free=this.safeString(e,"AVAILABLE_"+o),a.total=this.safeString(e,o)),t[r]=a}return this.safeBalance(t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetAccountBalanceV2(e);return this.parseBalance(t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={pair:this.market(e).id},r=await this.publicGetExchangesPairOrderbook(this.extend(s,i)),a=this.safeList(r,"bids",[]),n=this.safeList(r,"asks",[]),d=[],h=[];for(let e=0;e<a.length;e++){let t=a[e],i=this.safeString(t,1);o.Y.stringGt(i,"0")&&d.push(t)}for(let e=0;e<n.length;e++){let t=n[e],i=this.safeString(t,1);o.Y.stringGt(i,"0")&&h.push(t)}return this.parseOrderBook({bids:d,asks:h},e)}parseTicker(e,t){let i=this.safeSymbol(void 0,t),s=this.safeString(e,"av"),r=this.safeString(e,"a"),a=this.safeString(e,"ll");return this.safeTicker({symbol:i,timestamp:void 0,datetime:void 0,high:void 0,low:void 0,bid:this.safeString(e,"h"),bidVolume:void 0,ask:this.safeString(e,"l"),askVolume:void 0,vwap:void 0,open:void 0,close:a,last:a,previousClose:void 0,change:void 0,percentage:void 0,average:s,baseVolume:r,quoteVolume:void 0,info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={pair:i.id},r=await this.publicGetExchangesPairTicker(this.extend(s,t));return this.parseTicker(r,i)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o=this.safeString(this.options,"fetchTradesMethod"),n=this.handleOption("fetchTrades","method",o),d={pair:r.id};void 0!==t&&(d.date=this.parseToInt(t)),void 0!==i&&(d.limit=i);let h=[];if("public_get_exchanges_pair_trades"===n){let e=await this.publicGetExchangesPairTrades(this.extend(d,s));if("string"==typeof e)throw new a.ExchangeError(e);h=this.toArray(e)}else{let e=await this.publicGetExchangesPairLasttrades(this.extend(d,s));if("string"==typeof e)throw new a.ExchangeError(e);h=this.toArray(e)}return this.parseTrades(h,r,t,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetAccountBalance(e),i=this.safeDict(t,"Fees",{}),s=Object.keys(i),r={};for(let e=0;e<s.length;e++){let t=s[e],a=this.safeSymbol(t),n=this.safeDict(i,t),d=this.safeString(n,"FeeMaker"),h=this.safeString(n,"FeeTaker"),c=this.parseNumber(o.Y.stringDiv(d,"100")),l=this.parseNumber(o.Y.stringDiv(h,"100"));r[a]={info:n,symbol:a,taker:l,maker:c,percentage:!0,tierBased:!0}}return r}async createOrder(e,t,i,s,r,a={}){let n;void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h={Amount:s,Pair:d.id};if("market"===t)n="buy"===i?await this.privatePostOrderAddOrderMarketPriceBuy(this.extend(h,a)):await this.privatePostOrderAddOrderMarketPriceSell(this.extend(h,a));else{h.Price=r;let e=this.numberToString(s),t=this.numberToString(r);h.Total=this.parseToNumeric(o.Y.stringMul(e,t)),h.IsBid="buy"===i,n=await this.privatePostOrderAddOrder(this.extend(h,a))}return this.parseOrder(n,d)}async cancelOrder(e,t,i={}){let s=await this.privatePostOrderCancelOrder(this.extend({id:e},i));return this.parseOrder(s)}async fetchOpenOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOpenOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={pair:r.id},n=await this.privateGetOrderMyOrders(this.extend(o,s)),d=this.safeDict(n,r.id,{}),h=this.safeList(d,"ask",[]),c=this.safeList(d,"bid",[]);return this.parseOrders(this.arrayConcat(h,c),r,t,i)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r=await this.privateGetOrderGetById(this.extend({id:e},i));return this.parseOrder(r,s)}parseOrder(e,t){let i,s,r,a,o=!1;"NewOrder"in e?(i=e.NewOrder,o=!0):i=e;let n=this.safeString(i,"id"),d=this.safeSymbol(void 0,t),h=this.safeIntegerProduct(i,"created",1e3);if(o){let e=this.safeInteger(i,"status_type");0===e||1===e?s="open":5===e&&(s="closed")}else{let e=this.safeString(i,"status");"New"===e||"Open"===e?s="open":"Completed"===e&&(s="closed")}let c=this.safeString(i,"order_type");"0"===c?c="limit":"1"===c&&(c="market");let l=this.safeString(i,"type");"0"===l?l="buy":"1"===l&&(l="sell");let u=this.safeString(i,"price");return r=o?this.safeString(i,"amount"):this.safeString(i,"initialAmount"),a=this.safeString(i,"amount"),this.safeOrder({id:n,clientOrderId:void 0,timestamp:h,datetime:this.iso8601(h),lastTradeTimestamp:void 0,status:s,symbol:d,type:c,timeInForce:void 0,postOnly:void 0,side:l,price:u,triggerPrice:void 0,amount:r,filled:void 0,remaining:a,cost:void 0,trades:void 0,fee:void 0,info:e,average:void 0},t)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==i&&(a.take=i),a.take=i,void 0!==t&&(a.toTime=this.yyyymmdd(this.milliseconds(),"."),a.fromTime=this.yyyymmdd(t,".")),void 0!==e&&(a.pair=(r=this.market(e)).id);let o=await this.privateGetOrderOrderHistory(this.extend(a,s)),n=[];return void 0!==o&&(n=this.toArray(o)),this.parseTrades(n,r,t,i)}removeCommaFromValue(e){let t="",i=e.split(",");for(let e=0;e<i.length;e++)t+=i[e];return t}parseTrade(e,t){let i,s,r,a,o,n,d,h,c,l=this.safeString(e,"reference");if(void 0!==l){s=l,i=this.safeTimestamp(e,"ticks");let u=this.safeString(e,"price");void 0!==u&&(a=this.removeCommaFromValue(u)),o=this.safeString(e,"firstAmount");let f=l.split("|"),p=this.safeString(e,"pair"),m=this.safeMarket(p,t);c=this.safeMarket(f[0],m);let g=this.safeBool(e,"isMaker");h=!0===g?"maker":"taker",n=!0===g?f[2]:f[1],r=0===this.safeInteger(e,"action")?"buy":"sell";let v=this.safeString(e,"feeAmount");void 0!==v&&(d={cost:v,currency:"NIS"})}else i=this.safeTimestamp(e,"date"),s=this.safeString(e,"tid"),a=this.safeString(e,"price"),o=this.safeString(e,"amount"),c=this.safeMarket(void 0,t),void 0!==(r=this.safeValue(e,"isBid"))&&(r=void 0!==r&&""!==r?"buy":"sell");let u=this.safeMarket(void 0,c);return this.safeTrade({info:e,id:s,timestamp:i,datetime:this.iso8601(i),symbol:u.symbol,order:n,type:void 0,side:r,takerOrMaker:h,price:a,amount:o,cost:void 0,fee:d},u)}isFiat(e){return"NIS"===e}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e);if(this.isFiat(e))throw new a.NotSupported(this.id+" fetchDepositAddress() does not support fiat currencies");let s={Coin:i.id},r=await this.privatePostFundsAddCoinFundsRequest(this.extend(s,t));return this.parseDepositAddress(r,i)}parseDepositAddress(e,t){let i=this.safeString(e,"address");return this.checkAddress(i),{info:e,currency:this.safeCurrencyCode(void 0,t),network:void 0,address:i,tag:void 0}}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},o,n){let d,h,c=this.safeString(this.urls.api,"rest");if(void 0===c)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let l=c+"/"+this.implodeParams(e,r);if("public"===t)l+=".json";else{this.checkRequiredCredentials();let e=this.incrementingNonce(),t=this.extend({nonce:e},r),a=this.urlencode(t);"GET"===i?Object.keys(t).length>0&&(l+="?"+a):d=a;let o=this.hmac(this.encode(a),this.encode(this.secret),s.Zf,"base64");h={"Content-Type":"application/x-www-form-urlencoded",key:this.apiKey,sign:o}}return{url:l,method:i,body:void 0===d?n:d,headers:void 0===h?o:h}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"error");if(void 0===c&&(c=this.safeString(n,"Error")),void 0!==c){let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,c,e),this.throwBroadlyMatchedException(this.exceptions.broad,c,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>n})},4749(e,t,i){"use strict";var s=i(4721),r=i(2330),a=i(1453);class o extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bitbank",name:"bitbank",countries:["JP"],version:"v1",rateLimit:100,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!1,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createReduceOnlyOrder:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchTransfer:!1,fetchTransfers:!1,fetchVolatilityHistory:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,withdraw:!0},timeframes:{"1m":"1min","5m":"5min","15m":"15min","30m":"30min","1h":"1hour","4h":"4hour","8h":"8hour","12h":"12hour","1d":"1day","1w":"1week"},hostname:"bitbank.cc",urls:{logo:"https://github.com/user-attachments/assets/9d616de0-8a88-4468-8e38-d269acab0348",api:{public:"https://public.{hostname}",private:"https://api.{hostname}",markets:"https://api.{hostname}"},www:"https://bitbank.cc/",doc:"https://docs.bitbank.cc/",fees:"https://bitbank.cc/docs/fees/"},api:{public:{get:{"{pair}/ticker":{cost:1},tickers:{cost:1},tickers_jpy:{cost:1},"{pair}/depth":{cost:1},"{pair}/transactions":{cost:1},"{pair}/transactions/{yyyymmdd}":{cost:1},"{pair}/candlestick/{candletype}/{yyyymmdd}":{cost:1},"{pair}/circuit_break_info":{cost:1}}},private:{get:{"user/assets":{cost:1},"user/spot/order":{cost:1},"user/spot/active_orders":{cost:1},"user/margin/status":{cost:1},"user/margin/positions":{cost:1},"user/spot/trade_history":{cost:1},"user/deposit_history":{cost:1},"user/unconfirmed_deposits":{cost:1},"user/deposit_originators":{cost:1},"user/withdrawal_account":{cost:1},"user/withdrawal_history":{cost:1},"spot/status":{cost:1},"spot/pairs":{cost:1}},post:{"user/spot/order":{cost:1.66},"user/spot/cancel_order":{cost:1.66},"user/spot/cancel_orders":{cost:1.66},"user/spot/orders_info":{cost:1.66},"user/confirm_deposits":{cost:1.66},"user/confirm_deposits_all":{cost:1.66},"user/request_withdrawal":{cost:1.66}}},markets:{get:{"spot/pairs":{cost:1}}}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:void 0,untilDays:void 0,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:1e3,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:{limit:1e3}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},precisionMode:4,exceptions:{exact:{20001:a.AuthenticationError,20002:a.AuthenticationError,20003:a.AuthenticationError,20005:a.AuthenticationError,20004:a.InvalidNonce,40020:a.InvalidOrder,40021:a.InvalidOrder,40025:a.ExchangeError,40013:a.OrderNotFound,40014:a.OrderNotFound,50008:a.PermissionDenied,50009:a.OrderNotFound,50010:a.OrderNotFound,60001:a.InsufficientFunds,60005:a.InvalidOrder}}})}async fetchMarkets(e={}){let t=await this.marketsGetSpotPairs(e),i=this.safeDict(t,"data"),s=this.safeList(i,"pairs",[]);return this.parseMarkets(s)}parseMarket(e){let t=this.safeString(e,"name"),i=this.safeString(e,"base_asset"),s=this.safeString(e,"quote_asset"),r=this.safeCurrencyCode(i),a=this.safeCurrencyCode(s);if(void 0!==r&&void 0!==a)return this.safeMarketStructure({id:t,symbol:r+"/"+a,base:r,quote:a,settle:void 0,baseId:i,quoteId:s,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:this.safeBool(e,"is_enabled"),contract:!1,linear:void 0,inverse:void 0,taker:this.safeNumber(e,"taker_fee_rate_quote"),maker:this.safeNumber(e,"maker_fee_rate_quote"),contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(e,"amount_digits"))),price:this.parseNumber(this.parsePrecision(this.safeString(e,"price_digits")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(e,"unit_amount"),max:this.safeNumber(e,"limit_max_amount")},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:e})}parseTicker(e,t){let i=this.safeSymbol(void 0,t),s=this.safeInteger(e,"timestamp"),r=this.safeString(e,"last");return this.safeTicker({symbol:i,timestamp:s,datetime:this.iso8601(s),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"buy"),bidVolume:void 0,ask:this.safeString(e,"sell"),askVolume:void 0,vwap:void 0,open:void 0,close:r,last:r,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"vol"),quoteVolume:void 0,info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={pair:i.id},r=await this.publicGetPairTicker(this.extend(s,t)),a=this.safeDict(r,"data",{});return this.parseTicker(a,i)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={pair:s.id},a=await this.publicGetPairDepth(this.extend(r,i)),o=this.safeDict(a,"data",{}),n=this.safeInteger(o,"timestamp");return this.parseOrderBook(o,s.symbol,n)}parseTrade(e,t){let i,s=this.safeInteger(e,"executed_at"),r=this.safeMarket(void 0,t),a=this.safeString(e,"price"),o=this.safeString(e,"amount"),n=this.safeString2(e,"transaction_id","trade_id"),d=this.safeString(e,"maker_taker"),h=this.safeString(e,"fee_amount_quote");void 0!==h&&(i={currency:r.quote,cost:h});let c=this.safeString(e,"order_id"),l=this.safeString(e,"type"),u=this.safeString(e,"side");return this.safeTrade({timestamp:s,datetime:this.iso8601(s),symbol:r.symbol,id:n,order:c,type:l,side:u,takerOrMaker:d,price:a,amount:o,cost:void 0,fee:i,info:e},r)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={pair:r.id},o=await this.publicGetPairTransactions(this.extend(a,s)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"transactions",[]);return this.parseTrades(d,r,t,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.marketsGetSpotPairs(e),i=this.safeDict(t,"data",{}),s=this.safeList(i,"pairs",[]),r={};for(let e=0;e<s.length;e++){let t=s[e],i=this.safeString(t,"name"),a=this.safeMarket(i).symbol;r[a]={info:t,symbol:a,maker:this.safeNumber(t,"maker_fee_rate_quote"),taker:this.safeNumber(t,"taker_fee_rate_quote"),percentage:!0,tierBased:!1}}return r}parseOHLCV(e,t){return[this.safeInteger(e,5),this.safeNumber(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4)]}async fetchOHLCV(e,t="1m",i,s,r={}){let a=void 0===s?1e3:s,o=void 0===i?a:s,n=this.parseTimeframe(t),d=void 0===i?this.milliseconds()-1e3*n*a:i;void 0===this.markets&&await this.loadMarkets();let h=this.market(e),c={pair:h.id,candletype:this.safeString(this.timeframes,t,t),yyyymmdd:this.yyyymmdd(d,"")},l=await this.publicGetPairCandlestickCandletypeYyyymmdd(this.extend(c,r)),u=this.safeDict(l,"data",{}),f=this.safeList(u,"candlestick",[]),p=this.safeDict(f,0,{}),m=this.safeList(p,"ohlcv",[]);return this.parseOHLCVs(m,h,t,d,o)}parseBalance(e){let t={info:e,timestamp:void 0,datetime:void 0},i=this.safeDict(e,"data",{}),s=this.safeList(i,"assets",[]);for(let e=0;e<s.length;e++){let i=this.safeDict(s,e),r=this.safeString(i,"asset"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(i,"free_amount"),o.used=this.safeString(i,"locked_amount"),o.total=this.safeString(i,"onhand_amount"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetUserAssets(e);return this.parseBalance(t)}parseOrderStatus(e){return this.safeString({UNFILLED:"open",PARTIALLY_FILLED:"open",FULLY_FILLED:"closed",CANCELED_UNFILLED:"canceled",CANCELED_PARTIALLY_FILLED:"canceled"},e,e)}parseOrder(e,t){let i=this.safeString(e,"order_id"),s=this.safeString(e,"pair"),r=this.safeMarket(s,t),a=this.safeInteger(e,"ordered_at"),o=this.safeString(e,"price"),n=this.safeString(e,"start_amount"),d=this.safeString(e,"executed_amount"),h=this.safeString(e,"remaining_amount"),c=this.safeString(e,"average_price"),l=this.parseOrderStatus(this.safeString(e,"status")),u=this.safeStringLower(e,"type"),f=this.safeStringLower(e,"side");return this.safeOrder({id:i,clientOrderId:void 0,datetime:this.iso8601(a),timestamp:a,lastTradeTimestamp:void 0,status:l,symbol:r.symbol,type:u,timeInForce:void 0,postOnly:void 0,side:f,price:o,triggerPrice:void 0,cost:void 0,average:c,amount:n,filled:d,remaining:h,trades:void 0,fee:void 0,info:e},r)}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={pair:o.id,amount:this.amountToPrecision(e,s),side:i,type:t};"limit"===t&&(n.price=this.priceToPrecision(e,r));let d=await this.privatePostUserSpotOrder(this.extend(n,a)),h=this.safeDict(d,"data");return this.parseOrder(h,o)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={order_id:e,pair:this.market(t).id},r=await this.privatePostUserSpotCancelOrder(this.extend(s,i)),a=this.safeDict(r,"data");return this.parseOrder(a)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r={order_id:e,pair:s.id},a=await this.privateGetUserSpotOrder(this.extend(r,i)),o=this.safeDict(a,"data");return this.parseOrder(o,s)}async fetchOpenOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={pair:r.id};void 0!==i&&(a.count=i),void 0!==t&&(a.since=this.parseToInt(t/1e3));let o=await this.privateGetUserSpotActiveOrders(this.extend(a,s)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"orders",[]);return this.parseOrders(d,r,t,i)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.pair=(r=this.market(e)).id),void 0!==i&&(a.count=i),void 0!==t&&(a.since=this.parseToInt(t/1e3));let o=await this.privateGetUserSpotTradeHistory(this.extend(a,s)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"trades",[]);return this.parseTrades(d,r,t,i)}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={asset:i.id},r=await this.privateGetUserWithdrawalAccount(this.extend(s,t)),a=this.safeDict(r,"data",{}),o=this.safeList(a,"accounts",[]),n=this.safeDict(o,0,{}),d=this.safeString(n,"address");return{info:r,currency:i.code,network:void 0,address:d,tag:void 0}}async withdraw(e,t,i,s,r={}){let o=this.handleWithdrawTagAndParams(s,r)[1];if(!("uuid"in o))throw new a.ExchangeError(this.id+" uuid is required for withdrawal");void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d={asset:n.id,amount:t},h=await this.privatePostUserRequestWithdrawal(this.extend(d,o)),c=this.safeDict(h,"data",{});return this.parseTransaction(c,n)}parseTransaction(e,t){let i=this.safeString(e,"txid");return{id:i,txid:i,timestamp:void 0,datetime:void 0,network:void 0,addressFrom:void 0,address:void 0,addressTo:void 0,amount:void 0,type:void 0,currency:this.safeCurrency(void 0,t).code,status:void 0,updated:void 0,tagFrom:void 0,tag:void 0,tagTo:void 0,comment:void 0,internal:void 0,fee:void 0,info:e}}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},o,n){let d,h,c=this.omit(r,this.extractParams(e)),l=this.safeString(this.urls.api,t);if(void 0===l)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let u=this.implodeHostname(l)+"/";if("public"===t||"markets"===t)u+=this.implodeParams(e,r),Object.keys(c).length>0&&(u+="?"+this.urlencode(c));else{this.checkRequiredCredentials();let t="timeWindow"===this.safeString(this.options,"authMethod","timeWindow"),a=this.milliseconds().toString(),o=this.safeString(this.options,"timeWindow","5000"),n=this.incrementingNonce().toString(),l=n;t&&(l=a+o),u+=this.version+"/"+this.implodeParams(e,r),"POST"===i?l+=d=this.json(c):(l+="/"+this.version+"/"+e,Object.keys(c).length>0&&(u+="?"+(c=this.urlencode(c)),l+="?"+c)),h={"Content-Type":"application/json","ACCESS-KEY":this.apiKey,"ACCESS-SIGNATURE":this.hmac(this.encode(l),this.encode(this.secret),s.sc)},t?(h["ACCESS-REQUEST-TIME"]=a,h["ACCESS-TIME-WINDOW"]=o):h["ACCESS-NONCE"]=n}return{url:u,method:i,body:void 0===d?n:d,headers:void 0===h?o:h}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeInteger(n,"success"),l=this.safeDict(n,"data");if(void 0===c||0===c||void 0===l){let e=this.safeString(l,"code"),t=this.safeString({1e4:"URL does not exist",10001:"A system error occurred. Please contact support",10002:"Invalid JSON format. Please check the contents of transmission",10003:"A system error occurred. Please contact support",10005:"A timeout error occurred. Please wait for a while and try again",20001:"API authentication failed",20002:"Illegal API key",20003:"API key does not exist",20004:"API Nonce does not exist",20005:"API signature does not exist",20011:"Two-step verification failed",20014:"SMS authentication failed",30001:"Please specify the order quantity",30006:"Please specify the order ID",30007:"Please specify the order ID array",30009:"Please specify the stock",30012:"Please specify the order price",30013:"Trade Please specify either",30015:"Please specify the order type",30016:"Please specify asset name",30019:"Please specify uuid",30039:"Please specify the amount to be withdrawn",40001:"The order quantity is invalid",40006:"Count value is invalid",40007:"End time is invalid",40008:"end_id Value is invalid",40009:"The from_id value is invalid",40013:"The order ID is invalid",40014:"The order ID array is invalid",40015:"Too many specified orders",40017:"Incorrect issue name",40020:"The order price is invalid",40021:"The trading classification is invalid",40022:"Start date is invalid",40024:"The order type is invalid",40025:"Incorrect asset name",40028:"uuid is invalid",40048:"The amount of withdrawal is illegal",50003:"Currently, this account is in a state where you can not perform the operation you specified. Please contact support",50004:"Currently, this account is temporarily registered. Please try again after registering your account",50005:"Currently, this account is locked. Please contact support",50006:"Currently, this account is locked. Please contact support",50008:"User identification has not been completed",50009:"Your order does not exist",50010:"Can not cancel specified order",50011:"API not found",60001:"The number of possessions is insufficient",60002:"It exceeds the quantity upper limit of the tender buying order",60003:"The specified quantity exceeds the limit",60004:"The specified quantity is below the threshold",60005:"The specified price is above the limit",60006:"The specified price is below the lower limit",70001:"A system error occurred. Please contact support",70002:"A system error occurred. Please contact support",70003:"A system error occurred. Please contact support",70004:"We are unable to accept orders as the transaction is currently suspended",70005:"Order can not be accepted because purchase order is currently suspended",70006:"We can not accept orders because we are currently unsubscribed ",70009:"We are currently temporarily restricting orders to be carried out. Please use the limit order.",70010:"We are temporarily raising the minimum order quantity as the system load is now rising."},e,"Error");throw this.throwExactlyMatchedException(this.exceptions.exact,e,t),new a.ExchangeError(this.id+" "+this.json(n))}}}i.d(t,{A:()=>o})},7658(e,t,i){"use strict";var s=i(4721),r=i(5987),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bitbns",name:"Bitbns",countries:["IN"],rateLimit:1e3,certified:!1,version:"v2",has:{CORS:void 0,spot:!0,margin:void 0,swap:!1,future:!1,option:void 0,cancelAllOrders:!1,cancelOrder:!0,createOrder:!0,createStopOrder:!0,createTriggerOrder:!0,fechCurrencies:!1,fetchBalance:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchFundingHistory:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchIndexOHLCV:!1,fetchMarginMode:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyTrades:!0,fetchOHLCV:!1,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchPositionMode:!1,fetchPremiumIndexOHLCV:!1,fetchStatus:!0,fetchTicker:"emulated",fetchTickers:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTransfer:!1,fetchTransfers:!1,fetchWithdrawal:!1,fetchWithdrawals:!0,transfer:!1,withdraw:!1},hostname:"bitbns.com",urls:{logo:"https://github.com/user-attachments/assets/a5b9a562-cdd8-4bea-9fa7-fd24c1dad3d9",api:{www:"https://{hostname}",v1:"https://api.{hostname}/api/trade/v1",v2:"https://api.{hostname}/api/trade/v2"},www:"https://bitbns.com",referral:"https://ref.bitbns.com/1090961",doc:["https://bitbns.com/trade/#/api-trading/"],fees:"https://bitbns.com/fees"},api:{www:{get:{"order/fetchMarkets":{cost:1},"order/fetchTickers":{cost:1},"order/fetchOrderbook":{cost:1},"order/getTickerWithVolume":{cost:1},"exchangeData/ohlc":{cost:1},"exchangeData/orderBook":{cost:1},"exchangeData/tradedetails":{cost:1}}},v1:{get:{"platform/status":{cost:1},tickers:{cost:1},"orderbook/sell/{symbol}":{cost:1},"orderbook/buy/{symbol}":{cost:1}},post:{"currentCoinBalance/EVERYTHING":{cost:1},"getApiUsageStatus/USAGE":{cost:1},"getOrderSocketToken/USAGE":{cost:1},"currentCoinBalance/{symbol}":{cost:1},"orderStatus/{symbol}":{cost:1},"depositHistory/{symbol}":{cost:1},"withdrawHistory/{symbol}":{cost:1},"withdrawHistoryAll/{symbol}":{cost:1},"depositHistoryAll/{symbol}":{cost:1},userHistoryNew:{cost:1},"listOpenOrders/{symbol}":{cost:1},"listOpenOrdersOther/{symbol}":{cost:1},"listOpenStopOrders/{symbol}":{cost:1},"getCoinAddress/{symbol}":{cost:1},"placeSellOrder/{symbol}":{cost:1},"placeSellOrderOther/{symbol}":{cost:1},"placeBuyOrder/{symbol}":{cost:1},"placeBuyOrderOther/{symbol}":{cost:1},"buyStopLoss/{symbol}":{cost:1},"sellStopLoss/{symbol}":{cost:1},"cancelOrder/{symbol}":{cost:1},"cancelOrderOther/{symbol}":{cost:1},"cancelStopLossOrder/{symbol}":{cost:1},"listExecutedOrders/{symbol}":{cost:1},"placeMarketOrder/{symbol}":{cost:1},"placeMarketOrderQnty/{symbol}":{cost:1}}},v2:{post:{orders:{cost:1},cancel:{cost:1},getordersnew:{cost:1},marginOrders:{cost:1}}}},fees:{trading:{feeSide:"quote",tierBased:!1,percentage:!0,taker:this.parseNumber("0.0025"),maker:this.parseNumber("0.0025")}},precisionMode:4,features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!1,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:void 0,daysBack:void 0,untilDays:void 0,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!0,trailing:!1,symbolRequired:!0},fetchOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:{limit:100}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},exceptions:{exact:{400:a.BadRequest,409:a.BadSymbol,416:a.InsufficientFunds,417:a.OrderNotFound},broad:{}}})}async fetchStatus(e={}){let t=await this.v1GetPlatformStatus(e),i=this.safeString(t,"status");return{status:this.safeString({1:"ok"},i,i),updated:void 0,eta:void 0,url:void 0,info:t}}async fetchMarkets(e={}){let t=await this.wwwGetOrderFetchMarkets(e),i=[],s=this.toArray(t);for(let e=0;e<s.length;e++){let t=s[e],r=this.safeString(t,"id"),a=this.safeString(t,"base"),o=this.safeString(t,"quote"),n=this.safeCurrencyCode(a),d=this.safeCurrencyCode(o);if(void 0===a||void 0===n||void 0===d)continue;let h=this.safeDict(t,"precision",{}),c=this.safeDict(t,"limits",{}),l=this.safeDict(c,"amount",{}),u=this.safeDict(c,"price",{}),f=this.safeDict(c,"cost",{}),p=a;"USDT"===o&&(p=a+"_"+o),i.push({id:r,uppercaseId:p,symbol:n+"/"+d,base:n,quote:d,settle:void 0,baseId:a,quoteId:o,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:this.safeBool(t,"active"),contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(h,"amount"))),price:this.parseNumber(this.parsePrecision(this.safeString(h,"price")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(l,"min"),max:this.safeNumber(l,"max")},price:{min:this.safeNumber(u,"min"),max:this.safeNumber(u,"max")},cost:{min:this.safeNumber(f,"min"),max:this.safeNumber(f,"max")}},created:void 0,info:t})}return i}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};void 0!==t&&(r.limit=t);let a=await this.wwwGetOrderFetchOrderbook(this.extend(r,i)),o=this.safeInteger(a,"timestamp");return this.parseOrderBook(a,s.symbol,o)}parseTicker(e,t){let i=this.safeInteger(e,"timestamp"),s=this.safeString(e,"symbol"),r=this.safeSymbol(s,t),a=this.safeString(e,"last");return this.safeTicker({symbol:r,timestamp:i,datetime:this.iso8601(i),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"bid"),bidVolume:this.safeString(e,"bidVolume"),ask:this.safeString(e,"ask"),askVolume:this.safeString(e,"askVolume"),vwap:this.safeString(e,"vwap"),open:this.safeString(e,"open"),close:a,last:a,previousClose:this.safeString(e,"previousClose"),change:this.safeString(e,"change"),percentage:this.safeString(e,"percentage"),average:this.safeString(e,"average"),baseVolume:this.safeString(e,"baseVolume"),quoteVolume:this.safeString(e,"quoteVolume"),info:e},t)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.wwwGetOrderFetchTickers(t);return this.parseTickers(i,e)}parseBalance(e){let t,i={info:e,timestamp:t,datetime:this.iso8601(t)},s=this.safeDict(e,"data",{}),r=Object.keys(s);for(let e=0;e<r.length;e++){let t=r[e],a=t.split("availableorder");if(a.length>1){let e=this.safeString(a,1),r=this.account();r.free=this.safeString(s,t),r.used=this.safeString(s,"inorder"+e),"Money"===e&&(e="INR");let o=this.safeCurrencyCode(e);void 0!==o&&(i[o]=r)}}return this.safeBalance(i)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v1PostCurrentCoinBalanceEVERYTHING(e);return this.parseBalance(t)}parseStatus(e){return this.safeString({"-1":"cancelled",0:"open",1:"open",2:"done"},e,e)}parseOrder(e,t){let i=this.safeString2(e,"id","entry_id"),s=this.safeString(e,"time"),r=this.safeString(e,"t_rate"),a=this.safeString(e,"type");"0"===a?a="buy":"1"===a&&(a="sell");let o=this.safeString(e,"data"),n=this.safeString(e,"status");return n="Successfully cancelled the order"===o?"cancelled":this.parseStatus(n),this.safeOrder({info:e,id:i,clientOrderId:void 0,timestamp:this.parse8601(s),datetime:s,lastTradeTimestamp:void 0,symbol:this.safeString(t,"symbol"),timeInForce:void 0,postOnly:void 0,side:a,price:this.safeString(e,"rate"),triggerPrice:r,amount:this.safeString(e,"btc"),cost:void 0,average:void 0,filled:void 0,remaining:void 0,status:n,fee:{cost:void 0,currency:void 0,rate:void 0},trades:void 0},t)}async createOrder(e,t,i,s,r,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=this.safeStringN(a,["triggerPrice","stopPrice","t_rate"]),h=this.safeString(a,"target_rate"),c=this.safeString(a,"trail_rate"),l=this.omit(a,["triggerPrice","stopPrice","trail_rate","target_rate","t_rate"]);this.checkRequiredArgument("createOrder",i,"side");let u={side:i.toUpperCase(),symbol:n.uppercaseId,quantity:this.amountToPrecision(e,s)};"limit"===t?u.rate=this.priceToPrecision(e,r):u.market=n.quoteId,void 0!==d&&(u.t_rate=this.priceToPrecision(e,d)),void 0!==h&&(u.target_rate=this.priceToPrecision(e,h)),void 0!==c&&(u.trail_rate=this.priceToPrecision(e,c));let f=void 0===(o="limit"===t?await this.v2PostOrders(this.extend(u,l)):await this.v1PostPlaceMarketOrderQntySymbol(this.extend(u,l)))?{}:o;return this.parseOrder(f,n)}async cancelOrder(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),o=this.safeBool2(i,"trigger","stop"),n=this.omit(i,["trigger","stop"]),d={entry_id:e,symbol:r.uppercaseId},h="USDT"===r.quoteId?"usdtcancel":"cancel";d.side=h+=!0===o?"StopLossOrder":"Order";let c=void 0===(s=await this.v2PostCancel(this.extend(d,n)))?{}:s;return this.parseOrder(c,r)}async fetchOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r={symbol:s.id,entry_id:e};if(!0===this.safeBool2(i,"trigger","stop"))throw new a.BadRequest(this.id+" fetchOrder cannot fetch stop orders");let o=await this.v1PostOrderStatusSymbol(this.extend(r,i)),n=this.safeList(o,"data",[]),d=this.safeDict(n,0,{});return this.parseOrder(d,s)}async fetchOpenOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOpenOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o=this.safeBool2(s,"trigger","stop"),n=this.omit(s,["trigger","stop"]),d="listOpen";"USDT"===r.quoteId&&(d="usdtListOpen");let h={symbol:r.uppercaseId,page:0,side:!0===o?d+"StopOrders":d+"Orders"},c=await this.v2PostGetordersnew(this.extend(h,n)),l=this.safeList(c,"data",[]);return this.parseOrders(l,r,t,i)}parseTrade(e,t){let i,s,r=this.safeMarket(void 0,t),a=this.safeString2(e,"id","tradeId"),n=this.parse8601(this.safeString(e,"date"));n=this.safeInteger(e,"timestamp",n);let d=this.safeString2(e,"rate","price"),h=this.safeString(e,"amount"),c=this.safeStringLower(e,"type");void 0!==c&&(c.indexOf("buy")>=0?c="buy":c.indexOf("sell")>=0&&(c="sell"));let l=this.safeString(e,"factor");void 0!==l?h=o.Y.stringDiv(h,l):(h=this.safeString(e,"base_volume"),i=this.safeString(e,"quote_volume"));let u=r.symbol,f=this.safeString(e,"fee");return void 0!==f&&(s={cost:f,currency:r.quote}),this.safeTrade({info:e,timestamp:n,datetime:this.iso8601(n),symbol:u,id:a,order:a,type:void 0,side:c,takerOrMaker:void 0,price:d,amount:h,cost:i,fee:s},r)}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={symbol:r.id,page:0};void 0!==t&&(o.since=this.iso8601(t));let n=await this.v1PostListExecutedOrdersSymbol(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTrades(d,r,t,i)}async fetchTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={coin:r.baseId,market:r.quoteId},n=await this.wwwGetExchangeDataTradedetails(this.extend(o,s));return this.parseTrades(n,r,t,i)}async fetchDeposits(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchDeposits() requires a currency code argument");void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),o={symbol:r.id,page:0},n=await this.v1PostDepositHistorySymbol(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTransactions(d,r,t,i)}async fetchWithdrawals(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchWithdrawals() requires a currency code argument");void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),o={symbol:r.id,page:0},n=await this.v1PostWithdrawHistorySymbol(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTransactions(d,r,t,i)}parseTransactionStatusByType(e,t){let i=this.safeDict({deposit:{0:"pending",1:"ok"},withdrawal:{0:"pending",1:"canceled",2:"pending",3:"failed",4:"pending",5:"failed",6:"ok"}},t,{});return this.safeString(i,e,e)}parseTransaction(e,t){let i,s,r=this.safeString(e,"unit"),a=this.safeCurrencyCode(r,t),o=this.parse8601(this.safeString2(e,"date","timestamp")),n=this.safeString(e,"type"),d=this.safeString(e,"expTime","");void 0!==n&&(n.indexOf("deposit")>=0?(n="deposit",i="ok"):(n.indexOf("withdraw")>=0||d.indexOf("withdraw")>=0)&&(n="withdrawal"));let h=this.safeNumber(e,"amount"),c=this.safeNumber(e,"fee");return void 0!==c&&(s={currency:a,cost:c}),{info:e,id:void 0,txid:void 0,timestamp:o,datetime:this.iso8601(o),network:void 0,address:void 0,addressTo:void 0,addressFrom:void 0,tag:void 0,tagTo:void 0,tagFrom:void 0,type:n,amount:h,currency:a,status:i,updated:void 0,comment:void 0,internal:void 0,fee:s}}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={symbol:this.currency(e).id},s=await this.v1PostGetCoinAddressSymbol(this.extend(i,t)),r=this.safeDict(s,"data",{}),a=this.safeString(r,"token"),o=this.safeString(r,"tag");return this.checkAddress(a),{info:s,currency:e,network:void 0,address:a,tag:o}}nonce(){return this.milliseconds()}sign(e,t="www",i="GET",r={},o,n){if(!(t in this.urls.api))throw new a.ExchangeError(this.id+" does not have a testnet/sandbox URL for "+t+" endpoints");"www"!==t&&this.checkRequiredCredentials();let d={"X-BITBNS-APIKEY":this.apiKey},h="www"!==t?d:o,c=this.safeString(this.urls.api,t);if(void 0===c)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let l=this.implodeHostname(c)+"/"+this.implodeParams(e,r),u=this.omit(r,this.extractParams(e)),f=this.nonce().toString(),p=Object.keys(u).length,m="{}";p>0&&(m=this.json(u));let g="POST"===i?m:n;if("GET"===i)p>0&&(l+="?"+this.urlencode(u));else if("POST"===i){let e=this.stringToBase64(this.json({timeStamp_nonce:f,body:g})),t=this.hmac(this.encode(e),this.encode(this.secret),s.Zf);(h=void 0===h?{}:h)["X-BITBNS-PAYLOAD"]=e,h["X-BITBNS-SIGNATURE"]=t,h["Content-Type"]="application/x-www-form-urlencoded"}return{url:l,method:i,body:g,headers:h}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"code"),l=this.safeString(n,"msg");if(void 0!==c&&"200"!==c&&"204"!==c||void 0!==l){let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,c,e),this.throwExactlyMatchedException(this.exceptions.exact,l,e),this.throwBroadlyMatchedException(this.exceptions.broad,l,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>n})},7967(e,t,i){"use strict";var s=i(4721),r=i(1453),a=i(7749),o=i(4986);class n extends o.A{describe(){return this.deepExtend(super.describe(),{id:"bitfinex",name:"Bitfinex",countries:["VG"],version:"v2",certified:!1,pro:!0,has:{CORS:void 0,spot:!0,margin:!0,swap:!0,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,createDepositAddress:!0,createLimitOrder:!0,createMarketOrder:!0,createOrder:!0,createOrders:!0,createPostOnlyOrder:!0,createReduceOnlyOrder:!0,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,createTrailingAmountOrder:!0,createTrailingPercentOrder:!1,createTriggerOrder:!0,editOrder:!0,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrder:!0,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDepositsWithdrawals:!0,fetchFundingHistory:!1,fetchFundingRate:"emulated",fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLedger:!0,fetchLeverage:!1,fetchLeverageTiers:!1,fetchLiquidations:!0,fetchMarginMode:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!0,fetchOpenInterests:!0,fetchOpenOrder:!0,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrderTrades:!0,fetchPosition:!1,fetchPositionMode:!1,fetchPositions:!0,fetchPremiumIndexOHLCV:!1,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!1,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchTransactionFees:void 0,fetchTransactions:"emulated",fetchVolatilityHistory:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!0,setMarginMode:!1,setPositionMode:!1,signIn:!1,transfer:!0,withdraw:!0},timeframes:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","3h":"3h","4h":"4h","6h":"6h","12h":"12h","1d":"1D","1w":"7D","2w":"14D","1M":"1M"},rateLimit:250,urls:{logo:"https://github.com/user-attachments/assets/4a8e947f-ab46-481a-a8ae-8b20e9b03178",api:{v1:"https://api.bitfinex.com",public:"https://api-pub.bitfinex.com",private:"https://api.bitfinex.com"},www:"https://www.bitfinex.com",doc:["https://docs.bitfinex.com/v2/docs/","https://github.com/bitfinexcom/bitfinex-api-node"],fees:"https://www.bitfinex.com/fees"},api:{public:{get:{"conf/{config}":{cost:2.7},"conf/pub:{action}:{object}":{cost:2.7},"conf/pub:{action}:{object}:{detail}":{cost:2.7},"conf/pub:map:{object}":{cost:2.7},"conf/pub:map:{object}:{detail}":{cost:2.7},"conf/pub:map:currency:{detail}":{cost:2.7},"conf/pub:map:currency:sym":{cost:2.7},"conf/pub:map:currency:label":{cost:2.7},"conf/pub:map:currency:unit":{cost:2.7},"conf/pub:map:currency:undl":{cost:2.7},"conf/pub:map:currency:pool":{cost:2.7},"conf/pub:map:currency:explorer":{cost:2.7},"conf/pub:map:currency:tx:fee":{cost:2.7},"conf/pub:map:tx:method":{cost:2.7},"conf/pub:list:{object}":{cost:2.7},"conf/pub:list:{object}:{detail}":{cost:2.7},"conf/pub:list:currency":{cost:2.7},"conf/pub:list:pair:exchange":{cost:2.7},"conf/pub:list:pair:margin":{cost:2.7},"conf/pub:list:pair:futures":{cost:2.7},"conf/pub:list:competitions":{cost:2.7},"conf/pub:info:{object}":{cost:2.7},"conf/pub:info:{object}:{detail}":{cost:2.7},"conf/pub:info:pair":{cost:2.7},"conf/pub:info:pair:futures":{cost:2.7},"conf/pub:info:tx:status":{cost:2.7},"conf/pub:fees":{cost:2.7},"platform/status":{cost:8},tickers:{cost:2.7},"ticker/{symbol}":{cost:2.7},"tickers/hist":{cost:2.7},"trades/{symbol}/hist":{cost:2.7},"book/{symbol}/{precision}":{cost:1},"book/{symbol}/P0":{cost:1},"book/{symbol}/P1":{cost:1},"book/{symbol}/P2":{cost:1},"book/{symbol}/P3":{cost:1},"book/{symbol}/R0":{cost:1},"stats1/{key}:{size}:{symbol}:{side}/{section}":{cost:2.7},"stats1/{key}:{size}:{symbol}:{side}/last":{cost:2.7},"stats1/{key}:{size}:{symbol}:{side}/hist":{cost:2.7},"stats1/{key}:{size}:{symbol}/{section}":{cost:2.7},"stats1/{key}:{size}:{symbol}/last":{cost:2.7},"stats1/{key}:{size}:{symbol}/hist":{cost:2.7},"stats1/{key}:{size}:{symbol}:long/last":{cost:2.7},"stats1/{key}:{size}:{symbol}:long/hist":{cost:2.7},"stats1/{key}:{size}:{symbol}:short/last":{cost:2.7},"stats1/{key}:{size}:{symbol}:short/hist":{cost:2.7},"candles/trade:{timeframe}:{symbol}:{period}/{section}":{cost:2.7},"candles/trade:{timeframe}:{symbol}/{section}":{cost:2.7},"candles/trade:{timeframe}:{symbol}/last":{cost:2.7},"candles/trade:{timeframe}:{symbol}/hist":{cost:2.7},"status/{type}":{cost:2.7},"status/deriv":{cost:2.7},"status/deriv/{symbol}/hist":{cost:2.7},"liquidations/hist":{cost:80},"rankings/{key}:{timeframe}:{symbol}/{section}":{cost:2.7},"rankings/{key}:{timeframe}:{symbol}/hist":{cost:2.7},"pulse/hist":{cost:2.7},"pulse/profile/{nickname}":{cost:2.7},"funding/stats/{symbol}/hist":{cost:10},"ext/vasps":{cost:1}},post:{"calc/trade/avg":{cost:2.7},"calc/fx":{cost:2.7}}},private:{post:{"auth/r/wallets":{cost:2.7},"auth/r/wallets/hist":{cost:2.7},"auth/r/orders":{cost:2.7},"auth/r/orders/{symbol}":{cost:2.7},"auth/w/order/submit":{cost:2.7},"auth/w/order/update":{cost:2.7},"auth/w/order/cancel":{cost:2.7},"auth/w/order/multi":{cost:2.7},"auth/w/order/cancel/multi":{cost:2.7},"auth/r/orders/{symbol}/hist":{cost:2.7},"auth/r/orders/hist":{cost:2.7},"auth/r/orders/otc/{symbol}/hist":{cost:2.7},"auth/r/order/{symbol}:{id}/trades":{cost:2.7},"auth/r/trades/{symbol}/hist":{cost:2.7},"auth/r/trades/hist":{cost:2.7},"auth/r/ledgers/{currency}/hist":{cost:2.7},"auth/r/ledgers/hist":{cost:2.7},"auth/r/info/margin/{key}":{cost:2.7},"auth/r/info/margin/base":{cost:2.7},"auth/r/info/margin/sym_all":{cost:2.7},"auth/r/positions":{cost:2.7},"auth/w/position/claim":{cost:2.7},"auth/w/position/increase:":{cost:2.7},"auth/r/position/increase/info":{cost:2.7},"auth/r/positions/hist":{cost:2.7},"auth/r/positions/audit":{cost:2.7},"auth/r/positions/snap":{cost:2.7},"auth/w/position/update/funding/type":{cost:2.7},"auth/w/deriv/collateral/set":{cost:2.7},"auth/w/deriv/collateral/limits":{cost:2.7},"auth/r/funding/offers":{cost:2.7},"auth/r/funding/offers/{symbol}":{cost:2.7},"auth/w/funding/offer/submit":{cost:2.7},"auth/w/funding/offer/cancel":{cost:2.7},"auth/w/funding/offer/cancel/all":{cost:2.7},"auth/w/funding/close":{cost:2.7},"auth/w/funding/auto":{cost:2.7},"auth/w/funding/keep":{cost:2.7},"auth/r/funding/offers/{symbol}/hist":{cost:2.7},"auth/r/funding/offers/hist":{cost:2.7},"auth/r/funding/loans":{cost:2.7},"auth/r/funding/loans/hist":{cost:2.7},"auth/r/funding/loans/{symbol}":{cost:2.7},"auth/r/funding/loans/{symbol}/hist":{cost:2.7},"auth/r/funding/credits":{cost:2.7},"auth/r/funding/credits/hist":{cost:2.7},"auth/r/funding/credits/{symbol}":{cost:2.7},"auth/r/funding/credits/{symbol}/hist":{cost:2.7},"auth/r/funding/trades/{symbol}/hist":{cost:2.7},"auth/r/funding/trades/hist":{cost:2.7},"auth/r/info/funding/{key}":{cost:2.7},"auth/r/info/user":{cost:2.7},"auth/r/summary":{cost:2.7},"auth/r/logins/hist":{cost:2.7},"auth/r/permissions":{cost:2.7},"auth/w/token":{cost:2.7},"auth/r/audit/hist":{cost:2.7},"auth/w/transfer":{cost:2.7},"auth/w/deposit/address":{cost:24},"auth/r/deposit/address/all":{cost:24},"auth/w/deposit/invoice":{cost:24},"auth/r/ext/invoice/payments":{cost:2.7},"auth/w/withdraw":{cost:24},"auth/r/movements/{currency}/hist":{cost:2.7},"auth/r/movements/hist":{cost:2.7},"auth/r/movements/info":{cost:2.7},"auth/r/alerts":{cost:5.34},"auth/w/alert/set":{cost:2.7},"auth/w/alert/price:{symbol}:{price}/del":{cost:2.7},"auth/w/alert/{type}:{symbol}:{price}/del":{cost:2.7},"auth/calc/order/avail":{cost:2.7},"auth/w/settings/set":{cost:2.7},"auth/r/settings":{cost:2.7},"auth/w/settings/del":{cost:2.7},"auth/r/pulse/hist":{cost:2.7},"auth/w/pulse/add":{cost:16},"auth/w/pulse/del":{cost:2.7},"auth/w/ext/wallets/deposits/request":{cost:2.7},"auth/w/ext/wallets/withdrawals/request":{cost:2.7},"auth/r/ext/wallets/transfers/free/count":{cost:2.7}}}},fees:{trading:{feeSide:"get",percentage:!0,tierBased:!0,maker:this.parseNumber("0.001"),taker:this.parseNumber("0.002"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.002")],[this.parseNumber("500000"),this.parseNumber("0.002")],[this.parseNumber("1000000"),this.parseNumber("0.002")],[this.parseNumber("2500000"),this.parseNumber("0.002")],[this.parseNumber("5000000"),this.parseNumber("0.002")],[this.parseNumber("7500000"),this.parseNumber("0.002")],[this.parseNumber("10000000"),this.parseNumber("0.0018")],[this.parseNumber("15000000"),this.parseNumber("0.0016")],[this.parseNumber("20000000"),this.parseNumber("0.0014")],[this.parseNumber("25000000"),this.parseNumber("0.0012")],[this.parseNumber("30000000"),this.parseNumber("0.001")]],maker:[[this.parseNumber("0"),this.parseNumber("0.001")],[this.parseNumber("500000"),this.parseNumber("0.0008")],[this.parseNumber("1000000"),this.parseNumber("0.0006")],[this.parseNumber("2500000"),this.parseNumber("0.0004")],[this.parseNumber("5000000"),this.parseNumber("0.0002")],[this.parseNumber("7500000"),this.parseNumber("0")],[this.parseNumber("10000000"),this.parseNumber("0")],[this.parseNumber("15000000"),this.parseNumber("0")],[this.parseNumber("20000000"),this.parseNumber("0")],[this.parseNumber("25000000"),this.parseNumber("0")],[this.parseNumber("30000000"),this.parseNumber("0")]]}},funding:{withdraw:{}}},precisionMode:3,options:{fetchOrderBook:{precision:"R0"},fetchCurrencies:{defaultPrecision:8},exchangeTypes:{MARKET:"market","EXCHANGE MARKET":"market",LIMIT:"limit","EXCHANGE LIMIT":"limit","EXCHANGE STOP":"market","EXCHANGE FOK":"limit","EXCHANGE STOP LIMIT":"limit","EXCHANGE IOC":"limit"},orderTypes:{market:"EXCHANGE MARKET",limit:"EXCHANGE LIMIT"},fiat:{USD:"USD",EUR:"EUR",JPY:"JPY",GBP:"GBP",CHN:"CHN"},v2AccountsByType:{spot:"exchange",exchange:"exchange",funding:"funding",margin:"margin",derivatives:"margin",future:"margin",swap:"margin"},withdraw:{includeFee:!1},networks:{BTC:"BITCOIN",LTC:"LITECOIN",ERC20:"ETHEREUM",OMNI:"TETHERUSO",LIQUID:"TETHERUSL",TRC20:"TETHERUSX",EOS:"TETHERUSS",AVAX:"TETHERUSDTAVAX",SOL:"TETHERUSDTSOL",ALGO:"TETHERUSDTALG",BCH:"TETHERUSDTBCH",KSM:"TETHERUSDTKSM",DVF:"TETHERUSDTDVF",OMG:"TETHERUSDTOMG"},networksById:{TETHERUSE:"ERC20"}},features:{default:{sandbox:!1,createOrder:{marginMode:!0,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!0,leverage:!0,marketBuyRequiresPrice:!1,marketBuyByCost:!0,selfTradePrevention:!1,iceberg:!1},createOrders:{max:75},fetchMyTrades:{marginMode:!1,limit:2500,daysBack:void 0,untilDays:1e5,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:void 0,daysBack:void 0,daysBackCanceled:void 0,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:1e4}},spot:{extends:"default"},swap:{linear:{extends:"default"},inverse:void 0},future:{linear:void 0,inverse:void 0}},exceptions:{exact:{11010:r.RateLimitExceeded,10001:r.PermissionDenied,10020:r.BadRequest,10100:r.AuthenticationError,10114:r.InvalidNonce,20060:r.OnMaintenance,temporarily_unavailable:r.ExchangeNotAvailable},broad:{"available balance is only":r.InsufficientFunds,"not enough exchange balance":r.InsufficientFunds,"Order not found":r.OrderNotFound,"symbol: invalid":r.BadSymbol}},commonCurrencies:{UST:"USDT",EUTF0:"EURT",USTF0:"USDT",ALG:"ALGO",AMP:"AMPL",ATO:"ATOM",BCHABC:"XEC",BCHN:"BCH",DAT:"DATA",DOG:"MDOGE",DSH:"DASH",EDO:"PNT",EUS:"EURS",EUT:"EURT",HTX:"HT",IDX:"ID",IOT:"IOTA",IQX:"IQ",LUNA:"LUNC",LUNA2:"LUNA",MNA:"MANA",ORS:"ORS Group",PAS:"PASS",QSH:"QASH",QTM:"QTUM",RBT:"RBTC",SNG:"SNGLS",STJ:"STORJ",TERRAUST:"USTC",TSD:"TUSD",YGG:"YEED",YYW:"YOYOW",UDC:"USDC",VSY:"VSYS",WAX:"WAXP",XCH:"XCHF",ZBT:"ZB"}})}isFiat(e){return e in this.options.fiat}getCurrencyName(e){if(e in this.options.currencyNames)return this.options.currencyNames[e];throw new r.NotSupported(this.id+" "+e+" not supported for withdrawal")}amountToPrecision(e,t){let i=this.safeSymbol(e),s=this.market(i);return this.decimalToPrecision(t,0,s.precision.amount,2)}priceToPrecision(e,t){let i=this.safeSymbol(e),s=this.market(i),r=this.decimalToPrecision(t,1,s.precision.price,this.precisionMode);return this.decimalToPrecision(r,0,8,2)}async fetchStatus(e={}){let t=await this.publicGetPlatformStatus(e),i=this.safeString(t,0);return{status:this.safeString({0:"maintenance",1:"ok"},i,i),updated:void 0,eta:void 0,url:void 0,info:t}}async fetchMarkets(e={}){let t=await this.publicGetConfConfig(this.extend({config:"pub:info:pair,pub:info:pair:futures,pub:list:pair:securities,pub:list:pair:margin"},e)),i=this.safeList(t,0,[]),s=this.safeList(t,1,[]),r=this.safeList(t,3,[]),a=this.arrayConcat(i,s),o=[];for(let e=0;e<a.length;e++){let t,i,s,n,d,h=this.safeList(a,e),c=this.safeStringUpper(h,0),l=this.safeValue(h,1,{}),u=!0;c.indexOf("F0")>=0?(u=!1,t="swap"):t="spot";let f="swap"===t;if(c.indexOf(":")>=0){let e=c.split(":");i=e[0],s=e[1]}else i=c.slice(0,3),s=c.slice(3,6);let p=this.safeCurrencyCode(i),m=this.safeCurrencyCode(s),g=p.split("F0"),v=m.split("F0");if(p=this.safeString(g,0),m=this.safeString(v,0),void 0===p||void 0===m)continue;let y=p+"/"+m;f&&(n=m,d=m,y=y+":"+n);let b=this.safeString(l,3),w=this.safeString(l,4);o.push({id:"t"+c,symbol:y,base:p,quote:m,settle:n,baseId:i,quoteId:s,settleId:d,type:t,spot:u,margin:u&&this.inArray(c,r),swap:f,future:!1,option:!1,active:!0,contract:!u,linear:!!f||void 0,inverse:!f&&void 0,contractSize:f?this.parseNumber("1"):void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:parseInt("8"),price:parseInt("5")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.parseNumber(b),max:this.parseNumber(w)},price:{min:this.parseNumber("1e-8"),max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:l})}return o}async fetchCurrencies(e={}){let t=await this.publicGetConfConfig(this.extend({config:"pub:list:currency,pub:map:currency:sym,pub:map:currency:label,pub:map:currency:unit,pub:map:currency:undl,pub:map:currency:pool,pub:map:currency:explorer,pub:map:currency:tx:fee,pub:map:tx:method,pub:info:tx:status,pub:list:currency:margin"},e)),i={sym:this.indexBy(this.safeList(t,1,[]),0),label:this.indexBy(this.safeList(t,2,[]),0),unit:this.indexBy(this.safeList(t,3,[]),0),undl:this.indexBy(this.safeList(t,4,[]),0),pool:this.indexBy(this.safeList(t,5,[]),0),explorer:this.indexBy(this.safeList(t,6,[]),0),fees:this.indexBy(this.safeList(t,7,[]),0),networks:this.safeList(t,8,[]),statuses:this.indexBy(this.safeList(t,9,[]),0),marginables:this.safeList(t,10,[])},s={};for(let e=0;e<i.networks.length;e++){let t=this.safeList(i.networks,e),r=this.safeString(t,0),a=this.safeList(t,1),o=this.safeString(a,0),n=this.safeList(s,o,[]);n.push(r),s[o]=n}let r=this.safeList(t,0,[]);return this.parseCurrenciesCustom(r,i,s)}parseCurrenciesCustom(e,t,i){let s=[];for(let t=0;t<e.length;t++){let i=e[t];i.endsWith("F0")||s.push(i)}let r={},a=this.toArray(s);for(let e=0;e<a.length;e++){let s=this.parseCurrencyCustom(a[e],t,i);r[s.code]=s}return r}parseCurrencyCustom(e,t,i){let s=this.safeCurrencyCode(e),r=this.safeList(t.label,e,[]),a=this.safeString(r,1),o=this.safeList(t.pool,e,[]),n=void 0!==this.safeString(o,1)||e in t.explorer,d=this.safeList(t.fees,e,[]),h=this.safeList(d,1,[]),c=this.safeNumber(h,1),l=this.safeList(t.undl,e,[]),u=this.safeString(this.options,"defaultCurrencyPrecision","8"),f=this.numberToString(this.handleOption("fetchCurrencies","defaultPrecision",u)),p={},m=this.safeList(i,e,[]);for(let e=0;e<m.length;e++){let i=this.safeString(m,e);if(void 0===i)continue;let r=this.networkIdToCode(i,s),a=this.safeList(t.statuses,i,[]);void 0!==r&&(p[r]={info:i,id:i.toLowerCase(),network:i,active:void 0,deposit:1===this.safeInteger(a,1),withdraw:1===this.safeInteger(a,2),fee:void 0,precision:void 0,limits:{withdraw:{min:void 0,max:void 0}}})}return this.safeCurrencyStructure({id:e,code:s,info:[e,r,o,d,l],type:n?"crypto":void 0,name:a,active:!0,deposit:void 0,withdraw:void 0,fee:c,precision:this.parseNumber(f),limits:{amount:{min:void 0,max:void 0},withdraw:{min:c,max:void 0}},networks:p,margin:this.inArray(e,t.marginables)})}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=this.safeDict(this.options,"v2AccountsByType",{}),i=this.safeString(e,"type","exchange"),s=this.safeString(t,i,i);if(void 0===s){let e=Object.keys(t);throw new r.ExchangeError(this.id+" fetchBalance() type parameter must be one of "+e.join(", "))}let a="derivatives"===i,o=this.omit(e,"type"),n=await this.privatePostAuthRWallets(o),d=this.toArray(n),h={info:n};for(let e=0;e<d.length;e++){let t=this.safeList(d,e),i=this.account(),r=this.safeString(t,3);"0"!==r&&(i.debt=r);let o=this.safeString(t,0),n=this.safeStringLower(t,1,""),c=n.length-2,l="f0"===n.slice(c),u=!a||l;if(s===o&&u){let e=this.safeCurrencyCode(n);i.total=this.safeString(t,2),i.free=this.safeString(t,4),void 0!==e&&(h[e]=i)}}return this.safeBalance(h)}async transfer(e,t,i,s,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.safeDict(this.options,"v2AccountsByType",{}),n=this.safeString(o,i);if(void 0===n){let e=Object.keys(o);throw new r.ArgumentsRequired(this.id+" transfer() fromAccount must be one of "+e.join(", "))}let d=this.safeString(o,s);if(void 0===d){let e=Object.keys(o);throw new r.ArgumentsRequired(this.id+" transfer() toAccount must be one of "+e.join(", "))}let h=this.currency(e),c=this.convertDerivativesId(h,i),l=this.convertDerivativesId(h,s),u=this.currencyToPrecision(e,t),f=await this.privatePostAuthWTransfer(this.extend({amount:u,currency:c,currency_to:l,from:n,to:d},a));if("error"===this.safeString(f,0)){let e=this.safeString(f,2,"");throw this.throwExactlyMatchedException(this.exceptions.exact,e,this.id+" "+e),new r.ExchangeError(this.id+" "+e)}return this.parseTransfer({result:f},h)}parseTransfer(e,t){let i=this.safeList(e,"result"),s=this.safeInteger(i,0),r=this.safeList(i,4),a=this.safeString(r,1),o=this.safeString(r,2),n=this.safeString(r,5),d=this.safeString(i,6);return{id:void 0,timestamp:s,datetime:this.iso8601(s),status:this.parseTransferStatus(d),amount:this.safeNumber(r,7),currency:this.safeCurrencyCode(n,t),fromAccount:a,toAccount:o,info:i}}parseTransferStatus(e){return this.safeString({SUCCESS:"ok",ERROR:"failed",FAILURE:"failed"},e,e)}convertDerivativesId(e,t){let i,s=this.safeList(e,"info"),r=this.safeString(s,0),a=this.safeList(s,4,[]);if("derivatives"===t){let e=(i=this.safeString(a,0,r)).length-2;"F0"!==i.slice(e)&&(i+="F0")}else i="margin"!==t?this.safeString(a,1,r):r;return i}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.handleOption("fetchOrderBook","precision","R0"),r=this.market(e),o={symbol:r.id,precision:s};void 0!==t&&(o.len=t);let n=this.extend(o,i),d=await this.publicGetBookSymbolPrecision(n),h=this.milliseconds(),c={symbol:r.symbol,bids:[],asks:[],timestamp:h,datetime:this.iso8601(h),nonce:void 0},l=+("R0"===n.precision),u=this.toArray(d);for(let e=0;e<u.length;e++){let t=u[e],i=this.safeNumber(t,l),s=this.safeString(t,2),r=a.Y.stringAbs(s),o="asks";a.Y.stringGt(s,"0")&&(o="bids"),c[o].push([i,this.parseNumber(r)])}return c.bids=this.sortBy(c.bids,0,!0),c.asks=this.sortBy(c.asks,0),c}parseTicker(e,t){let i,s,r,o,n,d,h,c,l,u,f=e.length,p=this.safeString(e,0),m=!(void 0!==p&&(p.startsWith("t")||p.startsWith("f"))),g=0;m&&(g=1);let v=this.safeString(e,0);return s=m?t:this.safeMarket(v,t),i=this.safeSymbol(void 0,s),f>=17?(r=this.safeString(e,10-g),o=this.safeString(e,2-g),n=this.safeString(e,5-g),d=this.safeString(e,8-g),h=a.Y.stringMul(this.safeString(e,9-g),"100"),c=this.safeString(e,11-g),l=this.safeString(e,12-g),u=this.safeString(e,13-g)):(r=this.safeString(e,7-g),o=this.safeString(e,1-g),n=this.safeString(e,3-g),d=this.safeString(e,5-g),h=this.safeString(e,6-g),h=a.Y.stringMul(h,"100"),c=this.safeString(e,8-g),l=this.safeString(e,9-g),u=this.safeString(e,10-g)),this.safeTicker({symbol:i,timestamp:void 0,datetime:void 0,high:l,low:u,bid:o,bidVolume:void 0,ask:n,askVolume:void 0,vwap:void 0,open:void 0,close:r,last:r,previousClose:void 0,change:d,percentage:h,average:void 0,baseVolume:c,quoteVolume:void 0,info:e},s)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s={};void 0!==i?s.symbols=this.marketIds(i).join(","):s.symbols="ALL";let r=await this.publicGetTickers(this.extend(s,t));return this.parseTickers(r,i)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetTickerSymbol(this.extend(s,t));return this.parseTicker(r,i)}parseTrade(e,t){let i,s,r,o,n,d=this.safeList(e,"result",[]),h=d.length>5,c=this.safeString(d,0),l=this.safeString(d,h?4:2),u=this.safeString(d,h?5:3);"-"===l[0]?(i="sell",l=a.Y.stringAbs(l)):i="buy";let f=this.safeSymbol(void 0,t),p=this.safeInteger(d,h?2:1);if(h){let e=d[1];f=this.safeSymbol(e),s=this.safeString(d,3),r=1===this.safeInteger(d,8)?"maker":"taker";let t=this.safeString(d,9);t=a.Y.stringNeg(t);let i=this.safeString(d,10);n={cost:t,currency:this.safeCurrencyCode(i)};let h=d[6];o=this.safeString(this.options.exchangeTypes,h)}return this.safeTrade({id:c,timestamp:p,datetime:this.iso8601(p),symbol:f,order:s,side:i,type:o,takerOrMaker:r,price:u,amount:l,cost:void 0,fee:n,info:d},t)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchTrades","paginate",!1);if(r)return await this.fetchPaginatedCallDynamic("fetchTrades",e,t,i,a,1e4);let o=this.market(e),n="-1",d={symbol:o.id};void 0!==t&&(d.start=t,n="1"),void 0!==i&&(d.limit=Math.min(i,1e4)),d.sort=n;let[h,c]=this.handleUntilOption("end",d,a),l=await this.publicGetTradesSymbolHist(this.extend(h,c)),u=this.toArray(l),f=this.sortBy(u,1),p=[];for(let e=0;e<f.length;e++)p.push({result:f[e]});return this.parseTrades(p,o,void 0,i)}async fetchOHLCV(e,t="1m",i,s=100,r={}){void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,o,1e4);let n=this.market(e),d=void 0===s?1e4:Math.min(s,1e4),h={symbol:n.id,timeframe:this.safeString(this.timeframes,t,t),limit:d};void 0!==i&&(h.start=i,h.sort=1);let[c,l]=this.handleUntilOption("end",h,o),u=await this.publicGetCandlesTradeTimeframeSymbolHist(this.extend(c,l));return this.parseOHLCVs(this.toArray(u),n,t,i,d)}parseOHLCV(e,t){return[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,2),this.safeNumber(e,5)]}parseOrderStatus(e){if(void 0===e)return;let t=e.split(" "),i=this.safeString(t,0);return this.safeString({ACTIVE:"open",PARTIALLY:"open",EXECUTED:"closed",CANCELED:"canceled",INSUFFICIENT:"canceled","POSTONLY CANCELED":"canceled",RSN_DUST:"rejected",RSN_PAUSE:"rejected","IOC CANCELED":"canceled","FILLORKILL CANCELED":"canceled"},i,e)}parseOrderFlags(e){return this.safeList({1024:["reduceOnly"],4096:["postOnly"],5120:["reduceOnly","postOnly"]},e,void 0)}parseTimeInForce(e){return this.safeString({"EXCHANGE IOC":"IOC","EXCHANGE FOK":"FOK",IOC:"IOC",FOK:"FOK"},e,"GTC")}parseOrder(e,t){let i,s,r=this.safeList(e,"result"),o=this.safeString(r,0),n=this.safeString(r,3),d=this.safeSymbol(n),h=this.safeInteger(r,5),c=a.Y.stringAbs(this.safeString(r,6)),l=this.safeString(r,7),u=a.Y.stringAbs(l),f="buy";a.Y.stringLt(l,"0")&&(f="sell");let p=this.safeString(r,8),m=this.safeString(this.safeDict(this.options,"exchangeTypes"),p),g=this.parseTimeInForce(p),v=this.safeString(r,12),y=this.parseOrderFlags(v),b=!1;if(void 0!==y)for(let e=0;e<y.length;e++)"postOnly"===y[e]&&(b=!0);let w=this.safeString(r,16);("EXCHANGE STOP"===p||"EXCHANGE STOP LIMIT"===p)&&(w=void 0,i=this.safeString(r,16),"EXCHANGE STOP LIMIT"===p&&(w=this.safeString(r,19)));let k=this.safeString(r,13);if(void 0!==k){let e=k.split(" @ ");s=this.parseOrderStatus(this.safeString(e,0))}let S=this.safeString(r,17),O=this.safeString(r,2);return this.safeOrder({info:r,id:o,clientOrderId:O,timestamp:h,datetime:this.iso8601(h),lastTradeTimestamp:void 0,symbol:d,type:m,timeInForce:g,postOnly:b,side:f,price:w,triggerPrice:i,amount:u,cost:void 0,average:S,filled:void 0,remaining:c,status:s,fee:void 0,trades:void 0},t)}createOrderRequest(e,t,i,s,o,n={}){if(void 0===t)throw new r.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new r.ArgumentsRequired(this.id+" requires a side argument");let d=this.market(e),h=this.amountToPrecision(e,s);h="buy"===i?h:a.Y.stringNeg(h);let c={symbol:d.id,amount:h},l=this.safeString2(n,"stopPrice","triggerPrice"),u=this.safeString(n,"trailingAmount"),f=this.safeString(n,"timeInForce"),p=this.safeBool(n,"postOnly",!1),m=this.safeBool(n,"reduceOnly",!1),g=this.safeValue2(n,"cid","clientOrderId"),v=t.toUpperCase();void 0!==u?(v="TRAILING STOP",c.price_trailing=u):void 0!==l&&(c.price=this.priceToPrecision(e,l),"limit"===t?(v="STOP LIMIT",c.price_aux_limit=this.priceToPrecision(e,o)):v="STOP");let y="IOC"===f,b="FOK"===f;if((y||b)&&void 0===o)throw new r.InvalidOrder(this.id+" createOrder() requires a price argument with IOC and FOK orders");if((y||b)&&"market"===t)throw new r.InvalidOrder(this.id+" createOrder() does not allow market IOC and FOK orders");"market"!==t&&void 0===l&&(c.price=this.priceToPrecision(e,o)),y?v="IOC":b&&(v="FOK");let[w,k]=this.handleMarginModeAndParams("createOrder",n);!0===d.spot&&void 0===w&&(v="EXCHANGE "+v),c.type=v;let S=0;(!0===p||"PO"===f)&&(S=this.sum(S,4096)),!0===m&&(S=this.sum(S,1024)),0!==S&&(c.flags=S),void 0!==g&&(c.cid=g);let O=this.omit(k,["triggerPrice","stopPrice","timeInForce","postOnly","reduceOnly","trailingAmount","clientOrderId"]);return this.extend(c,O)}async createOrder(e,t,i,s,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=this.createOrderRequest(e,t,i,s,a,o),h=await this.privatePostAuthWOrderSubmit(d),c=this.safeString(h,6);if("SUCCESS"!==c){let e=this.safeString(h,5),t=this.safeString(h,7);throw new r.ExchangeError(this.id+" "+c+": "+t+" (#"+e+")")}let l=this.safeList(h,4,[]),u=this.safeList(l,0);return this.parseOrder({result:u},n)}async createOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=[];for(let t=0;t<e.length;t++){let s=this.safeDict(e,t),r=this.safeString(s,"symbol"),a=this.safeString(s,"type"),o=this.safeString(s,"side"),n=this.safeNumber(s,"amount"),d=this.safeNumber(s,"price"),h=this.safeDict(s,"params",{}),c=this.createOrderRequest(r,a,o,n,d,h);i.push(["on",c])}let s=await this.privatePostAuthWOrderMulti({ops:i}),r=[],a=this.safeList(s,4,[]);for(let e=0;e<a.length;e++){let t=a[e][4];r.push({result:t[0]})}return this.parseOrders(r)}async cancelAllOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privatePostAuthWOrderCancelMulti(this.extend({all:1},t)),s=this.safeList(i,4,[]),r=[];for(let e=0;e<s.length;e++)r.push({result:s[e]});return this.parseOrders(r)}async cancelOrder(e,t,i={}){let s,a;void 0===this.markets&&await this.loadMarkets();let o=this.safeValue2(i,"cid","clientOrderId");if(void 0!==t&&(a=this.market(t)),void 0!==o){let e=this.safeValue(i,"cidDate");if(void 0===e)throw new r.InvalidOrder(this.id+" canceling an order by clientOrderId ('cid') requires both 'cid' and 'cid_date' ('YYYY-MM-DD')");s={cid:o,cid_date:e}}else s={id:parseInt(e)};let n=void 0!==o?this.omit(i,["cid","clientOrderId"]):i,d=await this.privatePostAuthWOrderCancel(this.extend(s,n)),h=this.safeValue(d,4);return this.parseOrder({result:h},a)}async cancelOrders(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=[];for(let t=0;t<e.length;t++)r.push(this.parseToNumeric(e[t]));void 0!==t&&(s=this.market(t));let a=await this.privatePostAuthWOrderCancelMulti(this.extend({id:r},i)),o=this.safeList(a,4,[]),n=[];for(let e=0;e<o.length;e++)n.push({result:o[e]});return this.parseOrders(n,s)}async fetchOpenOrder(e,t,i={}){let s={id:[parseInt(e)]},a=await this.fetchOpenOrders(t,void 0,void 0,this.extend(s,i)),o=this.safeValue(a,0);if(void 0===o)throw new r.OrderNotFound(this.id+" order "+e+" not found");return o}async fetchClosedOrder(e,t,i={}){let s={id:[parseInt(e)]},a=await this.fetchClosedOrders(t,void 0,void 0,this.extend(s,i)),o=this.safeValue(a,0);if(void 0===o)throw new r.OrderNotFound(this.id+" order "+e+" not found");return o}async fetchOpenOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o={};void 0===e?r=await this.privatePostAuthROrders(this.extend(o,s)):(o.symbol=(a=this.market(e)).id,r=await this.privatePostAuthROrdersSymbol(this.extend(o,s)));let n=[];for(let e=0;e<r.length;e++)n.push({result:r[e]});return this.parseOrders(n,a,t,i)}async fetchClosedOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(s,"fetchClosedOrders","paginate",!1);if(o)return await this.fetchPaginatedCallDynamic("fetchClosedOrders",e,t,i,n);let d={};void 0!==t&&(d.start=t),void 0!==i&&(d.limit=i);let[h,c]=this.handleUntilOption("end",d,n);void 0===e?r=await this.privatePostAuthROrdersHist(this.extend(h,c)):(h.symbol=(a=this.market(e)).id,r=await this.privatePostAuthROrdersSymbolHist(this.extend(h,c)));let l=[];for(let e=0;e<r.length;e++)l.push({result:r[e]});return this.parseOrders(l,a,t,i)}async fetchOrderTrades(e,t,i,s,a={}){if(void 0===t)throw new r.ArgumentsRequired(this.id+" fetchOrderTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let o=this.market(t),n={id:parseInt(e),symbol:o.id},d=await this.privatePostAuthROrderSymbolIdTrades(this.extend(n,a)),h=this.toArray(d),c=[];for(let e=0;e<h.length;e++)c.push({result:h[e]});return this.parseTrades(c,o,i,s)}async fetchMyTrades(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o={end:this.milliseconds()};void 0!==t&&(o.start=t),void 0!==i&&(o.limit=i),void 0!==e?(o.symbol=(a=this.market(e)).id,r=await this.privatePostAuthRTradesSymbolHist(this.extend(o,s))):r=await this.privatePostAuthRTradesHist(this.extend(o,s));let n=[];for(let e=0;e<r.length;e++)n.push({result:r[e]});return this.parseTrades(n,a,t,i)}async createDepositAddress(e,t={}){return void 0===this.markets&&await this.loadMarkets(),await this.fetchDepositAddress(e,this.extend({op_renew:1},t))}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s=this.safeString(t,"network",e),a=this.safeDict(i,"networks",{}),o=this.safeDict(a,s),n=this.safeString(o,"id");if(void 0===n)throw new r.ArgumentsRequired(this.id+" fetchDepositAddress() could not find a network for '"+e+"'. You can specify it by providing the 'network' value inside params");let d=this.safeString(t,"wallet","exchange"),h=this.omit(t,"network","wallet"),c=await this.privatePostAuthWDepositAddress(this.extend({method:n,wallet:d,op_renew:0},h)),l=this.safeList(c,4,[]),u=this.safeString(l,5),f=void 0===u?this.safeString(l,4):u,p=void 0===u?void 0:this.safeString(l,4);return this.checkAddress(f),{currency:e,address:f,tag:p,network:void 0,info:c}}parseTransactionStatus(e){return this.safeString({SUCCESS:"ok",COMPLETED:"ok",ERROR:"failed",FAILURE:"failed",CANCELED:"canceled","PENDING APPROVAL":"pending",PENDING:"pending","PENDING REVIEW":"pending","PENDING CANCELLATION":"pending",SENDING:"pending","USER APPROVED":"pending"},e,e)}parseTransaction(e,t){let i,s,r,o,n,d,h,c,l,u,f,p,m,g=e.length;if(8===g){let s=this.safeList(e,4,[]);i=this.safeInteger(e,0),void 0!==t&&(r=this.safeString(t,"code")),void 0!==(l=this.safeString(s,8))&&(l=a.Y.stringAbs(l)),o=this.safeNumber(s,5),n=this.safeInteger(s,0),d="ok",0===n&&(n=void 0,d="failed"),h=this.safeString(s,3),c="withdrawal";let u=this.safeString(s,2);p=this.networkIdToCode(u.toUpperCase(),r)}else if(22===g){n=this.safeString(e,0);let h=this.safeString(e,1);r=this.safeCurrencyCode(h,t);let g=this.safeString(e,2);p=this.networkIdToCode(g,r),i=this.safeInteger(e,5),s=this.safeInteger(e,6),d=this.parseTransactionStatus(this.safeString(e,9));let v=this.safeString(e,12);o=a.Y.stringAbs(v),void 0!==v&&(c=a.Y.stringLt(v,"0")?"withdrawal":"deposit"),void 0!==(l=this.safeString(e,13))&&(l=a.Y.stringAbs(l)),f=this.safeString(e,16),u=this.safeString(e,20),m=this.safeString(e,21)}return{info:e,id:n,txid:u,type:c,currency:r,network:p,amount:this.parseNumber(o),status:d,timestamp:i,datetime:this.iso8601(i),address:f,addressFrom:void 0,addressTo:f,tag:h,tagFrom:void 0,tagTo:h,updated:s,comment:m,internal:void 0,fee:{currency:r,cost:this.parseNumber(l),rate:void 0}}}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostAuthRSummary(e),i={},s=this.safeDict(this.options,"fiat",{}),r=this.safeList(t,4,[]),a=this.safeList(r,0,[]),o=this.safeList(r,1,[]),n=this.safeNumber(a,0),d=this.safeNumber(a,2),h=this.safeNumber(a,5),c=this.safeNumber(o,0),l=this.safeNumber(o,2),u=this.safeNumber(o,5);for(let e=0;e<this.symbols.length;e++){let r=this.symbols[e],a=this.market(r),o={info:t,symbol:r,percentage:!0,tierBased:!0};a.quote in s?(o.maker=d,o.taker=l):!0===a.contract?(o.maker=h,o.taker=u):(o.maker=n,o.taker=c),i[r]=o}return i}async fetchDepositsWithdrawals(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o={};if(void 0!==t&&(o.start=t),void 0!==i&&(o.limit=i),void 0!==e){o.currency=(a=this.currency(e)).id;let t=await this.privatePostAuthRMovementsCurrencyHist(this.extend(o,s));r=this.toArray(t)}else{let e=await this.privatePostAuthRMovementsHist(this.extend(o,s));r=this.toArray(e)}return this.parseTransactions(r,a,t,i)}async withdraw(e,t,i,s,a={}){this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let o=this.currency(e),n=this.safeString(a,"network",e),d=this.omit(a,"network"),h=this.safeDict(o,"networks",{}),c=this.safeDict(h,n),l=this.safeString(c,"id");if(void 0===l)throw new r.ArgumentsRequired(this.id+" withdraw() could not find a network for '"+e+"'. You can specify it by providing the 'network' value inside params");let u=this.safeString(d,"wallet","exchange"),f=this.omit(d,"network","wallet"),p={method:l,wallet:u,amount:this.numberToString(t),address:i};void 0!==s&&(p.payment_id=s);let m=this.safeDict(this.options,"withdraw",{});!0===this.safeBool(m,"includeFee",!1)&&(p.fee_deduct=1);let g=await this.privatePostAuthWWithdraw(this.extend(p,f));if("error"===this.safeString(g,0)){let e=this.id+" "+g,t=this.safeString(g,2,"");throw this.throwExactlyMatchedException(this.exceptions.exact,t,e),this.throwBroadlyMatchedException(this.exceptions.broad,t,e),new r.ExchangeError(e)}let v=this.safeString(g,7);return"success"!==v&&this.throwBroadlyMatchedException(this.exceptions.broad,v,v),this.parseTransaction(g,o)}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.privatePostAuthRPositions(t),r=this.toArray(s),a=[];for(let e=0;e<r.length;e++)a.push({result:r[e]});return this.parsePositions(a,i)}parsePosition(e,t){let i=this.safeList(e,"result"),s=this.safeString(i,0),r=this.safeString(i,2),o=this.safeInteger(i,12),n=this.safeString(i,19),d=this.safeString(n,"trade_price"),h=this.safeString(n,"trade_amount");return this.safePosition({info:i,id:this.safeString(i,11),symbol:this.safeSymbol(s,t),notional:this.parseNumber(r),marginMode:"isolated",liquidationPrice:this.safeNumber(i,8),entryPrice:this.safeNumber(i,3),unrealizedPnl:this.safeNumber(i,6),percentage:this.safeNumber(i,7),contracts:void 0,contractSize:void 0,markPrice:void 0,lastPrice:void 0,side:a.Y.stringGt(r,"0")?"long":"short",hedged:void 0,timestamp:o,datetime:this.iso8601(o),lastUpdateTimestamp:this.safeInteger(i,13),maintenanceMargin:this.safeNumber(i,18),maintenanceMarginPercentage:void 0,collateral:this.safeNumber(i,17),initialMargin:this.parseNumber(a.Y.stringMul(h,d)),initialMarginPercentage:void 0,leverage:this.safeNumber(i,9),marginRatio:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",a={},o,n){let d,h,c="/"+this.implodeParams(e,a),l=this.omit(a,this.extractParams(e));c="v1"===t?t+c:this.version+c;let u=this.safeString(this.urls.api,t);if(void 0===u)throw new r.ExchangeError(this.id+" sign() has no API URL for this endpoint");let f=u+"/"+c;if("public"===t&&Object.keys(l).length>0&&(f+="?"+this.urlencode(l)),"private"===t){this.checkRequiredCredentials();let e=this.incrementingNonce().toString(),t="/api/"+c+e+(d=this.json(l)),i=this.hmac(this.encode(t),this.encode(this.secret),s.qt);h={"bfx-nonce":e,"bfx-apikey":this.apiKey,"bfx-signature":i,"Content-Type":"application/json"}}return{url:f,method:i,body:void 0===d?n:d,headers:void 0===h?o:h}}handleErrors(e,t,i,s,a,o,n,d,h){if(void 0!==n){if(!Array.isArray(n)){let e=this.safeString2(n,"message","error"),t=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,e,t),this.throwBroadlyMatchedException(this.exceptions.broad,e,t),new r.ExchangeError(this.id+" "+o)}}else if(""===n)throw new r.ExchangeError(this.id+" returned empty response");if(429===e)throw new r.RateLimitExceeded(this.id+" "+o);if(500===e){let e=this.safeString(n,1,""),t=this.safeString(n,2,""),i=this.id+" "+t;throw this.throwBroadlyMatchedException(this.exceptions.broad,t,i),this.throwExactlyMatchedException(this.exceptions.exact,e,i),this.throwExactlyMatchedException(this.exceptions.exact,t,i),new r.ExchangeError(this.id+" "+t+" (#"+e+")")}return n}parseLedgerEntryType(e){if(void 0!==e){if(e.indexOf("fee")>=0||e.indexOf("charged")>=0)return"fee";if(e.indexOf("rebate")>=0)return"rebate";if(e.indexOf("deposit")>=0||e.indexOf("withdrawal")>=0)return"transaction";else if(e.indexOf("transfer")>=0)return"transfer";else if(e.indexOf("payment")>=0)return"payout";else if(e.indexOf("exchange")>=0||e.indexOf("position")>=0)return"trade";else return e}}parseLedgerEntry(e,t){let i,s=this.safeList(e,"result",[]),r=this.safeString(s,0),a=this.safeString(s,1),o=this.safeCurrencyCode(a,t),n=this.safeCurrency(a,t),d=this.safeInteger(s,3),h=this.safeNumber(s,5),c=this.safeNumber(s,6),l=this.safeString(s,8);if(void 0!==l){let e=l.split(" @ "),t=this.safeStringLower(e,0);i=this.parseLedgerEntryType(t)}return this.safeLedgerEntry({info:e,id:r,direction:void 0,account:void 0,referenceId:r,referenceAccount:void 0,type:i,currency:o,amount:h,timestamp:d,datetime:this.iso8601(d),before:void 0,after:c,status:void 0,fee:void 0},n)}async fetchLedger(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(s,"fetchLedger","paginate",!1);if(o)return await this.fetchPaginatedCallDynamic("fetchLedger",e,t,i,n,2500);let d={};void 0!==t&&(d.start=t),void 0!==i&&(d.limit=i);let[h,c]=this.handleUntilOption("end",d,n);void 0!==e?(h.currency=(a=this.currency(e)).id,r=await this.privatePostAuthRLedgersCurrencyHist(this.extend(h,c))):r=await this.privatePostAuthRLedgersHist(this.extend(h,c));let l=[];for(let e=0;e<r.length;e++){let t=r[e];l.push({result:t})}return this.parseLedger(l,a,t,i)}async fetchFundingRates(e,t={}){if(void 0===e)throw new r.ArgumentsRequired(this.id+" fetchFundingRates() requires a symbols argument");void 0===this.markets&&await this.loadMarkets();let i={keys:this.marketIds(e).join(",")},s=await this.publicGetStatusDeriv(this.extend(i,t));return this.parseFundingRates(s,e)}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new r.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchFundingRateHistory",e,t,i,"8h",o,5e3);let n=this.market(e),d={symbol:n.id};void 0!==t&&(d.start=t);let[h,c]=this.handleUntilOption("end",d,o),l=await this.publicGetStatusDerivSymbolHist(this.extend(h,c)),u=this.toArray(l),f=[];for(let e=0;e<u.length;e++){let t=u[e],i=this.parseFundingRateHistory(t,n);f.push(i)}let p=[],m=this.filterBySymbolSinceLimit(f,e,t,i),g=m.length;for(let e=0;e<g;e++){let t=m[g-e-1];p.push(t)}return p}parseFundingRate(e,t){let i=this.safeString(e,0),s=this.safeInteger(e,1),r=this.safeInteger(e,8);return{info:e,symbol:this.safeSymbol(i,t),markPrice:this.safeNumber(e,15),indexPrice:this.safeNumber(e,3),interestRate:void 0,estimatedSettlePrice:void 0,timestamp:s,datetime:this.iso8601(s),fundingRate:this.safeNumber(e,12),fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:this.safeNumber(e,9),nextFundingTimestamp:r,nextFundingDatetime:this.iso8601(r),previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:void 0}}parseFundingRateHistory(e,t){let i=this.safeInteger(e,0);return{info:e,symbol:this.safeSymbol(void 0,t),fundingRate:this.safeNumber(e,11),timestamp:i,datetime:this.iso8601(i)}}async fetchOpenInterests(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=["ALL"];void 0!==i&&(s=this.marketIds(i));let r={keys:s.join(",")},a=await this.publicGetStatusDeriv(this.extend(r,t));return this.parseOpenInterests(a,i)}async fetchOpenInterest(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={keys:i.id},r=await this.publicGetStatusDeriv(this.extend(s,t)),a=this.safeList(r,0);return this.parseOpenInterest(a,i)}async fetchOpenInterestHistory(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(r,"fetchOpenInterestHistory","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchOpenInterestHistory",e,i,s,"8h",o,5e3);let n=this.market(e),d={symbol:n.id};void 0!==i&&(d.start=i),void 0!==s&&(d.limit=s);let[h,c]=this.handleUntilOption("end",d,o),l=await this.publicGetStatusDerivSymbolHist(this.extend(h,c));return this.parseOpenInterestsHistory(l,n,i,s)}parseOpenInterest(e,t){let i=e.length,s=this.safeInteger(e,1),r=this.safeString(e,0);return this.safeOpenInterest({symbol:this.safeSymbol(r,t,void 0,"swap"),openInterestAmount:this.safeNumber(e,23===i?17:18),openInterestValue:void 0,timestamp:s,datetime:this.iso8601(s),info:e},t)}async fetchLiquidations(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchLiquidations","paginate",!1);if(r)return await this.fetchPaginatedCallDeterministic("fetchLiquidations",e,t,i,"8h",a,500);let o=this.market(e),n={};void 0!==t&&(n.start=t),void 0!==i&&(n.limit=i);let[d,h]=this.handleUntilOption("end",n,a),c=await this.publicGetLiquidationsHist(this.extend(d,h));return this.parseLiquidations(this.toArray(c),o,t,i)}parseLiquidation(e,t){let i=this.safeList(e,0),s=this.safeInteger(i,2),r=this.safeString(i,4),o=a.Y.stringAbs(this.safeString(i,5)),n=this.safeString(t,"contractSize"),d=a.Y.stringMul(o,n),h=this.safeString(i,11),c=this.safeInteger(i,8),l="sell";return 1===c&&(l="buy"),this.safeLiquidation({info:i,symbol:this.safeSymbol(r,t,void 0,"contract"),contracts:this.parseNumber(o),contractSize:this.parseNumber(n),price:this.parseNumber(h),side:l,baseValue:this.parseNumber(d),quoteValue:this.parseNumber(a.Y.stringMul(d,h)),timestamp:s,datetime:this.iso8601(s)})}async setMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e);if(!0!==s.swap)throw new r.NotSupported(this.id+" setMargin() only support swap markets");let a={symbol:s.id,collateral:this.parseToNumeric(t)},o=await this.privatePostAuthWDerivCollateralSet(this.extend(a,i)),n=this.safeValue(o,0);return this.parseMarginModification(n,s)}parseMarginModification(e,t){let i=e[0],s="failed";return 1===i&&(s="ok"),{info:e,symbol:this.safeString(t,"symbol"),type:void 0,marginMode:"isolated",amount:void 0,total:void 0,code:void 0,status:s,timestamp:void 0,datetime:void 0}}async fetchOrder(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets();let a={id:[this.parseToNumeric(e)]};void 0===t?s=await this.privatePostAuthROrders(this.extend(a,i)):(a.symbol=(r=this.market(t)).id,s=await this.privatePostAuthROrdersSymbol(this.extend(a,i)));let o=this.safeList(s,0);return this.parseOrder({result:o},r)}async editOrder(e,t,i,s,o,n,d={}){void 0===this.markets&&await this.loadMarkets();let h=this.market(t),c={id:this.parseToNumeric(e)};if(void 0!==o){let e=this.amountToPrecision(t,o);c.amount=e="buy"===s?e:a.Y.stringNeg(e)}let l=this.safeString2(d,"stopPrice","triggerPrice"),u=this.safeString(d,"trailingAmount"),f=this.safeString(d,"timeInForce"),p=this.safeBool(d,"postOnly",!1),m=this.safeBool(d,"reduceOnly",!1),g=this.safeInteger2(d,"cid","clientOrderId");void 0!==u?c.price_trailing=u:void 0!==l&&(c.price=this.priceToPrecision(t,l),"limit"===i&&(c.price_aux_limit=this.priceToPrecision(t,n))),"market"!==i&&void 0===l&&(c.price=this.priceToPrecision(t,n));let v=0;(!0===p||"PO"===f)&&(v=this.sum(v,4096)),!0===m&&(v=this.sum(v,1024)),0!==v&&(c.flags=v),void 0!==g&&(c.cid=g);let y=this.safeInteger2(d,"leverage","lev");void 0!==y&&(c.lev=y);let b=this.omit(d,["triggerPrice","stopPrice","timeInForce","postOnly","reduceOnly","trailingAmount","clientOrderId","leverage"]),w=await this.privatePostAuthWOrderUpdate(this.extend(c,b)),k=this.safeString(w,6);if("SUCCESS"!==k){let e=this.safeString(w,5),t=this.safeString(w,7);throw new r.ExchangeError(this.id+" "+k+": "+t+" (#"+e+")")}let S=this.safeList(w,4,[]);return this.parseOrder({result:S},h)}}i.d(t,{A:()=>n})},8993(e,t,i){"use strict";var s=i(4721),r=i(2240),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bitflyer",name:"bitFlyer",countries:["JP"],version:"v1",rateLimit:1e3,hostname:"bitflyer.com",has:{CORS:void 0,spot:!0,margin:!1,swap:void 0,future:void 0,option:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:void 0,cancelOrder:!0,createOrder:!0,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrders:"emulated",fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDeposits:!0,fetchFundingRate:!0,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchMarginMode:!1,fetchMarkets:!0,fetchMyTrades:!0,fetchOpenOrders:"emulated",fetchOption:!1,fetchOptionChain:!1,fetchOrder:"emulated",fetchOrderBook:!0,fetchOrders:!0,fetchPositionMode:!1,fetchPositions:!0,fetchTicker:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!1,fetchTransfer:!1,fetchTransfers:!1,fetchVolatilityHistory:!1,fetchWithdrawals:!0,repayCrossMargin:!1,repayIsolatedMargin:!1,transfer:!1,withdraw:!0},urls:{logo:"https://github.com/user-attachments/assets/d0217747-e54d-4533-8416-0d553dca74bb",api:{rest:"https://api.{hostname}"},www:"https://bitflyer.com",doc:"https://lightning.bitflyer.com/docs?lang=en"},api:{public:{get:{"getmarkets/usa":{cost:1},"getmarkets/eu":{cost:1},getmarkets:{cost:1},getboard:{cost:1},getticker:{cost:1},getexecutions:{cost:1},gethealth:{cost:1},getboardstate:{cost:1},getchats:{cost:1},getfundingrate:{cost:1},getfundingratehistory:{cost:1}}},private:{get:{getpermissions:{cost:1},getbalance:{cost:1},getbalancehistory:{cost:1},getcollateral:{cost:1},getcollateralhistory:{cost:1},getcollateralaccounts:{cost:1},getaddresses:{cost:1},getcoinins:{cost:1},getcoinouts:{cost:1},getbankaccounts:{cost:1},getdeposits:{cost:1},getwithdrawals:{cost:1},getchildorders:{cost:1},getparentorders:{cost:1},getparentorder:{cost:1},getexecutions:{cost:1},getpositions:{cost:1},gettradingcommission:{cost:1}},post:{sendcoin:{cost:1},withdraw:{cost:1},sendchildorder:{cost:1},cancelchildorder:{cost:1},sendparentorder:{cost:1},cancelparentorder:{cost:1},cancelallchildorders:{cost:1}}}},fees:{trading:{maker:this.parseNumber("0.002"),taker:this.parseNumber("0.002")}},precisionMode:4,features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!0},hedged:!1,trailing:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:void 0,untilDays:void 0,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:100,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:{marginMode:!1,limit:100,daysBack:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:{marginMode:!1,limit:100,daysBack:void 0,daysBackCanceled:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOHLCV:void 0},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},exceptions:{exact:{"-2":a.OnMaintenance}}})}parseExpiryDate(e){let t=e.slice(0,2),i=e.slice(2,5),s=e.slice(5,9),r=this.safeString({JAN:"01",FEB:"02",MAR:"03",APR:"04",MAY:"05",JUN:"06",JUL:"07",AUG:"08",SEP:"09",OCT:"10",NOV:"11",DEC:"12"},i);if(void 0!==r)return this.parse8601(s+"-"+r+"-"+t+"T00:00:00Z")}safeMarket(e,t,i,s){return super.safeMarket(e,t,i,"spot")}async fetchMarkets(e={}){let t=await this.publicGetGetmarkets(e),i=await this.publicGetGetmarketsUsa(e),s=await this.publicGetGetmarketsEu(e),r=this.arrayConcat(this.toArray(t),this.toArray(i));r=this.arrayConcat(r,this.toArray(s));let a=[];for(let e=0;e<r.length;e++){let t,i,s,o,n=r[e],d=this.safeString(n,"product_code"),h=d.split("_"),c=this.safeString(n,"market_type"),l="FX"===c,u="Futures"===c,f=!l&&!u,p="spot";if(f)i=this.safeString(h,0),s=this.safeString(h,1);else if(l)p="swap",i=this.safeString(h,1),s=this.safeString(h,2);else if(u){let e=this.safeString(n,"alias");if(void 0===e){i=d.slice(0,3),s=d.slice(3,6);let e=d.slice(-9);o=this.parseExpiryDate(e)}else{let t=e.split("_"),r=this.safeString(t,0);i=r.slice(0,-3),s=r.slice(-3);let a=d.split(r),n=this.safeString(a,1);if(void 0===n)continue;o=this.parseExpiryDate(n)}if(void 0===o)continue;p="future"}let m=this.safeCurrencyCode(i),g=this.safeCurrencyCode(s);if(void 0===m||void 0===g)continue;let v=m+"/"+g,y=this.fees.trading.taker,b=this.fees.trading.maker,w=l||u;w&&(b=0,y=0,v=v+":"+(t="JPY"),u&&(v=v+"-"+this.yymmdd(o))),a.push({id:d,symbol:v,base:m,quote:g,settle:t,baseId:i,quoteId:s,settleId:void 0,type:p,spot:f,margin:!1,swap:l,future:u,option:!1,active:!0,contract:w,linear:!f||void 0,inverse:!!f&&void 0,taker:y,maker:b,contractSize:void 0,expiry:o,expiryDatetime:this.iso8601(o),strike:void 0,optionType:void 0,precision:{amount:void 0,price:void 0},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:n})}return a}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"currency_code"),a=this.safeCurrencyCode(r),o=this.account();o.total=this.safeString(s,"amount"),o.free=this.safeString(s,"available"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetGetbalance(e);return this.parseBalance(t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={product_code:s.id},a=await this.publicGetGetboard(this.extend(r,i));return this.parseOrderBook(a,s.symbol,void 0,"bids","asks","price","size")}parseTicker(e,t){let i=this.safeSymbol(void 0,t),s=this.parse8601(this.safeString(e,"timestamp")),r=this.safeString(e,"ltp");return this.safeTicker({symbol:i,timestamp:s,datetime:this.iso8601(s),high:void 0,low:void 0,bid:this.safeString(e,"best_bid"),bidVolume:void 0,ask:this.safeString(e,"best_ask"),askVolume:void 0,vwap:void 0,open:void 0,close:r,last:r,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"volume_by_product"),quoteVolume:void 0,info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={product_code:i.id},r=await this.publicGetGetticker(this.extend(s,t));return this.parseTicker(r,i)}parseTrade(e,t){let i,s=this.safeStringLower(e,"side");if(void 0!==s&&s.length<1&&(s=void 0),void 0!==s){let t=s+"_child_order_acceptance_id";t in e&&(i=this.safeString(e,t))}void 0===i&&(i=this.safeString(e,"child_order_acceptance_id"));let r=this.parse8601(this.safeString(e,"exec_date")),a=this.safeString(e,"price"),o=this.safeString(e,"size"),n=this.safeString(e,"id"),d=this.safeMarket(void 0,t);return this.safeTrade({id:n,info:e,timestamp:r,datetime:this.iso8601(r),symbol:d.symbol,order:i,type:void 0,side:s,takerOrMaker:void 0,price:a,amount:o,cost:void 0,fee:void 0},d)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={product_code:r.id};void 0!==i&&(a.count=i);let o=await this.publicGetGetexecutions(this.extend(a,s));return this.parseTrades(o,r,t,i)}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={product_code:i.id},r=await this.privateGetGettradingcommission(this.extend(s,t)),a=this.safeNumber(r,"commission_rate");return{info:r,symbol:i.symbol,maker:a,taker:a,percentage:void 0,tierBased:void 0}}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o={product_code:this.marketId(e),child_order_type:t.toUpperCase(),side:i.toUpperCase(),price:r,size:s},n=await this.privatePostSendchildorder(this.extend(o,a)),d=this.safeString(n,"child_order_acceptance_id");return this.safeOrder({id:d,info:n})}async cancelOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s={product_code:this.marketId(t),child_order_acceptance_id:e},r=await this.privatePostCancelchildorder(this.extend(s,i));return this.safeOrder({info:r})}parseOrderStatus(e){return this.safeString({ACTIVE:"open",COMPLETED:"closed",CANCELED:"canceled",EXPIRED:"canceled",REJECTED:"canceled"},e,e)}parseOrder(e,t){let i,s=this.parse8601(this.safeString(e,"child_order_date")),r=this.safeString(e,"price"),a=this.safeString(e,"size"),o=this.safeString(e,"executed_size"),n=this.safeString(e,"outstanding_size"),d=this.parseOrderStatus(this.safeString(e,"child_order_state")),h=this.safeStringLower(e,"child_order_type"),c=this.safeStringLower(e,"side"),l=this.safeString(e,"product_code"),u=this.safeSymbol(l,t),f=this.safeNumber(e,"total_commission");void 0!==f&&(i={cost:f,currency:void 0,rate:void 0});let p=this.safeString(e,"child_order_acceptance_id");return this.safeOrder({id:p,clientOrderId:void 0,info:e,timestamp:s,datetime:this.iso8601(s),lastTradeTimestamp:void 0,status:d,symbol:u,type:h,timeInForce:void 0,postOnly:void 0,side:c,price:r,triggerPrice:void 0,cost:void 0,amount:a,filled:o,remaining:n,fee:i,average:void 0,trades:void 0},t)}async fetchOrders(e,t,i=100,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={product_code:r.id,count:i},n=await this.privateGetGetchildorders(this.extend(o,s)),d=this.parseOrders(n,r,t,i);return void 0!==e&&(d=this.filterBy(d,"symbol",e)),d}async fetchOpenOrders(e,t,i=100,s={}){return await this.fetchOrders(e,t,i,this.extend({child_order_state:"ACTIVE"},s))}async fetchClosedOrders(e,t,i=100,s={}){return await this.fetchOrders(e,t,i,this.extend({child_order_state:"COMPLETED"},s))}async fetchOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");let s=await this.fetchOrders(t),r=this.indexBy(s,"id");if(e in r)return this.safeDict(r,e);throw new a.OrderNotFound(this.id+" No order found with id "+e)}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={product_code:r.id};void 0!==i&&(o.count=i);let n=await this.privateGetGetexecutions(this.extend(o,s));return this.parseTrades(n,r,t,i)}async fetchPositions(e,t={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchPositions() requires a `symbols` argument, exactly one symbol in an array");void 0===this.markets&&await this.loadMarkets();let i={product_code:this.marketIds(e)};return await this.privateGetGetpositions(this.extend(i,t))}async withdraw(e,t,i,s,r={}){if(this.checkAddress(i),void 0===this.markets&&await this.loadMarkets(),"JPY"!==e&&"USD"!==e&&"EUR"!==e)throw new a.ExchangeError(this.id+" allows withdrawing JPY, USD, EUR only, "+e+" is not supported");let o=this.currency(e),n={currency_code:o.id,amount:t},d=await this.privatePostWithdraw(this.extend(n,r));return this.parseTransaction(d,o)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(r=this.currency(e)),void 0!==i&&(a.count=i);let o=await this.privateGetGetcoinins(this.extend(a,s));return this.parseTransactions(o,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(r=this.currency(e)),void 0!==i&&(a.count=i);let o=await this.privateGetGetcoinouts(this.extend(a,s));return this.parseTransactions(o,r,t,i)}parseDepositStatus(e){return this.safeString({PENDING:"pending",COMPLETED:"ok"},e,e)}parseWithdrawalStatus(e){return this.safeString({PENDING:"pending",COMPLETED:"ok"},e,e)}parseTransaction(e,t){let i,s,r,a=this.safeString2(e,"id","message_id"),n=this.safeString(e,"address"),d=this.safeString(e,"currency_code"),h=this.safeCurrencyCode(d,t),c=this.parse8601(this.safeString(e,"event_date")),l=this.safeNumber(e,"amount"),u=this.safeString(e,"tx_hash"),f=this.safeString(e,"status");if("fee"in e){i="withdrawal",s=this.parseWithdrawalStatus(f);let t=this.safeString(e,"fee"),a=this.safeString(e,"additional_fee");r={currency:h,cost:this.parseNumber(o.Y.stringAdd(t,a))}}else i="deposit",s=this.parseDepositStatus(f);return{info:e,id:a,txid:u,timestamp:c,datetime:this.iso8601(c),network:void 0,address:n,addressTo:n,addressFrom:void 0,tag:void 0,tagTo:void 0,tagFrom:void 0,type:i,amount:l,currency:h,status:s,updated:void 0,comment:void 0,internal:void 0,fee:r}}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={product_code:i.id},r=await this.publicGetGetfundingrate(this.extend(s,t));return this.parseFundingRate(r,i)}parseFundingRate(e,t){let i=this.safeString(e,"next_funding_rate_settledate"),s=this.parse8601(i);return{info:e,symbol:this.safeString(t,"symbol"),markPrice:void 0,indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:void 0,fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:this.safeNumber(e,"current_funding_rate"),nextFundingTimestamp:s,nextFundingDatetime:this.iso8601(s),previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:void 0}}sign(e,t="public",i="GET",r={},o,n){let d,h,c="/"+this.version+"/";"private"===t&&(c+="me/"),c+=e,"GET"===i&&Object.keys(r).length>0&&(c+="?"+this.urlencode(r));let l=this.safeString(this.urls.api,"rest");if(void 0===l)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let u=this.implodeHostname(l)+c;if("private"===t){this.checkRequiredCredentials();let e=this.nonce().toString(),t=[e,i,c].join("");Object.keys(r).length>0&&"GET"!==i&&(t+=d=this.json(r)),h={"ACCESS-KEY":this.apiKey,"ACCESS-TIMESTAMP":e,"ACCESS-SIGN":this.hmac(this.encode(t),this.encode(this.secret),s.sc),"Content-Type":"application/json"}}return{url:u,method:i,body:void 0===d?n:d,headers:void 0===h?o:h}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.id+" "+o,l=this.safeString(n,"error_message"),u=this.safeInteger(n,"status");if(void 0!==l)throw this.throwExactlyMatchedException(this.exceptions.exact,u,c),new a.ExchangeError(c)}}i.d(t,{A:()=>n})},8271(e,t,i){"use strict";var s=i(4721),r=i(5458),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bitget",name:"Bitget",countries:["SG"],version:"v2",rateLimit:50,certified:!0,pro:!0,has:{CORS:void 0,spot:!0,margin:!0,swap:!0,future:!0,option:!1,addMargin:!0,borrowCrossMargin:!0,borrowIsolatedMargin:!0,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!0,closePosition:!0,createConvertTrade:!0,createDepositAddress:!1,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!0,createPostOnlyOrder:!0,createReduceOnlyOrder:!1,createStopLimitOrder:!0,createStopLossOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,createTakeProfitOrder:!0,createTrailingAmountOrder:!1,createTrailingPercentOrder:!0,createTriggerOrder:!0,editOrder:!0,fetchAccounts:!1,fetchBalance:!0,fetchBorrowInterest:!0,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchCanceledAndClosedOrders:!0,fetchCanceledOrders:!0,fetchClosedOrders:!0,fetchConvertCurrencies:!0,fetchConvertQuote:!0,fetchConvertTrade:!1,fetchConvertTradeHistory:!0,fetchCrossBorrowRate:!0,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!1,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!0,fetchFundingInterval:!0,fetchFundingIntervals:!0,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchIndexOHLCV:!0,fetchIsolatedBorrowRate:!0,fetchIsolatedBorrowRates:!1,fetchLedger:!0,fetchLeverage:!0,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!0,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!0,fetchMarketLeverageTiers:!0,fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMarkPrice:!0,fetchMyLiquidations:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!1,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrders:!1,fetchOrderTrades:!1,fetchPosition:!0,fetchPositionHistory:"emulated",fetchPositionMode:!1,fetchPositions:!0,fetchPositionsHistory:!0,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchStatus:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTransactions:!1,fetchTransfer:!1,fetchTransfers:!0,fetchWithdrawAddresses:!1,fetchWithdrawal:!0,fetchWithdrawals:!0,reduceMargin:!0,repayCrossMargin:!0,repayIsolatedMargin:!0,setLeverage:!0,setMargin:!1,setMarginMode:!0,setPositionMode:!0,signIn:!1,transfer:!0,withdraw:!0},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","12h":"12h","1d":"1d","3d":"3d","1w":"1w","1M":"1m"},hostname:"bitget.com",urls:{logo:"https://github.com/user-attachments/assets/b54bb4c2-416d-4231-8968-85a77748ba45",api:{spot:"https://api.{hostname}",mix:"https://api.{hostname}",user:"https://api.{hostname}",p2p:"https://api.{hostname}",broker:"https://api.{hostname}",margin:"https://api.{hostname}",common:"https://api.{hostname}",tax:"https://api.{hostname}",convert:"https://api.{hostname}",copy:"https://api.{hostname}",earn:"https://api.{hostname}",uta:"https://api.{hostname}"},www:"https://www.bitget.com",doc:["https://www.bitget.com/api-doc/common/intro","https://www.bitget.com/api-doc/spot/intro","https://www.bitget.com/api-doc/contract/intro","https://www.bitget.com/api-doc/broker/intro","https://www.bitget.com/api-doc/margin/intro","https://www.bitget.com/api-doc/copytrading/intro","https://www.bitget.com/api-doc/earn/intro","https://bitgetlimited.github.io/apidoc/en/mix","https://bitgetlimited.github.io/apidoc/en/spot","https://bitgetlimited.github.io/apidoc/en/broker","https://bitgetlimited.github.io/apidoc/en/margin"],fees:"https://www.bitget.cc/zh-CN/rate?tab=1",referral:"https://www.bitget.com/expressly?languageType=0&channelCode=ccxt&vipCode=tg9j"},api:{public:{common:{get:{"v2/public/annoucements":{cost:1},"v2/public/time":{cost:1}}},spot:{get:{"spot/v1/notice/queryAllNotices":{cost:1},"spot/v1/public/time":{cost:1},"spot/v1/public/currencies":{cost:6.6667},"spot/v1/public/products":{cost:1},"spot/v1/public/product":{cost:1},"spot/v1/market/ticker":{cost:1},"spot/v1/market/tickers":{cost:1},"spot/v1/market/fills":{cost:2},"spot/v1/market/fills-history":{cost:2},"spot/v1/market/candles":{cost:1},"spot/v1/market/depth":{cost:1},"spot/v1/market/spot-vip-level":{cost:2},"spot/v1/market/merge-depth":{cost:1},"spot/v1/market/history-candles":{cost:1},"spot/v1/public/loan/coinInfos":{cost:2},"spot/v1/public/loan/hour-interest":{cost:2},"v2/spot/public/coins":{cost:6.6667},"v2/spot/public/symbols":{cost:1},"v2/spot/market/vip-fee-rate":{cost:2},"v2/spot/market/tickers":{cost:1},"v2/spot/market/merge-depth":{cost:1},"v2/spot/market/orderbook":{cost:1},"v2/spot/market/candles":{cost:1},"v2/spot/market/history-candles":{cost:1},"v2/spot/market/fills":{cost:2},"v2/spot/market/fills-history":{cost:2}}},mix:{get:{"mix/v1/market/contracts":{cost:1},"mix/v1/market/depth":{cost:1},"mix/v1/market/ticker":{cost:1},"mix/v1/market/tickers":{cost:1},"mix/v1/market/contract-vip-level":{cost:2},"mix/v1/market/fills":{cost:1},"mix/v1/market/fills-history":{cost:2},"mix/v1/market/candles":{cost:1},"mix/v1/market/index":{cost:1},"mix/v1/market/funding-time":{cost:1},"mix/v1/market/history-fundRate":{cost:1},"mix/v1/market/current-fundRate":{cost:1},"mix/v1/market/open-interest":{cost:1},"mix/v1/market/mark-price":{cost:1},"mix/v1/market/symbol-leverage":{cost:1},"mix/v1/market/queryPositionLever":{cost:1},"mix/v1/market/open-limit":{cost:1},"mix/v1/market/history-candles":{cost:1},"mix/v1/market/history-index-candles":{cost:1},"mix/v1/market/history-mark-candles":{cost:1},"mix/v1/market/merge-depth":{cost:1},"v2/mix/market/vip-fee-rate":{cost:2},"v2/mix/market/union-interest-rate-history":{cost:4},"v2/mix/market/exchange-rate":{cost:4},"v2/mix/market/discount-rate":{cost:4},"v2/mix/market/merge-depth":{cost:1},"v2/mix/market/ticker":{cost:1},"v2/mix/market/tickers":{cost:1},"v2/mix/market/fills":{cost:1},"v2/mix/market/fills-history":{cost:2},"v2/mix/market/candles":{cost:1},"v2/mix/market/history-candles":{cost:1},"v2/mix/market/history-index-candles":{cost:1},"v2/mix/market/history-mark-candles":{cost:1},"v2/mix/market/open-interest":{cost:1},"v2/mix/market/funding-time":{cost:1},"v2/mix/market/symbol-price":{cost:1},"v2/mix/market/history-fund-rate":{cost:1},"v2/mix/market/current-fund-rate":{cost:1},"v2/mix/market/oi-limit":{cost:2},"v2/mix/market/contracts":{cost:1},"v2/mix/market/query-position-lever":{cost:2},"v2/mix/market/account-long-short":{cost:20}}},margin:{get:{"margin/v1/cross/public/interestRateAndLimit":{cost:2},"margin/v1/isolated/public/interestRateAndLimit":{cost:2},"margin/v1/cross/public/tierData":{cost:2},"margin/v1/isolated/public/tierData":{cost:2},"margin/v1/public/currencies":{cost:1},"v2/margin/currencies":{cost:2},"v2/margin/market/long-short-ratio":{cost:20}}},earn:{get:{"v2/earn/loan/public/coinInfos":{cost:2},"v2/earn/loan/public/hour-interest":{cost:2}}},uta:{get:{"v3/market/instruments":{cost:1},"v3/market/tickers":{cost:1},"v3/market/orderbook":{cost:1},"v3/market/fills":{cost:1},"v3/market/proof-of-reserves":{cost:1},"v3/market/open-interest":{cost:1},"v3/market/candles":{cost:1},"v3/market/history-candles":{cost:1},"v3/market/current-fund-rate":{cost:1},"v3/market/history-fund-rate":{cost:1},"v3/market/risk-reserve":{cost:1},"v3/market/discount-rate":{cost:1},"v3/market/margin-loans":{cost:1},"v3/market/position-tier":{cost:1},"v3/market/oi-limit":{cost:2},"v3/market/index-components":{cost:2},"v3/market/risk-reserve-all":{cost:6.6667},"v3/market/risk-reserve-hour":{cost:1},"v3/market/score-weights":{cost:4},"v3/market/fee-group":{cost:4},"v3/market/cash-dividend-records":{cost:2},"v3/market/split-records":{cost:4},"v3/market/liquidations":{cost:4},"v3/market/rpi-orderbook":{cost:2},"v3/market/rpi-symbols":{cost:2},"v3/market/spot-whale-flow":{cost:20},"v3/market/spot-fund-flow":{cost:20},"v3/market/spot-net-flow":{cost:20},"v3/market/margin-long-short":{cost:20},"v3/market/margin-loan-growth":{cost:20},"v3/market/margin-isolated-borrow":{cost:20},"v3/market/futures-active-buy-sell":{cost:20},"v3/market/futures-long-short":{cost:20},"v3/market/futures-position-long-short":{cost:20},"v3/market/futures-account-long-short":{cost:20},"v3/reality/market/stock-info":{cost:20},"v3/reality/market/states":{cost:20},"v3/reality/market/calendar":{cost:20},"v3/reality/market/company-overview":{cost:20},"v3/reality/market/valuation-indicators":{cost:20},"v3/reality/market/earnings-forecast":{cost:20},"v3/reality/market/suspension-resumption-info":{cost:20},"v3/reality/market/dividends":{cost:20},"v3/reality/market/share-capital-change":{cost:20},"v3/reality/market/inner-trades":{cost:20},"v3/reality/market/executive-shareholdings":{cost:20},"v3/reality/market/sharehold-detail":{cost:20},"v3/account/custom-collateral-coins":{cost:2}}}},private:{spot:{get:{"spot/v1/wallet/deposit-address":{cost:4},"spot/v1/wallet/withdrawal-list":{cost:1},"spot/v1/wallet/deposit-list":{cost:1},"spot/v1/account/getInfo":{cost:20},"spot/v1/account/assets":{cost:2},"spot/v1/account/assets-lite":{cost:2},"spot/v1/account/transferRecords":{cost:1},"spot/v1/convert/currencies":{cost:2},"spot/v1/convert/convert-record":{cost:2},"spot/v1/loan/ongoing-orders":{cost:2},"spot/v1/loan/repay-history":{cost:2},"spot/v1/loan/revise-history":{cost:2},"spot/v1/loan/borrow-history":{cost:2},"spot/v1/loan/debts":{cost:2},"v2/spot/trade/orderInfo":{cost:1},"v2/spot/trade/unfilled-orders":{cost:1},"v2/spot/trade/history-orders":{cost:1},"v2/spot/trade/fills":{cost:2},"v2/spot/trade/current-plan-order":{cost:1},"v2/spot/trade/history-plan-order":{cost:1},"v2/spot/account/info":{cost:20},"v2/spot/account/assets":{cost:2},"v2/spot/account/subaccount-assets":{cost:2},"v2/spot/account/bills":{cost:2},"v2/spot/account/transferRecords":{cost:1},"v2/account/funding-assets":{cost:2},"v2/account/bot-assets":{cost:2},"v2/account/all-account-balance":{cost:20},"v2/spot/wallet/deposit-address":{cost:2},"v2/spot/wallet/deposit-records":{cost:2},"v2/spot/wallet/withdrawal-records":{cost:2},"v2/spot/account/upgrade-status":{cost:20}},post:{"spot/v1/wallet/transfer":{cost:4},"spot/v1/wallet/transfer-v2":{cost:4},"spot/v1/wallet/subTransfer":{cost:10},"spot/v1/wallet/withdrawal":{cost:4},"spot/v1/wallet/withdrawal-v2":{cost:4},"spot/v1/wallet/withdrawal-inner":{cost:4},"spot/v1/wallet/withdrawal-inner-v2":{cost:4},"spot/v1/account/sub-account-spot-assets":{cost:200},"spot/v1/account/bills":{cost:2},"spot/v1/trade/orders":{cost:2},"spot/v1/trade/batch-orders":{cost:4},"spot/v1/trade/cancel-order":{cost:2},"spot/v1/trade/cancel-order-v2":{cost:2},"spot/v1/trade/cancel-symbol-order":{cost:2},"spot/v1/trade/cancel-batch-orders":{cost:4},"spot/v1/trade/cancel-batch-orders-v2":{cost:4},"spot/v1/trade/orderInfo":{cost:1},"spot/v1/trade/open-orders":{cost:1},"spot/v1/trade/history":{cost:1},"spot/v1/trade/fills":{cost:1},"spot/v1/plan/placePlan":{cost:1},"spot/v1/plan/modifyPlan":{cost:1},"spot/v1/plan/cancelPlan":{cost:1},"spot/v1/plan/currentPlan":{cost:1},"spot/v1/plan/historyPlan":{cost:1},"spot/v1/plan/batchCancelPlan":{cost:2},"spot/v1/convert/quoted-price":{cost:4},"spot/v1/convert/trade":{cost:4},"spot/v1/loan/borrow":{cost:2},"spot/v1/loan/repay":{cost:2},"spot/v1/loan/revise-pledge":{cost:2},"spot/v1/trace/order/orderCurrentList":{cost:2},"spot/v1/trace/order/orderHistoryList":{cost:2},"spot/v1/trace/order/closeTrackingOrder":{cost:2},"spot/v1/trace/order/updateTpsl":{cost:2},"spot/v1/trace/order/followerEndOrder":{cost:2},"spot/v1/trace/order/spotInfoList":{cost:2},"spot/v1/trace/config/getTraderSettings":{cost:2},"spot/v1/trace/config/getFollowerSettings":{cost:2},"spot/v1/trace/user/myTraders":{cost:2},"spot/v1/trace/config/setFollowerConfig":{cost:2},"spot/v1/trace/user/myFollowers":{cost:2},"spot/v1/trace/config/setProductCode":{cost:2},"spot/v1/trace/user/removeTrader":{cost:2},"spot/v1/trace/getRemovableFollower":{cost:2},"spot/v1/trace/user/removeFollower":{cost:2},"spot/v1/trace/profit/totalProfitInfo":{cost:2},"spot/v1/trace/profit/totalProfitList":{cost:2},"spot/v1/trace/profit/profitHisList":{cost:2},"spot/v1/trace/profit/profitHisDetailList":{cost:2},"spot/v1/trace/profit/waitProfitDetailList":{cost:2},"spot/v1/trace/user/getTraderInfo":{cost:2},"v2/spot/trade/place-order":{cost:2},"v2/spot/trade/cancel-order":{cost:2},"v2/spot/trade/batch-orders":{cost:20},"v2/spot/trade/batch-cancel-order":{cost:2},"v2/spot/trade/cancel-symbol-order":{cost:4},"v2/spot/trade/place-plan-order":{cost:1},"v2/spot/trade/modify-plan-order":{cost:1},"v2/spot/trade/cancel-plan-order":{cost:1},"v2/spot/trade/cancel-replace-order":{cost:2},"v2/spot/trade/batch-cancel-plan-order":{cost:2},"v2/spot/wallet/transfer":{cost:2},"v2/spot/wallet/subaccount-transfer":{cost:2},"v2/spot/wallet/withdrawal":{cost:2},"v2/spot/wallet/cancel-withdrawal":{cost:2},"v2/spot/wallet/modify-deposit-account":{cost:2},"v2/spot/account/upgrade":{cost:20}}},mix:{get:{"mix/v1/account/account":{cost:2},"mix/v1/account/accounts":{cost:2},"mix/v1/position/singlePosition":{cost:2},"mix/v1/position/singlePosition-v2":{cost:2},"mix/v1/position/allPosition":{cost:4},"mix/v1/position/allPosition-v2":{cost:4},"mix/v1/position/history-position":{cost:1},"mix/v1/account/accountBill":{cost:2},"mix/v1/account/accountBusinessBill":{cost:4},"mix/v1/order/current":{cost:1},"mix/v1/order/marginCoinCurrent":{cost:1},"mix/v1/order/history":{cost:2},"mix/v1/order/historyProductType":{cost:4},"mix/v1/order/detail":{cost:2},"mix/v1/order/fills":{cost:2},"mix/v1/order/allFills":{cost:2},"mix/v1/plan/currentPlan":{cost:1},"mix/v1/plan/historyPlan":{cost:2},"mix/v1/trace/currentTrack":{cost:2},"mix/v1/trace/followerOrder":{cost:2},"mix/v1/trace/followerHistoryOrders":{cost:2},"mix/v1/trace/historyTrack":{cost:2},"mix/v1/trace/summary":{cost:1},"mix/v1/trace/profitSettleTokenIdGroup":{cost:1},"mix/v1/trace/profitDateGroupList":{cost:1},"mix/v1/trade/profitDateList":{cost:2},"mix/v1/trace/waitProfitDateList":{cost:1},"mix/v1/trace/traderSymbols":{cost:1},"mix/v1/trace/traderList":{cost:2},"mix/v1/trace/traderDetail":{cost:2},"mix/v1/trace/queryTraceConfig":{cost:2},"v2/mix/account/account":{cost:2},"v2/mix/account/accounts":{cost:2},"v2/mix/account/sub-account-assets":{cost:200},"v2/mix/account/interest-history":{cost:4},"v2/mix/account/max-open":{cost:1},"v2/mix/account/liq-price":{cost:1},"v2/mix/account/open-count":{cost:2},"v2/mix/account/bill":{cost:2},"v2/mix/account/transfer-limits":{cost:20},"v2/mix/account/union-config":{cost:20},"v2/mix/account/switch-union-usdt":{cost:20},"v2/mix/account/isolated-symbols":{cost:2},"v2/mix/market/query-position-lever":{cost:2},"v2/mix/position/single-position":{cost:2},"v2/mix/position/all-position":{cost:4},"v2/mix/position/adlRank":{cost:4},"v2/mix/position/history-position":{cost:1},"v2/mix/order/detail":{cost:2},"v2/mix/order/fills":{cost:2},"v2/mix/order/fill-history":{cost:2},"v2/mix/order/orders-pending":{cost:2},"v2/mix/order/orders-history":{cost:2},"v2/mix/order/plan-sub-order":{cost:2},"v2/mix/order/orders-plan-pending":{cost:2},"v2/mix/order/orders-plan-history":{cost:2},"v2/mix/market/position-long-short":{cost:20}},post:{"mix/v1/account/sub-account-contract-assets":{cost:200},"mix/v1/account/open-count":{cost:1},"mix/v1/account/setLeverage":{cost:4},"mix/v1/account/setMargin":{cost:4},"mix/v1/account/setMarginMode":{cost:4},"mix/v1/account/setPositionMode":{cost:4},"mix/v1/order/placeOrder":{cost:2},"mix/v1/order/batch-orders":{cost:2},"mix/v1/order/cancel-order":{cost:2},"mix/v1/order/cancel-batch-orders":{cost:2},"mix/v1/order/modifyOrder":{cost:2},"mix/v1/order/cancel-symbol-orders":{cost:2},"mix/v1/order/cancel-all-orders":{cost:2},"mix/v1/order/close-all-positions":{cost:20},"mix/v1/plan/placePlan":{cost:2},"mix/v1/plan/modifyPlan":{cost:2},"mix/v1/plan/modifyPlanPreset":{cost:2},"mix/v1/plan/placeTPSL":{cost:2},"mix/v1/plan/placeTrailStop":{cost:2},"mix/v1/plan/placePositionsTPSL":{cost:2},"mix/v1/plan/modifyTPSLPlan":{cost:2},"mix/v1/plan/cancelPlan":{cost:2},"mix/v1/plan/cancelSymbolPlan":{cost:2},"mix/v1/plan/cancelAllPlan":{cost:2},"mix/v1/trace/closeTrackOrder":{cost:2},"mix/v1/trace/modifyTPSL":{cost:2},"mix/v1/trace/closeTrackOrderBySymbol":{cost:2},"mix/v1/trace/setUpCopySymbols":{cost:2},"mix/v1/trace/followerSetBatchTraceConfig":{cost:2},"mix/v1/trace/followerCloseByTrackingNo":{cost:2},"mix/v1/trace/followerCloseByAll":{cost:2},"mix/v1/trace/followerSetTpsl":{cost:2},"mix/v1/trace/cancelCopyTrader":{cost:4},"mix/v1/trace/traderUpdateConfig":{cost:2},"mix/v1/trace/myTraderList":{cost:2},"mix/v1/trace/myFollowerList":{cost:2},"mix/v1/trace/removeFollower":{cost:2},"mix/v1/trace/public/getFollowerConfig":{cost:2},"mix/v1/trace/report/order/historyList":{cost:2},"mix/v1/trace/report/order/currentList":{cost:2},"mix/v1/trace/queryTraderTpslRatioConfig":{cost:2},"mix/v1/trace/traderUpdateTpslRatioConfig":{cost:2},"v2/mix/account/set-auto-margin":{cost:4},"v2/mix/account/set-leverage":{cost:4},"v2/mix/account/set-all-leverage":{cost:4},"v2/mix/account/set-margin":{cost:4},"v2/mix/account/set-asset-mode":{cost:10},"v2/mix/account/set-margin-mode":{cost:4},"v2/mix/account/union-convert":{cost:20},"v2/mix/account/set-position-mode":{cost:4},"v2/mix/order/place-order":{cost:2},"v2/mix/order/click-backhand":{cost:20},"v2/mix/order/batch-place-order":{cost:20},"v2/mix/order/modify-order":{cost:2},"v2/mix/order/cancel-order":{cost:2},"v2/mix/order/batch-cancel-orders":{cost:2},"v2/mix/order/close-positions":{cost:20},"v2/mix/order/cancel-all-orders":{cost:20},"v2/mix/order/place-tpsl-order":{cost:2},"v2/mix/order/place-pos-tpsl":{cost:2},"v2/mix/order/place-plan-order":{cost:2},"v2/mix/order/modify-tpsl-order":{cost:2},"v2/mix/order/modify-plan-order":{cost:2},"v2/mix/order/cancel-plan-order":{cost:2}}},user:{get:{"user/v1/fee/query":{cost:2},"user/v1/sub/virtual-list":{cost:2},"user/v1/sub/virtual-api-list":{cost:2},"user/v1/tax/spot-record":{cost:1},"user/v1/tax/future-record":{cost:1},"user/v1/tax/margin-record":{cost:1},"user/v1/tax/p2p-record":{cost:1},"v2/user/virtual-subaccount-list":{cost:2},"v2/user/virtual-subaccount-apikey-list":{cost:2}},post:{"user/v1/sub/virtual-create":{cost:4},"user/v1/sub/virtual-modify":{cost:4},"user/v1/sub/virtual-api-batch-create":{cost:20},"user/v1/sub/virtual-api-create":{cost:4},"user/v1/sub/virtual-api-modify":{cost:4},"v2/user/create-virtual-subaccount":{cost:4},"v2/user/modify-virtual-subaccount":{cost:4},"v2/user/batch-create-subaccount-and-apikey":{cost:20},"v2/user/create-virtual-subaccount-apikey":{cost:4},"v2/user/modify-virtual-subaccount-apikey":{cost:4},"v2/user/create-agent-subaccount":{cost:20}}},p2p:{get:{"p2p/v1/merchant/merchantList":{cost:2},"p2p/v1/merchant/merchantInfo":{cost:2},"p2p/v1/merchant/advList":{cost:2},"p2p/v1/merchant/orderList":{cost:2},"v2/p2p/merchantList":{cost:2},"v2/p2p/merchantInfo":{cost:2},"v2/p2p/orderList":{cost:2},"v2/p2p/advList":{cost:2}}},broker:{get:{"broker/v1/account/info":{cost:2},"broker/v1/account/sub-list":{cost:20},"broker/v1/account/sub-email":{cost:20},"broker/v1/account/sub-spot-assets":{cost:2},"broker/v1/account/sub-future-assets":{cost:2},"broker/v1/account/subaccount-transfer":{cost:1},"broker/v1/account/subaccount-deposit":{cost:1},"broker/v1/account/subaccount-withdrawal":{cost:1},"broker/v1/account/sub-api-list":{cost:2},"v2/broker/account/info":{cost:2},"v2/broker/account/subaccount-list":{cost:20},"v2/broker/account/subaccount-email":{cost:2},"v2/broker/account/subaccount-spot-assets":{cost:2},"v2/broker/account/subaccount-future-assets":{cost:2},"v2/broker/manage/subaccount-apikey-list":{cost:2},"v2/broker/sub-customer-list":{cost:2},"v2/broker/agent-commission":{cost:2},"v2/broker/customer-commissions":{cost:2},"v2/broker/customer-kyc-result":{cost:2},"v2/broker/order-commission":{cost:1},"v2/broker/rebate-info":{cost:1},"v2/broker/total-commission":{cost:1}},post:{"broker/v1/account/sub-create":{cost:20},"broker/v1/account/sub-modify":{cost:20},"broker/v1/account/sub-modify-email":{cost:20},"broker/v1/account/sub-address":{cost:2},"broker/v1/account/sub-withdrawal":{cost:2},"broker/v1/account/sub-auto-transfer":{cost:4},"broker/v1/account/sub-api-create":{cost:2},"broker/v1/account/sub-api-modify":{cost:2},"v2/broker/account/modify-subaccount-email":{cost:2},"v2/broker/account/create-subaccount":{cost:20},"v2/broker/account/modify-subaccount":{cost:20},"v2/broker/account/subaccount-address":{cost:2},"v2/broker/account/subaccount-withdrawal":{cost:2},"v2/broker/account/set-subaccount-autotransfer":{cost:2},"v2/broker/manage/create-subaccount-apikey":{cost:2},"v2/broker/manage/modify-subaccount-apikey":{cost:2},"v2/broker/customer-asset":{cost:2},"v2/broker/customer-deposit":{cost:2},"v2/broker/customer-list":{cost:2},"v2/broker/customer-trade-volume":{cost:2}}},margin:{get:{"margin/v1/cross/account/riskRate":{cost:2},"margin/v1/cross/account/maxTransferOutAmount":{cost:2},"margin/v1/isolated/account/maxTransferOutAmount":{cost:2},"margin/v1/isolated/order/openOrders":{cost:2},"margin/v1/isolated/order/history":{cost:2},"margin/v1/isolated/order/fills":{cost:2},"margin/v1/isolated/loan/list":{cost:2},"margin/v1/isolated/repay/list":{cost:2},"margin/v1/isolated/interest/list":{cost:2},"margin/v1/isolated/liquidation/list":{cost:2},"margin/v1/isolated/fin/list":{cost:2},"margin/v1/cross/order/openOrders":{cost:2},"margin/v1/cross/order/history":{cost:2},"margin/v1/cross/order/fills":{cost:2},"margin/v1/cross/loan/list":{cost:2},"margin/v1/cross/repay/list":{cost:2},"margin/v1/cross/interest/list":{cost:2},"margin/v1/cross/liquidation/list":{cost:2},"margin/v1/cross/fin/list":{cost:2},"margin/v1/cross/account/assets":{cost:2},"margin/v1/isolated/account/assets":{cost:2},"v2/margin/crossed/borrow-history":{cost:2},"v2/margin/crossed/repay-history":{cost:2},"v2/margin/crossed/interest-history":{cost:2},"v2/margin/crossed/liquidation-history":{cost:2},"v2/margin/crossed/financial-records":{cost:2},"v2/margin/crossed/account/assets":{cost:2},"v2/margin/crossed/account/risk-rate":{cost:2},"v2/margin/crossed/account/max-borrowable-amount":{cost:2},"v2/margin/crossed/account/max-transfer-out-amount":{cost:2},"v2/margin/crossed/interest-rate-and-limit":{cost:2},"v2/margin/crossed/tier-data":{cost:2},"v2/margin/crossed/open-orders":{cost:2},"v2/margin/crossed/history-orders":{cost:2},"v2/margin/crossed/fills":{cost:2},"v2/margin/isolated/borrow-history":{cost:2},"v2/margin/isolated/repay-history":{cost:2},"v2/margin/isolated/interest-history":{cost:2},"v2/margin/isolated/liquidation-history":{cost:2},"v2/margin/isolated/financial-records":{cost:2},"v2/margin/isolated/account/assets":{cost:2},"v2/margin/isolated/account/risk-rate":{cost:2},"v2/margin/isolated/account/max-borrowable-amount":{cost:2},"v2/margin/isolated/account/max-transfer-out-amount":{cost:2},"v2/margin/isolated/interest-rate-and-limit":{cost:2},"v2/margin/isolated/tier-data":{cost:2},"v2/margin/isolated/open-orders":{cost:2},"v2/margin/isolated/history-orders":{cost:2},"v2/margin/isolated/fills":{cost:2}},post:{"margin/v1/cross/account/borrow":{cost:2},"margin/v1/isolated/account/borrow":{cost:2},"margin/v1/cross/account/repay":{cost:2},"margin/v1/isolated/account/repay":{cost:2},"margin/v1/isolated/account/riskRate":{cost:2},"margin/v1/cross/account/maxBorrowableAmount":{cost:2},"margin/v1/isolated/account/maxBorrowableAmount":{cost:2},"margin/v1/isolated/account/flashRepay":{cost:2},"margin/v1/isolated/account/queryFlashRepayStatus":{cost:2},"margin/v1/cross/account/flashRepay":{cost:2},"margin/v1/cross/account/queryFlashRepayStatus":{cost:2},"margin/v1/isolated/order/placeOrder":{cost:4},"margin/v1/isolated/order/batchPlaceOrder":{cost:4},"margin/v1/isolated/order/cancelOrder":{cost:2},"margin/v1/isolated/order/batchCancelOrder":{cost:2},"margin/v1/cross/order/placeOrder":{cost:2},"margin/v1/cross/order/batchPlaceOrder":{cost:2},"margin/v1/cross/order/cancelOrder":{cost:2},"margin/v1/cross/order/batchCancelOrder":{cost:2},"v2/margin/crossed/account/borrow":{cost:2},"v2/margin/crossed/account/repay":{cost:2},"v2/margin/crossed/account/flash-repay":{cost:2},"v2/margin/crossed/account/query-flash-repay-status":{cost:2},"v2/margin/crossed/place-order":{cost:2},"v2/margin/crossed/batch-place-order":{cost:2},"v2/margin/crossed/cancel-order":{cost:2},"v2/margin/crossed/batch-cancel-order":{cost:2},"v2/margin/isolated/account/borrow":{cost:2},"v2/margin/isolated/account/repay":{cost:2},"v2/margin/isolated/account/flash-repay":{cost:2},"v2/margin/isolated/account/query-flash-repay-status":{cost:2},"v2/margin/isolated/place-order":{cost:2},"v2/margin/isolated/batch-place-order":{cost:2},"v2/margin/isolated/cancel-order":{cost:2},"v2/margin/isolated/batch-cancel-order":{cost:2}}},copy:{get:{"v2/copy/mix-trader/order-current-track":{cost:2},"v2/copy/mix-trader/order-history-track":{cost:2},"v2/copy/mix-trader/order-total-detail":{cost:2},"v2/copy/mix-trader/profit-history-summarys":{cost:1},"v2/copy/mix-trader/profit-history-details":{cost:1},"v2/copy/mix-trader/profit-details":{cost:1},"v2/copy/mix-trader/profits-group-coin-date":{cost:1},"v2/copy/mix-trader/config-query-symbols":{cost:1},"v2/copy/mix-trader/config-query-followers":{cost:2},"v2/copy/mix-follower/query-current-orders":{cost:2},"v2/copy/mix-follower/query-history-orders":{cost:1},"v2/copy/mix-follower/query-settings":{cost:2},"v2/copy/mix-follower/query-traders":{cost:2},"v2/copy/mix-follower/query-quantity-limit":{cost:2},"v2/copy/mix-broker/query-traders":{cost:2},"v2/copy/mix-broker/query-history-traces":{cost:2},"v2/copy/mix-broker/query-current-traces":{cost:2},"v2/copy/spot-trader/profit-summarys":{cost:2},"v2/copy/spot-trader/profit-history-details":{cost:2},"v2/copy/spot-trader/profit-details":{cost:2},"v2/copy/spot-trader/order-total-detail":{cost:2},"v2/copy/spot-trader/order-history-track":{cost:2},"v2/copy/spot-trader/order-current-track":{cost:2},"v2/copy/spot-trader/config-query-settings":{cost:2},"v2/copy/spot-trader/config-query-followers":{cost:2},"v2/copy/spot-follower/query-traders":{cost:2},"v2/copy/spot-follower/query-trader-symbols":{cost:2},"v2/copy/spot-follower/query-settings":{cost:2},"v2/copy/spot-follower/query-history-orders":{cost:2},"v2/copy/spot-follower/query-current-orders":{cost:2}},post:{"v2/copy/mix-trader/order-modify-tpsl":{cost:2},"v2/copy/mix-trader/order-close-positions":{cost:2},"v2/copy/mix-trader/config-setting-symbols":{cost:2},"v2/copy/mix-trader/config-setting-base":{cost:2},"v2/copy/mix-trader/config-remove-follower":{cost:2},"v2/copy/mix-follower/setting-tpsl":{cost:1},"v2/copy/mix-follower/settings":{cost:2},"v2/copy/mix-follower/close-positions":{cost:2},"v2/copy/mix-follower/cancel-trader":{cost:4},"v2/copy/spot-trader/order-modify-tpsl":{cost:2},"v2/copy/spot-trader/order-close-tracking":{cost:2},"v2/copy/spot-trader/config-setting-symbols":{cost:2},"v2/copy/spot-trader/config-remove-follower":{cost:2},"v2/copy/spot-follower/stop-order":{cost:2},"v2/copy/spot-follower/settings":{cost:2},"v2/copy/spot-follower/setting-tpsl":{cost:2},"v2/copy/spot-follower/order-close-tracking":{cost:2},"v2/copy/spot-follower/cancel-trader":{cost:2}}},tax:{get:{"v2/tax/spot-record":{cost:20},"v2/tax/future-record":{cost:20},"v2/tax/margin-record":{cost:20},"v2/tax/p2p-record":{cost:20}}},convert:{get:{"v2/convert/currencies":{cost:2},"v2/convert/quoted-price":{cost:2},"v2/convert/convert-record":{cost:2},"v2/convert/bgb-convert-coin-list":{cost:2},"v2/convert/bgb-convert-records":{cost:2}},post:{"v2/convert/trade":{cost:2},"v2/convert/bgb-convert":{cost:2}}},earn:{get:{"v2/earn/savings/product":{cost:2},"v2/earn/savings/account":{cost:2},"v2/earn/savings/assets":{cost:2},"v2/earn/savings/records":{cost:2},"v2/earn/savings/subscribe-info":{cost:2},"v2/earn/savings/subscribe-result":{cost:2},"v2/earn/savings/redeem-result":{cost:2},"v2/earn/sharkfin/product":{cost:2},"v2/earn/sharkfin/account":{cost:2},"v2/earn/sharkfin/assets":{cost:2},"v2/earn/sharkfin/records":{cost:2},"v2/earn/sharkfin/subscribe-info":{cost:2},"v2/earn/sharkfin/subscribe-result":{cost:4},"v2/earn/loan/ongoing-orders":{cost:2},"v2/earn/loan/repay-history":{cost:2},"v2/earn/loan/revise-history":{cost:2},"v2/earn/loan/borrow-history":{cost:2},"v2/earn/loan/debts":{cost:2},"v2/earn/loan/reduces":{cost:2},"v2/earn/account/assets":{cost:2},"v2/earn/elite/product":{cost:4},"v2/earn/elite/assets":{cost:4},"v2/earn/elite/records":{cost:4},"v2/earn/elite/subscribe-info":{cost:4},"v2/earn/elite/subscribe-result":{cost:4},"v2/earn/elite/redeem-info":{cost:4}},post:{"v2/earn/savings/subscribe":{cost:2},"v2/earn/savings/redeem":{cost:2},"v2/earn/sharkfin/subscribe":{cost:2},"v2/earn/loan/borrow":{cost:2},"v2/earn/loan/repay":{cost:2},"v2/earn/loan/revise-pledge":{cost:2},"v2/earn/elite/subscribe":{cost:4},"v2/earn/elite/redeem":{cost:4}}},common:{get:{"v2/common/trade-rate":{cost:2}}},uta:{get:{"v3/account/assets":{cost:1},"v3/account/funding-assets":{cost:1},"v3/account/settings":{cost:1},"v3/account/financial-records":{cost:1},"v3/account/repayable-coins":{cost:2},"v3/account/payment-coins":{cost:2},"v3/account/convert-records":{cost:1},"v3/account/deduct-info":{cost:20},"v3/account/fee-rate":{cost:6.6667},"v3/account/switch-status":{cost:4},"v3/account/max-transferable":{cost:6.6667},"v3/account/open-interest-limit":{cost:4},"v3/account/sub-unified-assets":{cost:20},"v3/account/transferable-coins":{cost:2},"v3/account/sub-transfer-record":{cost:4},"v3/account/deposit-address":{cost:2},"v3/account/sub-deposit-address":{cost:2},"v3/account/deposit-records":{cost:2},"v3/account/sub-deposit-records":{cost:2},"v3/account/withdrawal-records":{cost:2},"v3/broker/sub-list":{cost:1},"v3/broker/all-sub-deposit-withdrawal":{cost:1},"v3/broker/commission":{cost:1},"v3/broker/query-sub-apikey":{cost:1},"v3/ins-loan/transfered":{cost:6.6667},"v3/ins-loan/symbols":{cost:6.6667},"v3/ins-loan/risk-unit":{cost:6.6667},"v3/ins-loan/repaid-history":{cost:6.6667},"v3/ins-loan/product-infos":{cost:6.6667},"v3/ins-loan/loan-order":{cost:6.6667},"v3/ins-loan/ltv-convert":{cost:6.6667},"v3/ins-loan/ensure-coins-convert":{cost:6.6667},"v3/loan/coins":{cost:2},"v3/loan/interest":{cost:2},"v3/loan/borrow-ongoing":{cost:2},"v3/loan/borrow-history":{cost:2},"v3/loan/repay-history":{cost:2},"v3/loan/pledge-rate-history":{cost:2},"v3/loan/debts":{cost:2},"v3/loan/reduces":{cost:2},"v3/position/current-position":{cost:1},"v3/position/history-position":{cost:1},"v3/position/adlRank":{cost:20},"v3/tax/records":{cost:20},"v3/trade/order-info":{cost:1},"v3/trade/unfilled-orders":{cost:1},"v3/trade/unfilled-strategy-orders":{cost:1},"v3/trade/history-orders":{cost:1},"v3/trade/history-strategy-orders":{cost:1},"v3/trade/fills":{cost:1},"v3/user/sub-list":{cost:2},"v3/user/sub-api-list":{cost:2},"v3/account/info":{cost:4},"v3/account/all-fee-rate":{cost:6.6667},"v3/account/delta-info":{cost:1},"v3/account/withdraw-address":{cost:20},"v3/account/max-withdrawal":{cost:2},"v3/account/move-position-history":{cost:4},"v3/account/collateral-type":{cost:2},"v3/account/pre-set-leverage":{cost:2},"v3/account/eligible-symbols":{cost:2},"v3/account/eligible-margin-tier":{cost:2},"v3/account/eligible-loan-info":{cost:2},"v3/account/eligible-discount-rate":{cost:1},"v3/account/funding-financial-records":{cost:2},"v3/account/reality-orderbook":{cost:2},"v3/account/reality-fills":{cost:2},"v3/copy/futures/trading-pairs":{cost:4},"v3/copy/futures/position-summary":{cost:4},"v3/copy/futures/max-transferable":{cost:20},"v3/copy/futures/transfer-record":{cost:20},"v3/copy/futures/current-follower":{cost:20},"v3/copy/futures/history-follower":{cost:20},"v3/copy/futures/profit-summary":{cost:20},"v3/copy/futures/profit-details":{cost:20},"v3/convert/small-assets":{cost:2},"v3/convert/small-assets-history":{cost:2},"v3/earn/elite-product":{cost:4},"v3/earn/elite-assets":{cost:4},"v3/earn/elite-subscribe-info":{cost:4},"v3/earn/elite-records":{cost:4},"v3/earn/elite-subscribe-result":{cost:4},"v3/earn/elite-redeem-info":{cost:4},"v3/trade/loan-data":{cost:2},"v3/trade/strategy-sub-orders":{cost:2},"v3/trade/grid/bot-detail":{cost:2},"v3/trade/grid/list-details":{cost:20},"v3/trade/grid/neutral-bot-detail":{cost:2},"v3/trade/grid/neutral-list-details":{cost:20},"v3/user/rate-limit-quota":{cost:2},"v3/stockplus/market/option-quote":{cost:2},"v3/stockplus/market/option-chain-info":{cost:2},"v3/stockplus/market/option-expiry-date":{cost:2},"v3/stockplus/market/option-volume":{cost:2},"v3/stockplus/market/depth":{cost:2},"v3/stockplus/market/static":{cost:2},"v3/stockplus/market/quote":{cost:2},"v3/stockplus/market/trade":{cost:2},"v3/stockplus/market/intraday":{cost:2},"v3/stockplus/market/history-candlestick":{cost:2},"v3/stockplus/market/candlestick":{cost:2},"v3/stockplus/trade/today-orders":{cost:20},"v3/stockplus/trade/history-orders":{cost:20},"v3/stockplus/trade/order-detail":{cost:20},"v3/stockplus/trade/today-executions":{cost:20},"v3/stockplus/trade/history-executions":{cost:20},"v3/stockplus/asset/account":{cost:2},"v3/stockplus/asset/cash-flow":{cost:2},"v3/stockplus/asset/stock-position":{cost:2},"v3/stockplus/asset/transfer-records":{cost:2},"v3/p2p/ad-list":{cost:2},"v3/p2p/ad-info":{cost:2},"v3/p2p/ad-limit":{cost:2},"v3/p2p/my-ads":{cost:2},"v3/p2p/pending-orders":{cost:2},"v3/p2p/all-orders":{cost:2},"v3/p2p/order-info":{cost:2},"v3/p2p/user-info":{cost:2},"v3/p2p/currencies":{cost:2},"v3/p2p/pay-method":{cost:2},"v3/p2p/balance":{cost:2},"v3/p2p/exchange-rate":{cost:2}},post:{"v3/account/set-leverage":{cost:2},"v3/account/set-hold-mode":{cost:2},"v3/account/repay":{cost:4},"v3/account/switch-deduct":{cost:20},"v3/account/deposit-account":{cost:20},"v3/account/switch":{cost:20},"v3/account/adjust-account-mode":{cost:20},"v3/account/transfer":{cost:4},"v3/account/sub-transfer":{cost:4},"v3/account/sub-master-transfer":{cost:4},"v3/account/max-open-available":{cost:4},"v3/account/withdrawal":{cost:20},"v3/broker/create-sub":{cost:1},"v3/broker/modify-sub":{cost:1},"v3/broker/sub-withdrawal":{cost:1},"v3/broker/sub-deposit-address":{cost:1},"v3/broker/create-sub-apikey":{cost:1},"v3/broker/modify-sub-apikey":{cost:1},"v3/broker/delete-sub-apikey":{cost:1},"v3/ins-loan/bind-uid":{cost:6.6667},"v3/loan/borrow":{cost:2},"v3/loan/repay":{cost:2},"v3/loan/revise-pledge":{cost:2},"v3/trade/place-order":{cost:2},"v3/trade/place-strategy-order":{cost:2},"v3/trade/modify-order":{cost:2},"v3/trade/modify-strategy-order":{cost:2},"v3/trade/cancel-order":{cost:2},"v3/trade/cancel-strategy-order":{cost:2},"v3/trade/place-batch":{cost:4},"v3/trade/batch-modify-order":{cost:2},"v3/trade/cancel-batch":{cost:4},"v3/trade/cancel-symbol-order":{cost:4},"v3/trade/close-positions":{cost:4},"v3/trade/countdown-cancel-all":{cost:20},"v3/user/create-sub":{cost:2},"v3/user/freeze-sub":{cost:2},"v3/user/create-sub-api":{cost:2},"v3/user/update-sub-api":{cost:2},"v3/user/delete-sub-api":{cost:2},"v3/account/move-positions":{cost:20},"v3/account/cancel-withdrawal":{cost:20},"v3/account/set-margin":{cost:2},"v3/account/set-collateral-type":{cost:10},"v3/copy/futures/transfer":{cost:20},"v3/convert/small-assets-trade":{cost:2},"v3/earn/elite-subscribe":{cost:4},"v3/earn/elite-redeem":{cost:4},"v3/trade/place-reality-order":{cost:2},"v3/trade/cancel-reality-order":{cost:2},"v3/trade/grid/validate":{cost:20},"v3/trade/grid/create-bot":{cost:20},"v3/trade/grid/modify-bot":{cost:20},"v3/trade/grid/modify-grid-interval":{cost:20},"v3/trade/grid/add-investment":{cost:20},"v3/trade/grid/close-bot":{cost:20},"v3/trade/grid/validate-neutral":{cost:20},"v3/trade/grid/create-neutral-bot":{cost:20},"v3/trade/grid/modify-neutral-bot":{cost:20},"v3/trade/grid/modify-neutral-grid-interval":{cost:20},"v3/user/set-rate-limit-quota":{cost:4},"v3/user/sub-account/agent-create":{cost:20},"v3/stockplus/trade/place-order":{cost:20},"v3/stockplus/trade/cancel-order":{cost:20},"v3/stockplus/trade/modify-order":{cost:20},"v3/stockplus/asset/transfer":{cost:4},"v3/p2p/ad-create":{cost:2},"v3/p2p/ad-update":{cost:2},"v3/p2p/ad-operate":{cost:2},"v3/p2p/fee-simulate":{cost:2},"v3/p2p/order-pay":{cost:2},"v3/p2p/order-release":{cost:2}}}}},fees:{spot:{taker:this.parseNumber("0.002"),maker:this.parseNumber("0.002")},swap:{taker:this.parseNumber("0.0006"),maker:this.parseNumber("0.0004")}},requiredCredentials:{apiKey:!0,secret:!0,password:!0},exceptions:{exact:{"00001":a.BadRequest,1:a.ExchangeError,"failure to get a peer from the ring-balancer":a.ExchangeNotAvailable,4010:a.PermissionDenied,4001:a.ExchangeError,4002:a.ExchangeError,40020:a.BadRequest,30001:a.AuthenticationError,30002:a.AuthenticationError,30003:a.AuthenticationError,30004:a.AuthenticationError,30005:a.InvalidNonce,30006:a.AuthenticationError,30007:a.BadRequest,30008:a.RequestTimeout,30009:a.ExchangeError,30010:a.AuthenticationError,30011:a.PermissionDenied,30012:a.AuthenticationError,30013:a.AuthenticationError,30014:a.DDoSProtection,30015:a.AuthenticationError,30016:a.ExchangeError,30017:a.ExchangeError,30018:a.ExchangeError,30019:a.ExchangeNotAvailable,30020:a.BadRequest,30021:a.BadRequest,30022:a.PermissionDenied,30023:a.BadRequest,30024:a.BadSymbol,30025:a.BadRequest,30026:a.DDoSProtection,30027:a.AuthenticationError,30028:a.PermissionDenied,30029:a.AccountSuspended,30030:a.ExchangeError,30031:a.BadRequest,30032:a.BadSymbol,30033:a.BadRequest,30034:a.ExchangeError,30035:a.ExchangeError,30036:a.ExchangeError,30037:a.ExchangeNotAvailable,30038:a.OnMaintenance,32001:a.AccountSuspended,32002:a.PermissionDenied,32003:a.CancelPending,32004:a.ExchangeError,32005:a.InvalidOrder,32006:a.InvalidOrder,32007:a.InvalidOrder,32008:a.InvalidOrder,32009:a.InvalidOrder,32010:a.ExchangeError,32011:a.ExchangeError,32012:a.ExchangeError,32013:a.ExchangeError,32014:a.ExchangeError,32015:a.ExchangeError,32016:a.ExchangeError,32017:a.ExchangeError,32018:a.ExchangeError,32019:a.ExchangeError,32020:a.ExchangeError,32021:a.ExchangeError,32022:a.ExchangeError,32023:a.ExchangeError,32024:a.ExchangeError,32025:a.ExchangeError,32026:a.ExchangeError,32027:a.ExchangeError,32028:a.AccountSuspended,32029:a.ExchangeError,32030:a.InvalidOrder,32031:a.ArgumentsRequired,32038:a.AuthenticationError,32040:a.ExchangeError,32044:a.ExchangeError,32045:a.ExchangeError,32046:a.ExchangeError,32047:a.ExchangeError,32048:a.InvalidOrder,32049:a.ExchangeError,32050:a.InvalidOrder,32051:a.InvalidOrder,32052:a.ExchangeError,32053:a.ExchangeError,32057:a.ExchangeError,32054:a.ExchangeError,32055:a.InvalidOrder,32056:a.ExchangeError,32058:a.ExchangeError,32059:a.InvalidOrder,32060:a.InvalidOrder,32061:a.InvalidOrder,32062:a.InvalidOrder,32063:a.InvalidOrder,32064:a.ExchangeError,32065:a.ExchangeError,32066:a.ExchangeError,32067:a.ExchangeError,32068:a.ExchangeError,32069:a.ExchangeError,32070:a.ExchangeError,32071:a.ExchangeError,32072:a.ExchangeError,32073:a.ExchangeError,32074:a.ExchangeError,32075:a.ExchangeError,32076:a.ExchangeError,32077:a.ExchangeError,32078:a.ExchangeError,32079:a.ExchangeError,32080:a.ExchangeError,32083:a.ExchangeError,33001:a.PermissionDenied,33002:a.AccountSuspended,33003:a.InsufficientFunds,33004:a.ExchangeError,33005:a.ExchangeError,33006:a.ExchangeError,33007:a.ExchangeError,33008:a.InsufficientFunds,33009:a.ExchangeError,33010:a.ExchangeError,33011:a.ExchangeError,33012:a.ExchangeError,33013:a.InvalidOrder,33014:a.OrderNotFound,33015:a.InvalidOrder,33016:a.ExchangeError,33017:a.InsufficientFunds,33018:a.ExchangeError,33020:a.ExchangeError,33021:a.BadRequest,33022:a.InvalidOrder,33023:a.ExchangeError,33024:a.InvalidOrder,33025:a.InvalidOrder,33026:a.ExchangeError,33027:a.InvalidOrder,33028:a.InvalidOrder,33029:a.InvalidOrder,33034:a.ExchangeError,33035:a.ExchangeError,33036:a.ExchangeError,33037:a.ExchangeError,33038:a.ExchangeError,33039:a.ExchangeError,33040:a.ExchangeError,33041:a.ExchangeError,33042:a.ExchangeError,33043:a.ExchangeError,33044:a.ExchangeError,33045:a.ExchangeError,33046:a.ExchangeError,33047:a.ExchangeError,33048:a.ExchangeError,33049:a.ExchangeError,33050:a.ExchangeError,33051:a.ExchangeError,33059:a.BadRequest,33060:a.BadRequest,33061:a.ExchangeError,33062:a.ExchangeError,33063:a.ExchangeError,33064:a.ExchangeError,33065:a.ExchangeError,21009:a.ExchangeError,34001:a.PermissionDenied,34002:a.InvalidAddress,34003:a.ExchangeError,34004:a.ExchangeError,34005:a.ExchangeError,34006:a.ExchangeError,34007:a.ExchangeError,34008:a.InsufficientFunds,34009:a.ExchangeError,34010:a.ExchangeError,34011:a.ExchangeError,34012:a.ExchangeError,34013:a.ExchangeError,34014:a.ExchangeError,34015:a.ExchangeError,34016:a.PermissionDenied,34017:a.AccountSuspended,34018:a.AuthenticationError,34019:a.PermissionDenied,34020:a.PermissionDenied,34021:a.InvalidAddress,34022:a.ExchangeError,34023:a.PermissionDenied,34026:a.ExchangeError,34036:a.ExchangeError,34037:a.ExchangeError,34038:a.ExchangeError,34039:a.ExchangeError,35001:a.ExchangeError,35002:a.ExchangeError,35003:a.ExchangeError,35004:a.ExchangeError,35005:a.AuthenticationError,35008:a.InvalidOrder,35010:a.InvalidOrder,35012:a.InvalidOrder,35014:a.InvalidOrder,35015:a.InvalidOrder,35017:a.ExchangeError,35019:a.InvalidOrder,35020:a.InvalidOrder,35021:a.InvalidOrder,35022:a.ExchangeError,35024:a.ExchangeError,35025:a.InsufficientFunds,35026:a.ExchangeError,35029:a.OrderNotFound,35030:a.InvalidOrder,35031:a.InvalidOrder,35032:a.ExchangeError,35037:a.ExchangeError,35039:a.ExchangeError,35040:a.InvalidOrder,35044:a.ExchangeError,35046:a.InsufficientFunds,35047:a.InsufficientFunds,35048:a.ExchangeError,35049:a.InvalidOrder,35050:a.InvalidOrder,35052:a.InsufficientFunds,35053:a.ExchangeError,35055:a.InsufficientFunds,35057:a.ExchangeError,35058:a.ExchangeError,35059:a.BadRequest,35060:a.BadRequest,35061:a.BadRequest,35062:a.InvalidOrder,35063:a.InvalidOrder,35064:a.InvalidOrder,35066:a.InvalidOrder,35067:a.InvalidOrder,35068:a.InvalidOrder,35069:a.InvalidOrder,35070:a.InvalidOrder,35071:a.InvalidOrder,35072:a.InvalidOrder,35073:a.InvalidOrder,35074:a.InvalidOrder,35075:a.InvalidOrder,35076:a.InvalidOrder,35077:a.InvalidOrder,35078:a.InvalidOrder,35079:a.InvalidOrder,35080:a.InvalidOrder,35081:a.InvalidOrder,35082:a.InvalidOrder,35083:a.InvalidOrder,35084:a.InvalidOrder,35085:a.InvalidOrder,35086:a.InvalidOrder,35087:a.InvalidOrder,35088:a.InvalidOrder,35089:a.InvalidOrder,35090:a.ExchangeError,35091:a.ExchangeError,35092:a.ExchangeError,35093:a.ExchangeError,35094:a.ExchangeError,35095:a.BadRequest,35096:a.ExchangeError,35097:a.ExchangeError,35098:a.ExchangeError,35099:a.ExchangeError,36001:a.BadRequest,36002:a.BadRequest,36005:a.ExchangeError,36101:a.AuthenticationError,36102:a.PermissionDenied,36103:a.AccountSuspended,36104:a.PermissionDenied,36105:a.PermissionDenied,36106:a.AccountSuspended,36107:a.PermissionDenied,36108:a.InsufficientFunds,36109:a.PermissionDenied,36201:a.PermissionDenied,36202:a.PermissionDenied,36203:a.InvalidOrder,36204:a.ExchangeError,36205:a.BadRequest,36206:a.BadRequest,36207:a.InvalidOrder,36208:a.InvalidOrder,36209:a.InvalidOrder,36210:a.InvalidOrder,36211:a.InvalidOrder,36212:a.InvalidOrder,36213:a.InvalidOrder,36214:a.ExchangeError,36216:a.OrderNotFound,36217:a.InvalidOrder,36218:a.InvalidOrder,36219:a.InvalidOrder,36220:a.InvalidOrder,36221:a.InvalidOrder,36222:a.InvalidOrder,36223:a.InvalidOrder,36224:a.InvalidOrder,36225:a.InvalidOrder,36226:a.InvalidOrder,36227:a.InvalidOrder,36228:a.InvalidOrder,36229:a.InvalidOrder,36230:a.InvalidOrder,400:a.BadRequest,401:a.AuthenticationError,403:a.PermissionDenied,404:a.BadRequest,405:a.BadRequest,415:a.BadRequest,429:a.DDoSProtection,500:a.ExchangeNotAvailable,1001:a.RateLimitExceeded,1002:a.ExchangeError,1003:a.ExchangeError,40001:a.AuthenticationError,40002:a.AuthenticationError,40003:a.AuthenticationError,40004:a.InvalidNonce,40005:a.InvalidNonce,40006:a.AuthenticationError,40007:a.BadRequest,40008:a.InvalidNonce,40009:a.AuthenticationError,40010:a.AuthenticationError,40011:a.AuthenticationError,40012:a.AuthenticationError,40013:a.ExchangeError,40014:a.PermissionDenied,40015:a.ExchangeError,40016:a.PermissionDenied,40017:a.BadRequest,400172:a.BadRequest,40018:a.PermissionDenied,40019:a.BadRequest,40031:a.AccountSuspended,40037:a.AuthenticationError,40102:a.BadRequest,40103:a.BadRequest,40104:a.ExchangeError,40105:a.ExchangeError,40106:a.ExchangeError,40107:a.ExchangeError,40108:a.InvalidOrder,40109:a.OrderNotFound,40200:a.OnMaintenance,40201:a.InvalidOrder,40202:a.ExchangeError,40203:a.BadRequest,40204:a.BadRequest,40205:a.BadRequest,40206:a.BadRequest,40207:a.BadRequest,40208:a.BadRequest,40209:a.BadRequest,40300:a.ExchangeError,40301:a.PermissionDenied,40302:a.BadRequest,40303:a.BadRequest,40304:a.BadRequest,40305:a.BadRequest,40306:a.ExchangeError,40308:a.OnMaintenance,40309:a.BadSymbol,40400:a.ExchangeError,40401:a.ExchangeError,40402:a.BadRequest,40403:a.BadRequest,40404:a.BadRequest,40405:a.BadRequest,40406:a.BadRequest,40407:a.ExchangeError,40408:a.ExchangeError,40409:a.ExchangeError,40500:a.InvalidOrder,40501:a.ExchangeError,40502:a.ExchangeError,40503:a.ExchangeError,40504:a.ExchangeError,40505:a.ExchangeError,40506:a.AuthenticationError,40507:a.AuthenticationError,40508:a.ExchangeError,40509:a.ExchangeError,40600:a.ExchangeError,40601:a.ExchangeError,40602:a.ExchangeError,40603:a.ExchangeError,40604:a.ExchangeNotAvailable,40605:a.ExchangeError,40606:a.ExchangeError,40607:a.ExchangeError,40608:a.ExchangeError,40609:a.ExchangeError,40700:a.BadRequest,40701:a.ExchangeError,40702:a.ExchangeError,40703:a.ExchangeError,40704:a.ExchangeError,40705:a.BadRequest,40706:a.InvalidOrder,40707:a.BadRequest,40708:a.BadRequest,40709:a.ExchangeError,40710:a.ExchangeError,40711:a.InsufficientFunds,40712:a.InsufficientFunds,40713:a.ExchangeError,40714:a.ExchangeError,40762:a.InsufficientFunds,40768:a.OrderNotFound,40808:a.InvalidOrder,41103:a.InvalidOrder,41114:a.OnMaintenance,43011:a.InvalidOrder,43001:a.OrderNotFound,43012:a.InsufficientFunds,43025:a.InvalidOrder,43115:a.OnMaintenance,45110:a.InvalidOrder,40774:a.InvalidOrder,40917:a.InvalidOrder,45122:a.InvalidOrder,"invalid sign":a.AuthenticationError,"invalid currency":a.BadSymbol,"invalid symbol":a.BadSymbol,"invalid period":a.BadRequest,"invalid user":a.ExchangeError,"invalid amount":a.InvalidOrder,"invalid type":a.InvalidOrder,"invalid orderId":a.InvalidOrder,"invalid record":a.ExchangeError,"invalid accountId":a.BadRequest,"invalid address":a.BadRequest,"accesskey not null":a.AuthenticationError,"illegal accesskey":a.AuthenticationError,"sign not null":a.AuthenticationError,"req_time is too much difference from server time":a.InvalidNonce,"permissions not right":a.PermissionDenied,"illegal sign invalid":a.AuthenticationError,"user locked":a.AccountSuspended,"Request Frequency Is Too High":a.RateLimitExceeded,"more than a daily rate of cash":a.BadRequest,"more than the maximum daily withdrawal amount":a.BadRequest,"need to bind email or mobile":a.ExchangeError,"user forbid":a.PermissionDenied,"User Prohibited Cash Withdrawal":a.PermissionDenied,"Cash Withdrawal Is Less Than The Minimum Value":a.BadRequest,"Cash Withdrawal Is More Than The Maximum Value":a.BadRequest,"the account with in 24 hours ban coin":a.PermissionDenied,"order cancel fail":a.BadRequest,"base symbol error":a.BadSymbol,"base date error":a.ExchangeError,"api signature not valid":a.AuthenticationError,"gateway internal error":a.ExchangeError,"audit failed":a.ExchangeError,"order queryorder invalid":a.BadRequest,"market no need price":a.InvalidOrder,"limit need price":a.InvalidOrder,"userid not equal to account_id":a.ExchangeError,"your balance is low":a.InsufficientFunds,"address invalid cointype":a.ExchangeError,"system exception":a.ExchangeError,50003:a.ExchangeError,50004:a.BadSymbol,50006:a.PermissionDenied,50007:a.PermissionDenied,50008:a.RequestTimeout,50009:a.RateLimitExceeded,50010:a.ExchangeError,50014:a.InvalidOrder,50015:a.InvalidOrder,50016:a.InvalidOrder,50017:a.InvalidOrder,50018:a.InvalidOrder,50019:a.InvalidOrder,50020:a.InsufficientFunds,50021:a.InvalidOrder,50026:a.InvalidOrder,"invalid order query time":a.ExchangeError,"invalid start time":a.BadRequest,"invalid end time":a.BadRequest,20003:a.ExchangeError,"01001":a.ExchangeError,40085:a.PermissionDenied,40024:a.RestrictedLocation,41117:a.InvalidOrder,43111:a.PermissionDenied,45113:a.InvalidOrder},broad:{"invalid size, valid range":a.ExchangeError}},precisionMode:4,commonCurrencies:{APX:"AstroPepeX",DEGEN:"DegenReborn",EVA:"Evadore",JADE:"Jade Protocol",OMNI:"omni",TONCOIN:"TON"},options:{uta:void 0,timeDifference:0,adjustForTimeDifference:!1,fetchMarkets:{types:["spot","swap"]},defaultType:"spot",defaultSubType:"linear",createOrder:{createMarketBuyOrderRequiresPrice:!0,timeInForce:"GTC"},broker:"p4sve",withdraw:{fillResponseFromRequest:!0},fetchOHLCV:{timeframes:{spot:{"1m":"1min","5m":"5min","3m":"3min","15m":"15min","30m":"30min","1h":"1h","4h":"4h","6h":"6Hutc","12h":"12Hutc","1d":"1Dutc","3d":"3Dutc","1w":"1Wutc","1M":"1Mutc"},swap:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1H","2h":"2H","4h":"4H","6h":"6Hutc","12h":"12Hutc","1d":"1Dutc","3d":"3Dutc","1w":"1Wutc","1M":"1Mutc"},uta:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1H","2h":"2H","4h":"4H","6h":"6H","12h":"12H","1d":"1D"}},maxRecentDaysPerTimeframe:{"1m":30,"3m":30,"5m":30,"15m":30,"30m":30,"1h":60,"2h":120,"4h":240,"6h":360,"12h":720,"1d":1440,"3d":4320,"1w":10080,"1M":43200},spot:{maxLimitPerTimeframe:{"1d":300,"3d":100,"1w":100,"1M":100},method:"publicSpotGetV2SpotMarketCandles"},swap:{maxLimitPerTimeframe:{"4h":540,"6h":360,"12h":180,"1d":90,"3d":30,"1w":13,"1M":4},method:"publicMixGetV2MixMarketCandles"}},fetchTrades:{spot:{method:"publicSpotGetV2SpotMarketFillsHistory"},swap:{method:"publicMixGetV2MixMarketFillsHistory"}},fetchFundingRate:{method:"publicMixGetV2MixMarketCurrentFundRate"},accountsByType:{funding:"spot",spot:"spot",cross:"crossed_margin",isolated:"isolated_margin",swap:"usdt_futures",usdc_swap:"usdc_futures",future:"coin_futures",p2p:"p2p",uta:"uta",unified:"uta"},accountsById:{spot:"spot",crossed_margin:"cross",isolated_margin:"isolated",usdt_futures:"swap",usdc_futures:"usdc_swap",coin_futures:"future",p2p:"p2p",uta:"uta"},sandboxMode:!1,networks:{TRC20:"TRC20",ERC20:"ERC20",BEP20:"BSC",ATOM:"ATOM",ACA:"AcalaToken",APT:"Aptos",ARBITRUM:"ArbitrumOne",ARBITRUM_NOVA:"ArbitrumNova",AVAXC:"C-Chain",AVAXX:"X-Chain",AR:"Arweave",BCH:"BCH",BCHA:"BCHA",BITCI:"BITCI",BTC:"BTC",CELO:"CELO",CSPR:"CSPR",ADA:"Cardano",CHZ:"ChilizChain",CRC20:"CronosChain",DOGE:"DOGE",DOT:"DOT",EOS:"EOS",ETHF:"ETHFAIR",ETHW:"ETHW",ETC:"ETC",EGLD:"Elrond",FIL:"FIL",FIO:"FIO",FTM:"Fantom",HRC20:"HECO",ONE:"Harmony",HNT:"Helium",ICP:"ICP",IOTX:"IoTeX",KARDIA:"KAI",KAVA:"KAVA",KDA:"KDA",KLAY:"Klaytn",KSM:"Kusama",LAT:"LAT",LTC:"LTC",MINA:"MINA",MOVR:"MOVR",METIS:"MetisToken",GLMR:"Moonbeam",NEAR:"NEARProtocol",NULS:"NULS",OASYS:"OASYS",OASIS:"ROSE",OMNI:"OMNI",ONT:"Ontology",OPTIMISM:"Optimism",OSMO:"Osmosis",POKT:"PocketNetwork",MATIC:"Polygon",QTUM:"QTUM",REEF:"REEF",SOL:"SOL",SYS:"SYS",SXP:"Solar",XYM:"Symbol",TON:"TON",TT:"TT",TLOS:"Telos",THETA:"ThetaToken",VITE:"VITE",WAVES:"WAVES",WAX:"WAXP",WEMIX:"WEMIXMainnet",XDC:"XDCNetworkXDC",XRP:"XRP",FET:"FETCH",NEM:"NEM",REI:"REINetwork",ZIL:"ZIL",ABBC:"ABBCCoin",RSK:"RSK",AZERO:"AZERO",TRC10:"TRC10",JUNO:"JUNO",CANTO:"CANTO-EVM",ZKSYNC:"zkSyncEra",STARKNET:"Starknet",VIC:"VICTION"},networksById:{},fetchPositions:{method:"privateMixGetV2MixPositionAllPosition"},fetchCurrencies:{fiatCurrencies:["EUR","VND","PLN","CZK","HUF","DKK","AUD","CAD","NOK","SEK","CHF","MXN","COP","ARS","GBP","BRL","UAH","ZAR"]}},rollingWindowSize:1e3,features:{spot:{sandbox:!0,createOrder:{marginMode:!0,triggerPrice:!0,triggerPriceType:{last:!0,mark:!0,index:!1},triggerDirection:!1,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:{triggerPriceType:{last:!1,mark:!1,index:!1},price:!0},timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,marketBuyRequiresPrice:!0,marketBuyByCost:!0},createOrders:{max:50},fetchMyTrades:{marginMode:!0,limit:100,daysBack:void 0,untilDays:90,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!0,limit:100,trigger:!0,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!0,limit:100,daysBack:void 0,daysBackCanceled:void 0,untilDays:90,trigger:!0,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:200}},forPerps:{extends:"spot",createOrder:{triggerPrice:!0,triggerPriceType:{last:!0,mark:!0,index:!1},triggerDirection:!1,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:{triggerPriceType:{last:!0,mark:!0,index:!0},price:!1},timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!0,trailing:!0,marketBuyRequiresPrice:!1,marketBuyByCost:!1},fetchMyTrades:{untilDays:7},fetchClosedOrders:{trailing:!0}},swap:{linear:{extends:"forPerps"},inverse:{extends:"forPerps"}},future:{linear:{extends:"forPerps"},inverse:{extends:"forPerps"}}}})}setSandboxMode(e){this.options.sandboxMode=e}enableDemoTrading(e){this.setSandboxMode(e)}handleProductTypeAndParams(e,t={}){let i,s,r;[i,s]=this.handleSubTypeAndParams("handleProductTypeAndParams",void 0,t),void 0!==i&&void 0===e&&(r="linear"===i?"USDT-FUTURES":"COIN-FUTURES");let o=this.safeString2(s,"productType","category",r);if(void 0===o&&void 0!==e){let t=e.settle;if(!0===e.spot){let e;[e,s]=this.handleMarginModeAndParams("handleProductTypeAndParams",s),o=void 0!==e?"MARGIN":"SPOT"}else o="USDT"===t?"USDT-FUTURES":"USDC"===t?"USDC-FUTURES":"SUSDT"===t?"SUSDT-FUTURES":"SUSDC"===t?"SUSDC-FUTURES":"SBTC"===t||"SETH"===t||"SEOS"===t?"SCOIN-FUTURES":"COIN-FUTURES"}if(void 0===o)throw new a.ArgumentsRequired(this.id+' requires a productType param, one of "USDT-FUTURES", "USDC-FUTURES", "COIN-FUTURES", "SUSDT-FUTURES", "SUSDC-FUTURES", "SCOIN-FUTURES" or for uta only "SPOT"');return[o,s=this.omit(s,["productType","category"])]}async handleUTAAndParams(e,t,i=!1){let[s,r]=this.handleOptionAndParams(e,t,"uta");if(void 0!==s)return[s,r];if(this.checkRequiredCredentials(!1)){let e=!1;try{await this.privateUtaGetV3AccountSettings(),e=!0}catch(t){e=!1}return this.options.uta=e,[e,r]}return[i,r]}async fetchTime(e={}){let t=await this.publicCommonGetV2PublicTime(e),i=this.safeDict(t,"data",{});return this.safeInteger(i,"serverTime")}async fetchMarkets(e={}){this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference();let[t,i]=await this.handleUTAAndParams(e,"fetchMarkets",!1);return!0===t?await this.fetchUtaMarkets(i):await this.fetchDefaultMarkets(i)}async fetchDefaultMarkets(e){let t,i=this.safeDict(this.options,"fetchMarkets"),s=["spot","swap"];t=void 0!==i?this.safeList(i,"types",s):this.safeList(this.options,"fetchMarkets",s);let r=[],n=!1;for(let i=0;i<t.length;i++){let s=t[i];if("swap"===s||"future"===s){let t=["USDT-FUTURES","COIN-FUTURES","USDC-FUTURES","SUSDT-FUTURES","SCOIN-FUTURES","SUSDC-FUTURES"];for(let i=0;i<t.length;i++)r.push(this.publicMixGetV2MixMarketContracts(this.extend(e,{productType:t[i]})))}else if("spot"===s)r.push(this.publicSpotGetV2SpotPublicSymbols(e)),n=!0,r.push(this.publicMarginGetV2MarginCurrencies(e));else throw new a.NotSupported(this.id+" does not support "+s+" market")}let d=await Promise.all(r),h=[];this.options.crossMarginPairsData=[],this.options.isolatedMarginPairsData=[];for(let e=0;e<d.length;e++){let t=this.safeDict(d,e),i=this.safeList(t,"data",[]),s=this.safeDict(i,0,{}),r=this.safeBool(s,"isBorrowable");if(n&&void 0!==r){let e=[],t=[];for(let s=0;s<i.length;s++){let r=this.safeDict(i,s,{}),a=this.safeString(r,"symbol"),o=this.safeBool(r,"isBorrowable",!0);!0===o&&this.safeBool(r,"isCrossBorrowable",!0)&&e.push(a);let n=this.safeBool(r,"isIsolatedBaseBorrowable",!0),d=this.safeBool2(r,"isIsolatedQuotedBorrowable","isIsolatedQuoteBorrowable",!0);!0===o&&(!0===n||!0===d)&&t.push(a)}this.options.crossMarginPairsData=e,this.options.isolatedMarginPairsData=t}else h=this.arrayConcat(h,i)}let c=[];for(let e=0;e<h.length;e++){let t,i,s,r,a,n,d,l,u,f,p,m=h[e],g=this.safeString(m,"symbol"),v=this.safeString(m,"quoteCoin"),y=this.safeString(m,"baseCoin"),b=this.safeCurrencyCode(v),w=this.safeCurrencyCode(y);if(void 0===w||void 0===b)continue;let k=this.safeList(m,"supportMarginCoins",[]);t=this.inArray(y,k)?y:this.inArray(v,k)?v:this.safeString(k,0);let S=this.safeCurrencyCode(t),O=w+"/"+b,T=!1,P=!1,I=!1,A=!1,x=this.safeString(m,"symbolType"),M=!1;if(void 0===x){i="spot",P=!0,s=this.parseNumber(this.parsePrecision(this.safeString(m,"pricePrecision"))),r=this.parseNumber(this.parsePrecision(this.safeString(m,"quantityPrecision")));let e=this.inArray(g,this.options.crossMarginPairsData),t=this.inArray(g,this.options.isolatedMarginPairsData);u={cross:e,isolated:t},M=e||t}else{if("perpetual"===x)i="swap",T=!0,O=O+":"+S;else if("delivery"===x){d=this.safeInteger(m,"deliveryTime");let e=(l=this.iso8601(d)).split("-"),t=this.safeString(e,0,""),s=this.safeString(e,2,"");i="future",I=!0,O=O+":"+S+"-"+(t.slice(2,4)+this.safeString(e,1)+s.slice(0,2))}A=!0,a=!(n=w===S);let e=this.safeInteger(m,"pricePlace"),t=this.safeInteger(m,"volumePlace"),h=this.safeString(m,"priceEndStep"),c=this.safeString(m,"sizeMultiplier"),f=new o.Y(h);f.decimals=Math.max(f.decimals,e),f.reduce();let p=f.toString();s=this.parseNumber(p);let g=new o.Y(c);g.decimals=Math.max(g.decimals,t),g.reduce();let v=g.toString();r=this.parseNumber(v),u={cross:!0,isolated:!0}}let _=this.safeString2(m,"status","symbolStatus");void 0!==_&&(f="online"===_||"normal"===_),"USDT"===b&&(p=this.safeNumber(m,"minTradeUSDT"));let C=A?1:void 0;c.push(this.safeMarketStructure({id:g,symbol:O,base:w,quote:b,settle:S,baseId:y,quoteId:v,settleId:t,type:i,spot:P,margin:P&&M,marginModes:u,swap:T,future:I,option:!1,active:f,contract:A,linear:a,inverse:n,taker:this.safeNumber(m,"takerFeeRate"),maker:this.safeNumber(m,"makerFeeRate"),contractSize:C,expiry:d,expiryDatetime:l,strike:void 0,optionType:void 0,precision:{amount:r,price:s},limits:{leverage:{min:this.safeNumber(m,"minLever"),max:this.safeNumber(m,"maxLever")},amount:{min:this.safeNumber2(m,"minTradeNum","minTradeAmount"),max:this.safeNumber(m,"maxTradeAmount")},price:{min:void 0,max:void 0},cost:{min:p,max:void 0}},created:this.safeInteger(m,"launchTime"),info:m}))}return c}async fetchUtaMarkets(e){let t=["SPOT","USDT-FUTURES","COIN-FUTURES","USDC-FUTURES"],i=[];for(let s=0;s<t.length;s++){let r=this.extend(e,{category:t[s]});i.push(this.publicUtaGetV3MarketInstruments(r))}let s=await Promise.all(i),r=[];for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),i=this.safeList(t,"data",[]);r=this.arrayConcat(r,i)}let a=[];for(let e=0;e<r.length;e++){let t,i,s,o,n,d,h,c,l,u,f,p=r[e],m=this.safeString(p,"category"),g=this.safeString(p,"symbol"),v=this.safeString(p,"quoteCoin"),y=this.safeString(p,"baseCoin"),b=this.safeCurrencyCode(v),w=this.safeCurrencyCode(y);if(void 0===w||void 0===b)continue;"USDT-FUTURES"===m?t="USDT":"USDC-FUTURES"===m?t="USDC":"COIN-FUTURES"===m&&(t=w),void 0!==t&&(i=this.safeCurrencyCode(t));let k=w+"/"+b,S=!1,O=!1,T=!1,P=!1,I=this.safeString(p,"type"),A=!1,x="MARGIN"===m;if(x||"SPOT"===m){if(s="spot",O=!0,x){let e=this.safeString(p,"isIsolatedBaseBorrowable"),t=this.safeString(p,"isIsolatedQuotedBorrowable"),i="YES"===e||"YES"===t;u={cross:"0"!==this.safeString(p,"maxCrossedLeverage"),isolated:i},A=!0}}else{if("perpetual"===I)s="swap",S=!0,k=k+":"+i;else if("delivery"===I){c=this.safeInteger(p,"deliveryTime");let e=(l=this.iso8601(c)).split("-"),t=this.safeString(e,0,""),r=this.safeString(e,2,"");s="future",T=!0,k=k+":"+i+"-"+(t.slice(2,4)+this.safeString(e,1)+r.slice(0,2))}P=!0,d=!(h=w===i),u={cross:!0,isolated:!0}}o=this.parseNumber(this.parsePrecision(this.safeString(p,"pricePrecision"))),n=this.parseNumber(this.parsePrecision(this.safeString(p,"quantityPrecision")));let M=this.safeString(p,"status");void 0!==M&&(f="online"===M||"normal"===M);let _=P?1:void 0;a.push(this.safeMarketStructure({id:g,symbol:k,base:w,quote:b,settle:i,baseId:y,quoteId:v,settleId:t,type:s,spot:O,margin:O&&A,marginModes:u,swap:S,future:T,option:!1,active:f,contract:P,linear:d,inverse:h,taker:this.safeNumber(p,"takerFeeRate"),maker:this.safeNumber(p,"makerFeeRate"),contractSize:_,expiry:c,expiryDatetime:l,strike:void 0,optionType:void 0,precision:{amount:n,price:o},limits:{leverage:{min:this.safeNumber(p,"minLeverage"),max:this.safeNumber(p,"maxLeverage")},amount:{min:this.safeNumber(p,"minOrderQty"),max:this.safeNumber(p,"maxOrderQty")},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(p,"minOrderAmount"),max:void 0}},created:this.safeInteger(p,"launchTime"),info:p}))}return a}async fetchCurrencies(e={}){let t=await this.publicSpotGetV2SpotPublicCoins(e),i=this.safeList(t,"data",[]);return this.parseCurrencies(i)}parseCurrency(e){let t,i,s=this.handleOption("fetchCurrencies","fiatCurrencies",[]),r=this.safeString(e,"coin"),o=this.safeCurrencyCode(r),n=this.safeList(e,"chains",[]),d={},h=n.length;0===h&&(t=!1,i=!1);for(let e=0;e<h;e++){let s=this.safeDict(n,e),r=this.safeString(s,"chain"),h=this.networkIdToCode(r,o);if(void 0===h)throw new a.ArgumentsRequired(this.id+" requires a network argument");h=h.toUpperCase();let c="true"===this.safeString(s,"withdrawable"),l="true"===this.safeString(s,"rechargeable");t=void 0===t?c:t||c,i=void 0===i?l:i||l,d[h]={info:s,id:r,network:h,limits:{withdraw:{min:this.safeNumber(s,"minWithdrawAmount"),max:void 0},deposit:{min:this.safeNumber(s,"minDepositAmount"),max:void 0}},active:void 0,withdraw:c,deposit:l,fee:this.safeNumber(s,"withdrawFee"),precision:this.parseNumber(this.parsePrecision(this.safeString(s,"withdrawMinScale")))}}let c=!0===t&&!0===i,l=this.inArray(o,s);return this.safeCurrencyStructure({info:e,id:r,code:o,networks:d,type:l?"fiat":"crypto",name:void 0,active:c,deposit:i,withdraw:t,fee:void 0,precision:void 0,limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},created:void 0})}async fetchMarketLeverageTiers(e,t={}){let i,s,r,o,n;void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h={};if([s,n]=this.handleMarginModeAndParams("fetchMarketLeverageTiers",t,"isolated"),[r,n]=this.handleProductTypeAndParams(d,n),[o,n]=await this.handleUTAAndParams(n,"fetchMarketLeverageTiers",!1),!0===o)"SPOT"===r&&void 0!==s&&(r="MARGIN"),h.symbol=d.id,h.category=r,i=await this.publicUtaGetV3MarketPositionTier(this.extend(h,n));else if(!0===d.swap||!0===d.future)h.productType=r,h.symbol=d.id,i=await this.publicMixGetV2MixMarketQueryPositionLever(this.extend(h,n));else if("isolated"===s)h.symbol=d.id,i=await this.privateMarginGetV2MarginIsolatedTierData(this.extend(h,n));else if("cross"===s){let e=this.safeString(n,"code");if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMarketLeverageTiers() requires a code argument");n=this.omit(n,"code"),h.coin=this.currency(e).id,i=await this.privateMarginGetV2MarginCrossedTierData(this.extend(h,n))}else throw new a.BadRequest(this.id+" fetchMarketLeverageTiers() symbol does not support market "+d.symbol);let c=this.safeList(i,"data",[]);return this.parseMarketLeverageTiers(c,d)}parseMarketLeverageTiers(e,t){let i=[],s=0;for(let r=0;r<e.length;r++){let a=e[r],o=this.safeNumber2(a,"startUnit","minTierValue");void 0!==o&&(s=o);let n=this.safeNumberN(a,["endUnit","maxBorrowableAmount","baseMaxBorrowableAmount","maxTierValue"]),d=this.safeString2(a,"coin","baseCoin"),h=void 0!==d?d:this.safeString(t,"base"),c=this.safeString(a,"symbol");i.push({tier:this.safeInteger2(a,"level","tier"),symbol:this.safeSymbol(c,t),currency:this.safeCurrencyCode(h),minNotional:s,maxNotional:n,maintenanceMarginRate:this.safeNumberN(a,["keepMarginRate","maintainMarginRate","mmr"]),maxLeverage:this.safeNumber(a,"leverage"),info:a}),s=n}return i}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=await this.handleUTAAndParams(s,"fetchDeposits",!1),[n,d]=this.handleOptionBoolAndParams(o,"fetchDeposits","paginate",!1);if(n)return!0===a?await this.fetchPaginatedCallCursor("fetchDeposits",void 0,t,i,d,"orderId","cursor",void 0,100):await this.fetchPaginatedCallCursor("fetchDeposits",void 0,t,i,d,"idLessThan","idLessThan",void 0,100);let h=void 0===t?this.milliseconds()-(!0===a?2592e6:7776e6):t,c={startTime:h,endTime:this.milliseconds()};void 0!==e&&(c.coin=this.currency(e).id),void 0!==i&&(c.limit=i);let[l,u]=this.handleUntilOption("endTime",c,d);r=!0===a?await this.privateUtaGetV3AccountDepositRecords(this.extend(l,u)):await this.privateSpotGetV2SpotWalletDepositRecords(this.extend(l,u));let f=this.safeList(r,"data",[]);return this.parseTransactions(f,void 0,h,i)}async fetchDeposit(e,t,i={}){let s=await this.fetchDeposits(t,void 0,void 0,this.extend({orderId:e},i));return this.safeDict(s,0,{})}async withdraw(e,t,i,s,r={}){let o;this.checkAddress(i);let[n,d]=this.handleNetworkCodeAndParams(r);if(void 0===n)throw new a.ArgumentsRequired(this.id+' withdraw() requires a "network" parameter');void 0===this.markets&&await this.loadMarkets();let[h,c]=await this.handleUTAAndParams(d,"withdraw",!1),l=this.currency(e),u=this.networkCodeToId(n,e),f={coin:l.id,address:i,chain:u,size:this.currencyToPrecision(e,t,n),transferType:"on_chain"};void 0!==s&&(f.tag=s),o=!0===h?await this.privateUtaPostV3AccountWithdrawal(this.extend(f,c)):await this.privateSpotPostV2SpotWalletWithdrawal(this.extend(f,c));let p=this.safeDict(o,"data",{}),m=this.parseTransaction(p,l);m.type="withdrawal";let g=this.safeDict(this.options,"withdraw",{});return!0===this.safeBool(g,"fillResponseFromRequest",!0)&&(m.currency=e,m.amount=t,m.tag=s,m.address=i,m.addressTo=i,m.network=n),m}async fetchWithdrawals(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[o,n]=await this.handleUTAAndParams(s,"fetchWithdrawals",!1),[d,h]=this.handleOptionBoolAndParams(n,"fetchWithdrawals","paginate",!1);if(d)return!0===o?await this.fetchPaginatedCallCursor("fetchWithdrawals",void 0,t,i,h,"orderId","cursor",void 0,100):await this.fetchPaginatedCallCursor("fetchWithdrawals",void 0,t,i,h,"idLessThan","idLessThan",void 0,100);void 0!==e&&(r=this.currency(e));let c=void 0===t?this.milliseconds()-(!0===o?2592e6:7776e6):t,l={startTime:c,endTime:this.milliseconds()};void 0!==r&&(l.coin=r.id);let[u,f]=this.handleUntilOption("endTime",l,h);void 0!==i&&(u.limit=i),a=!0===o?await this.privateUtaGetV3AccountWithdrawalRecords(this.extend(u,f)):await this.privateSpotGetV2SpotWalletWithdrawalRecords(this.extend(u,f));let p=this.safeList(a,"data",[]);return this.parseTransactions(p,r,c,i)}async fetchWithdrawal(e,t,i={}){let s=await this.fetchWithdrawals(t,void 0,void 0,this.extend({orderId:e},i));return this.safeDict(s,0,{})}parseTransaction(e,t){let i,s,r=this.safeString(e,"coin"),a=this.safeCurrencyCode(r,t),n=this.safeInteger2(e,"cTime","createdTime"),d=this.safeString(e,"chain"),h=this.safeString(e,"status"),c=this.safeString(e,"tag"),l=this.safeString(e,"tradeId");void 0===l&&"on_chain"===this.safeString(e,"dest")&&(l=this.safeString(e,"recordId"));let u=this.safeString(e,"fee");void 0!==u&&(i=o.Y.stringAbs(u));let f=this.safeString(e,"size");return void 0!==i&&(s={currency:a,cost:this.parseNumber(i)},f=o.Y.stringSub(f,i)),{id:this.safeString(e,"orderId"),info:e,txid:l,timestamp:n,datetime:this.iso8601(n),network:this.networkIdToCode(d,a),addressFrom:this.safeString(e,"fromAddress"),address:this.safeString(e,"toAddress"),addressTo:this.safeString(e,"toAddress"),amount:this.parseNumber(f),type:this.parseTransactionType(this.safeString(e,"type")),currency:a,status:this.parseTransactionStatus(h),updated:this.safeInteger2(e,"uTime","updatedTime"),tagFrom:void 0,tag:c,tagTo:c,comment:void 0,internal:void 0,fee:s}}parseTransactionType(e){return this.safeString({withdraw:"withdrawal"},e,e)}parseTransactionStatus(e){return this.safeString({success:"ok",Pending:"pending",pending:"pending",pending_review:"pending",pending_review_fail:"failed",fail:"failed",reject:"failed"},e,e)}async fetchDepositAddress(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let[s,r]=await this.handleUTAAndParams(t,"fetchDepositAddress",!1),[a,o]=this.handleNetworkCodeAndParams(r),n=this.currency(e),d={coin:n.id};void 0!==a&&(d.chain=this.networkCodeToId(a,e)),i=!0===s?await this.privateUtaGetV3AccountDepositAddress(this.extend(d,o)):await this.privateSpotGetV2SpotWalletDepositAddress(this.extend(d,o));let h=this.safeDict(i,"data",{});return this.parseDepositAddress(h,n)}parseDepositAddress(e,t){let i,s=this.safeString(e,"coin"),r=this.safeString(e,"chain"),a=this.safeCurrencyCode(s,t);return void 0!==r&&(i=this.networkIdToCode(r,a)),{info:e,currency:a,network:i,address:this.safeString(e,"address"),tag:this.safeString(e,"tag")}}async fetchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id};void 0!==t&&(a.limit=t);let[o,n]=this.handleProductTypeAndParams(r,i),[d,h]=await this.handleUTAAndParams(n,"fetchOrderBook",!1);!0===d?(a.category=o,s=await this.publicUtaGetV3MarketOrderbook(this.extend(a,h))):!0===r.spot?s=await this.publicSpotGetV2SpotMarketOrderbook(this.extend(a,h)):(a.productType=o,s=await this.publicMixGetV2MixMarketMergeDepth(this.extend(a,h)));let c=this.safeDict(s,"data",{}),l="bids";!0===d&&(l="b");let u="asks";!0===d&&(u="a");let f=this.safeInteger(c,"ts");return this.parseOrderBook(c,r.symbol,f,l,u)}parseTicker(e,t){let i=this.safeString(e,"symbol"),s=this.safeString2(e,"lastPr","lastPrice"),r=this.safeIntegerOmitZero(e,"ts"),a=this.safeString(e,"category"),n=this.safeString(e,"markPrice"),d=o.Y.stringMul(this.safeString2(e,"price24hPcnt","change24h"),"100");return this.safeTicker({symbol:this.safeSymbol(i,t,void 0,void 0!==n&&"SPOT"!==a?"contract":"spot"),timestamp:r,datetime:this.iso8601(r),high:this.safeString2(e,"high24h","highPrice24h"),low:this.safeString2(e,"low24h","lowPrice24h"),bid:this.safeString2(e,"bidPr","bid1Price"),bidVolume:this.safeString2(e,"bidSz","bid1Size"),ask:this.safeString2(e,"askPr","ask1Price"),askVolume:this.safeString2(e,"askSz","ask1Size"),vwap:void 0,open:this.safeStringN(e,["open","open24h","openPrice24h"]),close:s,last:s,previousClose:void 0,change:void 0,percentage:d,average:void 0,baseVolume:this.safeString2(e,"baseVolume","volume24h"),quoteVolume:this.safeString2(e,"quoteVolume","turnover24h"),indexPrice:this.safeString(e,"indexPrice"),markPrice:n,info:e},t)}async fetchTicker(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id},[a,o]=this.handleProductTypeAndParams(s,t),[n,d]=await this.handleUTAAndParams(o,"fetchTicker",!1);!0===n?(r.category=a,i=await this.publicUtaGetV3MarketTickers(this.extend(r,d))):!0===s.spot?i=await this.publicSpotGetV2SpotMarketTickers(this.extend(r,d)):(r.productType=a,i=await this.publicMixGetV2MixMarketTicker(this.extend(r,d)));let h=this.safeList(i,"data",[]);return this.parseTicker(h[0],s)}async fetchMarkPrice(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};if(!0===s.spot)throw new a.NotSupported(this.id+" fetchMarkPrice() is not supported for spot markets");{let[e,a]=this.handleProductTypeAndParams(s,t);r.productType=e,i=await this.publicMixGetV2MixMarketSymbolPrice(this.extend(r,a))}let o=this.safeList(i,"data",[]);return this.parseTicker(o[0],s)}async fetchTickers(e,t={}){let i,s;if(void 0===this.markets&&await this.loadMarkets(),void 0!==e){let t=this.safeString(e,0);i=this.market(t)}let r={},[a,o]=this.handleMarketTypeAndParams("fetchTickers",i,t),n=this.safeString(o,"subType"),[d,h]=this.handleProductTypeAndParams(i,o),[c,l]=await this.handleUTAAndParams(h,"fetchTickers",!1);!0===c?(void 0!==e&&1===e.length&&(r.symbol=this.safeString(i,"id")),r.category=d,s=await this.publicUtaGetV3MarketTickers(this.extend(r,l))):"spot"===a&&void 0===n?s=await this.publicSpotGetV2SpotMarketTickers(this.extend(r,l)):(r.productType=d,s=await this.publicMixGetV2MixMarketTickers(this.extend(r,l)));let u=this.safeList(s,"data",[]);return this.parseTickers(u,e)}parseTrade(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeSymbol(s,t),a=this.safeIntegerN(e,["cTime","ts","createdTime"]),n=this.safeValue(e,"feeDetail"),d=this.safeString(e,"posMode"),h=this.safeString(e,"category"),c=void 0!==d||void 0!==h?n[0]:n;if(void 0!==c){i={currency:this.safeCurrencyCode(this.safeString(c,"feeCoin"))};let e=this.safeString2(c,"totalFee","fee");"yes"===this.safeString(c,"deduction")?i.cost=e:i.cost=o.Y.stringNeg(e)}return this.safeTrade({info:e,id:this.safeString2(e,"tradeId","execId"),order:this.safeString(e,"orderId"),symbol:r,side:this.safeStringLower(e,"side"),type:this.safeString(e,"orderType"),takerOrMaker:this.safeString(e,"tradeScope"),price:this.safeStringN(e,["priceAvg","price","execPrice"]),amount:this.safeStringN(e,["baseVolume","size","execQty"]),cost:this.safeStringN(e,["quoteVolume","amount","execValue"]),timestamp:a,datetime:this.iso8601(a),fee:i},t)}async fetchTrades(e,t,i,s={}){let r,a,o,n;void 0===this.markets&&await this.loadMarkets();let d=!1;if([d,r]=this.handleOptionBoolAndParams(s,"fetchTrades","paginate",!1),d)return await this.fetchPaginatedCallCursor("fetchTrades",e,t,i,r,"idLessThan","idLessThan");let h=this.market(e),c={symbol:h.id};[a,r]=await this.handleUTAAndParams(r,"fetchTrades",!1),void 0!==i&&(!0===a?c.limit=Math.min(i,100):!0===h.contract?c.limit=Math.min(i,1e3):c.limit=i);let l=this.safeDict(this.options,"fetchTrades",{});if([n,r]=this.handleProductTypeAndParams(h,r),!0===a){if("SPOT"===n){let e;[e,r]=this.handleMarginModeAndParams("fetchTrades",r),void 0!==e&&(n="MARGIN")}c.category=n,o=await this.publicUtaGetV3MarketFills(this.extend(c,r))}else if(!0===h.spot){let e=this.safeDict(l,"spot",{}),i=this.safeString(e,"method","publicSpotGetV2SpotMarketFillsHistory"),s=this.safeString(r,"method",i);r=this.omit(r,"method"),"publicSpotGetV2SpotMarketFillsHistory"===s?([c,r]=this.handleUntilOption("endTime",c,r),void 0!==t&&(c.startTime=t),o=await this.publicSpotGetV2SpotMarketFillsHistory(this.extend(c,r))):"publicSpotGetV2SpotMarketFills"===s&&(o=await this.publicSpotGetV2SpotMarketFills(this.extend(c,r)))}else{let e=this.safeDict(l,"swap",{}),i=this.safeString(e,"method","publicMixGetV2MixMarketFillsHistory"),s=this.safeString(r,"method",i);r=this.omit(r,"method"),c.productType=n,"publicMixGetV2MixMarketFillsHistory"===s?([c,r]=this.handleUntilOption("endTime",c,r),void 0!==t&&(c.startTime=t),o=await this.publicMixGetV2MixMarketFillsHistory(this.extend(c,r))):"publicMixGetV2MixMarketFills"===s&&(o=await this.publicMixGetV2MixMarketFills(this.extend(c,r)))}let u=this.safeList(o,"data",[]);return this.parseTrades(u,h,t,i)}async fetchTradingFee(e,t={}){let i,s,r;void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={symbol:a.id};if([i,s]=await this.handleUTAAndParams(t,"fetchTradingFee",!1),!0===i){let e;[e,s]=this.handleProductTypeAndParams(a,s),o.category=e;let t=await this.privateUtaGetV3AccountFeeRate(this.extend(o,s)),i=this.safeDict(t,"data",{});return this.parseTradingFee(i,a)}[r,s]=this.handleMarginModeAndParams("fetchTradingFee",s),!0===a.spot?void 0!==r?o.businessType="margin":o.businessType="spot":o.businessType="mix";let n=await this.privateCommonGetV2CommonTradeRate(this.extend(o,s)),d=this.safeDict(n,"data",{});return this.parseTradingFee(d,a)}async fetchTradingFees(e={}){let t,i,s,r,o;if(void 0===this.markets&&await this.loadMarkets(),[i,r]=this.handleMarginModeAndParams("fetchTradingFees",e),[s,r]=this.handleMarketTypeAndParams("fetchTradingFees",void 0,r),[o,r]=await this.handleUTAAndParams(r,"fetchTradingFees",!1),!0===o){let e=this.safeBool(r,"margin",!1);r=this.omit(r,"margin");let t={};if("spot"===s)void 0!==i||!0===e?t.category="MARGIN":t.category="SPOT";else if("swap"===s||"future"===s){let e;[e,r]=this.handleProductTypeAndParams(void 0,r),t.category=e}else throw new a.NotSupported(this.id+" does not support "+s+" market");let o=await this.privateUtaGetV3AccountAllFeeRate(this.extend(t,r)),n=this.safeList(o,"data",[]),d={};for(let e=0;e<n.length;e++){let t=n[e],i=this.safeString(t,"symbol");if(void 0===i||void 0===this.markets_by_id||!(i in this.markets_by_id))continue;let r=this.safeMarket(i,void 0,void 0,s),a=this.safeString(r,"symbol");void 0!==a&&a!==i&&(d[a]=this.parseTradingFee(t,r))}return d}if("spot"===s){let e=this.safeBool(r,"margin",!1);r=this.omit(r,"margin"),t=void 0!==i||!0===e?await this.publicMarginGetV2MarginCurrencies(r):await this.publicSpotGetV2SpotPublicSymbols(r)}else if("swap"===s||"future"===s){let e;[e,r]=this.handleProductTypeAndParams(void 0,r),r.productType=e,t=await this.publicMixGetV2MixMarketContracts(r)}else throw new a.NotSupported(this.id+" does not support "+s+" market");let n=this.safeList(t,"data",[]),d={};for(let e=0;e<n.length;e++){let t=n[e],i=this.safeString(t,"symbol"),r=this.safeSymbol(i,void 0,void 0,s),a=this.market(r),o=this.parseTradingFee(t,a);d[r]=o}return d}parseTradingFee(e,t){let i=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(i,t),maker:this.safeNumber(e,"makerFeeRate"),taker:this.safeNumber(e,"takerFeeRate"),percentage:void 0,tierBased:void 0}}parseOHLCV(e,t){let i=this.safeBool(t,"inverse");return[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,!0===i?6:5)]}async fetchOHLCV(e,t="1m",i,s,r={}){let a,o,n,d;void 0===this.markets&&await this.loadMarkets();let h=this.safeBool(r,"useHistoryEndpoint",!1),c=this.safeBool(r,"useHistoryEndpointForPagination",!0),[l,u]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(l)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,u,!0===c?200:1e3);let f=this.market(e),p={symbol:f.id},m=this.handleOption("fetchOHLCV","timeframes"),[g,v]=await this.handleUTAAndParams(u,"fetchOHLCV",!1);!0===g?(a=m.uta,p.interval=this.safeString(a,t,t)):(a=m[!0===f.spot?"spot":"swap"],p.granularity=this.safeString(a,t,t));let y=this.milliseconds(),b=1e3*this.parseTimeframe(t),w=this.safeInteger(v,"until"),k=void 0!==s,S=void 0!==i,O=void 0!==w,T=this.omit(v,["until"]),P="swap";!0===f.spot&&(P="spot");let I=this.safeDict(this.options.fetchOHLCV,P,{}),A=this.safeDict(I,"maxLimitPerTimeframe",{}),x=this.safeInteger(A,t,s),M=this.safeDict(this.options.fetchOHLCV,"maxRecentDaysPerTimeframe",{}),_=this.safeInteger(M,t),C=100;k&&(C=Math.min(Math.min(s,1e3),x));let B=C*b;S&&(o=i,p.startTime=i,O||((n=this.sum(o,B))>y&&(n=y),p.endTime=n)),O&&((n=w)>y&&(n=y),p.endTime=n,S||(o=n-B));let E=!1;(void 0!==o&&o<=y-(_-1)*864e5||!0===h)&&(E=!0,p.startTime=o=n-(B=(C=Math.min(C,200))*b),!0!==f.spot&&n-o>7776e6&&(p.endTime=n=this.sum(o,7776e6))),p.limit=C;let[R,L]=this.handleParamString(T,"price"),[N,D]=this.handleProductTypeAndParams(f,L);if(!0===g)void 0!==R&&("mark"===R?p.type="MARK":"index"===R&&(p.type="INDEX")),p.category=N,d=await this.publicUtaGetV3MarketCandles(this.extend(p,D));else if(!0===f.spot)E?d=await this.publicSpotGetV2SpotMarketHistoryCandles(this.extend(p,D)):(k||(p.limit=1e3,C=1e3),d=await this.publicSpotGetV2SpotMarketCandles(this.extend(p,D)));else{p.productType=N;let e=this.extend(p,D);E||"mark"!==R&&"index"!==R?"mark"===R?d=await this.publicMixGetV2MixMarketHistoryMarkCandles(e):"index"===R?d=await this.publicMixGetV2MixMarketHistoryIndexCandles(e):E?d=await this.publicMixGetV2MixMarketHistoryCandles(e):(k||(e.limit=1e3,C=1e3),d=await this.publicMixGetV2MixMarketCandles(e)):(k||(e.limit=1e3,C=1e3),d=await this.publicMixGetV2MixMarketCandles(this.extend({kLineType:R},e)))}if(""===d)return[];let q=[];return q=Array.isArray(d)?d:this.safeList(d,"data",[]),this.parseOHLCVs(q,f,t,i,C)}async fetchBalance(e={}){let t,i,s,r,o;void 0===this.markets&&await this.loadMarkets();let n={};if([r,o]=await this.handleUTAAndParams(e,"fetchBalance",!1),[t,o]=this.handleMarketTypeAndParams("fetchBalance",void 0,o),[i,o]=this.handleMarginModeAndParams("fetchBalance",o),!0===r){let e;if("funding"===t)s=await this.privateUtaGetV3AccountFundingAssets(this.extend(n,o)),e=this.safeList(s,"data",[]);else{s=await this.privateUtaGetV3AccountAssets(this.extend(n,o));let t=this.safeDict(s,"data",{});e=this.safeList(t,"assets",[])}return this.parseUtaBalance(e)}if("swap"===t||"future"===t){let e;[e,o]=this.handleProductTypeAndParams(void 0,o),n.productType=e,s=await this.privateMixGetV2MixAccountAccounts(this.extend(n,o))}else if("isolated"===i)s=await this.privateMarginGetV2MarginIsolatedAccountAssets(this.extend(n,o));else if("cross"===i)s=await this.privateMarginGetV2MarginCrossedAccountAssets(this.extend(n,o));else if("spot"===t)s=await this.privateSpotGetV2SpotAccountAssets(this.extend(n,o));else throw new a.NotSupported(this.id+" fetchBalance() does not support "+t+" accounts");let d=this.safeList(s,"data",[]);return this.parseBalance(d)}parseUtaBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.account(),a=this.safeString(s,"coin"),o=this.safeCurrencyCode(a);r.debt=this.safeString(s,"debt"),r.used=this.safeString2(s,"locked","frozen"),r.free=this.safeString(s,"available"),r.total=this.safeString2(s,"equity","balance"),void 0!==o&&(t[o]=r)}return this.safeBalance(t)}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.account(),a=this.safeString2(s,"marginCoin","coin"),n=this.safeCurrencyCode(a),d=this.safeString(s,"borrow");if(void 0!==d){let e=this.safeString(s,"interest");r.free=this.safeString(s,"transferable"),r.total=this.safeString(s,"totalAmount"),r.debt=o.Y.stringAdd(d,e)}else{let e=this.safeString(s,"available"),t=this.safeString(s,"maxTransferOut");if(void 0!==t)r.free=t,r.total=this.safeString(s,"accountEquity");else{r.free=e;let t=this.safeString(s,"frozen"),i=this.safeString(s,"locked");r.used=o.Y.stringAdd(t,i)}}void 0!==n&&(t[n]=r)}return this.safeBalance(t)}parseOrderStatus(e){return this.safeString({new:"open",init:"open",not_trigger:"open",partial_fill:"open",partially_fill:"open",partially_filled:"open",triggered:"closed",full_fill:"closed",filled:"closed",fail_trigger:"rejected",cancel:"canceled",cancelled:"canceled",canceled:"canceled",live:"open",fail_execute:"rejected",executed:"closed"},e,e)}parseOrder(e,t){let i,s,r,a,n,d,h;if(void 0!==this.safeString(e,"errorMsg"))return this.safeOrder({info:e,id:this.safeString(e,"orderId"),clientOrderId:this.safeString2(e,"clientOrderId","clientOid"),status:"rejected"},t);let c=this.safeString(e,"posSide"),l="spot";void 0!==c&&(l="contract"),void 0!==t&&(l=this.safeString(t,"type"));let u=this.safeString(e,"symbol"),f=this.safeMarket(u,t,void 0,l),p=this.safeIntegerN(e,["cTime","ctime","createdTime"]),m=this.safeInteger2(e,"uTime","updatedTime"),g=this.safeStringN(e,["status","state","orderStatus","planStatus"]),v=this.safeString(e,"fee");void 0!==v&&(i={cost:this.parseNumber(o.Y.stringNeg(v)),currency:f.settle});let y=this.safeValue(e,"feeDetail");if(void 0!==this.safeString(e,"category")){let e=this.safeDict(y,0,{}),t=this.safeString(e,"fee");i={cost:this.parseNumber(o.Y.stringNeg(t)),currency:f.settle}}else if(void 0!==y){let e,t=Object.values(JSON.parse(y));for(let i=0;i<t.length;i++){let s=t[i];if(void 0!==this.safeString(s,"feeCoinCode")){e=s;break}}i={cost:this.parseNumber(o.Y.stringNeg(this.safeString(e,"totalFee"))),currency:this.safeCurrencyCode(this.safeString(e,"feeCoinCode"))}}let b=this.safeStringUpper2(e,"force","timeInForce");"POST_ONLY"===b&&(s=!0,b="PO");let w=this.safeString(e,"reduceOnly");void 0!==w&&(r="NO"!==w),void 0!==this.safeString(e,"basePrice")?(a=this.safeString(e,"priceAvg"),n=this.safeString(e,"basePrice")):(a=this.safeStringN(e,["price","executePrice","slLimitPrice","tpLimitPrice"]),n=this.safeString(e,"priceAvg"));let k=this.safeString(e,"baseSize");void 0!==k?(d=k,h=this.safeString(e,"size")):(d=this.safeString2(e,"size","qty"),h=this.safeString2(e,"baseVolume","cumExecQty"));let S=this.safeString(e,"side");"hedge_mode"===this.safeString(e,"posMode")&&!0===r&&(S="buy"===S?"sell":"buy");let O=this.safeString(e,"orderType"),T="buy"===S&&"market"===O;return!0===f.spot&&T&&(d=this.safeString(e,"baseVolume")),this.safeOrder({info:e,id:this.safeString2(e,"orderId","data"),clientOrderId:this.safeString2(e,"clientOrderId","clientOid"),timestamp:p,datetime:this.iso8601(p),lastTradeTimestamp:m,lastUpdateTimestamp:m,symbol:f.symbol,type:O,side:S,price:a,amount:d,cost:this.safeString2(e,"quoteVolume","quoteSize"),average:n,filled:h,remaining:void 0,timeInForce:b,postOnly:s,reduceOnly:r,triggerPrice:this.safeNumber(e,"triggerPrice"),takeProfitPrice:this.safeNumberN(e,["presetStopSurplusPrice","stopSurplusTriggerPrice","takeProfit"]),stopLossPrice:this.safeNumberN(e,["presetStopLossPrice","stopLossTriggerPrice","stopLoss"]),status:this.parseOrderStatus(g),fee:i,trades:void 0},f)}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new a.NotSupported(this.id+" createMarketBuyOrderWithCost() supports spot orders only");return await this.createOrder(e,"market","buy",t,void 0,this.extend({createMarketBuyOrderRequiresPrice:!1},i))}async createOrder(e,t,i,s,r,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=this.handleMarginModeAndParams("createOrder",a)[0],h=this.safeNumber2(a,"stopPrice","triggerPrice"),c=this.safeNumber(a,"stopLossPrice"),l=this.safeNumber(a,"takeProfitPrice"),u=this.safeString2(a,"trailingPercent","callbackRatio"),f=void 0!==h,p=void 0!==c||void 0!==l,[m,g]=await this.handleUTAAndParams(a,"createOrder",!1);if(!0===m){let a=this.createUtaOrderRequest(e,t,i,s,r,g);o=p?await this.privateUtaPostV3TradePlaceStrategyOrder(a):await this.privateUtaPostV3TradePlaceOrder(a)}else{let a=this.createOrderRequest(e,t,i,s,r,g);o=!0===n.spot?f?await this.privateSpotPostV2SpotTradePlacePlanOrder(a):"isolated"===d?await this.privateMarginPostV2MarginIsolatedPlaceOrder(a):"cross"===d?await this.privateMarginPostV2MarginCrossedPlaceOrder(a):await this.privateSpotPostV2SpotTradePlaceOrder(a):f||void 0!==u?await this.privateMixPostV2MixOrderPlacePlanOrder(a):p?await this.privateMixPostV2MixOrderPlaceTpslOrder(a):await this.privateMixPostV2MixOrderPlaceOrder(a)}let v=this.safeDict(o,"data",{});return this.parseOrder(v,n)}createUtaOrderRequest(e,t,i,s,r,o={}){let n,d,h;if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let c=this.market(e);if([n,d]=this.handleProductTypeAndParams(c,o),"SPOT"===n){let e;[e,d]=this.handleMarginModeAndParams("createOrder",d),void 0!==e&&(n="MARGIN")}let l={category:n,symbol:c.id,qty:this.amountToPrecision(e,s),side:i},u=this.safeString2(d,"clientOid","clientOrderId");void 0!==u&&(l.clientOid=u,d=this.omit(d,"clientOrderId"));let f=this.safeNumber(d,"stopLossPrice"),p=this.safeNumber(d,"takeProfitPrice"),m=this.safeDict(d,"stopLoss"),g=this.safeDict(d,"takeProfit"),v=void 0!==m,y=void 0!==g,b=void 0!==f,w=void 0!==p,k=b||w;if(k)b?(l.slTriggerBy=this.safeString(d,"slTriggerBy","mark"),l.stopLoss=this.priceToPrecision(e,f),void 0!==r?(l.slLimitPrice=this.priceToPrecision(e,r),l.slOrderType=this.safeString(d,"slOrderType","limit")):l.slOrderType=this.safeString(d,"slOrderType","market")):w&&(l.tpTriggerBy=this.safeString(d,"tpTriggerBy","mark"),l.takeProfit=this.priceToPrecision(e,p),void 0!==r?(l.tpLimitPrice=this.priceToPrecision(e,r),l.tpOrderType=this.safeString(d,"tpOrderType","limit")):l.tpOrderType=this.safeString(d,"tpOrderType","market")),d=this.omit(d,["stopLossPrice","takeProfitPrice"]);else{let i,s;if(v){let t=this.safeNumber2(m,"triggerPrice","stopPrice"),i=this.safeNumber(m,"price");l.stopLoss=this.priceToPrecision(e,t),void 0!==i?(l.slLimitPrice=this.priceToPrecision(e,i),l.slOrderType=this.safeString(d,"slOrderType","limit")):l.slOrderType=this.safeString(d,"slOrderType","market")}if(y){let t=this.safeNumber2(g,"triggerPrice","stopPrice"),i=this.safeNumber(g,"price");l.takeProfit=this.priceToPrecision(e,t),void 0!==i?(l.tpLimitPrice=this.priceToPrecision(e,i),l.tpOrderType=this.safeString(d,"tpOrderType","limit")):l.tpOrderType=this.safeString(d,"tpOrderType","market")}let a="market"===t;a||(l.price=this.priceToPrecision(e,r)),l.orderType=t;let o=this.safeString(d,"timeInForce");[i,d]=this.handlePostOnly(a,"post_only"===o,d),[s,d]=this.handleOptionStringAndParams(d,"createOrder","timeInForce"),void 0!==s&&(s=s.toUpperCase()),!0===i?l.timeInForce="post_only":"GTC"===s?l.timeInForce="gtc":"FOK"===s?l.timeInForce="fok":"IOC"===s&&(l.timeInForce="ioc")}let S=this.safeBool(d,"reduceOnly",!1);if([h,d]=this.handleParamBool(d,"hedged",!1),!0===S)if(!0===h||k){let e="short";"sell"===i&&(e="long"),l.posSide=e}else k||(l.reduceOnly="yes");else if(!0===h){let e="short";"buy"===i&&(e="long"),l.posSide=e}return d=this.omit(d,["stopLoss","takeProfit","postOnly","reduceOnly","hedged"]),this.extend(l,d)}createOrderRequest(e,t,i,s,r,n={}){let d,h,c,l,u,f,p;if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let m=this.market(e);[d,c]=this.handleMarketTypeAndParams("createOrder",m,n),[h,c]=this.handleMarginModeAndParams("createOrder",c);let g={symbol:m.id,orderType:t};[l,c]=this.handleParamBool(c,"hedged",!1),[u,c]=this.handleParamBool(c,"oneWayMode"),void 0!==u&&(l=!u);let v="market"===t,y=this.safeNumber2(c,"stopPrice","triggerPrice"),b=this.safeNumber(c,"stopLossPrice"),w=this.safeNumber(c,"takeProfitPrice"),k=this.safeDict(c,"stopLoss"),S=this.safeDict(c,"takeProfit"),O=void 0!==y,T=void 0!==b,P=void 0!==w,I=void 0!==k,A=void 0!==S,x=T||P,M=this.safeString(c,"trailingTriggerPrice",this.numberToString(r)),_=this.safeString2(c,"trailingPercent","callbackRatio"),C=void 0!==_;if(this.sum(O,T,P,C)>1)throw new a.ExchangeError(this.id+" createOrder() params can only contain one of triggerPrice, stopLossPrice, takeProfitPrice, trailingPercent");"limit"===t&&(g.price=this.priceToPrecision(e,r));let B=this.safeString2(c,"triggerPriceType","triggerType","mark_price"),E=this.safeBool(c,"reduceOnly",!1),R=this.safeString2(c,"clientOid","clientOrderId"),L=this.safeString2(c,"force","timeInForce");if([f,c]=this.handlePostOnly(v,"post_only"===L,c),[p,c]=this.handleOptionStringAndParams(c,"createOrder","timeInForce"),void 0!==p&&(p=p.toUpperCase()),!0===f?g.force="post_only":"GTC"===p?g.force="GTC":"FOK"===p?g.force="FOK":"IOC"===p&&(g.force="IOC"),c=this.omit(c,["stopPrice","triggerType","stopLossPrice","takeProfitPrice","stopLoss","takeProfit","postOnly","reduceOnly","clientOrderId","trailingPercent","trailingTriggerPrice"]),"swap"===d||"future"===d){let t;if(g.marginCoin=m.settleId,g.size=this.amountToPrecision(e,s),[t,c]=this.handleProductTypeAndParams(m,c),g.productType=t,void 0!==R&&(g.clientOid=R),(O||x||C)&&(g.triggerType=B),C){if(!v)throw new a.BadRequest(this.id+" createOrder() bitget trailing orders must be market orders");if(void 0===M)throw new a.ArgumentsRequired(this.id+" createOrder() bitget trailing orders must have a trailingTriggerPrice param");g.planType="track_plan",g.triggerPrice=this.priceToPrecision(e,M),g.callbackRatio=_}else if(O){if(g.planType="normal_plan",g.triggerPrice=this.priceToPrecision(e,y),void 0!==r&&(g.executePrice=this.priceToPrecision(e,r)),I){let t=this.safeString2(k,"triggerPrice","stopPrice");g.stopLossTriggerPrice=this.priceToPrecision(e,t);let i=this.safeString(k,"price");g.stopLossExecutePrice=this.priceToPrecision(e,i),g.stopLossTriggerType=this.safeString(k,"type","mark_price")}if(A){let t=this.safeString2(S,"triggerPrice","stopPrice");g.stopSurplusTriggerPrice=this.priceToPrecision(e,t);let i=this.safeString(S,"price");g.stopSurplusExecutePrice=this.priceToPrecision(e,i),g.stopSurplusTriggerType=this.safeString(S,"type","mark_price")}}else if(x)void 0!==r&&(g.executePrice=this.priceToPrecision(e,r),"price"in g&&delete g.price),!0===l?g.holdSide="sell"===i?"long":"short":g.holdSide="sell"===i?"buy":"sell",T?(g.triggerPrice=this.priceToPrecision(e,b),g.planType="pos_loss"):P&&(g.triggerPrice=this.priceToPrecision(e,w),g.planType="pos_profit");else{if(I){let t=this.safeNumber2(k,"triggerPrice","stopPrice");if(void 0===t)throw new a.ArgumentsRequired(this.id+" createOrder() requires a triggerPrice or a stopPrice inside the stopLoss parameter");g.presetStopLossPrice=this.priceToPrecision(e,t);let i=this.safeNumber(k,"price");void 0!==i&&(g.presetStopLossExecutePrice=this.priceToPrecision(e,i))}if(A){let t=this.safeNumber2(S,"triggerPrice","stopPrice");if(void 0===t)throw new a.ArgumentsRequired(this.id+" createOrder() requires a triggerPrice or a stopPrice inside the takeProfit parameter");g.presetStopSurplusPrice=this.priceToPrecision(e,t);let i=this.safeNumber(S,"price");void 0!==i&&(g.presetStopSurplusExecutePrice=this.priceToPrecision(e,i))}}if(!x){void 0===h&&(h="cross");let e="isolated";"cross"===h&&(e="crossed"),g.marginMode=e;let t=i;!0===E?!0!==l?g.reduceOnly="YES":(t="buy"===i?"sell":"buy",g.tradeSide="Close"):!0===l&&(g.tradeSide="Open"),g.side=t}}else if("spot"===d){let t,n;if(x||I||A)throw new a.InvalidOrder(this.id+" createOrder() does not support stop loss/take profit orders on spot markets, only swap markets");g.side=i;let d=!0;if([d,c]=this.handleOptionBoolAndParams(c,"createOrder","createMarketBuyOrderRequiresPrice",!0),v&&"buy"===i){n="total";let i=this.safeNumber(c,"cost");if(c=this.omit(c,"cost"),void 0!==i)t=this.costToPrecision(e,i);else if(d)if(void 0===r)throw new a.InvalidOrder(this.id+' createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice in options["createOrder"] or params to false and pass the cost to spend in the amount argument');else{let i=this.numberToString(s),a=this.numberToString(r),n=o.Y.stringMul(i,a);t=this.costToPrecision(e,n)}else t=this.costToPrecision(e,s)}else n="amount",t=this.amountToPrecision(e,s);void 0!==R&&(g.clientOid=R),void 0!==h?(g.loanType="normal",v&&"buy"===i?g.quoteSize=t:g.baseSize=t):(void 0!==t&&(g.size=t),void 0!==y&&(g.planType=n,g.triggerType=B,g.triggerPrice=this.priceToPrecision(e,y),void 0!==r&&(g.executePrice=this.priceToPrecision(e,r))))}else throw new a.NotSupported(this.id+" createOrder() does not support "+d+" orders");return this.extend(g,c)}async createUtaOrders(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=[];for(let t=0;t<e.length;t++){let o=this.safeDict(e,t),n=this.safeString(o,"symbol");if(void 0===i)i=n;else if(i!==n)throw new a.BadRequest(this.id+" createOrders() requires all orders to have the same symbol");let d=this.safeString(o,"type"),h=this.safeString(o,"side"),c=this.safeNumber(o,"amount"),l=this.safeNumber(o,"price"),u=this.safeDict(o,"params",{}),f=this.handleMarginModeAndParams("createOrders",u)[0];if(void 0!==f){if(void 0===s)s=f;else if(s!==f)throw new a.BadRequest(this.id+" createOrders() requires all orders to have the same margin mode (isolated or cross)")}let p=this.createUtaOrderRequest(n,d,h,c,l,u);r.push(p)}let o=this.market(i),n=await this.privateUtaPostV3TradePlaceBatch(r),d=this.safeList(n,"data",[]);return this.parseOrders(d,o)}async createOrders(e,t={}){let i,s,r,o,n;if(void 0===this.markets&&await this.loadMarkets(),[i,s]=await this.handleUTAAndParams(t,"createOrders",!1),!0===i)return await this.createUtaOrders(e,s);let d=[];for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s=this.safeString(i,"symbol");if(void 0===r)r=s;else if(r!==s)throw new a.BadRequest(this.id+" createOrders() requires all orders to have the same symbol");let n=this.safeString(i,"type"),h=this.safeString(i,"side"),c=this.safeNumber(i,"amount"),l=this.safeNumber(i,"price"),u=this.safeDict(i,"params",{}),f=this.handleMarginModeAndParams("createOrders",u)[0];if(void 0!==f){if(void 0===o)o=f;else if(o!==f)throw new a.BadRequest(this.id+" createOrders() requires all orders to have the same margin mode (isolated or cross)")}let p=this.createOrderRequest(s,n,h,c,l,u);d.push(p)}let h=this.market(r),c={symbol:h.id,orderList:d};if(!0===h.swap||!0===h.future){let e;void 0===o&&(o="cross");let t="isolated";"cross"===o&&(t="crossed"),c.marginMode=t,c.marginCoin=h.settleId,[e,s]=this.handleProductTypeAndParams(h,s),c.productType=e,n=await this.privateMixPostV2MixOrderBatchPlaceOrder(c)}else n="isolated"===o?await this.privateMarginPostV2MarginIsolatedBatchPlaceOrder(c):"cross"===o?await this.privateMarginPostV2MarginCrossedBatchPlaceOrder(c):await this.privateSpotPostV2SpotTradeBatchOrders(c);let l=this.safeDict(n,"data",{}),u=this.safeList(l,"failureList",[]),f=this.safeList(l,"successList",[]),p=this.arrayConcat(f,u);return this.parseOrders(p,h)}async editOrder(e,t,i,s,r,n,d={}){let h,c,l;void 0===this.markets&&await this.loadMarkets();let u=this.market(t),f={},p=this.safeString2(d,"clientOrderId","clientOid");void 0!==p?f.clientOid=p:f.orderId=e;let m="market"===i,g=this.safeNumber2(d,"stopPrice","triggerPrice"),v=void 0!==g,y=this.safeNumber(d,"stopLossPrice"),b=void 0!==y,w=this.safeNumber(d,"takeProfitPrice"),k=void 0!==w,S=this.safeDict(d,"stopLoss"),O=this.safeDict(d,"takeProfit"),T=void 0!==S,P=void 0!==O,I=this.safeString(d,"trailingTriggerPrice",this.numberToString(n)),A=this.safeString2(d,"trailingPercent","newCallbackRatio"),x=void 0!==A;if(this.sum(v,b,k,x)>1)throw new a.ExchangeError(this.id+" editOrder() params can only contain one of triggerPrice, stopLossPrice, takeProfitPrice, trailingPercent");let M=this.omit(d,["stopPrice","triggerType","stopLossPrice","takeProfitPrice","stopLoss","takeProfit","clientOrderId","trailingTriggerPrice","trailingPercent"]);if([c,M]=this.handleProductTypeAndParams(u,M),[l,M]=await this.handleUTAAndParams(M,"editOrder",!1),!0===l)void 0!==r&&(f.qty=this.amountToPrecision(t,r)),b||k?(b?(f.slTriggerBy=this.safeString(M,"slTriggerBy","mark"),f.stopLoss=this.priceToPrecision(t,y),void 0!==n?(f.slLimitPrice=this.priceToPrecision(t,n),f.slOrderType=this.safeString(M,"slOrderType","limit")):f.slOrderType=this.safeString(M,"slOrderType","market")):k&&(f.tpTriggerBy=this.safeString(M,"tpTriggerBy","mark"),f.takeProfit=this.priceToPrecision(t,w),void 0!==n?(f.tpLimitPrice=this.priceToPrecision(t,n),f.tpOrderType=this.safeString(M,"tpOrderType","limit")):f.tpOrderType=this.safeString(M,"tpOrderType","market")),M=this.omit(M,["stopLossPrice","takeProfitPrice"]),h=await this.privateUtaPostV3TradeModifyStrategyOrder(this.extend(f,M))):(void 0!==n&&(f.price=this.priceToPrecision(t,n)),h=await this.privateUtaPostV3TradeModifyOrder(this.extend(f,M)));else if(!0===u.spot){let e=this.safeString(M,"cost");if(M=this.omit(M,"cost"),(!0===this.safeBool(this.options,"editMarketBuyOrderRequiresPrice",!0)||void 0!==e)&&m&&"buy"===s)if(void 0===n&&void 0===e)throw new a.InvalidOrder(this.id+" editOrder() requires price argument for market buy orders on spot markets to calculate the total amount to spend (amount * price), alternatively provide `cost` in the params");else{let i=this.numberToString(r),s=this.numberToString(n),a=e;void 0===e&&(a=o.Y.stringMul(i,s)),f.size=this.priceToPrecision(t,a)}else f.size=this.amountToPrecision(t,r);f.orderType=i,void 0!==g?(f.triggerPrice=this.priceToPrecision(t,g),void 0!==n&&(f.executePrice=this.priceToPrecision(t,n))):f.price=this.priceToPrecision(t,n),void 0!==g?h=await this.privateSpotPostV2SpotTradeModifyPlanOrder(this.extend(f,M)):(f.symbol=u.id,h=await this.privateSpotPostV2SpotTradeCancelReplaceOrder(this.extend(f,M)))}else{if(!0!==u.swap&&!0!==u.future)throw new a.NotSupported(this.id+" editOrder() does not support "+u.type+" orders");if(f.symbol=u.id,f.productType=c,k||b||(void 0!==r&&(f.newSize=this.amountToPrecision(t,r)),void 0===n||x||(f.newPrice=this.priceToPrecision(t,n))),x){if(!m)throw new a.BadRequest(this.id+" editOrder() bitget trailing orders must be market orders");void 0!==I&&(f.newTriggerPrice=this.priceToPrecision(t,I)),f.newCallbackRatio=A,h=await this.privateMixPostV2MixOrderModifyPlanOrder(this.extend(f,M))}else if(k||b)f.marginCoin=u.settleId,f.size=this.amountToPrecision(t,r),void 0!==n&&(f.executePrice=this.priceToPrecision(t,n)),b?f.triggerPrice=this.priceToPrecision(t,y):k&&(f.triggerPrice=this.priceToPrecision(t,w)),h=await this.privateMixPostV2MixOrderModifyTpslOrder(this.extend(f,M));else if(v){if(f.newTriggerPrice=this.priceToPrecision(t,g),T){let e=this.safeNumber2(S,"triggerPrice","stopPrice");f.newStopLossTriggerPrice=this.priceToPrecision(t,e);let i=this.safeNumber(S,"price");f.newStopLossExecutePrice=this.priceToPrecision(t,i),f.newStopLossTriggerType=this.safeString(S,"type","mark_price")}if(P){let e=this.safeNumber2(O,"triggerPrice","stopPrice");f.newSurplusTriggerPrice=this.priceToPrecision(t,e);let i=this.safeNumber(O,"price");f.newStopSurplusExecutePrice=this.priceToPrecision(t,i),f.newStopSurplusTriggerType=this.safeString(O,"type","mark_price")}h=await this.privateMixPostV2MixOrderModifyPlanOrder(this.extend(f,M))}else{let e=this.uuid(),i=this.safeString2(M,"newClientOid","newClientOrderId",e);if(M=this.omit(M,"newClientOrderId"),f.newClientOid=i,T){let e=this.safeNumber2(S,"triggerPrice","stopPrice");f.newPresetStopLossPrice=this.priceToPrecision(t,e)}if(P){let e=this.safeNumber2(O,"triggerPrice","stopPrice");f.newPresetStopSurplusPrice=this.priceToPrecision(t,e)}h=await this.privateMixPostV2MixOrderModifyOrder(this.extend(f,M))}}let _=this.safeDict(h,"data",{});return this.parseOrder(_,u)}async cancelOrder(e,t,i={}){let s,r,o;if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let n=this.market(t),d={};[s,r]=this.handleMarginModeAndParams("cancelOrder",i);let h={},c=this.safeBool(r,"trailing"),l=this.safeBool2(r,"stop","trigger");r=this.omit(r,["stop","trigger","trailing"]),(!0!==n.spot||!0!==l)&&(h.symbol=n.id),[o,r]=await this.handleUTAAndParams(r,"cancelOrder",!1);let u=(!0===n.swap||!0===n.future)&&(!0===l||!0===c)&&!0!==o,f=this.safeString2(r,"clientOrderId","clientOid");if(u){let t=[],i={};void 0!==f?(r=this.omit(r,"clientOrderId"),i.clientOid=f):i.orderId=e,t.push(i),h.orderIdList=t}else void 0!==f?(r=this.omit(r,"clientOrderId"),h.clientOid=f):h.orderId=e;if(!0===o)d=!0===l?await this.privateUtaPostV3TradeCancelStrategyOrder(this.extend(h,r)):await this.privateUtaPostV3TradeCancelOrder(this.extend(h,r));else if(!0===n.swap||!0===n.future){let e;[e,r]=this.handleProductTypeAndParams(n,r),h.productType=e,!0===c?(h.planType=this.safeString(r,"planType","track_plan"),d=await this.privateMixPostV2MixOrderCancelPlanOrder(this.extend(h,r))):d=!0===l?await this.privateMixPostV2MixOrderCancelPlanOrder(this.extend(h,r)):await this.privateMixPostV2MixOrderCancelOrder(this.extend(h,r))}else if(!0===n.spot)void 0!==s?"isolated"===s?d=await this.privateMarginPostV2MarginIsolatedCancelOrder(this.extend(h,r)):"cross"===s&&(d=await this.privateMarginPostV2MarginCrossedCancelOrder(this.extend(h,r))):d=!0===l?await this.privateSpotPostV2SpotTradeCancelPlanOrder(this.extend(h,r)):await this.privateSpotPostV2SpotTradeCancelOrder(this.extend(h,r));else throw new a.NotSupported(this.id+" cancelOrder() does not support "+n.type+" orders");let p=this.safeDict(d,"data",{}),m={};if(u){let e=this.safeList(p,"successList",[]);m=this.safeDict(e,0,{})}else m=!0===o&&!0===l?d:p;return this.parseOrder(m,n)}async cancelUtaOrders(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r=this.handleProductTypeAndParams(s,i)[0],o=[];for(let t=0;t<e.length;t++){let i={orderId:e[t],symbol:s.id,category:r};o.push(i)}let n=await this.privateUtaPostV3TradeCancelBatch(o),d=this.safeList(n,"data",[]);return this.parseOrders(d,s)}async cancelOrders(e,t,i={}){let s,r,o,n;if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let d=this.market(t);if([s,r]=await this.handleUTAAndParams(i,"cancelOrders",!1),!0===s)return await this.cancelUtaOrders(e,t,r);[o,r]=this.handleMarginModeAndParams("cancelOrders",r);let h=this.safeBool2(r,"stop","trigger");r=this.omit(r,["stop","trigger"]);let c=[];for(let t=0;t<e.length;t++){let i={orderId:e[t]};c.push(i)}let l={symbol:d.id};if(!0===d.spot&&void 0===o?l.orderList=c:l.orderIdList=c,!0===d.spot)n=void 0!==o?"cross"===o?await this.privateMarginPostV2MarginCrossedBatchCancelOrder(this.extend(l,r)):await this.privateMarginPostV2MarginIsolatedBatchCancelOrder(this.extend(l,r)):await this.privateSpotPostV2SpotTradeBatchCancelOrder(this.extend(l,r));else{let e;[e,r]=this.handleProductTypeAndParams(d,r),l.productType=e,n=!0===h?await this.privateMixPostV2MixOrderCancelPlanOrder(this.extend(l,r)):await this.privateMixPostV2MixOrderBatchCancelOrders(this.extend(l,r))}let u=this.safeDict(n,"data",{}),f=this.safeList(u,"successList",[]);return this.parseOrders(f,d)}async cancelAllOrders(e,t={}){let i,s,r,o,n,d;if(void 0===e)throw new a.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let h=this.market(e);[i,s]=this.handleMarginModeAndParams("cancelAllOrders",t),[r,s]=this.handleProductTypeAndParams(h,s);let c={symbol:h.id},l=this.safeBool2(s,"stop","trigger");if(s=this.omit(s,["stop","trigger"]),[n,s]=await this.handleUTAAndParams(s,"cancelAllOrders",!1),!0===n)"SPOT"===r&&void 0!==i&&(r="MARGIN"),c.category=r,o=await this.privateUtaPostV3TradeCancelSymbolOrder(this.extend(c,s));else if(!0===h.spot)if(void 0!==i)throw new a.NotSupported(this.id+" cancelAllOrders() does not support margin markets, you can use cancelOrders() instead");else{if(!0===l){let e={symbolList:[h.id]};o=await this.privateSpotPostV2SpotTradeBatchCancelPlanOrder(this.extend(e,s))}else o=await this.privateSpotPostV2SpotTradeCancelSymbolOrder(this.extend(c,s));let e=this.safeInteger(o,"requestTime"),t=this.safeDict(o,"data"),i=this.safeString(t,"symbol");return[this.safeOrder({info:o,symbol:this.safeSymbol(i,void 0,void 0,"spot"),timestamp:e,datetime:this.iso8601(e)})]}else c.productType=r,o=!0===l?await this.privateMixPostV2MixOrderCancelPlanOrder(this.extend(c,s)):await this.privateMixPostV2MixOrderBatchCancelOrders(this.extend(c,s));let u=this.safeDict(o,"data"),f=this.safeListN(u,["resultList","successList","list"]),p=this.safeList2(u,"failure","failureList");return d=void 0!==f&&void 0!==p?this.arrayConcat(f,p):f,this.parseOrders(d)}async fetchOrder(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),o={},n=this.safeString2(i,"clientOrderId","clientOid");void 0!==n?o.clientOid=n:o.orderId=e;let d=void 0!==n?this.omit(i,["clientOrderId"]):i,[h,c]=await this.handleUTAAndParams(d,"fetchOrder",!1);if(!0===h)s=await this.privateUtaGetV3TradeOrderInfo(this.extend(o,c));else if(!0===r.spot)s=await this.privateSpotGetV2SpotTradeOrderInfo(this.extend(o,c));else if(!0===r.swap||!0===r.future){o.symbol=r.id;let[e,t]=this.handleProductTypeAndParams(r,c);o.productType=e,s=await this.privateMixGetV2MixOrderDetail(this.extend(o,t))}else throw new a.NotSupported(this.id+" fetchOrder() does not support "+r.type+" orders");!0!==h&&"string"==typeof s&&(s=JSON.parse(s));let l=this.safeDict(s,"data");if(void 0!==l&&!Array.isArray(l))return this.parseOrder(l,r);let u=this.safeList(s,"data",[]);if(0===u.length)throw new a.OrderNotFound(this.id+" fetchOrder() could not find order id "+e+" in "+this.json(s));let f=this.safeDict(u,0,{});return this.parseOrder(f,r)}async fetchOpenOrders(e,t,i,s={}){let r,a,o,n,d,h,c,l;void 0===this.markets&&await this.loadMarkets();let u={};if([o,n]=this.handleMarginModeAndParams("fetchOpenOrders",s),[d,n]=await this.handleUTAAndParams(n,"fetchOpenOrders",!1),void 0!==e){r=this.market(e),u.symbol=r.id;let t=this.safeString2(this.options,"fetchOpenOrders","defaultType","spot");"type"in r&&(t=r.type),a=this.safeString(n,"type",t)}else{let e=this.safeString2(this.options,"fetchOpenOrders","defaultType","spot");a=this.safeString(n,"type",e)}let f=!1;if([f,n]=this.handleOptionBoolAndParams(n,"fetchOpenOrders","paginate",!1),f){let s,r;return!0===d?(s="cursor",r="cursor"):"spot"===a?void 0!==o&&(s="minId",r="idLessThan"):(s="endId",r="idLessThan"),await this.fetchPaginatedCallCursor("fetchOpenOrders",e,t,i,n,s,r)}let p=this.safeBool(n,"trailing"),m=this.safeBool2(n,"stop","trigger"),g=void 0!==this.safeString(n,"planType");if([u,n]=this.handleUntilOption("endTime",u,n),void 0!==t&&(u.startTime=t),void 0!==i&&(u.limit=i),!0!==d&&("swap"===a||"future"===a||void 0!==o)){let e=this.safeString2(n,"clientOid","clientOrderId");n=this.omit(n,"clientOrderId"),void 0!==e&&(u.clientOid=e)}if([l,n]=this.handleProductTypeAndParams(r,n),n=this.omit(n,["type","stop","trigger","trailing"]),!0===d)"spot"===a&&(l=void 0!==o?"MARGIN":"SPOT"),u.category=l,h=!0===m?await this.privateUtaGetV3TradeUnfilledStrategyOrders(this.extend(u,n)):await this.privateUtaGetV3TradeUnfilledOrders(this.extend(u,n));else if("spot"===a)void 0!==o?(void 0===t&&(c=this.milliseconds()-7776e6,u.startTime=c),"isolated"===o?h=await this.privateMarginGetV2MarginIsolatedOpenOrders(this.extend(u,n)):"cross"===o&&(h=await this.privateMarginGetV2MarginCrossedOpenOrders(this.extend(u,n)))):h=!0===m?await this.privateSpotGetV2SpotTradeCurrentPlanOrder(this.extend(u,n)):await this.privateSpotGetV2SpotTradeUnfilledOrders(this.extend(u,n));else if(u.productType=l,!0===p){let e=this.safeString(n,"planType","track_plan");u.planType=e,h=await this.privateMixGetV2MixOrderOrdersPlanPending(this.extend(u,n))}else if(!0===m||g){let e=this.safeString(n,"planType","normal_plan");u.planType=e,h=await this.privateMixGetV2MixOrderOrdersPlanPending(this.extend(u,n))}else h=await this.privateMixGetV2MixOrderOrdersPending(this.extend(u,n));let v=void 0===c?t:c,y=this.safeValue(h,"data");if(!0===d){let e;return e=!0===m?this.safeList(h,"data",[]):this.safeList(y,"list",[]),this.parseOrders(e,r,v,i)}if("spot"===a){if(void 0!==o||!0===m){let e=this.safeList(y,"orderList",[]);return this.parseOrders(e,r,v,i)}}else{let e=this.safeList(y,"entrustedList",[]);return this.parseOrders(e,r,v,i)}return this.parseOrders(y,r,v,i)}async fetchClosedOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.fetchCanceledAndClosedOrders(e,t,i,s);return this.filterBy(r,"status","closed")}async fetchCanceledOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.fetchCanceledAndClosedOrders(e,t,i,s);return this.filterBy(r,"status","canceled")}async fetchCanceledAndClosedOrders(e,t,i,s={}){let r,o,n,d,h,c,l;if([r,o]=await this.handleUTAAndParams(s,"fetchCanceledAndClosedOrders",!1),!0===r)return await this.fetchUtaCanceledAndClosedOrders(e,t,i,o);void 0===this.markets&&await this.loadMarkets();let u={};void 0!==e&&(n=this.market(e),u.symbol=n.id),[d,o]=this.handleMarketTypeAndParams("fetchCanceledAndClosedOrders",n,o),[h,o]=this.handleMarginModeAndParams("fetchCanceledAndClosedOrders",o);let f=!1;if([f,o]=this.handleOptionBoolAndParams(o,"fetchCanceledAndClosedOrders","paginate",!1),f){let s;return"spot"===d?void 0!==h&&(s="minId"):s="endId",await this.fetchPaginatedCallCursor("fetchCanceledAndClosedOrders",e,t,i,o,s,"idLessThan")}let p=this.safeBool(o,"trailing"),m=this.safeBool2(o,"stop","trigger");if(o=this.omit(o,["stop","trigger","trailing"]),[u,o]=this.handleUntilOption("endTime",u,o),void 0!==t&&(u.startTime=t),void 0!==i&&(u.limit=i),"swap"===d||"future"===d||void 0!==h){let e=this.safeString2(o,"clientOid","clientOrderId");o=this.omit(o,"clientOrderId"),void 0!==e&&(u.clientOid=e)}let g=this.milliseconds();if("spot"===d)if(void 0!==h)void 0===t&&(l=g-7776e6,u.startTime=l),"isolated"===h?c=await this.privateMarginGetV2MarginIsolatedHistoryOrders(this.extend(u,o)):"cross"===h&&(c=await this.privateMarginGetV2MarginCrossedHistoryOrders(this.extend(u,o)));else if(!0===m){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchCanceledAndClosedOrders() requires a symbol argument");let i=this.safeInteger2(o,"endTime","until");o=this.omit(o,["until"]),void 0===t&&(l=g-7776e6,u.startTime=l),void 0===i&&(u.endTime=g),c=await this.privateSpotGetV2SpotTradeHistoryPlanOrder(this.extend(u,o))}else c=await this.privateSpotGetV2SpotTradeHistoryOrders(this.extend(u,o));else{let e;[e,o]=this.handleProductTypeAndParams(n,o),u.productType=e;let t=void 0!==this.safeString(o,"planType");if(!0===p){let e=this.safeString(o,"planType","track_plan");u.planType=e,c=await this.privateMixGetV2MixOrderOrdersPlanHistory(this.extend(u,o))}else if(!0===m||t){let e=this.safeString(o,"planType","normal_plan");u.planType=e,c=await this.privateMixGetV2MixOrderOrdersPlanHistory(this.extend(u,o))}else c=await this.privateMixGetV2MixOrderOrdersHistory(this.extend(u,o))}let v=void 0===l?t:l,y=this.safeDict(c,"data",{});if("spot"!==d)return this.parseOrders(this.safeList(y,"entrustedList"),n,v,i);if(void 0!==h||!0===m)return this.parseOrders(this.safeList(y,"orderList"),n,v,i);"string"==typeof c&&(c=JSON.parse(c));let b=this.safeList(c,"data",[]);return this.parseOrders(b,n,v,i)}async fetchUtaCanceledAndClosedOrders(e,t,i,s={}){let r,a,o,n;if(void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e)),[a,o]=this.handleProductTypeAndParams(r,s),"SPOT"===a){let e;[e,o]=this.handleMarginModeAndParams("fetchCanceledAndClosedOrders",o),void 0!==e&&(a="MARGIN")}let d={category:a},h=!1;if([h,o]=this.handleOptionBoolAndParams(o,"fetchCanceledAndClosedOrders","paginate",!1),h)return await this.fetchPaginatedCallCursor("fetchCanceledAndClosedOrders",e,t,i,o,"cursor","cursor");[d,o]=this.handleUntilOption("endTime",d,o),void 0!==t&&(d.startTime=t),void 0!==i&&(d.limit=i);let c=this.safeBool2(o,"stop","trigger");o=this.omit(o,["stop","trigger"]),n=!0===c?await this.privateUtaGetV3TradeHistoryStrategyOrders(this.extend(d,o)):await this.privateUtaGetV3TradeHistoryOrders(this.extend(d,o));let l=this.safeDict(n,"data",{}),u=this.safeList(l,"list",[]);return this.parseOrders(u,r,t,i)}async fetchLedger(e,t,i,s={}){let r,a,o,n,d;void 0===this.markets&&await this.loadMarkets();let h=this.safeString(s,"symbol"),c=this.omit(s,"symbol");void 0!==h&&(r=this.market(h)),[a,c]=this.handleMarketTypeAndParams("fetchLedger",r,c),[o,c]=await this.handleUTAAndParams(c,"fetchLedger",!1);let l=!1;if([l,c]=this.handleOptionBoolAndParams(c,"fetchLedger","paginate",!1),l){let s;return!0===o?(c=this.extend(c,{uta:!0,type:a}),void 0!==h&&(c=this.extend(c,{symbol:h})),await this.fetchPaginatedCallCursor("fetchLedger",e,t,i,c,"id","cursor",void 0,100)):("spot"!==a&&(s="endId"),c=this.extend(c,{type:a}),void 0!==h&&(c=this.extend(c,{symbol:h})),await this.fetchPaginatedCallCursor("fetchLedger",e,t,i,c,s,"idLessThan"))}let u={};if(void 0!==e&&(n=this.currency(e),u.coin=n.id),[u,c]=this.handleUntilOption("endTime",u,c),void 0!==t&&(u.startTime=t),void 0!==i&&(u.limit=i),!0===o){if("funding"===a)d=await this.privateUtaGetV3AccountFundingFinancialRecords(this.extend(u,c));else{let e;if([e,c]=this.handleMarginModeAndParams("fetchLedger",c),"spot"===a)void 0!==e?u.category="MARGIN":u.category="SPOT";else{let e;[e,c]=this.handleProductTypeAndParams(r,c),u.category=e}void 0!==h&&(u.symbol=this.safeString(r,"id")),d=await this.privateUtaGetV3AccountFinancialRecords(this.extend(u,c))}let e=this.safeDict(d,"data",{}),s=this.safeList(e,"list",[]);return this.parseLedger(s,n,t,i)}if("spot"===a)d=await this.privateSpotGetV2SpotAccountBills(this.extend(u,c));else{let e;void 0!==h&&(u.symbol=this.safeString(r,"id")),[e,c]=this.handleProductTypeAndParams(r,c),u.productType=e,d=await this.privateMixGetV2MixAccountBill(this.extend(u,c))}let f=this.safeValue(d,"data");if("swap"===a||"future"===a){let e=this.safeList(f,"bills",[]);return this.parseLedger(e,n,t,i)}return this.parseLedger(f,n,t,i)}parseLedgerEntry(e,t){let i,s,r=this.safeString(e,"coin"),a=this.safeCurrencyCode(r,t),n=this.safeCurrency(r,t),d=this.safeInteger2(e,"cTime","ts"),h=this.safeString(e,"balance"),c=this.parseNumber(h),l=this.safeString2(e,"fees","fee");void 0!==l&&(i=this.parseNumber(o.Y.stringAbs(l)));let u=this.safeString2(e,"size","amount",""),f=this.parseNumber(o.Y.stringAbs(u));void 0!==h&&""!==u&&(s=this.parseNumber(o.Y.stringSub(h,u)));let p="in";return u.indexOf("-")>=0&&(p="out"),this.safeLedgerEntry({info:e,id:this.safeString2(e,"billId","id"),timestamp:d,datetime:this.iso8601(d),direction:p,account:void 0,referenceId:void 0,referenceAccount:void 0,type:this.parseLedgerType(this.safeStringN(e,["businessType","groupType","type"])),currency:a,amount:f,before:s,after:c,status:void 0,fee:{currency:a,cost:i}},n)}parseLedgerType(e){return this.safeString({trans_to_cross:"transfer",trans_from_cross:"transfer",trans_to_exchange:"transfer",trans_from_exchange:"transfer",trans_to_isolated:"transfer",trans_from_isolated:"transfer",trans_to_contract:"transfer",trans_from_contract:"transfer",trans_to_otc:"transfer",trans_from_otc:"transfer",open_long:"trade",close_long:"trade",open_short:"trade",close_short:"trade",force_close_long:"trade",force_close_short:"trade",burst_long_loss_query:"trade",burst_short_loss_query:"trade",force_buy:"trade",force_sell:"trade",burst_buy:"trade",burst_sell:"trade",delivery_long:"settlement",delivery_short:"settlement",contract_settle_fee:"fee",append_margin:"transaction",adjust_down_lever_append_margin:"transaction",reduce_margin:"transaction",auto_append_margin:"transaction",cash_gift_issue:"cashback",cash_gift_recycle:"cashback",bonus_issue:"rebate",bonus_recycle:"rebate",bonus_expired:"rebate",transfer_in:"transfer",transfer_out:"transfer",deposit:"deposit",withdraw:"withdrawal",buy:"trade",sell:"trade",transaction:"transaction",transfer:"transfer",financial:"transaction",strategy:"trade",trace:"trade",loan:"transaction",fait:"transaction",convert:"trade",ipo_prime:"transaction",pre_c2c:"trade",paptrading:"trade",on_chain:"transaction",debit:"transaction",cfd:"trade",pay:"transaction",compliance_wall:"transaction",live:"transaction",broker:"transaction",rwa:"transaction",stock:"trade",TRANSFER_IN:"transfer",TRANSFER_OUT:"transfer",RESERVE_TRANSFER_IN:"transfer",RESERVE_TRANSFER_OUT:"transfer",LIQ_TRANSFER_IN:"transfer",LIQ_TRANSFER_OUT:"transfer",ON_CHAIN_TRANSFER_REFUND:"transfer",ON_CHAIN_TRANSFER_OUT:"transfer",MT5_TRANSFER_IN:"transfer",MT5_REFUND_IN:"transfer",MT5_TRANSFER_OUT:"transfer",TRACE_TRANSFER_USER_OUT:"transfer",TRACE_TRANSFER_USER_IN:"transfer",TRACE_TRANSFER_REFUND_IN:"transfer",FINANCIAL_TRANSFER_OUT:"transfer",FINANCIAL_TRANSFER_IN:"transfer",CONVERT_TRANSFER_IN:"transfer",CONVERT_TRANSFER_OUT:"transfer",BGPAY_TRANSFER_OUT:"transfer",BGPAY_REFUND_IN:"transfer",ORDER_DEALT_FROZEN_OUT:"trade",ORDER_DEALT_IN:"trade",OPEN_LONG:"trade",OPEN_SHORT:"trade",BUY_DEAL:"trade",SELL_DEAL:"trade",CLOSE_LONG:"trade",CLOSE_SHORT:"trade",FORCE_CLOSE_LONG:"trade",FORCE_CLOSE_SHORT:"trade",BURST_CLOSE_LONG:"trade",BURST_CLOSE_SHORT:"trade",OFFSET_REDUCE_CLOSE_LONG:"trade",OFFSET_REDUCE_CLOSE_SHORT:"trade",FORCE_BUY_SSM:"trade",FORCE_SELL_SSM:"trade",BURST_BUY_SSM:"trade",BURST_SELL_SSM:"trade",RISK_LIQ_USER_IN:"trade",RISK_LIQ_USER_OUT:"trade",LIQ_FUND_OUT:"trade",LIQ_FUND_IN:"trade",LIQ_CONVERT_USER_OUT:"trade",LIQ_CONVERT_SYS_IN:"trade",LIQ_CONVERT_SYS_OUT:"trade",LIQ_CONVERT_USER_IN:"trade",MARGIN_OPEN_LONG:"trade",MARGIN_OPEN_SHORT:"trade",MARIN_BUY_DEAL:"trade",MARIN_SELL_DEAL:"trade",MARGIN_BACK:"trade",MARGIN_OFFSET_IN_SSM_LONG:"trade",MARGIN_OFFSET_IN_SSM_SHORT:"trade",FIXED_OFFSET_IN_SSM_LONG:"trade",FIXED_OFFSET_IN_SSM_SHORT:"trade",FIXED_CLOSE_LONG:"trade",FIXED_CLOSE_SHORT:"trade",FIXED_FORCE_CLOSE_LONG:"trade",FIXED_FORCE_CLOSE_SHORT:"trade",FIXED_BURST_CLOSE_LONG:"trade",FIXED_BURST_CLOSE_SHORT:"trade",FIXED_ADL_CLOSE_LONG:"trade",FIXED_ADL_CLOSE_SHORT:"trade",FIXED_RISK_LIQ_USER_IN:"trade",FIXED_RISK_LIQ_USER_OUT:"trade",FIXED_FORCE_BUY_SSM:"trade",FIXED_FORCE_SELL_SSM:"trade",FIXED_BURST_BUY_SSM:"trade",FIXED_BURST_SELL_SSM:"trade",RWA_CONTRACT_REBASE_USER_OPEN_LONG:"trade",RWA_CONTRACT_REBASE_USER_OPEN_SHORT:"trade",RWA_CONTRACT_REBASE_USER_CLOSE_LONG:"trade",RWA_CONTRACT_REBASE_USER_CLOSE_SHORT:"trade",RWA_CONTRACT_REBASE_USER_BUY_IN_SSM:"trade",RWA_CONTRACT_REBASE_USER_SELL_IN_SSM:"trade",ORDER_PLF_FEE_OUT:"fee",INTEREST_SETTLEMENT_OUT:"fee",INTEREST_REPAYMENT:"fee",CONTRACT_MAIN_SETTLE_FEE_USER_IN:"fee",CONTRACT_MAIN_SETTLE_FEE_USER_OUT:"fee",MARGIN_SETTLE_FEE_USER_IN:"fee",MARGIN_SETTLE_FEE_USER_OUT:"fee",LIQ_FEE:"fee",SMALL_ASSET_FEE_SYS_IN:"fee",RWA_FIXED_SETTLE_FEE_USER_IN:"fee",RWA_FIXED_SETTLE_FEE_USER_OUT:"fee",RWA_CONTRACT_MAIN_SETTLE_FEE_SYSTEM_IN:"fee",RWA_CONTRACT_MAIN_SETTLE_FEE_SYSTEM_OUT:"fee",RWA_CONTRACT_MAIN_SETTLE_FEE_SYSTEM_KEEP_IN:"fee",RWA_CONTRACT_MAIN_SETTLE_FEE_SYSTEM_KEEP_OUT:"fee",RWA_CONTRACT_MAIN_SETTLE_FEE_USER_IN:"fee",RWA_CONTRACT_MAIN_SETTLE_FEE_USER_OUT:"fee",INCREASE_MARGIN:"margin",REDUCE_MARGIN:"margin",MARGIN_LEVER_ORDER_REFROZEN:"margin",MARGIN_LEVER_ORDER_FROZEN:"margin",MARGIN_LEVER_POS_IN:"margin",CONVERSION_UPON_DELISTING:"transaction",EXCHANGE_SOURCE_TOKEN_USER_OUT:"transaction",EXCHANGE_TARGET_TOKEN_USER_IN:"transaction",BORROW:"transaction",REPAYMENT:"transaction",LIQ_REPAYMENT:"transaction",DELIST_MARGIN_TOKEN_SOURCE_USER_OUT:"transaction",DELIST_MARGIN_TOKEN_SOURCE_SYS_IN:"transaction",DELIST_MARGIN_TOKEN_TARGET_SYS_OUT:"transaction",DELIST_MARGIN_TOKEN_TARGET_USER_IN:"transaction",CONFISCATE_TOKEN_USER_OUT:"transaction",CONFISCATE_TOKEN_SYS_IN:"transaction",DELIST_SMALL_BALANCE_USER_OUT:"transaction",DELIST_SMALL_BALANCE_SYS_IN:"transaction",DELIST_SMALL_LIABILITY_SYS_OUT:"transaction",DELIST_SMALL_LIABILITY_USER_IN:"transaction",SMALL_ASSET_SOURCE_TOKEN_USER_OUT:"transaction",SMALL_ASSET_SOURCE_TOKEN_SYS_IN:"transaction",SMALL_ASSET_TARGET_TOKEN_SYS_OUT:"transaction",SMALL_ASSET_TARGET_TOKEN_USER_IN:"transaction",TRACE_LOCK_USER_OUT:"transaction",TRACE_LOCK_USER_IN:"transaction",TRACE_SHARE_BENEFIT_USER_OUT:"referral",TRACE_SHARE_BENEFIT_SYSTEM_IN:"referral",TRACE_SHARE_BENEFIT_SYSTEM_OUT:"referral",TRACE_SHARE_BENEFIT_USER_IN:"referral"},e,e)}async fetchMyTrades(e,t,i,s={}){let r,o,n,d;if([r,o]=await this.handleUTAAndParams(s,"fetchMyTrades",!1),!0!==r&&void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let h=this.market(e),c={};[c,o]=this.handleUntilOption("endTime",c,o),void 0!==t&&(c.startTime=t),void 0!==i&&(c.limit=i);let l=!1;if([l,o]=this.handleOptionBoolAndParams(o,"fetchMyTrades","paginate",!1),[n,o]=this.handleMarginModeAndParams("fetchMyTrades",o),l){let s,a;return!0===r?(s="cursor",a="cursor"):!0===h.spot?void 0!==n&&(s="minId",a="idLessThan"):(s="endId",a="idLessThan"),await this.fetchPaginatedCallCursor("fetchMyTrades",e,t,i,o,s,a)}if(!0===r)d=await this.privateUtaGetV3TradeFills(this.extend(c,o));else if(c.symbol=h.id,!0===h.spot)void 0!==n?(void 0===t&&(c.startTime=this.milliseconds()-7776e6),"isolated"===n?d=await this.privateMarginGetV2MarginIsolatedFills(this.extend(c,o)):"cross"===n&&(d=await this.privateMarginGetV2MarginCrossedFills(this.extend(c,o)))):d=await this.privateSpotGetV2SpotTradeFills(this.extend(c,o));else{let e;[e,o]=this.handleProductTypeAndParams(h,o),c.productType=e,d=await this.privateMixGetV2MixOrderFills(this.extend(c,o))}let u=this.safeValue(d,"data");if(!0===r){let e=this.safeList(u,"list",[]);return this.parseTrades(e,h,t,i)}if(!0===h.swap||!0===h.future){let e=this.safeList(u,"fillList",[]);return this.parseTrades(e,h,t,i)}if(void 0!==n){let e=this.safeList(u,"fills",[]);return this.parseTrades(e,h,t,i)}return this.parseTrades(u,h,t,i)}async fetchPosition(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),[a,o]=this.handleProductTypeAndParams(r,t),n={symbol:r.id},[d,h]=await this.handleUTAAndParams(o,"fetchPosition",!1);if(!0===d){n.category=a,i=await this.privateUtaGetV3PositionCurrentPosition(this.extend(n,h));let e=this.safeDict(i,"data",{});s=this.safeList(e,"list",[])}else n.marginCoin=r.settleId,n.productType=a,i=await this.privateMixGetV2MixPositionSinglePosition(this.extend(n,h)),s=this.safeList(i,"data",[]);let c=this.safeDict(s,0,{});return this.parsePosition(c,r)}async fetchPositions(e,t={}){let i,s,r,o,n,d;void 0===this.markets&&await this.loadMarkets();let h=!1;if([h,i]=this.handleOptionBoolAndParams(t,"fetchPositions","paginate",!1),h)return await this.fetchPaginatedCallCursor("fetchPositions",void 0,void 0,void 0,i,"endId","idLessThan");if(!0===this.safeBool(i,"useHistoryEndpoint",!1)?s="privateMixGetV2MixPositionHistoryPosition":[s,i]=this.handleOptionStringAndParams(i,"fetchPositions","method","privateMixGetV2MixPositionAllPosition"),void 0!==e){let t=this.safeString(e,0);void 0!==t&&(r=this.market(t))}[o,i]=this.handleProductTypeAndParams(r,i);let c={},l=!1;if([d,i]=await this.handleUTAAndParams(i,"fetchPositions",!1),!0===d)c.category=o,n=await this.privateUtaGetV3PositionCurrentPosition(this.extend(c,i));else if("privateMixGetV2MixPositionAllPosition"===s){let e=this.safeString(i,"marginCoin","USDT");if(void 0!==r)e=r.settleId;else if("USDT-FUTURES"===o)e="USDT";else if("USDC-FUTURES"===o)e="USDC";else if("SUSDT-FUTURES"===o)e="SUSDT";else if("SUSDC-FUTURES"===o)e="SUSDC";else if(("SCOIN-FUTURES"===o||"COIN-FUTURES"===o)&&void 0===e)throw new a.ArgumentsRequired(this.id+" fetchPositions() requires a marginCoin parameter that matches the productType");c.marginCoin=e,c.productType=o,n=await this.privateMixGetV2MixPositionAllPosition(this.extend(c,i))}else l=!0,void 0!==r&&(c.symbol=r.id),c.productType=o,n=await this.privateMixGetV2MixPositionHistoryPosition(this.extend(c,i));let u=[];if(!0===d||l){let e=this.safeDict(n,"data",{});u=this.safeList(e,"list",[])}else u=this.safeList(n,"data",[]);let f=[];for(let e=0;e<u.length;e++)f.push(this.parsePosition(u[e],r));let p=this.marketSymbols(e);return this.filterByArrayPositions(f,"symbol",p)}parsePosition(e,t){let i,s,r,a=this.safeString(e,"symbol"),n=this.safeMarket(a,t,void 0,"contract"),d=n.symbol,h=this.safeIntegerN(e,["cTime","ctime","createdTime"]),c=this.safeString(e,"marginMode"),l=this.safeString2(e,"unrealizedPL","unrealisedPnl"),u=this.safeString2(e,"marginSize","positionBalance");"isolated"===c?i=o.Y.stringAdd(u,l):"crossed"===c&&(c="cross",s=u);let f=this.safeString2(e,"posMode","holdMode");"hedge_mode"===f?r=!0:"one_way_mode"===f&&(r=!1);let p=this.safeString2(e,"holdSide","posSide"),m=this.safeString(e,"leverage"),g=this.safeNumber(n,"contractSize"),v=this.numberToString(g),y=this.safeString2(e,"total","openTotalPos"),b=this.safeStringN(e,["openPriceAvg","openAvgPrice","avgPrice"]),w=this.safeString(e,"keepMarginRate"),k=o.Y.stringMul(b,y);void 0===s&&(s=o.Y.stringDiv(k,m));let S=this.parseNumber(o.Y.stringDiv(y,v));void 0===S&&(S=this.safeNumber(e,"closeTotalPos"));let O=this.safeString(e,"markPrice"),T=o.Y.stringMul(y,O),P=o.Y.stringDiv(s,T),I=this.parseNumber(this.omitZero(this.safeString(e,"liquidationPrice"))),A="0.9994";if(void 0===I&&"isolated"===c&&o.Y.stringGt(y,"0")){let e=o.Y.stringDiv(u,y),t=w;"short"===p&&(e=o.Y.stringNeg(e),t=o.Y.stringNeg(t));let i=o.Y.stringSub("1",t),s=o.Y.stringSub(b,e);"long"===p?i=o.Y.stringMul(i,A):s=o.Y.stringMul(s,A),I=this.parseNumber(o.Y.stringDiv(s,i))}let x=o.Y.stringMul(T,"0.0006"),M=o.Y.stringAdd(o.Y.stringMul(w,T),x),_=o.Y.stringMul(o.Y.stringDiv(l,s,4),"100");return this.safePosition({info:e,id:this.safeString2(e,"orderId","positionId"),symbol:d,notional:this.parseNumber(T),marginMode:c,liquidationPrice:I,entryPrice:this.parseNumber(b),unrealizedPnl:this.parseNumber(l),realizedPnl:this.safeNumberN(e,["pnl","curRealisedPnl","cumRealisedPnl"]),percentage:this.parseNumber(_),contracts:S,contractSize:g,markPrice:this.parseNumber(O),lastPrice:this.safeNumber2(e,"closeAvgPrice","closePriceAvg"),side:p,hedged:r,timestamp:h,datetime:this.iso8601(h),lastUpdateTimestamp:this.safeInteger2(e,"utime","updatedTime"),maintenanceMargin:this.parseNumber(M),maintenanceMarginPercentage:this.parseNumber(w),collateral:this.parseNumber(i),initialMargin:this.parseNumber(s),initialMarginPercentage:this.parseNumber(P),leverage:this.parseNumber(m),marginRatio:this.safeNumber2(e,"marginRatio","mmr"),stopLossPrice:void 0,takeProfitPrice:void 0})}async fetchFundingRateHistory(e,t,i,s={}){let r,o,n,d,h;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let c=this.market(e),l={symbol:c.id};if([r,h]=this.handleProductTypeAndParams(c,s),[o,h]=await this.handleUTAAndParams(h,"fetchFundingRateHistory",!1),!0===o){void 0!==i&&(l.limit=i),l.category=r,n=await this.publicUtaGetV3MarketHistoryFundRate(this.extend(l,h));let e=this.safeDict(n,"data",{});d=this.safeList(e,"resultList",[])}else{let s=!1;if([s,h]=this.handleOptionBoolAndParams(h,"fetchFundingRateHistory","paginate",!1),s)return await this.fetchPaginatedCallIncremental("fetchFundingRateHistory",e,t,i,h,"pageNo",100);void 0!==i&&(l.pageSize=i),l.productType=r,n=await this.publicMixGetV2MixMarketHistoryFundRate(this.extend(l,h)),d=this.safeList(n,"data",[])}let u=[];for(let e=0;e<d.length;e++){let t=d[e],i=this.safeString(t,"symbol"),s=this.safeSymbol(i,c),r=this.safeInteger2(t,"fundingTime","fundingRateTimestamp");u.push({info:t,symbol:s,fundingRate:this.safeNumber(t,"fundingRate"),timestamp:r,datetime:this.iso8601(r)})}let f=this.sortBy(u,"timestamp");return this.filterBySymbolSinceLimit(f,this.safeString(c,"symbol"),t,i)}async fetchFundingRate(e,t={}){let i,s,r,o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e);if(!0!==n.swap)throw new a.BadSymbol(this.id+" fetchFundingRate() supports swap contracts only");[i,s]=this.handleProductTypeAndParams(n,t);let d={symbol:n.id};if([r,s]=await this.handleUTAAndParams(s,"fetchFundingRate",!1),!0===r)o=await this.publicUtaGetV3MarketCurrentFundRate(this.extend(d,s));else{let e;d.productType=i,[e,s]=this.handleOptionStringAndParams(s,"fetchFundingRate","method","publicMixGetV2MixMarketCurrentFundRate"),"publicMixGetV2MixMarketCurrentFundRate"===e?o=await this.publicMixGetV2MixMarketCurrentFundRate(this.extend(d,s)):"publicMixGetV2MixMarketFundingTime"===e&&(o=await this.publicMixGetV2MixMarketFundingTime(this.extend(d,s)))}let h=this.safeList(o,"data",[]);return this.parseFundingRate(h[0],n)}async fetchFundingRates(e,t={}){let i,s;if(void 0===this.markets&&await this.loadMarkets(),void 0!==e){let t=this.safeString(e,0);i=this.market(t)}let r={},[a,o]=this.handleProductTypeAndParams(i,t),[n,d]=this.handleOptionStringAndParams(o,"fetchFundingRates","method","publicMixGetV2MixMarketTickers");r.productType=a,"publicMixGetV2MixMarketTickers"===n?s=await this.publicMixGetV2MixMarketTickers(this.extend(r,d)):"publicMixGetV2MixMarketCurrentFundRate"===n&&(s=await this.publicMixGetV2MixMarketCurrentFundRate(this.extend(r,d)));let h=this.marketSymbols(e),c=this.safeList(s,"data",[]);return this.parseFundingRates(c,h)}async fetchFundingIntervals(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.extend({method:"publicMixGetV2MixMarketCurrentFundRate"},t);return await this.fetchFundingRates(e,i)}parseFundingRate(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeSymbol(s,t,void 0,"swap"),a=this.safeInteger2(e,"nextFundingTime","nextUpdate"),o=this.safeString2(e,"ratePeriod","fundingRateInterval"),n=this.safeInteger(e,"ts"),d=this.safeNumber(e,"markPrice"),h=this.safeNumber(e,"indexPrice");return void 0!==o&&(i=o+"h"),{info:e,symbol:r,markPrice:d,indexPrice:h,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:n,datetime:this.iso8601(n),fundingRate:this.safeNumber(e,"fundingRate"),fundingTimestamp:a,fundingDatetime:this.iso8601(a),nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:i}}async fetchFundingHistory(e,t,i,s={}){let r;if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingHistory() requires a symbol argument");let[o,n]=await this.handleUTAAndParams(s,"fetchFundingHistory",!1),[d,h]=this.handleOptionBoolAndParams(n,"fetchFundingHistory","paginate",!1);if(d)return!0===o?await this.fetchPaginatedCallCursor("fetchFundingHistory",e,t,i,h,"cursor","cursor"):await this.fetchPaginatedCallCursor("fetchFundingHistory",e,t,i,h,"endId","idLessThan");let c=this.market(e);if(!0!==c.swap)throw new a.BadSymbol(this.id+" fetchFundingHistory() supports swap contracts only");let[l,u]=this.handleProductTypeAndParams(c,h),[f,p]=this.handleUntilOption("endTime",{},u);void 0!==t&&(f.startTime=t),void 0!==i&&(f.limit=i),!0===o?(f.coin=c.settleId,f.category=l,r=await this.privateUtaGetV3AccountFinancialRecords(this.extend(f,p))):(f.symbol=c.id,f.marginCoin=c.settleId,f.businessType="contract_settle_fee",f.productType=l,r=await this.privateMixGetV2MixAccountBill(this.extend(f,p)));let m=this.safeDict(r,"data",{}),g=this.safeList2(m,"bills","list",[]);return!0===o&&(g=this.filterByArray(g,"type",["CONTRACT_MAIN_SETTLE_FEE_USER_IN","CONTRACT_MAIN_SETTLE_FEE_USER_OUT"],!1)),this.parseFundingHistories(g,c,t,i)}parseFundingHistory(e,t){let i=this.safeString(e,"symbol"),s=this.safeString(e,"coin"),r=this.safeInteger2(e,"cTime","ts");return{info:e,symbol:this.safeSymbol(i,t,void 0,"swap"),timestamp:r,datetime:this.iso8601(r),code:this.safeCurrencyCode(s),amount:this.safeNumber(e,"amount"),id:this.safeString2(e,"billId","id")}}parseFundingHistories(e,t,i,s){let r,a=[];for(let i=0;i<e.length;i++){let s=this.safeDict(e,i);a.push(this.parseFundingHistory(s,t))}let o=this.sortBy(a,"timestamp");return void 0!==t&&(r=this.safeString(t,"symbol")),this.filterBySymbolSinceLimit(o,r,i,s)}async modifyMarginHelper(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.safeString(s,"holdSide"),a=this.market(e),[o,n]=this.handleProductTypeAndParams(a,s),d={symbol:a.id,marginCoin:a.settleId,amount:this.amountToPrecision(e,t),holdSide:r,productType:o},h=this.omit(n,"holdSide"),c=await this.privateMixPostV2MixAccountSetMargin(this.extend(d,h));return this.extend(this.parseMarginModification(c,a),{amount:this.parseNumber(t),type:i})}parseMarginModification(e,t){let i=this.safeString(e,"code"),s="failed";return"00000"===i&&(s="ok"),{info:e,symbol:this.safeString(t,"symbol"),type:void 0,marginMode:"isolated",amount:void 0,total:void 0,code:this.safeString(t,"settle"),status:s,timestamp:void 0,datetime:void 0}}async reduceMargin(e,t,i={}){if(t>0)throw new a.BadRequest(this.id+" reduceMargin() amount parameter must be a negative value");if(void 0===this.safeString(i,"holdSide"))throw new a.ArgumentsRequired(this.id+" reduceMargin() requires a holdSide parameter, either long or short");return await this.modifyMarginHelper(e,t,"reduce",i)}async addMargin(e,t,i={}){if(void 0===this.safeString(i,"holdSide"))throw new a.ArgumentsRequired(this.id+" addMargin() requires a holdSide parameter, either long or short");return await this.modifyMarginHelper(e,t,"add",i)}async fetchLeverage(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),[s,r]=this.handleProductTypeAndParams(i,t),a={symbol:i.id,marginCoin:i.settleId,productType:s},o=await this.privateMixGetV2MixAccountAccount(this.extend(a,r)),n=this.safeDict(o,"data",{});return this.parseLeverage(n,i)}parseLeverage(e,t){let i="crossed"===this.safeString(e,"marginMode"),s="isolatedLongLever";i&&(s="crossedMarginLeverage");let r="isolatedShortLever";return i&&(r="crossedMarginLeverage"),{info:e,symbol:this.safeString(t,"symbol"),marginMode:i?"cross":"isolated",longLeverage:this.safeInteger(e,s),shortLeverage:this.safeInteger(e,r)}}async setLeverage(e,t,i={}){let s,r,o;if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let n=this.market(t);[s,r]=this.handleProductTypeAndParams(n,i);let d={symbol:n.id,leverage:this.numberToString(e)},h={};if([o,r]=await this.handleUTAAndParams(r,"setLeverage",!1),!0===o){if("SPOT"===s){let e;[e,r]=this.handleMarginModeAndParams("setLeverage",r),void 0!==e&&(s="MARGIN")}d.coin=n.settleId,d.category=s,h=await this.privateUtaPostV3AccountSetLeverage(this.extend(d,r))}else d.marginCoin=n.settleId,d.productType=s,h=await this.privateMixPostV2MixAccountSetLeverage(this.extend(d,r));return h}async setMarginMode(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");let s=e.toLowerCase();if("cross"===s&&(s="crossed"),"isolated"!==s&&"crossed"!==s)throw new a.ArgumentsRequired(this.id+" setMarginMode() marginMode must be either isolated or crossed (cross)");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),[o,n]=this.handleProductTypeAndParams(r,i),d={symbol:r.id,marginCoin:r.settleId,marginMode:s,productType:o};return await this.privateMixPostV2MixAccountSetMarginMode(this.extend(d,n))}async setPositionMode(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r="one_way_mode";e&&(r="hedge_mode");let a={};void 0!==t&&(s=this.market(t));let o={},[n,d]=this.handleProductTypeAndParams(s,i),[h,c]=await this.handleUTAAndParams(d,"setPositionMode",!1);return!0===h?(a.holdMode=r,o=await this.privateUtaPostV3AccountSetHoldMode(this.extend(a,c))):(a.posMode=r,a.productType=n,o=await this.privateMixPostV2MixAccountSetPositionMode(this.extend(a,c))),o}async fetchOpenInterest(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e);if(!0!==s.contract)throw new a.BadRequest(this.id+" fetchOpenInterest() supports contract markets only");let[r,o]=this.handleProductTypeAndParams(s,t),n={symbol:s.id},[d,h]=await this.handleUTAAndParams(o,"fetchOpenInterest",!1);!0===d?(n.category=r,i=await this.publicUtaGetV3MarketOpenInterest(this.extend(n,h))):(n.productType=r,i=await this.publicMixGetV2MixMarketOpenInterest(this.extend(n,h)));let c=this.safeDict(i,"data",{});return this.parseOpenInterest(c,s)}parseOpenInterest(e,t){let i=this.safeList2(e,"openInterestList","list",[]),s=this.safeInteger(e,"ts"),r=this.safeString(i[0],"symbol");return this.safeOpenInterest({symbol:this.safeSymbol(r,t,void 0,"contract"),openInterestAmount:this.safeNumber2(i[0],"size","openInterest"),openInterestValue:void 0,timestamp:s,datetime:this.iso8601(s),info:e},t)}async fetchTransfers(e,t,i,s={}){let r,o;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchTransfers() requires a code argument");void 0===this.markets&&await this.loadMarkets(),[r,o]=this.handleMarketTypeAndParams("fetchTransfers",void 0,s);let n=this.safeString(o,"fromAccount",r);o=this.omit(o,"fromAccount");let d=this.safeDict(this.options,"accountsByType",{});r=this.safeString(d,n);let h=this.currency(e),c={coin:h.id,fromType:r};void 0!==t&&(c.startTime=t),void 0!==i&&(c.limit=i),[c,o]=this.handleUntilOption("endTime",c,o);let l=await this.privateSpotGetV2SpotAccountTransferRecords(this.extend(c,o)),u=this.safeList(l,"data",[]);return this.parseTransfers(u,h,t,i)}async transfer(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let[o,n]=await this.handleUTAAndParams(r,"transfer",!1),d=this.currency(e),h=this.safeDict(this.options,"accountsByType",{}),c={fromType:this.safeString(h,i),toType:this.safeString(h,s),amount:t,coin:d.id},l=this.safeString(n,"symbol"),u=this.omit(n,"symbol");void 0!==l&&(c.symbol=this.market(l).id),a=!0===o?await this.privateUtaPostV3AccountTransfer(this.extend(c,u)):await this.privateSpotPostV2SpotWalletTransfer(this.extend(c,u));let f=this.safeDict(a,"data",{});return f.ts=this.safeInteger(a,"requestTime"),this.parseTransfer(f,d)}parseTransfer(e,t){let i=this.safeInteger(e,"ts"),s=this.safeStringLower(e,"status"),r=this.safeString(e,"coin"),a=this.safeString(e,"fromType"),o=this.safeDict(this.options,"accountsById",{}),n=this.safeString(o,a,a),d=this.safeString(e,"toType"),h=this.safeString(o,d,d);return{info:e,id:this.safeString(e,"transferId"),timestamp:i,datetime:this.iso8601(i),currency:this.safeCurrencyCode(r,t),amount:this.safeNumber(e,"size"),fromAccount:n,toAccount:h,status:this.parseTransferStatus(s)}}parseTransferStatus(e){return this.safeString({successful:"ok"},e,e)}parseDepositWithdrawFee(e,t){let i=this.safeList(e,"chains",[]),s=i.length,r={info:e,withdraw:{fee:void 0,percentage:void 0},deposit:{fee:void 0,percentage:void 0},networks:{}};for(let e=0;e<s;e++){let a=this.safeDict(i,e),o=this.safeString(a,"chain"),n=this.safeString(t,"code"),d=this.networkIdToCode(o,n);void 0!==d&&(r.networks[d]={deposit:{fee:void 0,percentage:void 0},withdraw:{fee:this.safeNumber(a,"withdrawFee"),percentage:!1}}),1===s&&(r.withdraw.fee=this.safeNumber(a,"withdrawFee"),r.withdraw.percentage=!1)}return r}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicSpotGetV2SpotPublicCoins(t),s=this.safeList(i,"data",[]);return this.parseDepositWithdrawFees(s,e,"coin")}async borrowCrossMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.currency(e),r={coin:s.id,borrowAmount:this.currencyToPrecision(e,t)},a=await this.privateMarginPostV2MarginCrossedAccountBorrow(this.extend(r,i)),o=this.safeDict(a,"data",{});return this.parseMarginLoan(o,s)}async borrowIsolatedMargin(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.currency(t),a=this.market(e),o={coin:r.id,borrowAmount:this.currencyToPrecision(t,i),symbol:a.id},n=await this.privateMarginPostV2MarginIsolatedAccountBorrow(this.extend(o,s)),d=this.safeDict(n,"data",{});return this.parseMarginLoan(d,r,a)}async repayIsolatedMargin(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.currency(t),a=this.market(e),o={coin:r.id,repayAmount:this.currencyToPrecision(t,i),symbol:a.id},n=await this.privateMarginPostV2MarginIsolatedAccountRepay(this.extend(o,s)),d=this.safeDict(n,"data",{});return this.parseMarginLoan(d,r,a)}async repayCrossMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.currency(e),r={coin:s.id,repayAmount:this.currencyToPrecision(e,t)},a=await this.privateMarginPostV2MarginCrossedAccountRepay(this.extend(r,i)),o=this.safeDict(a,"data",{});return this.parseMarginLoan(o,s)}parseMarginLoan(e,t,i){let s,r=this.safeString(e,"coin"),a=this.safeString(e,"symbol");return void 0!==a&&(s=this.safeSymbol(a,i,void 0,"spot")),{id:this.safeString2(e,"loanId","repayId"),currency:this.safeCurrencyCode(r,t),amount:this.safeNumber2(e,"borrowAmount","repayAmount"),symbol:s,timestamp:void 0,datetime:void 0,info:e}}async fetchMyLiquidations(e,t,i,s={}){let r,o;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOptionBoolAndParams(s,"fetchMyLiquidations","paginate",!1);if(n)return await this.fetchPaginatedCallCursor("fetchMyLiquidations",e,t,i,d,"minId","idLessThan");void 0!==e&&(r=this.market(e));let[h,c]=this.handleMarketTypeAndParams("fetchMyLiquidations",r,d);if("spot"!==h)throw new a.NotSupported(this.id+" fetchMyLiquidations() supports spot margin markets only");let[l,u]=this.handleUntilOption("endTime",{},c);void 0!==t?l.startTime=t:l.startTime=this.milliseconds()-7776e6,void 0!==i&&(l.limit=i);let[f,p]=this.handleMarginModeAndParams("fetchMyLiquidations",u,"cross");if("isolated"===f){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyLiquidations() requires a symbol argument");l.symbol=this.safeString(r,"id"),o=await this.privateMarginGetV2MarginIsolatedLiquidationHistory(this.extend(l,p))}else"cross"===f&&(o=await this.privateMarginGetV2MarginCrossedLiquidationHistory(this.extend(l,p)));let m=this.safeDict(o,"data",{}),g=this.safeList(m,"resultList",[]);return this.parseLiquidations(g,r,t,i)}parseLiquidation(e,t){let i=this.safeString(e,"symbol"),s=this.safeInteger(e,"liqEndTime"),r=this.safeString2(e,"LiqFee","liqFee"),a=this.safeString(e,"totalDebt"),n=o.Y.stringAdd(r,a);return this.safeLiquidation({info:e,symbol:this.safeSymbol(i,t),contracts:void 0,contractSize:void 0,price:void 0,baseValue:void 0,quoteValue:this.parseNumber(n),timestamp:s,datetime:this.iso8601(s)})}async fetchIsolatedBorrowRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.privateMarginGetV2MarginIsolatedInterestRateAndLimit(this.extend(s,t)),a=this.safeInteger(r,"requestTime"),o=this.safeList(r,"data",[]),n=this.safeDict(o,0,{});return n.timestamp=a,this.parseIsolatedBorrowRate(n,i)}parseIsolatedBorrowRate(e,t){let i=this.safeString(e,"symbol"),s=this.safeSymbol(i,t,void 0,"spot"),r=this.safeString(e,"baseCoin"),a=this.safeString(e,"quoteCoin"),o=this.safeInteger(e,"timestamp");return{symbol:s,base:this.safeCurrencyCode(r),baseRate:this.safeNumber(e,"baseDailyInterestRate"),quote:this.safeCurrencyCode(a),quoteRate:this.safeNumber(e,"quoteDailyInterestRate"),period:864e5,timestamp:o,datetime:this.iso8601(o),info:e}}async fetchCrossBorrowRate(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.currency(e),r={coin:s.id},a={},[o,n]=await this.handleUTAAndParams(t,"fetchCrossBorrowRate",!1);if(!0===o)i=await this.publicUtaGetV3MarketMarginLoans(this.extend(r,n)),a=this.safeDict(i,"data",{});else{i=await this.privateMarginGetV2MarginCrossedInterestRateAndLimit(this.extend(r,n));let e=this.safeList(i,"data",[]);a=this.safeDict(e,0,{})}let d=this.safeInteger(i,"requestTime");return a.timestamp=d,this.parseBorrowRate(a,s)}parseBorrowRate(e,t){let i=this.safeString(e,"coin"),s=this.safeInteger(e,"timestamp");return{currency:this.safeCurrencyCode(i,t),rate:this.safeNumber2(e,"dailyInterestRate","dailyInterest"),period:864e5,timestamp:s,datetime:this.iso8601(s),info:e}}async fetchBorrowInterest(e,t,i,s,r={}){let o,n;void 0===this.markets&&await this.loadMarkets();let[d,h]=this.handleOptionBoolAndParams(r,"fetchBorrowInterest","paginate",!1);if(d)return await this.fetchPaginatedCallCursor("fetchBorrowInterest",t,i,s,h,"minId","idLessThan");void 0!==t&&(o=this.market(t));let c={};void 0!==e&&(c.coin=this.currency(e).id),void 0!==i?c.startTime=i:c.startTime=this.milliseconds()-7776e6,void 0!==s&&(c.limit=s);let[l,u]=this.handleMarginModeAndParams("fetchBorrowInterest",h,"cross");if("isolated"===l){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchBorrowInterest() requires a symbol argument");c.symbol=this.safeString(o,"id"),n=await this.privateMarginGetV2MarginIsolatedInterestHistory(this.extend(c,u))}else"cross"===l&&(n=await this.privateMarginGetV2MarginCrossedInterestHistory(this.extend(c,u)));let f=this.safeDict(n,"data",{}),p=this.safeList(f,"resultList",[]),m=this.parseBorrowInterests(p,o);return this.filterByCurrencySinceLimit(m,e,i,s)}parseBorrowInterest(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r="cross";void 0!==i&&(r="isolated");let a=this.safeInteger(e,"cTime");return{info:e,symbol:this.safeString(s,"symbol"),currency:this.safeCurrencyCode(this.safeString(e,"interestCoin")),interest:this.safeNumber(e,"interestAmount"),interestRate:this.safeNumber(e,"dailyInterestRate"),amountBorrowed:void 0,marginMode:r,timestamp:a,datetime:this.iso8601(a)}}async closePosition(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id},[o,n]=this.handleProductTypeAndParams(r,i),[d,h]=await this.handleUTAAndParams(n,"closePosition",!1);!0===d?(void 0!==t&&(a.posSide=t),a.category=o,s=await this.privateUtaPostV3TradeClosePositions(this.extend(a,h))):(void 0!==t&&(a.holdSide=t),a.productType=o,s=await this.privateMixPostV2MixOrderClosePositions(this.extend(a,h)));let c=this.safeDict(s,"data",{}),l=this.safeList2(c,"successList","list",[]);return this.parseOrder(l[0],r)}async closeAllPositions(e={}){let t;void 0===this.markets&&await this.loadMarkets();let i={},[s,r]=this.handleProductTypeAndParams(void 0,e),[a,o]=await this.handleUTAAndParams(r,"closeAllPositions",!1);!0===a?(i.category=s,t=await this.privateUtaPostV3TradeClosePositions(this.extend(i,o))):(i.productType=s,t=await this.privateMixPostV2MixOrderClosePositions(this.extend(i,o)));let n=this.safeDict(t,"data",{}),d=this.safeList2(n,"successList","list",[]);return this.parsePositions(d,void 0,o)}async fetchMarginMode(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),[s,r]=this.handleProductTypeAndParams(i,t),a={symbol:i.id,marginCoin:i.settleId,productType:s},o=await this.privateMixGetV2MixAccountAccount(this.extend(a,r)),n=this.safeDict(o,"data",{});return this.parseMarginMode(n,i)}parseMarginMode(e,t){let i=this.safeString(e,"marginMode");return"crossed"===i&&(i="cross"),{info:e,symbol:this.safeString(t,"symbol"),marginMode:i}}async fetchPositionsHistory(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o={};void 0!==e&&e.length>0&&(o.symbol=(r=this.market(e[0])).id),void 0!==t&&(o.startTime=t),void 0!==i&&(o.limit=i);let[n,d]=this.handleUntilOption("endTime",o,s),[h,c]=this.handleProductTypeAndParams(r,d),[l,u]=await this.handleUTAAndParams(c,"fetchPositionsHistory",!1);!0===l?(n.category=h,a=await this.privateUtaGetV3PositionHistoryPosition(this.extend(n,u))):a=await this.privateMixGetV2MixPositionHistoryPosition(this.extend(n,u));let f=this.safeDict(a,"data",{}),p=this.safeList(f,"list",[]),m=this.parsePositions(p,e,u);return this.filterBySinceLimit(m,t,i)}async fetchConvertQuote(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={fromCoin:e,toCoin:t,fromCoinSize:this.numberToString(i)},a=await this.privateConvertGetV2ConvertQuotedPrice(this.extend(r,s)),o=this.safeDict(a,"data",{}),n=this.safeString(o,"fromCoin",e),d=this.currency(n),h=this.safeString(o,"toCoin",t),c=this.currency(h);return this.parseConversion(o,d,c)}async createConvertTrade(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let o=this.safeString2(r,"price","cnvtPrice");if(void 0===o)throw new a.ArgumentsRequired(this.id+" createConvertTrade() requires a price parameter");let n=this.safeString2(r,"toAmount","toCoinSize");if(void 0===n)throw new a.ArgumentsRequired(this.id+" createConvertTrade() requires a toAmount parameter");let d=this.omit(r,["price","toAmount"]),h={traceId:e,fromCoin:t,toCoin:i,fromCoinSize:this.numberToString(s),toCoinSize:n,cnvtPrice:o},c=await this.privateConvertPostV2ConvertTrade(this.extend(h,d)),l=this.safeDict(c,"data",{}),u=this.safeString(l,"toCoin",i),f=this.currency(u);return this.parseConversion(l,void 0,f)}async fetchConvertTradeHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={},a=this.milliseconds();void 0!==t?r.startTime=t:r.startTime=a-864e5;let o=this.safeString2(s,"endTime","until");void 0!==o?r.endTime=o:r.endTime=a,void 0!==i&&(r.limit=i);let n=this.omit(s,"until"),d=await this.privateConvertGetV2ConvertConvertRecord(this.extend(r,n)),h=this.safeDict(d,"data",{}),c=this.safeList(h,"dataList",[]);return this.parseConversions(c,e,"fromCoin","toCoin",t,i)}parseConversion(e,t,i){let s=this.safeInteger(e,"ts"),r=this.safeString(e,"fromCoin"),a=this.safeCurrencyCode(r,t),o=this.safeString(e,"toCoin"),n=this.safeCurrencyCode(o,i);return{info:e,timestamp:s,datetime:this.iso8601(s),id:this.safeString2(e,"id","traceId"),fromCurrency:a,fromAmount:this.safeNumber(e,"fromCoinSize"),toCurrency:n,toAmount:this.safeNumber(e,"toCoinSize"),price:this.safeNumber(e,"cnvtPrice"),fee:this.safeNumber(e,"fee")}}async fetchConvertCurrencies(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateConvertGetV2ConvertCurrencies(e),i={},s=this.safeList(t,"data",[]);for(let e=0;e<s.length;e++){let t=s[e],r=this.safeString(t,"coin"),a=this.safeCurrencyCode(r);void 0!==a&&(i[a]={info:t,id:r,code:a,networks:void 0,type:void 0,name:void 0,active:void 0,deposit:void 0,withdraw:this.safeNumber(t,"available"),fee:void 0,precision:void 0,limits:{amount:{min:this.safeNumber(t,"minAmount"),max:this.safeNumber(t,"maxAmount")},withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},created:void 0})}return i}async fetchFundingInterval(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),[r,a]=this.handleProductTypeAndParams(s,t),o={symbol:s.id},[n,d]=await this.handleUTAAndParams(a,"fetchFundingInterval",!1);!0===n?i=await this.publicUtaGetV3MarketCurrentFundRate(this.extend(o,d)):(o.productType=r,i=await this.publicMixGetV2MixMarketFundingTime(this.extend(o,d)));let h=this.safeList(i,"data",[]),c=this.safeDict(h,0,{});return this.parseFundingRate(c,s)}async fetchLongShortRatioHistory(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={symbol:o.id};void 0!==t&&(n.period=t),a=!0===o.swap||!0===o.future?await this.publicMixGetV2MixMarketAccountLongShort(this.extend(n,r)):await this.publicMarginGetV2MarginMarketLongShortRatio(this.extend(n,r));let d=this.safeList(a,"data",[]);return this.parseLongShortRatioHistory(d,o)}parseLongShortRatio(e,t){let i=this.safeString(e,"symbol"),s=this.safeIntegerOmitZero(e,"ts");return{info:e,symbol:this.safeSymbol(i,t,void 0,"contract"),timestamp:s,datetime:this.iso8601(s),timeframe:void 0,longShortRatio:this.safeNumber2(e,"longShortRatio","longShortAccountRatio")}}handleErrors(e,t,i,s,r,o,n,d,h){if(null==n)return;let c=this.safeString2(n,"err_msg","msg"),l=this.id+" "+o,u=void 0!==c&&""!==c&&"success"!==c;u&&(this.throwExactlyMatchedException(this.exceptions.exact,c,l),this.throwBroadlyMatchedException(this.exceptions.broad,c,l));let f=this.safeString2(n,"code","err_code"),p=void 0!==f&&"00000"!==f;if(p&&this.throwExactlyMatchedException(this.exceptions.exact,f,l),p||u)throw new a.ExchangeError(l)}nonce(){let e=this.safeInteger(this.options,"timeDifference");if(void 0===e)throw new a.ExchangeError(this.id+' nonce() requires a numeric options["timeDifference"]');return this.milliseconds()-e}sign(e,t=[],i="GET",r={},o,n){let d,h,c="private"===t[0],l=t[1],u="/api/"+this.implodeParams(e,r),f=this.safeString(this.urls.api,l);if(void 0===f)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let p=this.implodeHostname(f)+u,m=this.omit(r,this.extractParams(e));if(!c&&"GET"===i&&Object.keys(m).length>0&&(p=p+"?"+this.urlencode(m)),c){this.checkRequiredCredentials();let e=this.nonce().toString(),t=e+i+u;if("POST"===i)t+=d=this.json(r);else if(Object.keys(r).length>0){let e=this.keysort(r),i="?"+this.urlencode(e,!0);i.indexOf("%24")>-1&&(i=i.replace("%24","$")),p+=i,t+="?"+this.rawencode(e,!0)}let a=this.hmac(this.encode(t),this.encode(this.secret),s.sc,"base64"),o=this.safeString(this.options,"broker");h={"ACCESS-KEY":this.apiKey,"ACCESS-SIGN":a,"ACCESS-TIMESTAMP":e,"ACCESS-PASSPHRASE":this.password,"X-CHANNEL-API-CODE":o},"POST"===i&&(h["Content-Type"]="application/json")}let g=void 0===h?o:h;if(!0===this.safeBool2(this.options,"sandboxMode","sandbox",!1)&&"v2/public/time"!==e&&"v3/market/current-fund-rate"!==e){void 0===g&&(g={});let e=this.safeString(r,"productType");"SCOIN-FUTURES"!==e&&"SUSDT-FUTURES"!==e&&"SUSDC-FUTURES"!==e&&(g.PAPTRADING="1")}return{url:p,method:i,body:void 0===d?n:d,headers:g}}}i.d(t,{A:()=>n})},3267(e,t,i){"use strict";var s=i(4721),r=i(6148),a=i(8748),o=i(1453),n=i(7749);class d extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bithumb",name:"Bithumb",countries:["KR"],rateLimit:8.334,pro:!0,has:{CORS:!0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!1,closePosition:!1,createDepositAddress:!0,createMarketBuyOrderWithCost:!0,createMarketOrder:!0,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createReduceOnlyOrder:!1,createTwapOrder:!0,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCanceledOrders:!0,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDeposit:!0,fetchDepositAddress:!0,fetchDepositAddresses:!0,fetchDeposits:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchTransfer:!1,fetchTransfers:!1,fetchVolatilityHistory:!1,fetchWithdrawal:!0,fetchWithdrawals:!0,fetchWithdrawalWhitelist:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,withdraw:!0},hostname:"bithumb.com",urls:{logo:"https://github.com/user-attachments/assets/c9e0eefb-4777-46b9-8f09-9d7f7c4af82d",api:{public:"https://api.{hostname}",private:"https://api.{hostname}"},www:"https://www.bithumb.com",doc:"https://apidocs.bithumb.com",fees:"https://en.bithumb.com/customer_support/info_fee"},api:{public:{get:{"public/ticker/ALL_{quoteId}":{cost:1},"public/ticker/{baseId}_{quoteId}":{cost:1},"public/orderbook/ALL_{quoteId}":{cost:1},"public/orderbook/{baseId}_{quoteId}":{cost:1},"public/transaction_history/{baseId}_{quoteId}":{cost:1},"public/network-info":{cost:1},"public/assetsstatus/multichain/ALL":{cost:1},"public/assetsstatus/multichain/{currency}":{cost:1},"public/withdraw/minimum/ALL":{cost:1},"public/withdraw/minimum/{currency}":{cost:1},"public/assetsstatus/ALL":{cost:1},"public/assetsstatus/{baseId}":{cost:1},"public/candlestick/{baseId}_{quoteId}/{interval}":{cost:1},"v1/market/all":{cost:1},"v1/candles/minutes/{unit}":{cost:1},"v1/candles/days":{cost:1},"v1/candles/weeks":{cost:1},"v1/candles/months":{cost:1},"v1/trades/ticks":{cost:1},"v1/ticker":{cost:1},"v1/orderbook":{cost:1},"v1/market/virtual_asset_warning":{cost:1},"v1/notices":{cost:1},"v2/fee/inout/{currency}":{cost:1}}},private:{get:{"v1/accounts":{cost:1},"v1/orders/chance":{cost:1},"v1/order":{cost:1},"v1/orders":{cost:1},"v2/orders/pending":{cost:1},"v2/orders/history":{cost:1},"v1/twap":{cost:1},"v1/withdraws":{cost:1},"v1/withdraws/krw":{cost:1},"v1/withdraw":{cost:1},"v1/withdraws/chance":{cost:1},"v1/withdraws/coin_addresses":{cost:1},"v1/deposits":{cost:1},"v1/deposits/krw":{cost:1},"v1/deposit":{cost:1},"v1/deposits/coin_addresses":{cost:1},"v1/deposits/coin_address":{cost:1},"v1/status/wallet":{cost:1},"v1/api_keys":{cost:1}},post:{"info/account":{cost:1},"info/balance":{cost:1},"info/wallet_address":{cost:1},"info/ticker":{cost:1},"info/orders":{cost:1},"info/user_transactions":{cost:1},"info/order_detail":{cost:1},"trade/place":{cost:5},"trade/cancel":{cost:5},"trade/btc_withdrawal":{cost:1},"trade/krw_deposit":{cost:1},"trade/krw_withdrawal":{cost:1},"trade/market_buy":{cost:1},"trade/market_sell":{cost:1},"trade/stop_limit":{cost:1},"v2/orders":{cost:1},"v2/orders/batch":{cost:6},"v2/orders/cancel":{cost:6},"v2/orders/search":{cost:1},"v1/twap":{cost:1},"v1/withdraws/coin":{cost:1},"v1/withdraws/krw":{cost:1},"v1/deposits/generate_coin_address":{cost:1},"v1/deposits/krw":{cost:1}},delete:{"v2/order":{cost:1},"v1/twap":{cost:1},"v1/withdraws/coin":{cost:1}}}},fees:{trading:{maker:this.parseNumber("0.0025"),taker:this.parseNumber("0.0025")}},precisionMode:3,features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{GTC:!0,IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyRequiresPrice:!0,marketBuyByCost:!0,selfTradePrevention:!1,iceberg:!1},createOrders:{max:20,marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{GTC:!0,IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,iceberg:!1},fetchMyTrades:void 0,fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:100,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:100,daysBack:0,untilDays:0,trigger:!1,trailing:!1,symbolRequired:!1},fetchCanceledOrders:{marginMode:!1,limit:100,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:100,daysBack:0,daysBackCanceled:0,untilDays:0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:200}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},exceptions:{400:o.BadRequest,"Bad Request(SSL)":o.BadRequest,"Bad Request(Bad Method)":o.BadRequest,"Bad Request.(Auth Data)":o.AuthenticationError,"Not Member":o.AuthenticationError,"Invalid Apikey":o.AuthenticationError,"Method Not Allowed.(Access IP)":o.PermissionDenied,"Method Not Allowed.(BTC Adress)":o.InvalidAddress,"Method Not Allowed.(Access)":o.PermissionDenied,"Database Fail":o.ExchangeNotAvailable,"Invalid Parameter":o.BadRequest,5600:o.ExchangeError,"Unknown Error":o.ExchangeError,"After May 23th, recent_transactions is no longer, hence users will not be able to connect to recent_transactions":o.ExchangeError,"Missing request parameter error. Check the required parameters!":o.BadRequest},timeframes:{"1m":1,"3m":3,"5m":5,"10m":10,"15m":15,"30m":30,"1h":60,"4h":240},options:{generation:2,fetchTickersGeneration2MaxMarketIdsPerRequest:300,createMarketBuyOrderRequiresPrice:!0,quoteCurrencies:{KRW:{limits:{cost:{min:500,max:5e9}}},BTC:{limits:{cost:{min:2e-4,max:100}}}}},commonCurrencies:{FTC:"FTC2",SOC:"Soda Coin"}})}safeMarket(e,t,i,s){return super.safeMarket(e,t,i,"spot")}amountToPrecision(e,t){let i=this.market(e);return this.decimalToPrecision(t,0,i.precision.amount,2)}getGen2MarketId(e){let t=this.safeString(e,"id");return void 0!==t&&t.indexOf("-")>=0?t:this.safeString2(e,"quoteId","quote")+"-"+this.safeString2(e,"baseId","base")}async fetchMarkets(e={}){let t=[],i={},[s,r]=this.handleOptionIntegerAndParams(e,"fetchMarkets","generation",2);if(2===s){i.isDetails=!0;let e=await this.publicGetV1MarketAll(this.extend(i,r));for(let i=0;i<e.length;i++){let s,r,a,o,n=e[i],d=this.safeString(n,"market");if(void 0!==d){let e=d.split("-");s=e[1],r=e[0],a=this.safeCurrencyCode(s),o=this.safeCurrencyCode(r)}void 0!==a&&void 0!==o&&t.push({id:d,symbol:a+"/"+o,base:a,quote:o,settle:void 0,baseId:s,quoteId:r,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:!0,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:parseInt("4"),price:parseInt("4")},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:n})}}else{let e=this.safeDict(this.options,"quoteCurrencies",{}),s=Object.keys(e),a=[];for(let e=0;e<s.length;e++)i.quoteId=s[e],a.push(this.publicGetPublicTickerALLQuoteId(this.extend(i,r)));let o=await Promise.all(a);for(let i=0;i<s.length;i++){let r=s[i],a=this.safeDict(o,i),n=this.safeDict(a,"data",{}),d=this.safeDict(e,r,{}),h=Object.keys(n);for(let e=0;e<h.length;e++){let i=h[e];if("date"===i)continue;let s=n[i],a=this.safeCurrencyCode(i);if(void 0===a)continue;let o=!0;Array.isArray(s)&&0===s.length&&(o=!1);let c=this.deepExtend({id:i,symbol:a+"/"+r,base:a,quote:r,settle:void 0,baseId:i,quoteId:r,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:o,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:parseInt("4"),price:parseInt("4")},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{}},created:void 0,info:s},d);t.push(c)}}}return t}parseBalance(e){let t={info:e},i=this.safeDict(e,"data");if(void 0!==i){let e=Object.keys(this.currencies);for(let s=0;s<e.length;s++){let r=e[s],a=this.account(),o=this.currency(r),n=this.safeStringLower(o,"id");a.total=this.safeString(i,"total_"+n),a.used=this.safeString(i,"in_use_"+n),a.free=this.safeString(i,"available_"+n),t[r]=a}}else for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.account(),a=this.safeString(s,"currency"),o=this.safeCurrencyCode(a);void 0!==o&&(r.free=this.safeString(s,"balance"),r.used=this.safeString(s,"locked"),t[o]=r)}return this.safeBalance(t)}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionIntegerAndParams(e,"fetchBalance","generation",2);return t=2===i?await this.privateGetV1Accounts(s):await this.privatePostInfoBalance(this.extend({currency:"ALL"},s)),this.parseBalance(t)}async fetchOrderBook(e,t,i={}){let s,r,a;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionIntegerAndParams(i,"fetchOrderBook","generation",2),d=this.market(e),h={};if(2===o){h.markets=this.getGen2MarketId(d),s=await this.publicGetV1Orderbook(this.extend(h,n));let e=this.safeDict(s,0,{});a=this.safeInteger(e,"timestamp");let t=this.safeList(e,"orderbook_units",[]),i=[],o=[];for(let e=0;e<t.length;e++){let s=this.safeDict(t,e);i.push({price:this.safeString(s,"bid_price"),quantity:this.safeString(s,"bid_size")}),o.push({price:this.safeString(s,"ask_price"),quantity:this.safeString(s,"ask_size")})}r={bids:i,asks:o}}else h.baseId=d.baseId,h.quoteId=d.quoteId,void 0!==t&&(h.count=t),s=await this.publicGetPublicOrderbookBaseIdQuoteId(this.extend(h,n)),r=this.safeDict(s,"data",{}),a=this.safeInteger(r,"timestamp");return this.parseOrderBook(r,e,a,"bids","asks","price","quantity")}parseTicker(e,t){let i=this.safeInteger2(e,"date","trade_timestamp"),s=this.safeString(e,"market"),r=this.safeSymbol(s,t),a=this.safeString2(e,"closing_price","trade_price"),o=this.safeString2(e,"signed_change_price","change_price"),d=this.safeString2(e,"signed_change_rate","change_rate"),h=this.safeString(e,"opening_price"),c=this.omitZero(h);if(void 0!==s&&void 0!==c&&void 0!==a){let e=n.Y.stringSub(a,h);void 0!==o&&n.Y.stringEq(o,"0")&&!n.Y.stringEq(e,"0")&&(o=e,d=void 0)}let l=this.safeString2(e,"max_price","high_price"),u=this.safeString2(e,"min_price","low_price");return void 0!==a&&void 0!==l&&n.Y.stringGt(a,l)&&(l=a),void 0!==a&&void 0!==u&&n.Y.stringLt(a,u)&&(u=a),this.safeTicker({symbol:r,timestamp:i,datetime:this.iso8601(i),high:l,low:u,bid:this.safeString(e,"buy_price"),bidVolume:this.safeString(e,"acc_bid_volume"),ask:this.safeString(e,"sell_price"),askVolume:this.safeString(e,"acc_ask_volume"),vwap:void 0,open:h,close:a,last:a,previousClose:this.safeString(e,"prev_closing_price"),change:o,percentage:d,average:void 0,baseVolume:this.safeString2(e,"units_traded_24H","acc_trade_volume_24h"),quoteVolume:this.safeString2(e,"acc_trade_value_24H","acc_trade_price_24h"),info:e},t)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionIntegerAndParams(t,"fetchTickers","generation",2),r={},a={};if(2===i){let t=[],i=void 0===e?this.symbols:e,o=i.length;for(let e=0;e<o;e++){let s=this.market(i[e]);t.push(this.getGen2MarketId(s))}let n=t.length;if(0===n)return a;let d=[],h=[];if(void 0!==e)r.markets=t.join(","),d.push(t),h.push(this.publicGetV1Ticker(this.extend(r,s)));else{let e=this.safeInteger(this.options,"fetchTickersGeneration2MaxMarketIdsPerRequest",300);(void 0===e||e<1)&&(e=300);let i=[];for(let a=0;a<n;a++){i.push(t[a]);let o=i.length,c=a===n-1;(o>=e||c)&&(d.push(i),r.markets=i.join(","),h.push(this.publicGetV1Ticker(this.extend(r,s))),i=[])}}let c=await Promise.all(h),l=c.length;for(let e=0;e<l;e++){let t,i=c[e];this.isDictionary(i)&&"data"in i&&void 0!==i.data&&(i=i.data);let s=this.safeList(d,e,[]),r=this.safeString(s,0);void 0!==r&&void 0===this.safeString(s,1)&&(t=r);let o=[];if(Array.isArray(i))o=i;else if(this.isDictionary(i))if("market"in i||"trade_date"in i||"trade_timestamp"in i)o=[i];else{let e=Object.keys(i);for(let t=0;t<e.length;t++){let s=e[t],r=this.safeDict(i,s);void 0!==r&&(r.market=this.safeString(r,"market",s),o.push(r))}}for(let e=0;e<o.length;e++){let i=o[e],s=this.safeString(i,"market",t);if(void 0===s)continue;let r=this.safeMarket(s),n=this.safeSymbol(s,r);void 0!==n&&(a[n]=this.parseTicker(i,r))}}}else{let t=this.safeDict(this.options,"quoteCurrencies",{}),i=Object.keys(t);if(void 0!==e){let s={};for(let i=0;i<e.length;i++){let r=e[i],a=this.market(r),o=this.safeString(a,"quoteId");void 0!==o&&o in t&&(s[o]=!0)}let r=Object.keys(s);void 0!==this.safeString(r,0)&&(i=r)}let o=[];for(let e=0;e<i.length;e++)r.quoteId=i[e],o.push(this.publicGetPublicTickerALLQuoteId(this.extend(r,s)));let n=await Promise.all(o);for(let e=0;e<i.length;e++){let t=i[e],s=this.safeDict(n,e),r=this.safeDict(s,"data",{}),o=this.safeInteger(r,"date"),d=Object.keys(this.omit(r,"date"));for(let e=0;e<d.length;e++){let i=d[e],s=r[i],n=this.safeCurrencyCode(i);if(void 0===n||void 0===t)continue;let h=n+"/"+t,c=this.safeMarket(h);s.date=o,a[h]=this.parseTicker(s,c)}}}return this.filterByArrayTickers(a,"symbol",e)}async fetchTicker(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleOptionIntegerAndParams(t,"fetchTicker","generation",2),a=this.market(e),o={},n={};return 2===s?(o.markets=this.getGen2MarketId(a),i=await this.publicGetV1Ticker(this.extend(o,r)),n=this.safeDict(i,0,{})):(o.baseId=a.baseId,o.quoteId=a.quoteId,i=await this.publicGetPublicTickerBaseIdQuoteId(this.extend(o,r)),n=this.safeDict(i,"data",{})),this.parseTicker(n,a)}parseOHLCV(e,t){return[Array.isArray(e)?this.safeInteger2(e,0,"timestamp"):this.parse8601(this.safeString2(e,"candle_date_time_utc","candle_date_time_kst")),this.safeNumber2(e,1,"opening_price"),this.safeNumber2(e,3,"high_price"),this.safeNumber2(e,4,"low_price"),this.safeNumber2(e,2,"trade_price"),this.safeNumber2(e,5,"candle_acc_trade_volume")]}async fetchOHLCV(e,t="1m",i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOptionIntegerAndParams(r,"fetchOHLCV","generation",2),h=this.market(e),c={},l=[];if(2===n){if(c.market=this.getGen2MarketId(h),void 0!==s&&(c.count=s),"1d"===t)a=await this.publicGetV1CandlesDays(this.extend(c,d));else if("1w"===t)a=await this.publicGetV1CandlesWeeks(this.extend(c,d));else if("1M"===t)a=await this.publicGetV1CandlesMonths(this.extend(c,d));else{let e=this.safeInteger(this.timeframes,t);if(void 0===e)throw new o.BadRequest(this.id+" fetchOHLCV() unsupported timeframe "+t);c.unit=e,a=await this.publicGetV1CandlesMinutesUnit(this.extend(c,d))}l=a}else c.interval=this.safeString({"1m":"1m","3m":"3m","5m":"5m","10m":"10m","30m":"30m","1h":"1h","6h":"6h","12h":"12h","1d":"24h","1w":"1w","1M":"1mm"},t,t),c.baseId=h.baseId,c.quoteId=h.quoteId,a=await this.publicGetPublicCandlestickBaseIdQuoteIdInterval(this.extend(c,d)),l=this.safeList(a,"data",[]);return this.parseOHLCVs(l,h,t,i,s)}parseTrade(e,t){let i,s=this.safeInteger(e,"timestamp"),r=void 0!==s,a=this.safeString(e,"transaction_date");if(void 0!==a){let t=a.split(" ");if(t.length>1){let e=t[0],i=t[1];i.length<8&&(i="0"+i),s=this.parse8601(e+" "+i)}else s=this.safeIntegerProduct(e,"transaction_date",.001)}void 0===s||r||(s-=324e5);let o=this.safeStringLower2(e,"ask_bid","type");o="bid"===o?"buy":"ask"===o?"sell":void 0;let n=this.safeString2(e,"cont_no","sequential_id"),d=this.safeString(e,"market"),h=this.safeMarket(d,t),c=this.safeString2(e,"price","trade_price"),l=this.safeString(e,"trade_volume");void 0===l&&(l=this.fixCommaNumber(this.safeString2(e,"units_traded","units")));let u=this.safeString(e,"total"),f=this.safeString(e,"fee");if(void 0!==f){let t=this.safeString(e,"fee_currency");i={cost:f,currency:this.commonCurrencyCode(t)}}return this.safeTrade({id:n,info:e,timestamp:s,datetime:this.iso8601(s),symbol:h.symbol,order:void 0,type:void 0,side:o,takerOrMaker:void 0,price:c,amount:l,cost:u,fee:i},h)}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionIntegerAndParams(s,"fetchTrades","generation",2),n=this.market(e),d={};void 0!==i&&(d.count=i);let h=[];return 2===a?(d.market=this.getGen2MarketId(n),h=r=await this.publicGetV1TradesTicks(this.extend(d,o))):(d.baseId=n.baseId,d.quoteId=n.quoteId,r=await this.publicGetPublicTransactionHistoryBaseIdQuoteId(this.extend(d,o)),h=this.safeList(r,"data",[])),this.parseTrades(h,n,t,i)}async createOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionIntegerAndParams(t,"createOrders","generation",2);if(2!==i)throw new o.BadRequest(this.id+" createOrders is only supported for the generation 2 API");if(0===e.length)throw new o.ArgumentsRequired(this.id+" createOrders() requires a non-empty orders array");let r=[],a=[];for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s=this.safeString(i,"symbol");if(void 0===s)throw new o.ArgumentsRequired(this.id+" createOrders() requires each order to have a symbol");a.push(s);let n=this.safeString(i,"type");if(void 0===n)throw new o.ArgumentsRequired(this.id+" createOrders() requires each order to have a type");let d=this.safeString(i,"side");if(void 0===d)throw new o.ArgumentsRequired(this.id+" createOrders() requires each order to have a side");let h=this.safeValue(i,"amount"),c=this.safeValue(i,"price"),l=this.safeDict(i,"params",{}),u=this.createOrderRequest(s,n,d,h,c,l);r.push(u)}a=this.marketSymbols(a,void 0,!1,!0,!0);let n=this.market(a[0]),d=await this.privatePostV2OrdersBatch(this.extend({batch_orders:r},s)),h=this.safeList(d,"batch_orders_response",[]);return this.parseOrders(h,n)}createOrderRequest(e,t,i,s,r,a={}){let d,h=this.market(e),c={market:this.getGen2MarketId(h)};if("buy"===i)d="bid";else if("sell"===i)d="ask";else throw new o.InvalidOrder(this.id+" createOrder() invalid side "+i);c.side=d;let l=this.safeString2(a,"timeInForce","time_in_force"),u=void 0===l?"GTC":l,f=void 0===l?a:this.omit(a,"timeInForce"),[p,m]=this.handlePostOnly("market"===t,!1,f),g=p||"PO"===u,v=m;if(g&&(v=this.omit(m,"postOnly")),g?c.time_in_force="post_only":"FOK"===u?c.time_in_force="fok":"IOC"===u&&(c.time_in_force="ioc"),"limit"===t)c.price=this.priceToPrecision(e,r),c.volume=this.amountToPrecision(e,s),c.order_type="limit";else{let t;if("buy"===i){t="price";let i=this.safeString(v,"cost"),[a,d]=this.handleOptionBoolAndParams(this.omit(v,"cost"),"createOrder","createMarketBuyOrderRequiresPrice",!0);if(v=d,a)if(void 0===r&&void 0===i)throw new o.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument");else{let e=this.numberToString(s),t=this.numberToString(r);i=n.Y.stringMul(e,t)}else i=void 0===i?this.numberToString(s):i;c.price=this.priceToPrecision(e,i)}else c.volume=this.amountToPrecision(e,s),t="market";c.order_type=t}let y=this.safeString2(v,"clientOrderId","client_order_id");void 0!==y&&(c.client_order_id=y);let b=void 0!==y?this.omit(v,"clientOrderId"):v;return this.extend(c,b)}async createOrder(e,t,i,s,r,a={}){let n;void 0===this.markets&&await this.loadMarkets();let[d,h]=this.handleOptionIntegerAndParams(a,"createOrder","generation",2),c={},l=this.market(e);if(2===d)c=this.createOrderRequest(e,t,i,s,r,h),n=await this.privatePostV2Orders(c);else if(c.order_currency=l.base,c.payment_currency=l.quote,c.units=this.amountToPrecision(e,s),"limit"===t){let t;c.price=this.priceToPrecision(e,r),t="buy"===i?"bid":"ask",c.type=t,n=await this.privatePostTradePlace(this.extend(c,h))}else n="buy"===i?await this.privatePostTradeMarketBuy(this.extend(c,h)):await this.privatePostTradeMarketSell(this.extend(c,h));let u=this.safeString(n,"order_id");if(void 0===u)throw new o.InvalidOrder(this.id+" createOrder() did not return an order id");return this.extend(this.parseOrder(n,l),{info:n,symbol:e,type:t,side:i,id:u})}async createMarketBuyOrderWithCost(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleOptionIntegerAndParams(i,"createMarketBuyOrderWithCost","generation",2);if(2!==s)throw new o.BadRequest(this.id+" createMarketBuyOrderWithCost() is only supported for the generation 2 API");return r.createMarketBuyOrderRequiresPrice=!1,await this.createOrder(e,"market","buy",t,void 0,r)}async createTwapOrder(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let[a,d]=this.handleOptionIntegerAndParams(r,"createTwapOrder","generation",2);if(2!==a)throw new o.BadRequest(this.id+" createTwapOrder() is only supported for the generation 2 API");let h=this.market(e),c=this.numberToString(s),l=n.Y.stringDiv(c,"1000"),u={market:this.getGen2MarketId(h),duration:l};void 0!==i&&(u.volume=this.amountToPrecision(e,i)),u.side="buy"===t?"bid":"ask";let f=await this.privatePostV1Twap(this.extend(u,d));return this.parseOrder(f,h)}async fetchOrder(e,t,i={}){let s,r,a;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOptionIntegerAndParams(i,"fetchOrder","generation",2);void 0!==t&&(s=this.market(t));let h=this.safeBool(d,"twap",!1),c=this.omit(d,"twap"),l={};if(2===n)if(h){void 0!==s&&(l.market=this.getGen2MarketId(s)),l.uuids=[e],r=await this.privateGetV1Twap(this.extend(l,c));let t=this.safeList(r,"orders",[]);a=this.safeDict(t,0,{})}else{let t=this.safeString2(c,"clientOrderId","client_order_id"),i=void 0!==t?this.omit(c,["clientOrderId"]):c;void 0!==t?l.client_order_id=t:l.uuid=e,a=r=await this.privateGetV1Order(this.extend(l,i))}else{if(void 0===t)throw new o.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");let i=s,n=this.safeString(i,"base"),d=this.safeString(i,"quote");if(void 0===n||void 0===d)throw new o.ArgumentsRequired(this.id+" fetchOrder() requires a market with defined base and quote");l.order_id=e,l.order_currency=n,l.payment_currency=d,r=await this.privatePostInfoOrderDetail(this.extend(l,c)),a=this.safeDict(r,"data")}let u=this.extend(a,{order_id:e});return this.parseOrder(u,s)}parseOrderStatus(e){return this.safeString({Pending:"open",Completed:"closed",Cancel:"canceled",wait:"open",watch:"open",done:"closed",cancel:"canceled",progress:"open"},e,e)}parseOrder(e,t){let i,s,r,a,o,d=this.safeString(e,"created_at");if(void 0!==d)if(d.indexOf("+09:00")>-1){let e=d.replace("+09:00","Z"),t=this.parse8601(e);i=void 0!==t?t-324e5:this.parse8601(d)}else i=this.parse8601(d);else i=this.safeIntegerProduct(e,"order_date",.001),d=this.iso8601(i);let h=this.safeString2(e,"type","side");"bid"===h?s="buy":"ask"===h&&(s="sell");let c=this.parseOrderStatus(this.safeString2(e,"order_status","state")),l=this.safeString2(e,"order_price","price"),u=this.safeString2(e,"order_type","ord_type"),f=this.safeString(e,"progress_count");void 0===u&&void 0!==l&&void 0===f&&(u=n.Y.stringEquals(l,"0")?"market":"limit");let p=this.fixCommaNumber(this.safeStringN(e,["order_qty","units","volume"])),m=this.fixCommaNumber(this.safeString2(e,"units_remaining","remaining_volume"));void 0===m&&("closed"===c?m="0":"canceled"!==c&&(m=p));let g=this.safeString(e,"order_currency"),v=this.safeString(e,"payment_currency"),y=this.safeCurrencyCode(g),b=this.safeCurrencyCode(v);void 0!==y&&void 0!==b&&(r=y+"/"+b);let w=this.safeString(e,"market"),k=void 0===r?this.safeMarket(w,t):t;void 0===r&&(r=this.safeString(k,"symbol"));let S=this.safeStringN(e,["order_id","uuid","algo_order_id"]),O=this.safeList2(e,"contract","trades",[]),T=this.safeNumber(e,"reserved_fee");if(void 0!==T){let e;void 0!==k&&(e=this.safeString(k,"quote")),a={currency:e,cost:T,rate:void 0}}let P=this.safeStringUpper(e,"time_in_force");return"POST_ONLY"===P&&(P="PO",o=!0),this.safeOrder({info:e,id:S,clientOrderId:this.safeString(e,"client_order_id"),timestamp:i,datetime:d,lastTradeTimestamp:void 0,symbol:r,type:u,timeInForce:P,postOnly:o,side:s,price:l,triggerPrice:void 0,amount:p,cost:void 0,average:this.safeNumber(e,"avg_trade_price"),filled:void 0,remaining:m,status:c,fee:a,trades:O},k)}async fetchOpenOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOptionIntegerAndParams(s,"fetchOpenOrders","generation",2),h=void 0===i?100:i,c={};if(2===n){this.safeBool(d,"twap",!1)?d.state="progress":d.state="wait";let s=await this.fetchOrders(e,t,i,d);return this.filterBySinceLimit(s,t,i)}if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchOpenOrders() requires a symbol argument");r=this.market(e),void 0!==t&&(c.after=t),c.count=h,c.order_currency=r.base,c.payment_currency=r.quote,a=await this.privatePostInfoOrders(this.extend(c,d));let l=this.safeList(a,"data",[]);return this.parseOrders(l,r,t,h)}async fetchOrders(e,t,i,s={}){let r,a,n,d;void 0===this.markets&&await this.loadMarkets();let[h,c]=this.handleOptionIntegerAndParams(s,"fetchOrders","generation",2);if(2!==h)throw new o.BadRequest(this.id+" fetchOrders is only supported for the generation 2 API");let l={},u=this.safeBool(c,"twap",!1),f=this.omit(c,"twap"),p=void 0!==(r=u?void 0:this.safeList2(f,"client_order_ids","clientOrderIds"))?this.omit(f,["clientOrderIds"]):f;return void 0!==r&&(l.client_order_ids=r),void 0!==e&&(a=this.market(e),l.market=this.getGen2MarketId(a)),void 0!==i&&(l.limit=i),u?(n=await this.privateGetV1Twap(this.extend(l,p)),d=this.safeList(n,"orders",[])):d=n=await this.privateGetV1Orders(this.extend(l,p)),this.parseOrders(d,a,t,i)}async fetchClosedOrders(e,t,i,s={}){s.state="done";let r=await this.fetchOrders(e,t,i,s);return this.filterBySinceLimit(r,t,i)}async fetchCanceledOrders(e,t,i,s={}){s.state="cancel";let r=await this.fetchOrders(e,t,i,s);return this.filterBySinceLimit(r,t,i)}async cancelOrder(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets();let[a,n]=this.handleOptionIntegerAndParams(i,"cancelOrder","generation",2);void 0!==t&&(s=this.market(t));let d={},h=this.safeBool(n,"twap",!1),c=this.omit(n,"twap"),l=this.safeString2(c,"clientOrderId","client_order_id"),u=!h&&2===a&&void 0!==l,f=c;if(u&&(f=this.omit(c,["clientOrderId"])),h?d.algo_order_id=e:u?d.client_order_id=l:d.order_id=e,2===a)r=h?await this.privateDeleteV1Twap(this.extend(d,f)):await this.privateDeleteV2Order(this.extend(d,f));else{let e;if(void 0===t)throw new o.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");let i=s,a=this.safeString(i,"base"),n=this.safeString(i,"quote");if(void 0===a||void 0===n)throw new o.ArgumentsRequired(this.id+" cancelOrder() requires a market with defined base and quote");if(!("side"in f))throw new o.ArgumentsRequired(this.id+" cancelOrder() requires a `side` parameter (sell or buy)");e="buy"===this.safeString(f,"side")?"bid":"ask";let h=this.omit(f,"side");d.type=e,d.order_currency=a,d.payment_currency=n,r=await this.privatePostTradeCancel(this.extend(d,h))}return this.extend(this.parseOrder(r,s),{id:e})}async cancelOrders(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionIntegerAndParams(i,"cancelOrders","generation",2);if(2!==r)throw new o.BadRequest(this.id+" cancelOrders is only supported for the generation 2 API");void 0!==t&&(s=this.market(t));let n={},d=this.safeList2(a,"client_order_ids","clientOrderIds"),h=void 0!==d?this.omit(a,["clientOrderIds"]):a;void 0!==d?n.client_order_ids=d:n.order_ids=e;let c=await this.privatePostV2OrdersCancel(this.extend(n,h)),l=this.safeList(c,"success",[]);return this.parseOrders(l,s)}async cancelUnifiedOrder(e,t={}){let i={side:e.side};return await this.cancelOrder(e.id,e.symbol,this.extend(i,t))}async withdraw(e,t,i,s,r={}){let a,n;void 0===this.markets&&await this.loadMarkets();let[d,h]=this.handleOptionIntegerAndParams(r,"withdraw","generation",2),[c,l]=this.handleWithdrawTagAndParams(s,h);this.checkAddress(i);let u=this.safeString2(l,"network","net_type"),f=this.omit(l,"network"),p=this.currency(e),m={},g="XRP"===e||"XMR"===e||"EOS"===e||"STEEM"===e||"TON"===e,v=f;if(g&&(v=this.omit(f,["destination","secondary_address"])),g){let t=this.safeString2(f,"destination","secondary_address");if(void 0===c&&void 0===t)throw new o.ArgumentsRequired(this.id+" "+e+" withdraw() requires a tag argument or an extra destination param");n=void 0!==c?c:t}let y=this.safeString2(v,"receiver_type","cust_type_cd"),b=this.omit(v,["receiver_type","cust_type_cd"]);if(2===d)if("KRW"===e){if(void 0===this.safeString(b,"two_factor_type"))throw new o.ArgumentsRequired(this.id+" "+e+" withdraw() requires a two_factor_type parameter for withdrawing KRW");let i={amount:this.numberToString(t)};a=await this.privatePostV1WithdrawsKrw(this.extend(i,b))}else{if(void 0===u)throw new o.ArgumentsRequired(this.id+" "+e+" withdraw() requires a network parameter");m.address=i,m.currency=p.id,m.net_type=u,m.amount=this.numberToString(t),void 0!==n&&(m.secondary_address=n),void 0!==y&&(m.receiver_type=y),a=await this.privatePostV1WithdrawsCoin(this.extend(m,b))}else m.address=i,m.currency=p.id,m.units=t,void 0!==u&&(m.net_type=u),void 0!==n&&(m.destination=n),void 0!==y&&("corporation"===y?m.cust_type_cd="Corporation 02":"personal"===y?m.cust_type_cd="Individual 01":m.cust_type_cd=y),a=await this.privatePostTradeBtcWithdrawal(this.extend(m,b));return this.parseTransaction(a,p)}parseTransaction(e,t){let i=this.safeString(e,"type"),s=this.safeString(e,"currency"),r=this.safeCurrency(s,t),a=this.safeString(e,"created_at"),o=this.parse8601(a);if(void 0!==a&&a.indexOf("+09:00")>-1){let e=a.replace("+09:00","Z"),t=this.parse8601(e);void 0!==t&&(o=t-324e5)}return{id:this.safeString(e,"uuid"),txid:this.safeString(e,"txid"),timestamp:o,datetime:a,network:this.safeString(e,"net_type"),addressFrom:void 0,address:void 0,addressTo:void 0,amount:this.safeNumber(e,"amount"),type:i,currency:r.code,status:this.parseTransactionStatusByType(this.safeString(e,"state"),i),updated:void 0,tagFrom:void 0,tag:void 0,tagTo:void 0,comment:void 0,internal:void 0,fee:{currency:void 0,cost:this.safeNumber(e,"fee"),rate:void 0},info:e}}parseTransactionStatusByType(e,t){if(void 0===t)return e;let i=this.safeDict({deposit:{DEPOSIT_PROCESSING:"pending",DEPOSIT_ACCEPTED:"ok",DEPOSIT_CANCELLED:"canceled",PROCESSING:"pending",ACCEPTED:"ok",CANCELLED:"canceled"},withdraw:{processing:"pending",done:"ok",cancelled:"canceled",PROCESSING:"pending",DONE:"ok",CANCELLED:"canceled"}},t,{});return this.safeString(i,e,e)}async fetchWithdrawalWhitelist(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleOptionIntegerAndParams(e,"fetchWithdrawalWhitelist","generation",2);if(2!==t)throw new o.BadRequest(this.id+" fetchWithdrawalWhitelist() is only supported for the generation 2 API");return await this.privateGetV1WithdrawsCoinAddresses(i)}async fetchWithdrawal(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleOptionIntegerAndParams(i,"fetchWithdrawal","generation",2);if(2!==s)throw new o.BadRequest(this.id+" fetchWithdrawal() is only supported for the generation 2 API");if(void 0===t)throw new o.ArgumentsRequired(this.id+" fetchWithdrawal() requires a code argument");let a=this.currency(t),n={currency:a.id};void 0!==e&&(n.uuid=e);let d=await this.privateGetV1Withdraw(this.extend(n,r));return this.parseTransaction(d,a)}async fetchWithdrawals(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOptionIntegerAndParams(s,"fetchWithdrawals","generation",2);if(2!==n)throw new o.BadRequest(this.id+" fetchWithdrawals() is only supported for the generation 2 API");let h={};return void 0!==i&&(h.limit=i),"KRW"===e?(a=this.currency(e),r=await this.privateGetV1WithdrawsKrw(this.extend(h,d))):(void 0!==e&&(h.currency=(a=this.currency(e)).id),r=await this.privateGetV1Withdraws(this.extend(h,d))),this.parseTransactions(r,a,t,i)}async fetchDeposit(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleOptionIntegerAndParams(i,"fetchDeposit","generation",2);if(2!==s)throw new o.BadRequest(this.id+" fetchDeposit() is only supported for the generation 2 API");if(void 0===t)throw new o.ArgumentsRequired(this.id+" fetchDeposit() requires a code argument");let a=this.currency(t),n={currency:a.id};void 0!==e&&(n.uuid=e);let d=await this.privateGetV1Deposit(this.extend(n,r));return this.parseTransaction(d,a)}async fetchDeposits(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOptionIntegerAndParams(s,"fetchDeposits","generation",2);if(2!==n)throw new o.BadRequest(this.id+" fetchDeposits() is only supported for the generation 2 API");let h={};return void 0!==i&&(h.limit=i),"KRW"===e?(a=this.currency(e),r=await this.privateGetV1DepositsKrw(this.extend(h,d))):(void 0!==e&&(h.currency=(a=this.currency(e)).id),r=await this.privateGetV1Deposits(this.extend(h,d))),this.parseTransactions(r,a,t,i)}async createDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionIntegerAndParams(t,"createDepositAddress","generation",2);if(2!==i)throw new o.BadRequest(this.id+" createDepositAddress() is only supported for the generation 2 API");let r=this.currency(e),a={currency:r.id},n=this.safeString2(s,"network","net_type"),d=this.omit(s,"network");if(void 0===n)throw new o.ArgumentsRequired(this.id+" "+e+" createDepositAddress() requires a network parameter");a.net_type=n;let h=await this.privatePostV1DepositsGenerateCoinAddress(this.extend(a,d));return this.parseDepositAddress(h,r)}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionIntegerAndParams(t,"fetchDepositAddress","generation",2);if(2!==i)throw new o.BadRequest(this.id+" fetchDepositAddress() is only supported for the generation 2 API");let r=this.currency(e),a={currency:r.id},n=this.safeString2(s,"network","net_type"),d=this.omit(s,"network");if(void 0===n)throw new o.ArgumentsRequired(this.id+" "+e+" fetchDepositAddress() requires a network parameter");a.net_type=n;let h=await this.privateGetV1DepositsCoinAddress(this.extend(a,d));return this.parseDepositAddress(h,r)}async fetchDepositAddresses(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionIntegerAndParams(t,"fetchDepositAddresses","generation",2);if(2!==i)throw new o.BadRequest(this.id+" fetchDepositAddresses() is only supported for the generation 2 API");let r=await this.privateGetV1DepositsCoinAddresses(s);return this.parseDepositAddresses(r,e,!1,{})}parseDepositAddress(e,t){let i=this.safeString(e,"currency"),s=this.safeCurrencyCode(i,t),r=this.safeString(e,"deposit_address");if(void 0===r)throw new o.ExchangeError(this.id+" parseDepositAddress() could not find deposit_address");return this.checkAddress(r),{info:e,currency:s,network:this.safeString(e,"net_type"),address:r,tag:this.safeString(e,"secondary_address")}}fixCommaNumber(e){if(void 0===e)return;let t=e;for(;t.indexOf(",")>-1;)t=t.replace(",","");return t}nonce(){return this.milliseconds()}urlencodeWithArrayBrackets(e){let t=Object.keys(e),i="";for(let s=0;s<t.length;s++){let r=t[s],a=e[r];if(Array.isArray(a)){let e=this.encodeURIComponent(r)+"[]";for(let t=0;t<a.length;t++){let s=a[t],r=this.safeString(a,t);void 0===r&&(r=this.json(s)),i.length>0&&(i+="&"),i+=e+"="+this.encodeURIComponent(r)}}else{i.length>0&&(i+="&");let t=this.encodeURIComponent(r),s=this.safeString(e,r);i+=t+"="+this.encodeURIComponent(s)}}return i}sign(e,t="public",i="GET",r={},n,d){let h,c,l="/"+this.implodeParams(e,r),u=this.safeString(this.urls.api,t);if(void 0===u)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let f=this.implodeHostname(u)+l,p=this.omit(r,this.extractParams(e)),m=Object.keys(p).length>0;if("public"===t)h={"OPEN-API-PARTNER":"CCXT"},m&&(f+="?"+this.urlencode(p));else if(this.checkRequiredCredentials(),l.startsWith("/v1/")||l.startsWith("/v2/")){let e;h={Accept:"application/json","OPEN-API-PARTNER":"CCXT"};let t={access_key:this.apiKey,nonce:this.uuid(),timestamp:this.milliseconds()};if("GET"!==i&&"DELETE"!==i?(h["Content-Type"]="application/json",m&&(c=this.json(p),e=this.urlencodeWithArrayBrackets(p))):m&&(f+="?"+(e=this.urlencodeWithArrayBrackets(p))),m){let i=void 0===e?"":e;t.query_hash=this.hash(this.encode(i),s.Zf),t.query_hash_alg="SHA512"}let r=(0,a.a)(t,this.encode(this.secret),s.sc);h.Authorization="Bearer "+r}else{c=(c=this.urlencode(this.extend({endpoint:l},p))).split("%20").join("+");let e=this.nonce().toString(),t=l+"\0"+c+"\0"+e,i=this.hmac(this.encode(t),this.encode(this.secret),s.Zf),r=this.stringToBase64(i);h={Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Api-Key":this.apiKey,"Api-Sign":r,"Api-Nonce":e,"OPEN-API-PARTNER":"CCXT"}}return{url:f,method:i,body:void 0!==c?c:d,headers:void 0!==h?h:n}}handleErrors(e,t,i,s,r,a,n,d,h){if(void 0===n)return;let c=this.safeDict(n,"error");if(void 0!==c){let e=this.safeString(c,"name"),t=this.safeString(c,"message"),i=this.id+" "+t;throw void 0!==e&&this.throwExactlyMatchedException(this.exceptions,e,i),void 0!==t&&this.throwExactlyMatchedException(this.exceptions,t,i),new o.ExchangeError(i)}if("status"in n){let e=this.safeString(n,"status"),t=this.safeString(n,"message");if(void 0!==e){if("0000"===e||"거래 진행중인 내역이 존재하지 않습니다."===t)return;let i=this.id+" "+t;throw this.throwExactlyMatchedException(this.exceptions,e,i),this.throwExactlyMatchedException(this.exceptions,t,i),new o.ExchangeError(i)}}}}i.d(t,{A:()=>d})},2847(e,t,i){"use strict";var s=i(4721),r=i(7488),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bitopro",name:"BitoPro",countries:["TW"],version:"v3",rateLimit:100,pro:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!1,closePosition:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createReduceOnlyOrder:!1,createStopOrder:!0,createTriggerOrder:!0,editOrder:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!1,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchOrderTrades:!1,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!1,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchTransactionFees:!1,fetchTransactions:!1,fetchTransfer:!1,fetchTransfers:!1,fetchVolatilityHistory:!1,fetchWithdrawal:!0,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,withdraw:!0},timeframes:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","3h":"3h","6h":"6h","12h":"12h","1d":"1d","1w":"1w","1M":"1M"},urls:{logo:"https://github.com/user-attachments/assets/affc6337-b95a-44bf-aacd-04f9722364f6",api:{rest:"https://api.bitopro.com/v3"},www:"https://www.bitopro.com",doc:["https://github.com/bitoex/bitopro-offical-api-docs/blob/master/v3-1/rest-1/rest.md"],fees:"https://www.bitopro.com/fees"},requiredCredentials:{apiKey:!0,secret:!0},api:{public:{get:{"order-book/{pair}":{cost:1},tickers:{cost:1},"tickers/{pair}":{cost:1},"trades/{pair}":{cost:1},"provisioning/currencies":{cost:1},"provisioning/trading-pairs":{cost:1},"provisioning/limitations-and-fees":{cost:1},"trading-history/{pair}":{cost:1},"price/otc/{currency}":{cost:1}}},private:{get:{"accounts/balance":{cost:1},"orders/history":{cost:1},"orders/all/{pair}":{cost:1},"orders/trades/{pair}":{cost:1},"orders/{pair}/{orderId}":{cost:1},"wallet/withdraw/{currency}/{serial}":{cost:1},"wallet/withdraw/{currency}/id/{id}":{cost:1},"wallet/depositHistory/{currency}":{cost:1},"wallet/withdrawHistory/{currency}":{cost:1},"orders/open":{cost:1}},post:{"orders/{pair}":{cost:.5},"orders/batch":{cost:20/3},"wallet/withdraw/{currency}":{cost:10}},put:{orders:{cost:5}},delete:{"orders/{pair}/{id}":{cost:2/3},"orders/all":{cost:5},"orders/{pair}":{cost:5}}}},fees:{trading:{tierBased:!0,percentage:!0,maker:this.parseNumber("0.001"),taker:this.parseNumber("0.002"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.002")],[this.parseNumber("3000000"),this.parseNumber("0.00194")],[this.parseNumber("5000000"),this.parseNumber("0.0015")],[this.parseNumber("30000000"),this.parseNumber("0.0014")],[this.parseNumber("300000000"),this.parseNumber("0.0013")],[this.parseNumber("550000000"),this.parseNumber("0.0012")],[this.parseNumber("1300000000"),this.parseNumber("0.0011")]],maker:[[this.parseNumber("0"),this.parseNumber("0.001")],[this.parseNumber("3000000"),this.parseNumber("0.00097")],[this.parseNumber("5000000"),this.parseNumber("0.0007")],[this.parseNumber("30000000"),this.parseNumber("0.0006")],[this.parseNumber("300000000"),this.parseNumber("0.0005")],[this.parseNumber("550000000"),this.parseNumber("0.0004")],[this.parseNumber("1300000000"),this.parseNumber("0.0003")]]}}},options:{networks:{ERC20:"ERC20",ETH:"ERC20",TRX:"TRX",TRC20:"TRX",BEP20:"BSC",BSC:"BSC"},fetchCurrencies:{fiatCurrencies:["TWD"]}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!0,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:1e5,untilDays:1e5,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:1e3,daysBack:1e5,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:{marginMode:!1,limit:1e3,daysBack:1e5,daysBackCanceled:1,untilDays:1e4,trigger:!1,trailing:!1,symbolRequired:!0},fetchOHLCV:{limit:1e3}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},precisionMode:4,exceptions:{exact:{"Unsupported currency.":a.BadRequest,"Unsupported order type":a.BadRequest,"Invalid body":a.BadRequest,"Invalid Signature":a.AuthenticationError,"Address not in whitelist.":a.BadRequest},broad:{"Invalid amount":a.InvalidOrder,"Balance for ":a.InsufficientFunds,"Invalid ":a.BadRequest,"Wrong parameter":a.BadRequest}},commonCurrencies:{}})}async fetchCurrencies(e={}){let t=await this.publicGetProvisioningCurrencies(e),i=this.safeList(t,"data",[]);return this.parseCurrencies(i)}parseCurrency(e){let t=this.handleOption("fetchCurrencies","fiatCurrencies",[]),i=this.safeString(e,"currency"),s=this.safeCurrencyCode(i),r=this.safeBool(e,"deposit"),a=this.safeBool(e,"withdraw"),o=this.inArray(s,t);return this.safeCurrencyStructure({id:i,code:s,info:e,type:o?"fiat":"crypto",name:void 0,active:!0===r&&!0===a,deposit:r,withdraw:a,fee:this.safeNumber(e,"withdrawFee"),precision:void 0,limits:{withdraw:{min:this.safeNumber(e,"minWithdraw"),max:this.safeNumber(e,"maxWithdraw")},amount:{min:void 0,max:void 0}},networks:void 0})}async fetchMarkets(e={}){let t=await this.publicGetProvisioningTradingPairs(),i=this.safeList(t,"data",[]);return this.parseMarkets(i)}parseMarket(e){let t=!this.safeBool(e,"maintain",!1),i=this.safeString(e,"pair");if(void 0===i)throw new a.ExchangeError(this.id+" parseMarket() missing id");let s=i.toUpperCase(),r=this.safeString(e,"base"),o=this.safeString(e,"quote"),n=this.safeCurrencyCode(r),d=this.safeCurrencyCode(o);if(void 0===n||void 0===d)return;let h=n+"/"+d,c={amount:{min:this.safeNumber(e,"minLimitBaseAmount"),max:this.safeNumber(e,"maxLimitBaseAmount")},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0},leverage:{min:void 0,max:void 0}};return this.safeMarketStructure({id:i,uppercaseId:s,symbol:h,base:n,quote:d,baseId:n,quoteId:d,settle:void 0,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,limits:c,precision:{price:this.parseNumber(this.parsePrecision(this.safeString(e,"quotePrecision"))),amount:this.parseNumber(this.parsePrecision(this.safeString(e,"basePrecision")))},active:t,created:void 0,info:e})}parseTicker(e,t){let i=this.safeString(e,"pair"),s=this.safeMarket(i,t),r=this.safeString(s,"symbol");return this.safeTicker({symbol:r,timestamp:void 0,datetime:void 0,high:this.safeString(e,"high24hr"),low:this.safeString(e,"low24hr"),bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:void 0,close:this.safeString(e,"lastPrice"),last:this.safeString(e,"lastPrice"),previousClose:void 0,change:void 0,percentage:this.safeString(e,"priceChange24hr"),average:void 0,baseVolume:this.safeString(e,"volume24hr"),quoteVolume:void 0,info:e},s)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={pair:i.id},r=await this.publicGetTickersPair(this.extend(s,t)),a=this.safeDict(r,"data",{});return this.parseTicker(a,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetTickers(),s=this.safeList(i,"data",[]);return this.parseTickers(s,e)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={pair:s.id};void 0!==t&&(r.limit=t);let a=await this.publicGetOrderBookPair(this.extend(r,i));return this.parseOrderBook(a,s.symbol,void 0,"bids","asks","price","amount")}parseTrade(e,t){let i,s,r,a=this.safeString(e,"tradeId"),o=this.safeString(e,"orderId");i=void 0===a?this.safeTimestamp(e,"timestamp"):this.safeInteger(e,"timestamp");let n=this.safeString(e,"pair"),d=this.safeMarket(n,t),h=this.safeString(d,"symbol"),c=this.safeString(e,"price"),l=this.safeStringLower(e,"type"),u=this.safeStringLower(e,"action");void 0===u&&(u=!0===this.safeBool(e,"isBuyer")?"buy":"sell");let f=this.safeString(e,"amount");void 0===f&&(f=this.safeString(e,"baseAmount"));let p=this.safeString(e,"fee"),m=this.safeCurrencyCode(this.safeString(e,"feeSymbol"));void 0!==p&&(s={cost:p,currency:m,rate:void 0});let g=this.safeBool(e,"isTaker");return void 0!==g&&(r=g?"taker":"maker"),this.safeTrade({id:a,info:e,order:o,timestamp:i,datetime:this.iso8601(i),symbol:h,takerOrMaker:r,type:l,side:u,price:c,amount:f,cost:void 0,fee:s},d)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={pair:r.id},o=await this.publicGetTradesPair(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTrades(n,r,t,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.publicGetProvisioningLimitationsAndFees(e),i=this.safeDict(t,"tradingFeeRate",{}),s=this.safeDict(i,0),r={},a=this.safeNumber(s,"makerFee"),o=this.safeNumber(s,"takerFee"),n=this.symbols;for(let e=0;e<n.length;e++){let t=n[e];r[t]={info:s,symbol:t,maker:a,taker:o,percentage:!0,tierBased:!0}}return r}parseOHLCV(e,t){return[this.safeInteger(e,"timestamp"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchOHLCV(e,t="1m",i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=this.safeString(this.timeframes,t,t),d={pair:o.id,resolution:n},h=void 0===s?500:Math.min(s,75e3),c=this.parseTimeframe(t);if(void 0===i)d.to=this.seconds(),d.from=d.to-h*c;else{let e=1e3*c;a=Math.floor(i/e)*e,d.from=Math.floor(i/1e3),d.to=this.sum(d.from,h*c)}let l=await this.publicGetTradingHistoryPair(this.extend(d,r)),u=this.safeList(l,"data",[]),f=this.parseOHLCVs(u,o,t,i,h);return this.insertMissingCandles(f,c,a,h)}insertMissingCandles(e,t,i,s){let r;if(0===e.length)return e;let a=[],o=e[0];r=void 0===i?o[0]:i;let n=0,d=e.length,h=0;for(;h<s&&n<d;){let i=e[n];if(i[0]===r)a.push(i),n=this.sum(n,1);else{let e=this.arrayConcat([],o);e[0]=r,e[1]=e[4],e[2]=e[4],e[3]=e[4],e[5]=this.parseNumber("0"),a.push(e)}r=this.sum(r,1e3*t),h=a.length,o=a[h-1]}return a}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"currency"),a=this.safeCurrencyCode(r),o=this.safeString(s,"amount"),n={free:this.safeString(s,"available"),total:o};void 0!==a&&(t[a]=n)}return this.safeBalance(t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetAccountsBalance(e),i=this.safeList(t,"data",[]);return this.parseBalance(i)}parseOrderStatus(e){return void 0===e?void 0:this.safeString({"-1":"open",0:"open",1:"open",2:"closed",3:"closed",4:"canceled",6:"canceled"},e)}parseOrder(e,t){let i,s,r=this.safeString2(e,"id","orderId"),n=this.safeInteger2(e,"timestamp","createdTimestamp"),d=this.safeString(e,"action");if(void 0===d)throw new a.ExchangeError(this.id+" parseOrder() returned no side");d=d.toLowerCase();let h=this.safeString2(e,"amount","originalAmount"),c=this.safeString(e,"price"),l=this.safeString(e,"pair"),u=this.safeMarket(l,t,"_"),f=this.safeString(u,"symbol"),p=this.safeString(e,"status"),m=this.parseOrderStatus(p),g=this.safeStringLower(e,"type"),v=this.safeString(e,"avgExecutionPrice"),y=this.safeString(e,"executedAmount"),b=this.safeString(e,"remainingAmount"),w=this.safeString(e,"timeInForce");"POST_ONLY"===w&&(i=!0);let k=this.safeString(e,"fee"),S=this.safeCurrencyCode(this.safeString(e,"feeSymbol"));return o.Y.stringGt(k,"0")&&(s={currency:S,cost:k}),this.safeOrder({id:r,clientOrderId:void 0,timestamp:n,datetime:this.iso8601(n),lastTradeTimestamp:this.safeInteger(e,"updatedTimestamp"),symbol:f,type:g,timeInForce:w,postOnly:i,side:d,price:c,triggerPrice:void 0,amount:h,cost:void 0,average:v,filled:y,remaining:b,status:m,fee:s,trades:void 0,info:e},u)}async createOrder(e,t,i,s,r,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d={type:t,pair:n.id,action:i,amount:this.amountToPrecision(e,s),timestamp:this.milliseconds()},h=t.toUpperCase();if("LIMIT"===h&&(d.price=this.priceToPrecision(e,r)),"STOP_LIMIT"===h){d.price=this.priceToPrecision(e,r);let t=this.safeString2(o,"triggerPrice","stopPrice");if(void 0===t)throw new a.InvalidOrder(this.id+" createOrder() requires a triggerPrice parameter for "+h+" orders");d.stopPrice=this.priceToPrecision(e,t);let i=this.safeString(o,"condition");if(void 0===i)throw new a.InvalidOrder(this.id+" createOrder() requires a condition parameter for "+h+" orders");d.condition=i}let c="STOP_LIMIT"===h?this.omit(o,["triggerPrice","stopPrice"]):o;this.isPostOnly("MARKET"===h,void 0,c)&&(d.timeInForce="POST_ONLY");let l=await this.privatePostOrdersPair(this.extend(d,c));return this.parseOrder(l,n)}async cancelOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r={id:e,pair:s.id},o=await this.privateDeleteOrdersPairId(this.extend(r,i));return this.parseOrder(o,s)}parseCancelOrders(e){let t=Object.keys(e),i=[];for(let s=0;s<t.length;s++){let r=t[s],a=e[r];for(let e=0;e<a.length;e++)i.push(this.safeOrder({info:a[e],id:a[e],symbol:this.safeSymbol(r)}))}return i}async cancelOrders(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t).uppercaseId,r={};void 0!==s&&(r[s]=e);let o=await this.privatePutOrders(this.extend(r,i)),n=this.safeDict(o,"data");return this.parseCancelOrders(n)}async cancelAllOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={};void 0!==e?(s.pair=this.market(e).id,i=await this.privateDeleteOrdersPair(this.extend(s,t))):i=await this.privateDeleteOrdersAll(this.extend(s,t));let r=this.safeDict(i,"data",{});return this.parseCancelOrders(r)}async fetchOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r={orderId:e,pair:s.id},o=await this.privateGetOrdersPairOrderId(this.extend(r,i));return this.parseOrder(o,s)}async fetchOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={pair:r.id};void 0!==t&&(o.startTimestamp=t),void 0!==i&&(o.limit=i);let n=await this.privateGetOrdersAllPair(this.extend(o,s)),d=this.safeList(n,"data",[]);return void 0===d&&(d=[]),this.parseOrders(d,r,t,i)}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.pair=(r=this.market(e)).id);let o=await this.privateGetOrdersOpen(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseOrders(n,r,t,i)}async fetchClosedOrders(e,t,i,s={}){return this.fetchOrders(e,t,i,this.extend({statusKind:"DONE"},s))}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={pair:r.id},n=await this.privateGetOrdersTradesPair(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTrades(d,r,t,i)}parseTransactionStatus(e){return this.safeString({COMPLETE:"ok",INVALID:"failed",PROCESSING:"pending",WAIT_PROCESS:"pending",FAILED:"failed",EXPIRED:"failed",CANCELLED:"failed",EMAIL_VERIFICATION:"pending",WAIT_CONFIRMATION:"pending"},e,e)}parseTransaction(e,t){let i=this.safeString(e,"coin"),s=this.safeCurrencyCode(i,t),r=this.safeInteger(e,"timestamp"),a=this.safeString(e,"address"),o=this.safeString(e,"message"),n=this.safeString(e,"status"),d=this.safeString(e,"protocol");return"MAIN"===d&&(d=s),{info:e,id:this.safeString(e,"serial"),txid:this.safeString(e,"txid"),type:void 0,currency:s,network:this.networkIdToCode(d,s),amount:this.safeNumber(e,"total"),status:this.parseTransactionStatus(n),timestamp:r,datetime:this.iso8601(r),address:a,addressFrom:void 0,addressTo:a,tag:o,tagFrom:void 0,tagTo:o,updated:void 0,comment:void 0,internal:void 0,fee:{currency:s,cost:this.safeNumber(e,"fee"),rate:void 0}}}async fetchDeposits(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchDeposits() requires the code argument");void 0===this.markets&&await this.loadMarkets();let r=this.safeCurrency(e),o={currency:r.id};void 0!==t&&(o.startTimestamp=t),void 0!==i&&(o.limit=i);let n=await this.privateGetWalletDepositHistoryCurrency(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTransactions(d,r,t,i,{type:"deposit"})}async fetchWithdrawals(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchWithdrawals() requires the code argument");void 0===this.markets&&await this.loadMarkets();let r=this.safeCurrency(e),o={currency:r.id};void 0!==t&&(o.startTimestamp=t),void 0!==i&&(o.limit=i);let n=await this.privateGetWalletWithdrawHistoryCurrency(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTransactions(d,r,t,i,{type:"withdrawal"})}async fetchWithdrawal(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchWithdrawal() requires the code argument");void 0===this.markets&&await this.loadMarkets();let s=this.safeCurrency(t),r={serial:e,currency:s.id},o=await this.privateGetWalletWithdrawCurrencySerial(this.extend(r,i)),n=this.safeDict(o,"data",{});return this.parseTransaction(n,s)}async withdraw(e,t,i,s,r={}){let[o,n]=this.handleWithdrawTagAndParams(s,r);void 0===this.markets&&await this.loadMarkets(),this.checkAddress(i);let d=this.currency(e),h={currency:d.id,amount:this.numberToString(t),address:i},c="network"in n,l=n;if(c&&(l=this.omit(n,["network"])),c){let e=this.safeDict(this.options,"networks",{}),t=this.safeStringUpper(n,"network"),i=void 0===t?void 0:this.safeString(e,t);if(void 0===i)throw new a.ExchangeError(this.id+" invalid network "+t);h.protocol=i}void 0!==o&&(h.message=o);let u=await this.privatePostWalletWithdrawCurrency(this.extend(h,l)),f=this.safeDict(u,"data",{});return this.parseTransaction(f,d)}parseDepositWithdrawFee(e,t){return{info:e,withdraw:{fee:this.safeNumber(e,"withdrawFee"),percentage:!1},deposit:{fee:void 0,percentage:void 0},networks:{}}}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetProvisioningCurrencies(t),s=this.safeList(i,"data",[]);return this.parseDepositWithdrawFees(s,e,"currency")}sign(e,t="public",i="GET",r={},o,n){let d="/"+this.implodeParams(e,r),h=this.omit(r,this.extractParams(e)),c=void 0===o?{}:o,l=this.json(r),u=n;if("private"===t&&("POST"===i||"PUT"===i)&&(u=l),c["X-BITOPRO-API"]="ccxt","private"===t){if(this.checkRequiredCredentials(),"POST"===i||"PUT"===i){let e=this.stringToBase64(l),t=this.hmac(this.encode(e),this.encode(this.secret),s.qt);c["X-BITOPRO-APIKEY"]=this.apiKey,c["X-BITOPRO-PAYLOAD"]=e,c["X-BITOPRO-SIGNATURE"]=t}else if("GET"===i||"DELETE"===i){Object.keys(h).length>0&&(d+="?"+this.urlencode(h));let e=this.milliseconds(),t=this.json({nonce:e}),i=this.stringToBase64(t),r=this.hmac(this.encode(i),this.encode(this.secret),s.qt);c["X-BITOPRO-APIKEY"]=this.apiKey,c["X-BITOPRO-PAYLOAD"]=i,c["X-BITOPRO-SIGNATURE"]=r}}else"public"===t&&"GET"===i&&Object.keys(h).length>0&&(d+="?"+this.urlencode(h));let f=this.safeString(this.urls.api,"rest");if(void 0===f)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");return{url:f+d,method:i,body:u,headers:c}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n||e>=200&&e<300)return;let c=this.id+" "+o,l=this.safeString(n,"error");throw this.throwExactlyMatchedException(this.exceptions.exact,l,c),this.throwBroadlyMatchedException(this.exceptions.broad,l,c),new a.ExchangeError(c)}}i.d(t,{A:()=>n})},7551(e,t,i){"use strict";var s=i(4721),r=i(8418),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bitrue",name:"Bitrue",countries:["SG"],rateLimit:10,certified:!1,version:"v1",pro:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!0,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createReduceOnlyOrder:!0,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,fetchBalance:!0,fetchBidsAsks:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!1,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!1,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTransactionFees:!1,fetchTransactions:!1,fetchTransfers:!0,fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!0,setMargin:!0,setMarginMode:!1,setPositionMode:!1,transfer:!0,withdraw:!0},timeframes:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1H","2h":"2H","4h":"4H","1d":"1D","1w":"1W"},urls:{logo:"https://github.com/user-attachments/assets/67abe346-1273-461a-bd7c-42fa32907c8e",api:{spot:"https://www.bitrue.com/api",fapi:"https://fapi.bitrue.com/fapi",dapi:"https://fapi.bitrue.com/dapi",kline:"https://www.bitrue.com/kline-api"},www:"https://www.bitrue.com",referral:"https://www.bitrue.com/affiliate/landing?cn=600000&inviteCode=EZWETQE",doc:["https://github.com/Bitrue-exchange/bitrue-official-api-docs","https://www.bitrue.com/api-docs"],fees:"https://bitrue.zendesk.com/hc/en-001/articles/4405479952537"},api:{spot:{kline:{public:{get:{"public.json":{cost:.24},"public{currency}.json":{cost:.24}}}},v1:{public:{get:{ping:{cost:.24},time:{cost:.24},exchangeInfo:{cost:.24},depth:{cost:1,byLimit:[[100,.24],[500,1.2],[1e3,2.4]]},trades:{cost:.24},historicalTrades:{cost:1.2},aggTrades:{cost:.24},"ticker/24hr":{cost:.24,noSymbol:9.6},"ticker/price":{cost:.24},"ticker/bookTicker":{cost:.24},"market/kline":{cost:.24}}},private:{get:{order:{cost:5},openOrders:{cost:5},allOrders:{cost:25},account:{cost:25},myTrades:{cost:25},"etf/net-value/{symbol}":{cost:.24},"withdraw/history":{cost:120},"deposit/history":{cost:120}},post:{order:{cost:5},"withdraw/commit":{cost:120}},delete:{order:{cost:5}}}},v2:{private:{get:{myTrades:{cost:1.2}}}}},fapi:{v1:{public:{get:{ping:{cost:.24},time:{cost:.24},contracts:{cost:.24},depth:{cost:.24},ticker:{cost:.24},klines:{cost:.24}}}},v2:{private:{get:{myTrades:{cost:5},openOrders:{cost:5},order:{cost:5},account:{cost:5},leverageBracket:{cost:5},commissionRate:{cost:5},futures_transfer_history:{cost:5},forceOrdersHistory:{cost:5}},post:{positionMargin:{cost:5},level_edit:{cost:5},cancel:{cost:5},order:{cost:25},allOpenOrders:{cost:5},futures_transfer:{cost:5}}}}},dapi:{v1:{public:{get:{ping:{cost:.24},time:{cost:.24},contracts:{cost:.24},depth:{cost:.24},ticker:{cost:.24},klines:{cost:.24}}}},v2:{private:{get:{myTrades:{cost:5},openOrders:{cost:5},order:{cost:5},account:{cost:5},leverageBracket:{cost:5},commissionRate:{cost:5},futures_transfer_history:{cost:5},forceOrdersHistory:{cost:5}},post:{positionMargin:{cost:5},level_edit:{cost:5},cancel:{cost:5},order:{cost:5},allOpenOrders:{cost:5},futures_transfer:{cost:5}}}}}},fees:{trading:{feeSide:"get",tierBased:!1,percentage:!0,taker:this.parseNumber("0.00098"),maker:this.parseNumber("0.00098")},future:{trading:{feeSide:"quote",tierBased:!0,percentage:!0,taker:this.parseNumber("0.000400"),maker:this.parseNumber("0.000200"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.000400")],[this.parseNumber("250"),this.parseNumber("0.000400")],[this.parseNumber("2500"),this.parseNumber("0.000350")],[this.parseNumber("7500"),this.parseNumber("0.000320")],[this.parseNumber("22500"),this.parseNumber("0.000300")],[this.parseNumber("50000"),this.parseNumber("0.000270")],[this.parseNumber("100000"),this.parseNumber("0.000250")],[this.parseNumber("200000"),this.parseNumber("0.000220")],[this.parseNumber("400000"),this.parseNumber("0.000200")],[this.parseNumber("750000"),this.parseNumber("0.000170")]],maker:[[this.parseNumber("0"),this.parseNumber("0.000200")],[this.parseNumber("250"),this.parseNumber("0.000160")],[this.parseNumber("2500"),this.parseNumber("0.000140")],[this.parseNumber("7500"),this.parseNumber("0.000120")],[this.parseNumber("22500"),this.parseNumber("0.000100")],[this.parseNumber("50000"),this.parseNumber("0.000080")],[this.parseNumber("100000"),this.parseNumber("0.000060")],[this.parseNumber("200000"),this.parseNumber("0.000040")],[this.parseNumber("400000"),this.parseNumber("0.000020")],[this.parseNumber("750000"),this.parseNumber("0")]]}}},delivery:{trading:{feeSide:"base",tierBased:!0,percentage:!0,taker:this.parseNumber("0.000500"),maker:this.parseNumber("0.000100"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.000500")],[this.parseNumber("250"),this.parseNumber("0.000450")],[this.parseNumber("2500"),this.parseNumber("0.000400")],[this.parseNumber("7500"),this.parseNumber("0.000300")],[this.parseNumber("22500"),this.parseNumber("0.000250")],[this.parseNumber("50000"),this.parseNumber("0.000240")],[this.parseNumber("100000"),this.parseNumber("0.000240")],[this.parseNumber("200000"),this.parseNumber("0.000240")],[this.parseNumber("400000"),this.parseNumber("0.000240")],[this.parseNumber("750000"),this.parseNumber("0.000240")]],maker:[[this.parseNumber("0"),this.parseNumber("0.000100")],[this.parseNumber("250"),this.parseNumber("0.000080")],[this.parseNumber("2500"),this.parseNumber("0.000050")],[this.parseNumber("7500"),this.parseNumber("0.0000030")],[this.parseNumber("22500"),this.parseNumber("0")],[this.parseNumber("50000"),this.parseNumber("-0.000050")],[this.parseNumber("100000"),this.parseNumber("-0.000060")],[this.parseNumber("200000"),this.parseNumber("-0.000070")],[this.parseNumber("400000"),this.parseNumber("-0.000080")],[this.parseNumber("750000"),this.parseNumber("-0.000090")]]}}}},options:{createOrder:{createMarketBuyOrderRequiresPrice:!0},fetchMarkets:{types:["spot","linear","inverse"]},fetchMyTradesMethod:"v2PrivateGetMyTrades",hasAlreadyAuthenticatedSuccessfully:!1,currencyToPrecisionRoundingMode:0,recvWindow:5e3,timeDifference:0,adjustForTimeDifference:!1,parseOrderToPrecision:!1,newOrderRespType:{market:"FULL",limit:"FULL"},networks:{ERC20:"ETH",TRC20:"TRX",AETERNITY:"Aeternity",AION:"AION",ALGO:"Algorand",ASK:"ASK",ATOM:"ATOM",AVAXC:"AVAX C-Chain",BCH:"BCH",BEP2:"BEP2",BEP20:"BEP20",Bitcoin:"Bitcoin",BRP20:"BRP20",ADA:"Cardano",CASINOCOIN:"CasinoCoin","CASINOCOIN-XRPL":"CasinoCoin XRPL",CONTENTOS:"Contentos",DASH:"Dash",DECOIN:"Decoin",DFI:"DeFiChain",DGB:"DGB",DIVI:"Divi",DOGE:"dogecoin",EOS:"EOS",ETC:"ETC",FILECOIN:"Filecoin",FREETON:"FREETON",HBAR:"HBAR",HEDERA:"Hedera Hashgraph",HRC20:"HRC20",ICON:"ICON",ICP:"ICP",IGNIS:"Ignis",INTERNETCOMPUTER:"Internet Computer",IOTA:"IOTA",KAVA:"KAVA",KSM:"KSM",LTC:"LiteCoin",LUNA:"Luna",MATIC:"MATIC",MOBILECOIN:"Mobile Coin",MONACOIN:"MonaCoin",XMR:"Monero",NEM:"NEM",NEP5:"NEP5",OMNI:"OMNI",PAC:"PAC",DOT:"Polkadot",RAVEN:"Ravencoin",SAFEX:"Safex",SOL:"SOLANA",SGB:"Songbird",XML:"Stellar Lumens",XYM:"Symbol",XTZ:"Tezos",THETA:"THETA",VECHAIN:"VeChain",WANCHAIN:"Wanchain",XINFIN:"XinFin Network",XRP:"XRP",XRPL:"XRPL",ZIL:"ZIL"},defaultType:"spot",timeframes:{spot:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1H","2h":"2H","4h":"4H","12h":"12H","1d":"1D","1w":"1W"},future:{"1m":"1min","5m":"5min","15m":"15min","30m":"30min","1h":"1h","1d":"1day","1w":"1week","1M":"1month"}},accountsByType:{spot:"wallet",future:"contract",swap:"contract",funding:"wallet",fund:"wallet",contract:"contract"}},commonCurrencies:{MIM:"MIM Swarm"},precisionMode:4,features:{default:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:void 0,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyRequiresPrice:!0,marketBuyByCost:!0,selfTradePrevention:!1,iceberg:!0},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:1e5,untilDays:1e5,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:1e3,daysBack:90,daysBackCanceled:1,untilDays:90,trigger:!1,trailing:!1,symbolRequired:!0},fetchOHLCV:{limit:1440}},spot:{extends:"default"},forDerivatives:{extends:"default",createOrder:{marginMode:!0,leverage:!0,marketBuyRequiresPrice:!1,marketBuyByCost:!1},fetchOHLCV:{limit:300},fetchClosedOrders:void 0},swap:{linear:{extends:"forDerivatives"},inverse:{extends:"forDerivatives"}},future:{linear:void 0,inverse:void 0}},exceptions:{exact:{"System is under maintenance.":a.OnMaintenance,"System abnormality":a.ExchangeError,"You are not authorized to execute this request.":a.PermissionDenied,"API key does not exist":a.AuthenticationError,"Order would trigger immediately.":a.OrderImmediatelyFillable,"Stop price would trigger immediately.":a.OrderImmediatelyFillable,"Order would immediately match and take.":a.OrderImmediatelyFillable,"Account has insufficient balance for requested action.":a.InsufficientFunds,"Rest API trading is not enabled.":a.ExchangeNotAvailable,"You don't have permission.":a.PermissionDenied,"Market is closed.":a.ExchangeNotAvailable,"Too many requests. Please try again later.":a.DDoSProtection,"quantity less then minQty":a.InvalidOrder,"-1000":a.ExchangeNotAvailable,"-1001":a.ExchangeNotAvailable,"-1002":a.AuthenticationError,"-1003":a.RateLimitExceeded,"-1013":a.InvalidOrder,"-1015":a.RateLimitExceeded,"-1016":a.ExchangeNotAvailable,"-1020":a.BadRequest,"-1021":a.InvalidNonce,"-1022":a.AuthenticationError,"-1100":a.BadRequest,"-1101":a.BadRequest,"-1102":a.BadRequest,"-1103":a.BadRequest,"-1104":a.BadRequest,"-1105":a.BadRequest,"-1106":a.BadRequest,"-1111":a.BadRequest,"-1112":a.InvalidOrder,"-1114":a.BadRequest,"-1115":a.BadRequest,"-1116":a.BadRequest,"-1117":a.BadRequest,"-1166":a.InvalidOrder,"-1118":a.BadRequest,"-1119":a.BadRequest,"-1120":a.BadRequest,"-1121":a.BadSymbol,"-1125":a.AuthenticationError,"-1127":a.BadRequest,"-1128":a.BadRequest,"-1130":a.BadRequest,"-1131":a.BadRequest,"-1160":a.InvalidOrder,"-1156":a.InvalidOrder,"-2008":a.AuthenticationError,"-2010":a.ExchangeError,"-2011":a.OrderNotFound,"-2013":a.OrderNotFound,"-2014":a.AuthenticationError,"-2015":a.AuthenticationError,"-2017":a.InsufficientFunds,"-2019":a.InsufficientFunds,"-3005":a.InsufficientFunds,"-3006":a.InsufficientFunds,"-3008":a.InsufficientFunds,"-3010":a.ExchangeError,"-3015":a.ExchangeError,"-3022":a.AccountSuspended,"-4028":a.BadRequest,"-3020":a.InsufficientFunds,"-3041":a.InsufficientFunds,"-5013":a.InsufficientFunds,"-11008":a.InsufficientFunds,"-4051":a.InsufficientFunds},broad:{"Insufficient account balance":a.InsufficientFunds,"has no operation privilege":a.PermissionDenied,MAX_POSITION:a.InvalidOrder}}})}nonce(){return this.milliseconds()-this.safeInteger(this.options,"timeDifference",0)}async fetchStatus(e={}){let t=await this.spotV1PublicGetPing(e),i=Object.keys(t).length,s="ok";return i>0&&(s="maintenance"),{status:s,updated:void 0,eta:void 0,url:void 0,info:t}}async fetchTime(e={}){let t=await this.spotV1PublicGetTime(e);return this.safeInteger(t,"serverTime")}async fetchCurrencies(e={}){let t=await this.spotV1PublicGetExchangeInfo(e),i=this.safeList(t,"coins",[]);return this.parseCurrencies(i)}parseCurrency(e){let t=this.safeString(e,"coin"),i=this.safeString(e,"coinFulName"),s=this.safeCurrencyCode(t),r=this.safeList(e,"chainDetail",[]),a={};for(let e=0;e<r.length;e++){let t=r[e],i=this.safeString(t,"chain"),o=this.networkIdToCode(i,s);void 0!==o&&(a[o]={info:t,id:i,network:o,deposit:this.safeBool(t,"enableDeposit"),withdraw:this.safeBool(t,"enableWithdraw"),active:void 0,fee:this.safeNumber(t,"withdrawFee"),precision:void 0,limits:{withdraw:{min:this.safeNumber(t,"minWithdraw"),max:this.safeNumber(t,"maxWithdraw")}}})}return this.safeCurrencyStructure({id:t,name:i,code:s,precision:void 0,info:e,active:void 0,deposit:void 0,withdraw:void 0,networks:a,fee:void 0,fees:void 0,type:"crypto",limits:{withdraw:{min:void 0,max:void 0}}})}async fetchMarkets(e={}){let t,i=[],s=["spot","linear","inverse"],r=this.safeDict(this.options,"fetchMarkets");t=void 0!==r?this.safeList(r,"types",s):this.safeList(this.options,"fetchMarkets",s);for(let s=0;s<t.length;s++){let r=t[s];if("spot"===r)i.push(this.spotV1PublicGetExchangeInfo(e));else if("linear"===r)i.push(this.fapiV1PublicGetContracts(e));else if("inverse"===r)i.push(this.dapiV1PublicGetContracts(e));else throw new a.ExchangeError(this.id+' fetchMarkets() this.options fetchMarkets "'+r+'" is not a supported market type')}let o=await Promise.all(i),n=this.safeList(this.safeDict(o,0),"symbols",[]),d=this.safeValue(o,1),h=this.safeValue(o,2),c=n;return c=this.arrayConcat(c,d),c=this.arrayConcat(c,h),this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference(),this.parseMarkets(c)}parseMarket(e){let t,i,s,r,a=this.safeString(e,"symbol",""),n=this.safeStringLower(e,"symbol"),d=this.safeInteger(e,"side"),h="spot";void 0===d?h="spot":(h="swap",t=1===d,i=0===d);let c="spot"!==h,l=this.safeString(e,"baseAsset"),u=this.safeString(e,"quoteAsset");if(c){let e=a.split("-");l=this.safeString(e,1),u=this.safeString(e,2),s=!0===t?u:l,r=this.safeCurrencyCode(s)}let f=this.safeCurrencyCode(l),p=this.safeCurrencyCode(u);if(void 0===f||void 0===p)return;let m=f+"/"+p;void 0!==r&&(m+=":"+r);let g=this.safeList(e,"filters",[]),v=this.indexBy(g,"filterType"),y=this.safeString(e,"status"),b=this.safeDict(v,"PRICE_FILTER",{}),w=this.safeDict(v,"LOT_SIZE",{}),k=this.safeString(e,"pricePrecision"),S=this.safeString(e,"quantityPrecision"),O=this.safeString(b,"priceScale",k),T=this.safeString(w,"volumeScale",S),P=this.safeString(e,"multiplier"),I=this.safeNumber(w,"maxQty");void 0===I&&(I=this.safeNumber(e,"maxValidOrder"));let A=this.safeNumber(w,"minVal");void 0===A&&(A=this.safeNumber(e,"minOrderMoney"));let x="spot"===h;return this.safeMarketStructure({id:a,lowercaseId:n,symbol:m,base:f,quote:p,settle:r,baseId:l,quoteId:u,settleId:s,type:h,spot:x,margin:!1,swap:c,future:!1,option:!1,active:"TRADING"===y,contract:c,linear:t,inverse:i,contractSize:this.parseNumber(o.Y.stringAbs(P)),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(T)),price:this.parseNumber(this.parsePrecision(O))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(w,"minQty"),max:I},price:{min:this.safeNumber(b,"minPrice"),max:this.safeNumber(b,"maxPrice")},cost:{min:A,max:void 0}},created:void 0,info:e})}parseBalance(e){let t={info:e},i=this.safeInteger(e,"updateTime"),s=this.safeList2(e,"balances","account",[]);for(let e=0;e<s.length;e++){let i=this.safeDict(s,e),r=this.safeString2(i,"asset","marginCoin"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString2(i,"free","accountNormal"),o.used=this.safeString2(i,"locked","accountLock"),void 0!==a&&(t[a]=o)}return t.timestamp=i,t.datetime=this.iso8601(i),this.safeBalance(t)}async fetchBalance(e={}){let t,i;void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleMarketTypeAndParams("fetchBalance",void 0,e),[a,o]=this.handleSubTypeAndParams("fetchBalance",void 0,r);return"swap"===s?(t=void 0!==a&&"inverse"===a?await this.dapiV2PrivateGetAccount(o):await this.fapiV2PrivateGetAccount(o),i=this.safeDict(t,"data",{})):i=t=await this.spotV1PrivateGetAccount(o),this.parseBalance(i)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={};if(!0===s.swap){let e={contractName:s.id};void 0!==t&&(e.limit=Math.min(t,100)),!0===s.linear?r=await this.fapiV1PublicGetDepth(this.extend(e,i)):!0===s.inverse&&(r=await this.dapiV1PublicGetDepth(this.extend(e,i)))}else if(!0===s.spot){let e={symbol:s.id};void 0!==t&&(e.limit=Math.min(t,1e3)),r=await this.spotV1PublicGetDepth(this.extend(e,i))}else throw new a.NotSupported(this.id+" fetchOrderBook only support spot & swap markets");let o=this.safeInteger2(r,"time","lastUpdateId"),n=this.parseOrderBook(r,e,o);return n.nonce=this.safeInteger(r,"lastUpdateId"),n}parseTicker(e,t){let i,s=this.safeSymbol(void 0,t),r=this.safeString2(e,"lastPrice","last"),a=this.safeInteger(e,"time");return i=this.safeBool(t,"swap",!1)?o.Y.stringMul(this.safeString(e,"rose"),"100"):this.safeString(e,"priceChangePercent"),this.safeTicker({symbol:s,timestamp:a,datetime:this.iso8601(a),high:this.safeString2(e,"highPrice","high"),low:this.safeString2(e,"lowPrice","low"),bid:this.safeString2(e,"bidPrice","buy"),bidVolume:this.safeString(e,"bidQty"),ask:this.safeString2(e,"askPrice","sell"),askVolume:this.safeString(e,"askQty"),vwap:this.safeString(e,"weightedAvgPrice"),open:this.safeString(e,"openPrice"),close:r,last:r,previousClose:void 0,change:this.safeString(e,"priceChange"),percentage:i,average:void 0,baseVolume:this.safeString2(e,"volume","vol"),quoteVolume:this.safeString(e,"quoteVolume"),info:e},t)}async fetchTicker(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={};if(!0===s.swap){let e={contractName:s.id};!0===s.linear?i=await this.fapiV1PublicGetTicker(this.extend(e,t)):!0===s.inverse&&(i=await this.dapiV1PublicGetTicker(this.extend(e,t))),r=i}else if(!0===s.spot){let e={symbol:s.id};i=await this.spotV1PublicGetTicker24hr(this.extend(e,t)),r=this.safeDict(i,0,{})}else throw new a.NotSupported(this.id+" fetchTicker only support spot & swap markets");return this.parseTicker(r,s)}async fetchOHLCV(e,t="1m",i,s,r={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=this.safeDict(this.options,"timeframes",{}),h=[];if(!0===n.swap){let e=this.safeDict(d,"future",{}),i={contractName:n.id,interval:this.safeString(e,t,"1min")};void 0!==s&&(i.limit=s),!0===n.linear?o=await this.fapiV1PublicGetKlines(this.extend(i,r)):!0===n.inverse&&(o=await this.dapiV1PublicGetKlines(this.extend(i,r))),h=o}else if(!0===n.spot){let e=this.safeDict(d,"spot",{}),i={symbol:n.id,scale:this.safeString(e,t,"1m")};void 0!==s&&(i.limit=s);let a=this.safeInteger(r,"until");void 0!==a&&(i.fromIdx=a);let c=void 0!==a?this.omit(r,"until"):r;o=await this.spotV1PublicGetMarketKline(this.extend(i,c)),h=this.safeList(o,"data",[])}else throw new a.NotSupported(this.id+" fetchOHLCV only support spot & swap markets");return this.parseOHLCVs(h,n,t,i,s)}parseOHLCV(e,t){let i=this.safeTimestamp(e,"i");return void 0===i&&(i=this.safeInteger(e,"idx")),[i,this.safeNumber2(e,"o","open"),this.safeNumber2(e,"h","high"),this.safeNumber2(e,"l","low"),this.safeNumber2(e,"c","close"),this.safeNumber2(e,"v","vol")]}async fetchBidsAsks(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!1),r=this.safeString(s,0),o=this.market(r);if(!0===o.swap){let e={contractName:o.id};!0===o.linear?i=await this.fapiV1PublicGetTicker(this.extend(e,t)):!0===o.inverse&&(i=await this.dapiV1PublicGetTicker(this.extend(e,t)))}else if(!0===o.spot){let e={symbol:o.id};i=await this.spotV1PublicGetTickerBookTicker(this.extend(e,t))}else throw new a.NotSupported(this.id+" fetchBidsAsks only support spot & swap markets");let n={};return n[o.id]=i,this.parseTickers(n,s)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=[],r=[],o={};if(void 0!==i){let e=this.safeString(i,0),n=this.market(e);if(!0===n.swap)throw new a.NotSupported(this.id+" fetchTickers does not support swap markets, please use fetchTicker instead");if(!0===n.spot)s=await this.spotV1PublicGetTicker24hr(this.extend(o,t)),r=this.toArray(s);else throw new a.NotSupported(this.id+" fetchTickers only support spot & swap markets")}else{let[e,i]=this.handleMarketTypeAndParams("fetchTickers",void 0,t);if("spot"!==e)throw new a.NotSupported(this.id+" fetchTickers only support spot when symbols are not proved");s=await this.spotV1PublicGetTicker24hr(this.extend(o,i)),r=this.toArray(s)}let n={};for(let e=0;e<r.length;e++){let t=this.safeDict(r,e,{}),i=this.safeString(t,"symbol");void 0!==i&&(n[this.safeMarket(i).id]=t)}return this.parseTickers(n,i)}parseTrade(e,t){let i,s,r,a=this.safeInteger2(e,"ctime","time"),o=this.safeString(e,"price"),n=this.safeString(e,"qty"),d=this.safeString2(e,"symbol","contractName"),h=this.safeSymbol(d,t),c=this.safeString(e,"orderId"),l=this.safeString2(e,"id","tradeId"),u=this.safeBool(e,"isBuyerMaker"),f=this.safeBool(e,"isBuyer");void 0!==u&&(i=u?"sell":"buy"),void 0!==f&&(i=f?"buy":"sell"),"commission"in e&&(s={cost:this.safeString2(e,"commission","fee"),currency:this.safeCurrencyCode(this.safeString(e,"commissionAssert"))});let p=this.safeBool(e,"isMaker");return void 0!==p&&(r=p?"maker":"taker"),this.safeTrade({info:e,timestamp:a,datetime:this.iso8601(a),symbol:h,id:l,order:c,type:void 0,side:i,takerOrMaker:r,price:o,amount:n,cost:void 0,fee:s},t)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o=[];if(!0===r.spot){let e={symbol:r.id};void 0!==i&&(e.limit=i),o=await this.spotV1PublicGetTrades(this.extend(e,s))}else throw new a.NotSupported(this.id+" fetchTrades only support spot markets");return this.parseTrades(o,r,t,i)}parseOrderStatus(e){return this.safeString({INIT:"open",PENDING_CREATE:"open",NEW:"open",PARTIALLY_FILLED:"open",FILLED:"closed",CANCELED:"canceled",PENDING_CANCEL:"canceling",REJECTED:"rejected",EXPIRED:"expired"},e,e)}parseOrder(e,t){let i,s,r=this.parseOrderStatus(this.safeString2(e,"status","orderStatus")),a=this.safeString(e,"symbol"),n=this.safeSymbol(a,t),d=this.safeString(e,"executedQty");"time"in e?i=this.safeInteger(e,"time"):"transactTime"in e?i=this.safeInteger(e,"transactTime"):"updateTime"in e&&"open"===r&&(o.Y.stringGt(d,"0")?s=this.safeInteger(e,"updateTime"):i=this.safeInteger(e,"updateTime"));let h=this.safeString(e,"avgPrice"),c=this.safeString(e,"price"),l=this.safeString(e,"origQty"),u=this.safeString2(e,"cummulativeQuoteQty","cumQuote"),f=this.safeString(e,"orderId"),p=this.safeStringLower(e,"type"),m=this.safeStringLower(e,"side"),g=this.safeList(e,"fills",[]),v=this.safeString(e,"clientOrderId"),y=this.safeString(e,"timeInForce"),b="limit_maker"===p||"GTX"===y||"post_only"===p;"limit_maker"===p&&(p="limit");let w=this.parseNumber(this.omitZero(this.safeString(e,"stopPrice")));return this.safeOrder({info:e,id:f,clientOrderId:v,timestamp:i,datetime:this.iso8601(i),lastTradeTimestamp:s,symbol:n,type:p,timeInForce:y,postOnly:b,side:m,price:c,triggerPrice:w,amount:l,cost:u,average:h,filled:d,remaining:void 0,status:r,fee:void 0,trades:g},t)}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).swap)throw new a.NotSupported(this.id+" createMarketBuyOrderWithCost() supports swap orders only");return i.createMarketBuyOrderRequiresPrice=!1,await this.createOrder(e,"market","buy",t,void 0,i)}async createOrder(e,t,i,s,r,n={}){let d;void 0===this.markets&&await this.loadMarkets();let h=this.market(e),c={},l=t.toUpperCase(),u={side:i.toUpperCase(),type:l};if("LIMIT"===l){if(void 0===r)throw new a.InvalidOrder(this.id+" createOrder() requires a price argument");u.price=this.priceToPrecision(e,r)}if(!0===h.swap){let t="MARKET"===l,f=this.safeStringLower(n,"timeInForce");this.isPostOnly(t,void 0,n)?u.type="POST_ONLY":"fok"===f?u.type="FOK":"ioc"===f&&(u.type="IOC"),u.contractName=h.id;let[p,m]=this.handleOptionBoolAndParams(n,"createOrder","createMarketBuyOrderRequiresPrice",!0),g=t&&"buy"===i&&p,v=m;if(g&&(v=this.omit(m,"cost")),g){let t=this.safeString(m,"cost");if(void 0===r&&void 0===t)throw new a.InvalidOrder(this.id+' createOrder() requires the price argument with swap market buy orders to calculate total order cost (amount to spend), where cost = amount * price. Supply a price argument to createOrder() call if you want the cost to be calculated for you from price and amount, or, alternatively, add .options["createMarketBuyOrderRequiresPrice"] = false to supply the cost in the amount argument (the exchange-specific behaviour)');{let i=this.numberToString(s),a=this.numberToString(r),n=o.Y.stringMul(i,a);void 0!==t&&(n=t),u.amount=this.costToPrecision(e,n),u.volume=this.costToPrecision(e,n)}}else u.amount=this.parseToNumeric(s),u.volume=this.parseToNumeric(s);u.positionType=1,u.open=!0===this.safeBool2(v,"reduceOnly","reduce_only")?"CLOSE":"OPEN";let y=this.safeString(v,"leverage","1");u.leverage=this.parseToNumeric(y);let b=this.omit(v,["leverage","reduceOnly","reduce_only","timeInForce"]);!0===h.linear?d=await this.fapiV2PrivatePostOrder(this.extend(u,b)):!0===h.inverse&&(d=await this.dapiV2PrivatePostOrder(this.extend(u,b))),c=this.safeDict(d,"data",{})}else if(!0===h.spot){u.symbol=h.id,u.quantity=this.amountToPrecision(e,s);let i=this.safeValue(h.info,"orderTypes");if(!this.inArray(l,i))throw new a.InvalidOrder(this.id+" "+t+" is not a valid order type in market "+e);let r=this.safeString2(n,"newClientOrderId","clientOrderId");void 0!==r&&(u.newClientOrderId=r);let o=void 0!==r?this.omit(n,["newClientOrderId","clientOrderId"]):n,f=this.safeNumber2(o,"triggerPrice","stopPrice");void 0!==f&&(u.stopPrice=this.priceToPrecision(e,f));let p=void 0!==f?this.omit(o,["triggerPrice","stopPrice"]):o;c=d=await this.spotV1PrivatePostOrder(this.extend(u,p))}else throw new a.NotSupported(this.id+" createOrder only support spot & swap markets");return this.parseOrder(c,h)}async fetchOrder(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),o=this.safeString2(i,"origClientOrderId","clientOrderId"),n=this.omit(i,["origClientOrderId","clientOrderId"]),d={},h={};if(void 0===o?h.orderId=e:!0===r.swap?h.clientOrderId=o:h.origClientOrderId=o,!0===r.swap)h.contractName=r.id,!0===r.linear?s=await this.fapiV2PrivateGetOrder(this.extend(h,n)):!0===r.inverse&&(s=await this.dapiV2PrivateGetOrder(this.extend(h,n))),d=this.safeDict(s,"data",{});else if(!0===r.spot)h.orderId=e,h.symbol=r.id,d=s=await this.spotV1PrivateGetOrder(this.extend(h,n));else throw new a.NotSupported(this.id+" fetchOrder only support spot & swap markets");return this.parseOrder(d,r)}async fetchClosedOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchClosedOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e);if(!0!==r.spot)throw new a.NotSupported(this.id+" fetchClosedOrders only support spot markets");let o={symbol:r.id};void 0!==t&&(o.startTime=t),void 0!==i&&(o.limit=i);let n=await this.spotV1PrivateGetAllOrders(this.extend(o,s));return this.parseOrders(n,r,t,i)}async fetchOpenOrders(e,t,i,s={}){let r;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOpenOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=[],d={};if(!0===o.swap)d.contractName=o.id,!0===o.linear?r=await this.fapiV2PrivateGetOpenOrders(this.extend(d,s)):!0===o.inverse&&(r=await this.dapiV2PrivateGetOpenOrders(this.extend(d,s))),n=this.safeList(r,"data",[]);else if(!0===o.spot)d.symbol=o.id,n=r=await this.spotV1PrivateGetOpenOrders(this.extend(d,s));else throw new a.NotSupported(this.id+" fetchOpenOrders only support spot & swap markets");return this.parseOrders(n,o,t,i)}async cancelOrder(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),o=this.safeString2(i,"origClientOrderId","clientOrderId"),n=this.omit(i,["origClientOrderId","clientOrderId"]),d={},h={};if(void 0===o?h.orderId=e:!0===r.swap?h.clientOrderId=o:h.origClientOrderId=o,!0===r.swap)h.contractName=r.id,!0===r.linear?s=await this.fapiV2PrivatePostCancel(this.extend(h,n)):!0===r.inverse&&(s=await this.dapiV2PrivatePostCancel(this.extend(h,n))),d=this.safeDict(s,"data",{});else if(!0===r.spot)h.symbol=r.id,d=s=await this.spotV1PrivateDeleteOrder(this.extend(h,n));else throw new a.NotSupported(this.id+" cancelOrder only support spot & swap markets");return this.parseOrder(d,r)}async cancelAllOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=[];if(!0===s.swap){let e={contractName:s.id};!0===s.linear?i=await this.fapiV2PrivatePostAllOpenOrders(this.extend(e,t)):!0===s.inverse&&(i=await this.dapiV2PrivatePostAllOpenOrders(this.extend(e,t))),r=this.safeList(i,"data",[])}else throw new a.NotSupported(this.id+" cancelAllOrders only support future markets");return this.parseOrders(r,s)}async fetchMyTrades(e,t,i,s={}){let r;if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");let o=this.market(e),n=[],d={};void 0!==t&&(d.startTime=t);let h=void 0===i?void 0:Math.min(i,1e3);if(void 0!==h&&(d.limit=h),!0===o.swap)d.contractName=o.id,!0===o.linear?r=await this.fapiV2PrivateGetMyTrades(this.extend(d,s)):!0===o.inverse&&(r=await this.dapiV2PrivateGetMyTrades(this.extend(d,s))),n=this.safeList(r,"data",[]);else if(!0===o.spot)d.symbol=o.id,n=r=await this.spotV2PrivateGetMyTrades(this.extend(d,s));else throw new a.NotSupported(this.id+" fetchMyTrades only support spot & swap markets");return this.parseTrades(n,o,t,h)}async fetchDeposits(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchDeposits() requires a code argument");void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),o={coin:r.id,status:1};void 0!==t&&(o.startTime=t),void 0!==i&&(o.limit=i);let n=await this.spotV1PrivateGetDepositHistory(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTransactions(d,r,t,i)}async fetchWithdrawals(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchWithdrawals() requires a code argument");void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),o={coin:r.id,status:5};void 0!==t&&(o.startTime=t),void 0!==i&&(o.limit=i);let n=await this.spotV1PrivateGetWithdrawHistory(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTransactions(d,r)}parseTransactionStatusByType(e,t){let i=this.safeDict({deposit:{0:"pending",1:"ok"},withdrawal:{0:"pending",5:"ok",6:"canceled"}},t,{});return this.safeString(i,e,e)}parseTransaction(e,t){let i,s,r,a,o=this.safeString2(e,"id","withdrawId"),n=this.safeString(e,"tagType"),d=this.safeString(e,"addressTo"),h=this.safeString(e,"addressFrom");if(void 0!==n){if(void 0!==d){let e=d.split("_");d=this.safeString(e,0),i=this.safeString(e,1)}if(void 0!==h){let e=h.split("_");h=this.safeString(e,0),s=this.safeString(e,1)}}let c=this.safeString(e,"txid"),l=this.safeInteger(e,"createdAt"),u=this.safeInteger(e,"updatedAt"),f="payAmount"in e,p="ctime"in e,m="deposit";(f||p)&&(m="withdrawal");let g=this.parseTransactionStatusByType(this.safeString(e,"status"),m),v=this.safeNumber(e,"amount"),y=this.safeString2(e,"symbol","coin");if(void 0!==y){let e=y.split("_");y=this.safeString(e,0);let t=this.safeString(e,1);void 0!==t&&(r=t.toUpperCase())}let b=this.safeCurrencyCode(y,t),w=this.safeNumber(e,"fee");return void 0!==w&&(a={currency:b,cost:w}),{info:e,id:o,txid:c,timestamp:l,datetime:this.iso8601(l),network:r,address:d,addressTo:d,addressFrom:h,tag:i,tagTo:i,tagFrom:s,type:m,amount:v,currency:b,status:g,updated:u,internal:!1,comment:void 0,fee:a}}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d={coin:n.id,amount:t,addressTo:i},[h,c]=this.handleNetworkCodeAndParams(o);void 0!==h&&(d.chainName=this.networkCodeToId(h,this.safeString(n,"code"))),void 0!==a&&(d.tag=a);let l=await this.spotV1PrivatePostWithdrawCommit(this.extend(d,c)),u=this.safeDict(l,"data",{});return this.parseTransaction(u,n)}parseDepositWithdrawFee(e,t){let i=this.safeList(e,"chainDetail",[]),s=i.length,r={info:e,withdraw:{fee:void 0,percentage:void 0},deposit:{fee:void 0,percentage:void 0},networks:{}};if(0!==s)for(let e=0;e<s;e++){let a=this.safeDict(i,e),o=this.safeString(a,"chain"),n=this.safeString(t,"code"),d=this.networkIdToCode(o,n);void 0!==d&&(r.networks[d]={deposit:{fee:void 0,percentage:void 0},withdraw:{fee:this.safeNumber(a,"withdrawFee"),percentage:!1}}),1===s&&(r.withdraw.fee=this.safeNumber(a,"withdrawFee"),r.withdraw.percentage=!1)}return r}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.spotV1PublicGetExchangeInfo(t),s=this.safeList(i,"coins");return this.parseDepositWithdrawFees(s,e,"coin")}parseTransfer(e,t){let i,s,r=this.safeString(e,"transferType");if(void 0!==r){let e=r.split("_to_");i=this.safeString(e,0),s=this.safeString(e,1)}let a=this.safeInteger(e,"ctime");return{info:e,id:void 0,timestamp:a,datetime:this.iso8601(a),currency:this.safeString(t,"code"),amount:this.safeNumber(e,"amount"),fromAccount:i,toAccount:s,status:"ok"}}async fetchTransfers(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={transferType:this.safeString2(s,"type","transferType")};void 0!==e&&(a.coinSymbol=(r=this.currency(e)).id),void 0!==t&&(a.beginTime=t);let o=void 0===i?void 0:Math.min(i,200);void 0!==o&&(a.limit=o);let n=this.safeInteger(s,"until");void 0!==n&&(a.endTime=n);let d=void 0!==n?this.omit(s,"until"):s,h=await this.fapiV2PrivateGetFuturesTransferHistory(this.extend(a,d)),c=this.safeList(h,"data",[]);return this.parseTransfers(c,r,t,o)}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(e),o=this.safeDict(this.options,"accountsByType",{}),n=this.safeString(o,i,i),d=this.safeString(o,s,s),h={coinSymbol:a.id,amount:this.currencyToPrecision(e,t),transferType:n+"_to_"+d},c=await this.fapiV2PrivatePostFuturesTransfer(this.extend(h,r)),l=this.safeDict(c,"data",{});return this.parseTransfer(l,a)}async setLeverage(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");if(e<1||e>125)throw new a.BadRequest(this.id+" leverage should be between 1 and 125");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r={},o={contractName:s.id,leverage:e};if(!0!==s.swap)throw new a.NotSupported(this.id+" setLeverage only support swap markets");return!0===s.linear?r=await this.fapiV2PrivatePostLevelEdit(this.extend(o,i)):!0===s.inverse&&(r=await this.dapiV2PrivatePostLevelEdit(this.extend(o,i))),r}parseMarginModification(e,t){return{info:e,symbol:this.safeString(t,"symbol"),type:void 0,marginMode:"isolated",amount:void 0,total:void 0,code:void 0,status:void 0,timestamp:void 0,datetime:void 0}}async setMargin(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e);if(!0!==r.swap)throw new a.NotSupported(this.id+" setMargin only support swap markets");let o={contractName:r.id,amount:this.parseToNumeric(t)};return!0===r.linear?s=await this.fapiV2PrivatePostPositionMargin(this.extend(o,i)):!0===r.inverse&&(s=await this.dapiV2PrivatePostPositionMargin(this.extend(o,i))),this.parseMarginModification(s,r)}sign(e,t="public",i="GET",r={},o,n){let d,h,c=this.safeString(t,0),l=this.safeString(t,1),u=this.safeString(t,2),f=this.safeString(this.urls.api,c);if(void 0===f)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let p=f;"api"===c&&"kline"===l||"open"===c&&e.indexOf("listenKey")>=0||(p+="/"+l),p+="/"+this.implodeParams(e,r);let m=this.omit(r,this.extractParams(e));if("private"===u){this.checkRequiredCredentials();let t=this.safeInteger(this.options,"recvWindow",5e3);if("spot"===c||"open"===c){let e=this.urlencode(this.extend({timestamp:this.nonce(),recvWindow:t},m)),r=this.hmac(this.encode(e),this.encode(this.secret),s.sc);e+="&signature="+r,h={"X-MBX-APIKEY":this.apiKey},"GET"===i||"DELETE"===i?p+="?"+e:(d=e,h["Content-Type"]="application/x-www-form-urlencoded")}else{let r,a=this.nonce().toString();"fapi"===c?r="/fapi":"dapi"===c&&(r="/dapi");let o=a+i+(r=r+"/"+l+"/"+e);if("GET"===i){Object.keys(m).length>0&&(o+="?"+this.urlencode(m));let e=this.hmac(this.encode(o),this.encode(this.secret),s.sc);h={"X-CH-APIKEY":this.apiKey,"X-CH-SIGN":e,"X-CH-TS":a},p+="?"+this.urlencode(m)}else{let e=this.extend({recvWindow:t},m);o+=d=this.json(e);let i=this.hmac(this.encode(o),this.encode(this.secret),s.sc);h={"Content-Type":"application/json","X-CH-APIKEY":this.apiKey,"X-CH-SIGN":i,"X-CH-TS":a}}}}else Object.keys(m).length>0&&(p+="?"+this.urlencode(m));return{url:p,method:i,body:void 0===d?n:d,headers:void 0===h?o:h}}handleErrors(e,t,i,s,r,n,d,h,c){let l;if(418===e||429===e)throw new a.DDoSProtection(this.id+" "+e.toString()+" "+t+" "+n);if(e>=400){if(n.indexOf("Price * QTY is zero or less")>=0)throw new a.InvalidOrder(this.id+" order cost = amount * price is zero or less "+n);if(n.indexOf("LOT_SIZE")>=0)throw new a.InvalidOrder(this.id+" order amount should be evenly divisible by lot size "+n);if(n.indexOf("PRICE_FILTER")>=0)throw new a.InvalidOrder(this.id+" order price is invalid, i.e. exceeds allowed price precision, exceeds min price or max price limits or is invalid float value in general, use this.priceToPrecision (symbol, amount) "+n)}if(void 0===d)return;let u=this.safeBool(d,"success",!0);if(!0!==u){let e=this.safeString(d,"msg");if(void 0!==e)try{l=JSON.parse(e)}catch(e){l=void 0}}let f=void 0!==l?l:d,p=this.safeString(f,"msg");void 0!==p&&(this.throwExactlyMatchedException(this.exceptions.exact,p,this.id+" "+p),this.throwBroadlyMatchedException(this.exceptions.broad,p,this.id+" "+p));let m=this.safeString(f,"code");if(void 0!==m){if("200"===m||o.Y.stringEquals(m,"0"))return;if("-2015"===m&&this.safeBool(this.options,"hasAlreadyAuthenticatedSuccessfully",!1))throw new a.DDoSProtection(this.id+" temporary banned: "+n);let e=this.id+" "+n;throw this.throwExactlyMatchedException(this.exceptions.exact,m,e),new a.ExchangeError(e)}if(!0!==u)throw new a.ExchangeError(this.id+" "+n)}calculateRateLimiterCost(e,t,i,s,r={}){if("noSymbol"in r&&!("symbol"in s))return r.noSymbol;if("byLimit"in r&&"limit"in s){let e=s.limit,t=this.safeList(r,"byLimit",[]);for(let i=0;i<t.length;i++){let s=t[i];if(e<=s[0])return s[1]}}return this.safeValue(r,"cost",1)}}i.d(t,{A:()=>n})},5181(e,t,i){"use strict";var s=i(4721),r=i(138),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bitso",name:"Bitso",countries:["MX"],rateLimit:2e3,version:"v3",has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!1,closePosition:!1,createDepositAddress:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createReduceOnlyOrder:!1,fetchAccounts:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!1,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLedger:!0,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrderTrades:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!1,fetchTime:!1,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchTransactionFee:!1,fetchTransactionFees:!0,fetchTransactions:!1,fetchTransfer:!1,fetchTransfers:!1,fetchVolatilityHistory:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,withdraw:!0},urls:{logo:"https://github.com/user-attachments/assets/3d0c1e5e-8aaa-419f-968a-2b7409381ce4",api:{rest:"https://bitso.com/api"},test:{rest:"https://stage.bitso.com/api"},www:"https://bitso.com",doc:"https://bitso.com/api_info",fees:"https://bitso.com/fees",referral:"https://bitso.com/?ref=itej"},precisionMode:4,options:{networks:{TRC20:"trx",ERC20:"erc20",BEP20:"bsc",BEP2:"bep2"}},timeframes:{"1m":"60","5m":"300","15m":"900","30m":"1800","1h":"3600","4h":"14400","12h":"43200","1d":"86400","1w":"604800"},api:{public:{get:{available_books:{cost:1},catalogues:{cost:1},ticker:{cost:1},order_book:{cost:1},trades:{cost:1},ohlc:{cost:1}}},private:{get:{account_status:{cost:1},balance:{cost:1},fees:{cost:1},fundings:{cost:1},"fundings/{fid}":{cost:1},funding_destination:{cost:1},kyc_documents:{cost:1},ledger:{cost:1},"ledger/trades":{cost:1},"ledger/fees":{cost:1},"ledger/fundings":{cost:1},"ledger/withdrawals":{cost:1},mx_bank_codes:{cost:1},open_orders:{cost:1},"order_trades/{oid}":{cost:1},"orders/{oid}":{cost:1},user_trades:{cost:1},"user_trades/{tid}":{cost:1},"withdrawals/":{cost:1},"withdrawals/{wid}":{cost:1}},post:{bitcoin_withdrawal:{cost:1},debit_card_withdrawal:{cost:1},ether_withdrawal:{cost:1},orders:{cost:1},phone_number:{cost:1},phone_verification:{cost:1},phone_withdrawal:{cost:1},spei_withdrawal:{cost:1},ripple_withdrawal:{cost:1},bcash_withdrawal:{cost:1},litecoin_withdrawal:{cost:1}},delete:{orders:{cost:1},"orders/{oid}":{cost:1},"orders/all":{cost:1}},patch:{orders:{cost:1},"orders/{oid}":{cost:1}}}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:void 0,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:void 0,untilDays:void 0,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:500,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:{limit:300}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},exceptions:{"0201":a.AuthenticationError,104:a.InvalidNonce,"0304":a.BadRequest}})}async fetchLedger(e,t,i,s={}){let r={};void 0!==i&&(r.limit=i);let a=await this.privateGetLedger(this.extend(r,s)),o=this.safeList(a,"payload",[]),n=this.safeCurrency(e);return this.parseLedger(o,n,t,i)}parseLedgerEntryType(e){return this.safeString({funding:"transaction",withdrawal:"transaction",trade:"trade",fee:"fee"},e,e)}parseLedgerEntry(e,t){let i,s,r=this.safeString(e,"operation"),a=this.parseLedgerEntryType(r),n=this.safeList(e,"balance_updates",[]),d=this.safeDict(n,0,{}),h=this.safeString(d,"amount"),c=this.safeString(d,"currency"),l=this.safeCurrencyCode(c,t),u=this.safeCurrency(c,t),f=this.safeDict(e,"details",{}),p=this.safeString2(f,"fid","wid");void 0===p&&(p=this.safeString(f,"tid")),"funding"===r?i="in":"withdrawal"===r?i="out":"trade"===r?i=void 0:"fee"===r&&(i="out",s={cost:o.Y.stringAbs(h),currency:u});let m=this.parse8601(this.safeString(e,"created_at"));return this.safeLedgerEntry({info:e,id:this.safeString(e,"eid"),direction:i,account:void 0,referenceId:p,referenceAccount:void 0,type:a,currency:l,amount:h,timestamp:m,datetime:this.iso8601(m),before:void 0,after:void 0,status:"ok",fee:s},u)}async fetchMarkets(e={}){let t=await this.publicGetAvailableBooks(e),i=this.safeList(t,"payload",[]),s=this.safeDict(this.options,"cachedCurrencies"),r=[];for(let e=0;e<i.length;e++){let t=i[e],a=this.safeString(t,"book"),[n,d]=a.split("_"),h=n.toUpperCase(),c=d.toUpperCase();if(h=this.safeCurrencyCode(h),c=this.safeCurrencyCode(c),void 0===h||void 0===c)continue;let l=this.safeDict(t,"fees",{}),u=this.safeDict(l,"flat_rate",{}),f=this.safeString(u,"taker"),p=this.safeString(u,"maker"),m=this.parseNumber(o.Y.stringDiv(f,"100")),g=this.parseNumber(o.Y.stringDiv(p,"100")),v=this.safeList(l,"structure",[]),y={taker:m,maker:g,percentage:!0,tierBased:!0},b=[],w=[];for(let e=0;e<v.length;e++){let t=this.safeDict(v,e),i=this.safeNumber(t,"volume"),s=this.safeNumber(t,"taker"),r=this.safeNumber(t,"maker");b.push([i,s]),w.push([i,r]),0===e&&(y.taker=s,y.maker=r)}y.tiers={taker:b,maker:w};let k=this.safeDict(s,h);r.push(this.safeMarketStructure(this.extend({id:a,symbol:h+"/"+c,base:h,quote:c,settle:void 0,baseId:n,quoteId:d,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:void 0,contract:!1,linear:void 0,inverse:void 0,taker:m,maker:g,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(k,"precision"),price:this.safeNumber(t,"tick_size")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(t,"minimum_amount"),max:this.safeNumber(t,"maximum_amount")},price:{min:this.safeNumber(t,"minimum_price"),max:this.safeNumber(t,"maximum_price")},cost:{min:this.safeNumber(t,"minimum_value"),max:this.safeNumber(t,"maximum_value")}},created:void 0,info:t},y)))}return r}async fetchCurrencies(e={}){let t=await this.publicGetCatalogues(e),i=this.safeDict(t,"payload"),s=this.safeDict(i,"currencies"),r=this.safeList(s,"metadata",[]);return this.parseCurrencies(r)}parseCurrency(e){let t=this.safeString(e,"code"),i=this.safeCurrencyCode(t);return this.safeCurrencyStructure({info:e,code:i,id:t,name:this.safeString(e,"full_name"),active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,precision:this.parseNumber(this.parsePrecision(this.safeString(e,"precision"))),margin:this.safeBool(e,"marginAvailable"),limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},networks:void 0,type:this.safeString(e,"type")})}parseBalance(e){let t=this.safeDict(e,"payload",{}),i=this.safeList(t,"balances",[]),s={info:e,timestamp:void 0,datetime:void 0};for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),r=this.safeString(t,"currency"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(t,"available"),o.used=this.safeString(t,"locked"),o.total=this.safeString(t,"total"),void 0!==a&&(s[a]=o)}return this.safeBalance(s)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetBalance(e);return this.parseBalance(t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={book:s.id},a=await this.publicGetOrderBook(this.extend(r,i)),o=this.safeDict(a,"payload"),n=this.parse8601(this.safeString(o,"updated_at"));return this.parseOrderBook(o,s.symbol,n,"bids","asks","price","amount")}parseTicker(e,t){let i=this.safeSymbol(void 0,t),s=this.parse8601(this.safeString(e,"created_at")),r=this.safeString(e,"vwap"),a=this.safeString(e,"volume"),n=o.Y.stringMul(a,r),d=this.safeString(e,"last");return this.safeTicker({symbol:i,timestamp:s,datetime:this.iso8601(s),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"bid"),bidVolume:void 0,ask:this.safeString(e,"ask"),askVolume:void 0,vwap:r,open:void 0,close:d,last:d,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:a,quoteVolume:n,info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={book:i.id},r=await this.publicGetTicker(this.extend(s,t)),a=this.safeDict(r,"payload");return this.parseTicker(a,i)}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={book:a.id,time_bucket:this.safeString(this.timeframes,t,t)};if(void 0!==i){if(o.start=i,void 0!==s){let e=this.parseTimeframe(t);o.end=this.sum(i,e*s*1e3)}}else if(void 0!==s){let e=this.milliseconds();o.end=e,o.start=e-1e3*this.parseTimeframe(t)*s}let n=await this.publicGetOhlc(this.extend(o,r)),d=this.safeList(n,"payload",[]);return this.parseOHLCVs(d,a,t,i,s)}parseOHLCV(e,t){return[this.safeInteger(e,"bucket_start_time"),this.safeNumber(e,"first_rate"),this.safeNumber(e,"max_rate"),this.safeNumber(e,"min_rate"),this.safeNumber(e,"last_rate"),this.safeNumber(e,"volume")]}parseTrade(e,t){let i,s,r=this.parse8601(this.safeString(e,"created_at")),a=this.safeString(e,"book"),n=this.safeSymbol(a,t,"_"),d=this.safeString(e,"side"),h=this.safeString(e,"maker_side");void 0!==d?i=d===h?"maker":"taker":d="buy"===h?"sell":"buy";let c=this.safeString2(e,"amount","major");void 0!==c&&(c=o.Y.stringAbs(c));let l=this.safeString(e,"fees_amount");if(void 0!==l){let t=this.safeString(e,"fees_currency");s={cost:l,currency:this.safeCurrencyCode(t)}}let u=this.safeString(e,"minor");void 0!==u&&(u=o.Y.stringAbs(u));let f=this.safeString(e,"price"),p=this.safeString(e,"oid"),m=this.safeString(e,"tid");return this.safeTrade({id:m,info:e,timestamp:r,datetime:this.iso8601(r),symbol:n,order:p,type:void 0,side:d,takerOrMaker:i,price:f,amount:c,cost:u,fee:s},t)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={book:r.id},o=await this.publicGetTrades(this.extend(a,s)),n=this.safeList(o,"payload",[]);return this.parseTrades(n,r,t,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetFees(e),i=this.safeDict(t,"payload",{}),s=this.safeList(i,"fees",[]),r={};for(let e=0;e<s.length;e++){let t=s[e],i=this.safeString(t,"book"),a=this.safeSymbol(i,void 0,"_");r[a]={info:t,symbol:a,maker:this.safeNumber(t,"maker_fee_decimal"),taker:this.safeNumber(t,"taker_fee_decimal"),percentage:!0,tierBased:!0}}return r}async fetchMyTrades(e,t,i=25,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o="marker"in s;if(void 0!==t&&!o)throw new a.ExchangeError(this.id+" fetchMyTrades() does not support fetching trades starting from a timestamp with the `since` argument, use the `marker` extra param to filter starting from an integer trade id");let n=s;o&&(n=this.extend(s,{marker:parseInt(s.marker)}));let d={book:r.id,limit:i},h=await this.privateGetUserTrades(this.extend(d,n)),c=this.safeList(h,"payload",[]);return this.parseTrades(c,r,t,i)}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={book:o.id,side:i,type:t,major:this.amountToPrecision(o.symbol,s)};"limit"===t&&(n.price=this.priceToPrecision(o.symbol,r));let d=await this.privatePostOrders(this.extend(n,a)),h=this.safeDict(d,"payload",{}),c=this.safeString(h,"oid");return this.safeOrder({info:d,id:c},o)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateDeleteOrdersOid(this.extend({oid:e},i)),r=this.safeList(s,"payload",[]),a=this.safeString(r,0);return this.safeOrder({info:s,id:a})}async cancelOrders(e,t,i={}){let s;if(!Array.isArray(e))throw new a.ArgumentsRequired(this.id+" cancelOrders() ids argument should be an array");void 0!==t&&(s=this.market(t));let r=e.join(","),o=await this.privateDeleteOrders(this.extend({oids:r},i)),n=this.safeList(o,"payload",[]),d=[];for(let e=0;e<n.length;e++){let t=n[e];d.push(this.parseOrder(t,s))}return d}async cancelAllOrders(e,t={}){if(void 0!==e)throw new a.NotSupported(this.id+" cancelAllOrders() deletes all orders for user, it does not support filtering by symbol.");let i=await this.privateDeleteOrdersAll(t),s=this.safeList(i,"payload",[]),r=[];for(let e=0;e<s.length;e++){let t=this.parseOrder(s[e]);r.push(t)}return r}parseOrderStatus(e){return this.safeString({"partial-fill":"open","partially filled":"open",queued:"open",completed:"closed"},e,e)}parseOrder(e,t){let i;i="string"==typeof e?e:this.safeString(e,"oid");let s=this.safeString(e,"side"),r=this.parseOrderStatus(this.safeString(e,"status")),a=this.safeString(e,"book"),o=this.safeSymbol(a,t,"_"),n=this.safeString(e,"type"),d=this.parse8601(this.safeString(e,"created_at")),h=this.safeString(e,"price"),c=this.safeString(e,"original_amount"),l=this.safeString(e,"unfilled_amount"),u=this.safeString(e,"client_id");return this.safeOrder({info:e,id:i,clientOrderId:u,timestamp:d,datetime:this.iso8601(d),lastTradeTimestamp:void 0,symbol:o,type:n,timeInForce:void 0,postOnly:void 0,side:s,price:h,triggerPrice:void 0,amount:c,cost:void 0,remaining:l,filled:void 0,status:r,fee:void 0,average:void 0,trades:void 0},t)}async fetchOpenOrders(e,t,i=25,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o="marker"in s;if(void 0!==t&&!o)throw new a.ExchangeError(this.id+" fetchOpenOrders() does not support fetching orders starting from a timestamp with the `since` argument, use the `marker` extra param to filter starting from an integer trade id");let n=s;o&&(n=this.extend(s,{marker:parseInt(s.marker)}));let d={book:r.id,limit:i},h=await this.privateGetOpenOrders(this.extend(d,n)),c=this.safeList(h,"payload",[]);return this.parseOrders(c,r,t,i)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateGetOrdersOid({oid:e}),r=this.safeList(s,"payload");if(Array.isArray(r)&&1===r.length)return this.parseOrder(r[0]);throw new a.OrderNotFound(this.id+": The order "+e+" not found.")}async fetchOrderTrades(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(t),o=await this.privateGetOrderTradesOid(this.extend({oid:e},r)),n=this.safeList(o,"payload",[]);return this.parseTrades(n,a)}async fetchDeposit(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateGetFundingsFid(this.extend({fid:e},i)),r=this.safeList(s,"payload",[]),a=this.safeDict(r,0,{});return this.parseTransaction(a)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.currency(e));let a=await this.privateGetFundings(s),o=this.safeList(a,"payload",[]);return this.parseTransactions(o,r,t,i,s)}async fetchDepositAddress(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={fund_currency:this.currency(e).id},r=await this.privateGetFundingDestination(this.extend(s,t)),a=this.safeDict(r,"payload",{}),o=this.safeString(a,"account_identifier");if(o.indexOf("?dt=")>=0){let e=o.split("?dt=");o=this.safeString(e,0),i=this.safeString(e,1)}return this.checkAddress(o),{info:r,currency:e,network:void 0,address:o,tag:i}}async fetchTransactionFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privateGetFees(t),s={},r=this.safeDict(i,"payload",{}),a=this.safeList(r,"deposit_fees",[]);for(let t=0;t<a.length;t++){let i=a[t],r=this.safeString(i,"currency"),o=this.safeCurrencyCode(r);(void 0===e||this.inArray(o,e))&&void 0!==o&&(s[o]={deposit:this.safeNumber(i,"fee"),withdraw:void 0,info:{deposit:i,withdraw:void 0}})}let o=this.safeDict(r,"withdrawal_fees",{}),n=Object.keys(o);for(let t=0;t<n.length;t++){let i=n[t],r=this.safeCurrencyCode(i);(void 0===e||this.inArray(r,e))&&void 0!==r&&(s[r]={deposit:this.safeValue(this.safeDict(s,r),"deposit"),withdraw:this.safeNumber(o,i),info:{deposit:this.safeValue(this.safeDict(this.safeDict(s,r),"info"),"deposit"),withdraw:this.safeNumber(o,i)}})}return s}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privateGetFees(t),s=this.safeList(i,"payload",[]);return this.parseDepositWithdrawFees(s,e)}parseDepositWithdrawFees(e,t,i){let s={},r=this.safeList(e,"deposit_fees",[]),a=this.safeDict(e,"withdrawal_fees",{});for(let e=0;e<r.length;e++){let i=r[e],a=this.safeString(i,"currency"),o=this.safeCurrencyCode(a);(void 0===t||void 0!==o&&o in t)&&void 0!==o&&(s[o]={deposit:{fee:this.safeNumber(i,"fee"),percentage:!this.safeBool(i,"is_fixed",!1)},withdraw:{fee:void 0,percentage:void 0},networks:{},info:i})}let o=Object.keys(a);for(let e=0;e<o.length;e++){let i=o[e],r=this.safeCurrencyCode(i);if(void 0!==r&&(void 0===t||r in t)){let e=this.parseNumber(a[i]);void 0===this.safeDict(s,r)&&(s[r]=this.depositWithdrawFee({})),s[r].withdraw.fee=e,s[r].info[r]=e}}return s}async withdraw(e,t,i,s,r={}){let[o,n]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let d={BTC:"Bitcoin",ETH:"Ether",XRP:"Ripple",BCH:"Bcash",LTC:"Litecoin"},h=this.currency(e),c=e in d?d[e]:void 0;if(void 0===c)throw new a.ExchangeError(this.id+" not valid withdraw coin: "+e);let l=await this["privatePost"+c+"Withdrawal"](this.extend({amount:t,address:i,destination_tag:o},n)),u=this.safeList(l,"payload",[]),f=this.safeDict(u,0);return this.parseTransaction(f,h)}parseTransaction(e,t){let i=this.safeString2(e,"currency","asset"),s=this.safeCurrency(i,t),r=this.safeDict(e,"details",{}),a=this.safeString(e,"created_at"),o=this.safeString(r,"withdrawal_address"),n=this.safeString(r,"receiving_address"),d=this.safeString2(e,"network","method"),h=this.safeString(e,"status"),c=this.safeString(e,"wid"),l=this.networkIdToCode(d,this.safeString(s,"code")),u=void 0!==l?l.toUpperCase():void 0;return{id:this.safeString2(e,"wid","fid"),txid:this.safeString(r,"tx_hash"),timestamp:this.parse8601(a),datetime:a,network:u,addressFrom:n,address:void 0!==o?o:n,addressTo:o,amount:this.safeNumber(e,"amount"),type:void 0===c?"deposit":"withdrawal",currency:this.safeCurrencyCode(i,s),status:this.parseTransactionStatus(h),updated:void 0,tagFrom:void 0,tag:void 0,tagTo:void 0,comment:void 0,internal:void 0,fee:void 0,info:e}}parseTransactionStatus(e){return this.safeString({pending:"pending",in_progress:"pending",complete:"ok",failed:"failed"},e,e)}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},o,n){let d=o,h=n,c="/"+this.version+"/"+this.implodeParams(e,r),l=this.omit(r,this.extractParams(e));("GET"===i||"DELETE"===i)&&Object.keys(l).length>0&&(c+="?"+this.urlencode(l));let u=this.safeString(this.urls.api,"rest");if(void 0===u)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let f=u+c;if("private"===t){this.checkRequiredCredentials();let e=this.incrementingNonce().toString(),t=[e,i,c="/api"+c].join("");"GET"!==i&&"DELETE"!==i&&Object.keys(l).length>0&&(t+=h=this.json(l));let r=this.hmac(this.encode(t),this.encode(this.secret),s.sc);d={Authorization:"Bitso "+(this.apiKey+":"+e+":")+r}}return{url:f,method:i,body:h,headers:d}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0!==n&&"success"in n){let e=this.safeBool(n,"success",!1);if("string"==typeof e&&(e="true"===e||"1"===e),!0!==e){let e=this.id+" "+this.json(n),t=this.safeDict(n,"error");if(void 0===t)throw new a.ExchangeError(e);let i=this.safeString(t,"code");throw this.throwExactlyMatchedException(this.exceptions,i,e),new a.ExchangeError(e)}}}}i.d(t,{A:()=>n})},2056(e,t,i){"use strict";var s=i(4721),r=i(4705),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bitstamp",name:"Bitstamp",countries:["GB"],rateLimit:75,version:"v2",userAgent:this.userAgents.chrome,pro:!0,has:{CORS:!0,spot:!0,margin:!1,swap:!0,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,editOrder:!0,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDepositsWithdrawals:!0,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLedger:!0,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTransactionFees:!0,fetchTransactions:"emulated",fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!0,withdraw:!0},urls:{logo:"https://github.com/user-attachments/assets/d5480572-1fee-43cb-b900-d38c522d0024",api:{public:"https://www.bitstamp.net/api",private:"https://www.bitstamp.net/api"},www:"https://www.bitstamp.net",doc:"https://www.bitstamp.net/api"},timeframes:{"1m":"60","3m":"180","5m":"300","15m":"900","30m":"1800","1h":"3600","2h":"7200","4h":"14400","6h":"21600","12h":"43200","1d":"86400","1w":"259200"},requiredCredentials:{apiKey:!0,secret:!0},api:{public:{get:{"ohlc/{pair}/":{cost:1},"order_book/{pair}/":{cost:1},"ticker/":{cost:1},"ticker_hour/{pair}/":{cost:1},"ticker/{pair}/":{cost:1},"transactions/{pair}/":{cost:1},"trading-pairs-info/":{cost:1},"markets/":{cost:1},"currencies/":{cost:1},"eur_usd/":{cost:1},"travel_rule/vasps/":{cost:1},"funding_rate/{market_symbol}/":{cost:1},"funding_rate_history/{pair}/":{cost:1},"derivatives/market_hours/":{cost:1},"derivatives/market_hours/{market_symbol}/":{cost:1}}},private:{get:{"travel_rule/contacts/":{cost:1},"contacts/{contact_uuid}/":{cost:1},"travel_rule/utxo/xpub_registrations/":{cost:1},"travel_rule/utxo/xpub_registrations/{registration_id}/":{cost:1},"travel_rule/address_verification/":{cost:1},"crypto-transactions/deposits/":{cost:1},"earn/subscriptions/":{cost:1},"earn/transactions/":{cost:1},"trade_history/":{cost:1},"trade_history/{pair}":{cost:1}},post:{"account_balances/":{cost:1},"account_balances/{currency}/":{cost:1},"balance/":{cost:1},"balance/{pair}/":{cost:1},"bch_withdrawal/":{cost:1},"bch_address/":{cost:1},"user_transactions/":{cost:1},"user_transactions/{pair}/":{cost:1},"crypto-transactions/":{cost:1},"crypto-transactions/deposits/{deposit_id}/reject/":{cost:1},open_order:{cost:1},"open_orders/all/":{cost:1},"open_orders/{pair}/":{cost:1},"replace_order/":{cost:1},"order_status/":{cost:1},"cancel_order/":{cost:1},"cancel_all_orders/":{cost:1},"cancel_all_orders/{pair}/":{cost:1},"buy/{pair}/":{cost:1},"buy/market/{pair}/":{cost:1},"buy/instant/{pair}/":{cost:1},"sell/{pair}/":{cost:1},"sell/market/{pair}/":{cost:1},"sell/instant/{pair}/":{cost:1},"transfer-to-main/":{cost:1},"transfer-from-main/":{cost:1},"my_trading_pairs/":{cost:1},"fees/trading/":{cost:1},"fees/trading/{market_symbol}":{cost:1},"fees/withdrawal/":{cost:1},"fees/withdrawal/{currency}/":{cost:1},"withdrawal-requests/":{cost:1},"withdrawal/open/":{cost:1},"withdrawal/status/":{cost:1},"withdrawal/cancel/":{cost:1},"liquidation_address/new/":{cost:1},"liquidation_address/info/":{cost:1},"btc_unconfirmed/":{cost:1},"websockets_token/":{cost:1},"revoke_all_api_keys/":{cost:1},"get_max_order_amount/":{cost:1},"order_data/":{cost:1},"account_order_data/":{cost:1},"btc_withdrawal/":{cost:1},"btc_address/":{cost:1},"ripple_withdrawal/":{cost:1},"ripple_address/":{cost:1},"ltc_withdrawal/":{cost:1},"ltc_address/":{cost:1},"eth_withdrawal/":{cost:1},"eth_address/":{cost:1},"xrp_withdrawal/":{cost:1},"xrp_address/":{cost:1},"xlm_withdrawal/":{cost:1},"xlm_address/":{cost:1},"pax_withdrawal/":{cost:1},"pax_address/":{cost:1},"link_withdrawal/":{cost:1},"link_address/":{cost:1},"usdc_withdrawal/":{cost:1},"usdc_address/":{cost:1},"omg_withdrawal/":{cost:1},"omg_address/":{cost:1},"dai_withdrawal/":{cost:1},"dai_address/":{cost:1},"knc_withdrawal/":{cost:1},"knc_address/":{cost:1},"mkr_withdrawal/":{cost:1},"mkr_address/":{cost:1},"zrx_withdrawal/":{cost:1},"zrx_address/":{cost:1},"gusd_withdrawal/":{cost:1},"gusd_address/":{cost:1},"aave_withdrawal/":{cost:1},"aave_address/":{cost:1},"bat_withdrawal/":{cost:1},"bat_address/":{cost:1},"uma_withdrawal/":{cost:1},"uma_address/":{cost:1},"snx_withdrawal/":{cost:1},"snx_address/":{cost:1},"uni_withdrawal/":{cost:1},"uni_address/":{cost:1},"yfi_withdrawal/":{cost:1},"yfi_address/":{cost:1},"audio_withdrawal/":{cost:1},"audio_address/":{cost:1},"crv_withdrawal/":{cost:1},"crv_address/":{cost:1},"algo_withdrawal/":{cost:1},"algo_address/":{cost:1},"comp_withdrawal/":{cost:1},"comp_address/":{cost:1},"grt_withdrawal/":{cost:1},"grt_address/":{cost:1},"usdt_withdrawal/":{cost:1},"usdt_address/":{cost:1},"eurt_withdrawal/":{cost:1},"eurt_address/":{cost:1},"matic_withdrawal/":{cost:1},"matic_address/":{cost:1},"sushi_withdrawal/":{cost:1},"sushi_address/":{cost:1},"chz_withdrawal/":{cost:1},"chz_address/":{cost:1},"enj_withdrawal/":{cost:1},"enj_address/":{cost:1},"alpha_withdrawal/":{cost:1},"alpha_address/":{cost:1},"ftt_withdrawal/":{cost:1},"ftt_address/":{cost:1},"storj_withdrawal/":{cost:1},"storj_address/":{cost:1},"axs_withdrawal/":{cost:1},"axs_address/":{cost:1},"sand_withdrawal/":{cost:1},"sand_address/":{cost:1},"hbar_withdrawal/":{cost:1},"hbar_address/":{cost:1},"rgt_withdrawal/":{cost:1},"rgt_address/":{cost:1},"fet_withdrawal/":{cost:1},"fet_address/":{cost:1},"skl_withdrawal/":{cost:1},"skl_address/":{cost:1},"cel_withdrawal/":{cost:1},"cel_address/":{cost:1},"sxp_withdrawal/":{cost:1},"sxp_address/":{cost:1},"ada_withdrawal/":{cost:1},"ada_address/":{cost:1},"slp_withdrawal/":{cost:1},"slp_address/":{cost:1},"ftm_withdrawal/":{cost:1},"ftm_address/":{cost:1},"perp_withdrawal/":{cost:1},"perp_address/":{cost:1},"dydx_withdrawal/":{cost:1},"dydx_address/":{cost:1},"gala_withdrawal/":{cost:1},"gala_address/":{cost:1},"shib_withdrawal/":{cost:1},"shib_address/":{cost:1},"amp_withdrawal/":{cost:1},"amp_address/":{cost:1},"sgb_withdrawal/":{cost:1},"sgb_address/":{cost:1},"avax_withdrawal/":{cost:1},"avax_address/":{cost:1},"wbtc_withdrawal/":{cost:1},"wbtc_address/":{cost:1},"ctsi_withdrawal/":{cost:1},"ctsi_address/":{cost:1},"cvx_withdrawal/":{cost:1},"cvx_address/":{cost:1},"imx_withdrawal/":{cost:1},"imx_address/":{cost:1},"nexo_withdrawal/":{cost:1},"nexo_address/":{cost:1},"ust_withdrawal/":{cost:1},"ust_address/":{cost:1},"ant_withdrawal/":{cost:1},"ant_address/":{cost:1},"gods_withdrawal/":{cost:1},"gods_address/":{cost:1},"rad_withdrawal/":{cost:1},"rad_address/":{cost:1},"band_withdrawal/":{cost:1},"band_address/":{cost:1},"inj_withdrawal/":{cost:1},"inj_address/":{cost:1},"rly_withdrawal/":{cost:1},"rly_address/":{cost:1},"rndr_withdrawal/":{cost:1},"rndr_address/":{cost:1},"vega_withdrawal/":{cost:1},"vega_address/":{cost:1},"1inch_withdrawal/":{cost:1},"1inch_address/":{cost:1},"ens_withdrawal/":{cost:1},"ens_address/":{cost:1},"mana_withdrawal/":{cost:1},"mana_address/":{cost:1},"lrc_withdrawal/":{cost:1},"lrc_address/":{cost:1},"ape_withdrawal/":{cost:1},"ape_address/":{cost:1},"mpl_withdrawal/":{cost:1},"mpl_address/":{cost:1},"euroc_withdrawal/":{cost:1},"euroc_address/":{cost:1},"sol_withdrawal/":{cost:1},"sol_address/":{cost:1},"dot_withdrawal/":{cost:1},"dot_address/":{cost:1},"near_withdrawal/":{cost:1},"near_address/":{cost:1},"doge_withdrawal/":{cost:1},"doge_address/":{cost:1},"flr_withdrawal/":{cost:1},"flr_address/":{cost:1},"dgld_withdrawal/":{cost:1},"dgld_address/":{cost:1},"ldo_withdrawal/":{cost:1},"ldo_address/":{cost:1},"travel_rule/contacts/":{cost:1},"travel_rule/utxo/xpub_registrations/":{cost:1},"travel_rule/utxo/xpub_registrations/{registration_id}/revoke/":{cost:1},"earn/subscribe/":{cost:1},"earn/subscriptions/setting/":{cost:1},"earn/unsubscribe":{cost:1},"wecan_withdrawal/":{cost:1},"wecan_address/":{cost:1},"trac_withdrawal/":{cost:1},"trac_address/":{cost:1},"eurcv_withdrawal/":{cost:1},"eurcv_address/":{cost:1},"pyusd_withdrawal/":{cost:1},"pyusd_address/":{cost:1},"lmwr_withdrawal/":{cost:1},"lmwr_address/":{cost:1},"pepe_withdrawal/":{cost:1},"pepe_address/":{cost:1},"blur_withdrawal/":{cost:1},"blur_address/":{cost:1},"vext_withdrawal/":{cost:1},"vext_address/":{cost:1},"cspr_withdrawal/":{cost:1},"cspr_address/":{cost:1},"vchf_withdrawal/":{cost:1},"vchf_address/":{cost:1},"veur_withdrawal/":{cost:1},"veur_address/":{cost:1},"truf_withdrawal/":{cost:1},"truf_address/":{cost:1},"wif_withdrawal/":{cost:1},"wif_address/":{cost:1},"smt_withdrawal/":{cost:1},"smt_address/":{cost:1},"sui_withdrawal/":{cost:1},"sui_address/":{cost:1},"jup_withdrawal/":{cost:1},"jup_address/":{cost:1},"ondo_withdrawal/":{cost:1},"ondo_address/":{cost:1},"boba_withdrawal/":{cost:1},"boba_address/":{cost:1},"pyth_withdrawal/":{cost:1},"pyth_address/":{cost:1}}}},fees:{trading:{tierBased:!0,percentage:!0,taker:this.parseNumber("0.004"),maker:this.parseNumber("0.004"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.004")],[this.parseNumber("10000"),this.parseNumber("0.003")],[this.parseNumber("100000"),this.parseNumber("0.002")],[this.parseNumber("500000"),this.parseNumber("0.0018")],[this.parseNumber("1500000"),this.parseNumber("0.0016")],[this.parseNumber("5000000"),this.parseNumber("0.0012")],[this.parseNumber("20000000"),this.parseNumber("0.001")],[this.parseNumber("50000000"),this.parseNumber("0.0008")],[this.parseNumber("100000000"),this.parseNumber("0.0006")],[this.parseNumber("250000000"),this.parseNumber("0.0005")],[this.parseNumber("1000000000"),this.parseNumber("0.0003")]],maker:[[this.parseNumber("0"),this.parseNumber("0.003")],[this.parseNumber("10000"),this.parseNumber("0.002")],[this.parseNumber("100000"),this.parseNumber("0.001")],[this.parseNumber("500000"),this.parseNumber("0.0008")],[this.parseNumber("1500000"),this.parseNumber("0.0006")],[this.parseNumber("5000000"),this.parseNumber("0.0003")],[this.parseNumber("20000000"),this.parseNumber("0.002")],[this.parseNumber("50000000"),this.parseNumber("0.0001")],[this.parseNumber("100000000"),this.parseNumber("0")],[this.parseNumber("250000000"),this.parseNumber("0")],[this.parseNumber("1000000000"),this.parseNumber("0")]]}},funding:{tierBased:!1,percentage:!1,withdraw:{},deposit:{BTC:0,BCH:0,LTC:0,ETH:0,XRP:0,XLM:0,PAX:0,USD:7.5,EUR:0}}},precisionMode:4,commonCurrencies:{UST:"USTC"},options:{mica:!0,networksById:{"bitcoin-cash":"BCH",bitcoin:"BTC",ethereum:"ERC20",litecoin:"LTC",stellar:"XLM",xrpl:"XRP",tron:"TRC20",algorand:"ALGO",flare:"FLR",hedera:"HBAR",cardana:"ADA",songbird:"FLR","avalanche-c-chain":"AVAX",solana:"SOL",polkadot:"DOT",near:"NEAR",doge:"DOGE",sui:"SUI",casper:"CSRP"}},exceptions:{exact:{"No permission found":a.PermissionDenied,"API key not found":a.AuthenticationError,"IP address not allowed":a.PermissionDenied,"Invalid nonce":a.InvalidNonce,"Invalid signature":a.AuthenticationError,"Authentication failed":a.AuthenticationError,"Missing key, signature and nonce parameters":a.AuthenticationError,"Wrong API key format":a.AuthenticationError,"Your account is frozen":a.PermissionDenied,"Please update your profile with your FATCA information, before using API.":a.PermissionDenied,"Order not found.":a.OrderNotFound,"Bitstamp.net is under scheduled maintenance. We'll be back soon.":a.OnMaintenance,"Order could not be placed.":a.ExchangeNotAvailable,"Invalid offset.":a.BadRequest,"Trading is currently unavailable for your account.":a.AccountSuspended},broad:{"Minimum order size is":a.InvalidOrder,"Price is more than":a.InvalidOrder,"Check your account balance for details.":a.InsufficientFunds,"Ensure this value has at least":a.InvalidAddress,"Ensure that there are no more than":a.InvalidOrder}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!0},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:void 0,untilDays:30,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:{limit:1e3}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}}})}async fetchMarkets(e={}){let t=await this.fetchMarketsFromCache(e),i=[];for(let e=0;e<t.length;e++){let s,r,a,o=t[e],[n,d]=[this.safeString(o,"base_currency"),this.safeString(o,"counter_currency")],h=this.safeCurrencyCode(n),c=this.safeCurrencyCode(d);if(void 0===h||void 0===c)continue;let l=this.safeString(o,"market_type"),u=h+"/"+c;if("SPOT"===l)r="spot";else if("PERPETUAL"===l){r="swap",u=h+"/"+c+":"+(s=d);let e=this.safeString(o,"payoff_type");"Linear"===e?a="linear":"Inverse"===e&&(a="inverse")}let f="spot"===r,p=void 0!==s&&""!==s?this.safeCurrencyCode(s):void 0;i.push({id:this.safeString(o,"market_symbol"),symbol:u,base:h,quote:c,settle:p,baseId:n,quoteId:d,settleId:s,type:r,subType:a,spot:f,margin:!1,future:!1,swap:!f,option:!1,active:"Enabled"===this.safeString(o,"trading"),contract:!f,linear:!f||void 0,inverse:!!f&&void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(o,"base_decimals"))),price:this.parseNumber(this.parsePrecision(this.safeString(o,"counter_decimals")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(o,"minimum_order_amount"),max:this.safeNumber(o,"maximum_order_amount")},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(o,"minimum_order_value"),max:this.safeNumber(o,"maximum_order_value")}},created:void 0,info:o})}return i}constructCurrencyObject(e,t,i,s,r,a){let o="crypto",n=this.describe();this.isFiat(t)&&(o="fiat");let d=this.parseNumber(this.parsePrecision(this.numberToString(s)));return{id:e,code:t,info:a,type:o,name:i,active:!0,deposit:void 0,withdraw:void 0,fee:this.safeNumber(n.fees.funding.withdraw,t),precision:d,limits:{amount:{min:d,max:void 0},price:{min:d,max:void 0},cost:{min:r,max:void 0},withdraw:{min:void 0,max:void 0}},networks:{}}}async fetchMarketsFromCache(e={}){let t=this.safeDict(this.options,"fetchMarkets",{}),i=this.safeInteger(t,"timestamp"),s=this.safeInteger(t,"expires",1e3),r=this.milliseconds();if(void 0===i||r-i>s){let i=await this.publicGetMarkets(e);this.options.fetchMarkets=this.extend(t,{response:i,timestamp:r})}return this.safeValue(this.options.fetchMarkets,"response")}async fetchCurrencies(e={}){let t=await this.fetchMarketsFromCache(e);return this.parseCurrencies(t)}parseCurrencies(e){let t={},i=this.toArray(e);for(let e=0;e<i.length;e++){let s=i[e],[r,o]=[this.safeString(s,"base_currency"),this.safeString(s,"counter_currency")],n=this.safeCurrencyCode(r),d=this.safeCurrencyCode(o),h=this.safeString(s,"description");if(void 0===h)throw new a.ExchangeError(this.id+" parseCurrencies() missing description");let[c,l]=h.split(" / "),u=this.safeString(s,"minimum_order_value");if(void 0===u)throw new a.ExchangeError(this.id+" parseCurrencies() missing minimumOrder");let f=u.split(" ")[0];if(void 0!==n&&!(n in t)){let e=this.safeInteger(s,"base_decimals");t[n]=this.constructCurrencyObject(r,n,c,e,void 0,s)}if(void 0!==d&&!(d in t)){let e=this.safeInteger(s,"counter_decimals");t[d]=this.constructCurrencyObject(o,d,l,e,this.parseNumber(f),s)}}return t}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={pair:s.id},o=await this.publicGetOrderBookPair(this.extend(r,i)),n=this.safeInteger(o,"microtimestamp");if(void 0===n)throw new a.ExchangeError(this.id+" fetchOrderBook() missing microtimestamp");let d=this.parseToInt(n/1e3),h=this.parseOrderBook(o,s.symbol,d);return h.nonce=n,h}parseTicker(e,t){let i=this.safeString(e,"pair"),s=this.safeSymbol(i,t),r=this.safeTimestamp(e,"timestamp"),a=this.safeString(e,"vwap"),n=this.safeString(e,"volume"),d=o.Y.stringMul(n,a),h=this.safeString(e,"last");return this.safeTicker({symbol:s,timestamp:r,datetime:this.iso8601(r),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"bid"),bidVolume:void 0,ask:this.safeString(e,"ask"),askVolume:void 0,vwap:a,open:this.safeString(e,"open"),close:h,last:h,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:n,quoteVolume:d,info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={pair:i.id},r=await this.publicGetTickerPair(this.extend(s,t));return this.parseTicker(r,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetTicker(t);return this.parseTickers(i,e)}getCurrencyIdFromTransaction(e){let t=this.safeStringLower(e,"currency");if(void 0!==t)return t;let i=this.omit(e,["fee","price","datetime","type","status","id"]),s=Object.keys(i);for(let e=0;e<s.length;e++){let t=s[e];if(0>t.indexOf("_")){let e=this.safeInteger(i,t);if(void 0!==e&&0!==e)return t}}}getMarketFromTrade(e){let t=this.omit(e,["fee","price","datetime","tid","type","order_id","side"]),i=Object.keys(t),s=i.length;if(s>2)throw new a.ExchangeError(this.id+" getMarketFromTrade() too many keys: "+this.json(i)+" in the trade: "+this.json(t));if(2===s){let e=i[0]+i[1];if(void 0!==this.markets_by_id&&e in this.markets_by_id||(e=i[1]+i[0],void 0!==this.markets_by_id&&e in this.markets_by_id))return this.safeMarket(e)}}parseTrade(e,t){let i,s,r,a,n,d,h=this.safeString2(e,"id","tid"),c=this.safeString(e,"price"),l=this.safeString(e,"amount"),u=this.safeString(e,"order_id"),f=this.safeString(e,"cost"),p=t;if(void 0===t){let t=Object.keys(e);for(let e=0;e<t.length;e++){let i=t[e];"order_id"!==i&&i.indexOf("_")>=0&&(r=i,p=this.safeMarket(r,p,"_"))}}void 0===p&&(p=this.getMarketFromTrade(e));let m=this.safeString(e,"fee"),g=this.safeString(p,"quote");a=void 0!==r?r:this.safeString(p,"id"),c=this.safeString(e,a,c),l=this.safeString(e,this.safeString(p,"baseId"),l),f=this.safeString(e,this.safeString(p,"quoteId"),f);let v=this.safeStringLower(p,"baseId"),y=this.safeStringLower(p,"quoteId"),b=v+"_"+y;void 0===c&&(c=this.safeString(e,b)),void 0===l&&(l=this.safeString(e,v)),void 0===f&&(f=this.safeString(e,y)),i=this.safeString(p,"symbol");let w=this.safeString2(e,"date","datetime");return void 0!==w&&(n=w.indexOf(" ")>=0?this.parse8601(w):1e3*parseInt(w)),"id"in e?void 0!==l&&(o.Y.stringLt(l,"0")?(s="sell",l=o.Y.stringNeg(l)):s="buy"):s="1"===(s=this.safeString(e,"type"))?"sell":"0"===s?"buy":void 0,void 0!==f&&(f=o.Y.stringAbs(f)),void 0!==m&&(d={cost:m,currency:g}),this.safeTrade({id:h,info:e,timestamp:n,datetime:this.iso8601(n),symbol:i,order:u,type:void 0,side:s,takerOrMaker:void 0,price:c,amount:l,cost:f,fee:d},p)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={pair:r.id,time:"hour"},o=await this.publicGetTransactionsPair(this.extend(a,s));return this.parseTrades(o,r,t,i)}parseOHLCV(e,t){return[this.safeTimestamp(e,"timestamp"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={pair:a.id,step:this.safeString(this.timeframes,t,t)},n=this.parseTimeframe(t),d=this.safeInteger(r,"until"),h=void 0!==d,c=void 0===s?1e3:s;if(void 0===s)if(void 0===i){if(o.limit=c,h){let e=this.parseToInt(d/1e3);o.start=e-n*c-1,o.end=e}}else{let e=this.parseToInt(i/1e3);o.start=e,h?o.end=this.parseToInt(d/1e3):o.end=this.sum(e,n*c-1),o.limit=c}else{if(void 0!==i){let e=this.parseToInt(i/1e3);o.start=e;let t=this.sum(e,n*c-1);h&&(t=Math.min(t,this.parseToInt(d/1e3))),o.end=t}else if(h){let e=this.parseToInt(d/1e3);o.end=e,o.start=e-n*c-1}o.limit=Math.min(c,1e3)}let l=this.omit(r,"until"),u=await this.publicGetOhlcPair(this.extend(o,l)),f=this.safeDict(u,"data",{}),p=this.safeList(f,"ohlc",[]);return this.parseOHLCVs(p,a,t,i,c)}parseBalance(e){let t={info:e,timestamp:void 0,datetime:void 0},i=e;void 0===e&&(i=[]);for(let e=0;e<i.length;e++){let s=this.safeDict(i,e),r=this.safeString(s,"currency"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(s,"available"),o.used=this.safeString(s,"reserved"),o.total=this.safeString(s,"total"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostAccountBalances(e);return this.parseBalance(t)}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={market_symbol:i.id},r=await this.privatePostFeesTrading(this.extend(s,t)),a=this.indexBy(r,"currency_pair"),o=this.safeDict(a,i.id);return void 0===o&&(o={}),this.parseTradingFee(o,i)}parseTradingFee(e,t){let i=this.safeString(e,"market"),s=this.safeDict(e,"fees",{});return{info:e,symbol:this.safeSymbol(i,t),maker:this.safeNumber(s,"maker"),taker:this.safeNumber(s,"taker"),percentage:void 0,tierBased:void 0}}parseTradingFees(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.parseTradingFee(e[i]),r=s.symbol;void 0!==r&&(t[r]=s)}return t}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostFeesTrading(e);return this.parseTradingFees(t)}async fetchTransactionFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privatePostFeesWithdrawal(t);return this.parseTransactionFees(i)}parseTransactionFees(e,t){let i={},s=this.indexBy(e,"currency"),r=Object.keys(s);for(let a=0;a<r.length;a++){let o=r[a],n=this.safeDict(e,a,{}),d=this.safeCurrencyCode(o);(void 0===t||this.inArray(d,t))&&void 0!==d&&(i[d]={withdraw_fee:this.safeNumber(n,"fee"),deposit:{},info:this.safeDict(s,o)})}return i}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privatePostFeesWithdrawal(t),s=this.groupBy(i,"currency");return this.parseDepositWithdrawFees(s,e)}parseDepositWithdrawFee(e,t){let i=this.depositWithdrawFee(e),s=this.safeString(t,"code");for(let t=0;t<e.length;t++){let r=this.safeDict(e,t),a=this.safeString(r,"network"),o=this.networkIdToCode(a,s),n=this.safeNumber(r,"fee");i.withdraw={fee:n,percentage:void 0},void 0!==o&&(i.networks[o]={withdraw:{fee:n,percentage:void 0},deposit:{fee:void 0,percentage:void 0}})}return i}async createOrder(e,t,i,s,r,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d={pair:n.id,amount:this.amountToPrecision(e,s)},h=this.safeString2(a,"client_order_id","clientOrderId");void 0!==h&&(d.client_order_id=h);let c=void 0!==h?this.omit(a,["clientOrderId"]):a,l=this.capitalize(i);"market"===t?o="Buy"===l?await this.privatePostBuyMarketPair(this.extend(d,c)):await this.privatePostSellMarketPair(this.extend(d,c)):"instant"===t?o="Buy"===l?await this.privatePostBuyInstantPair(this.extend(d,c)):await this.privatePostSellInstantPair(this.extend(d,c)):(d.price=this.priceToPrecision(e,r),o="Buy"===l?await this.privatePostBuyPair(this.extend(d,c)):await this.privatePostSellPair(this.extend(d,c)));let u=void 0===o?{}:o,f=this.parseOrder(u,n);return f.type=t,f}async editOrder(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(t),d={amount:this.amountToPrecision(t,r),price:this.priceToPrecision(t,a)},h=this.safeString2(o,"client_order_id","clientOrderId");void 0!==h?d.client_order_id=h:d.id=e;let c=void 0!==h?this.omit(o,["clientOrderId"]):o,l=await this.privatePostReplaceOrder(this.extend(d,c)),u=this.parseOrder(l,n);return u.type=i,u}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privatePostCancelOrder(this.extend({id:e},i));return this.parseOrder(s)}async cancelAllOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={};void 0!==e?(s.pair=this.market(e).id,i=await this.privatePostCancelAllOrdersPair(this.extend(s,t))):i=await this.privatePostCancelAllOrders(this.extend(s,t));let r=this.safeList(i,"canceled");return this.parseOrders(r)}parseOrderStatus(e){return this.safeString({"In Queue":"open",Open:"open",Finished:"closed",Canceled:"canceled","Cancel pending":"canceling"},e,e)}async fetchOrderStatus(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.safeValue2(i,"client_order_id","clientOrderId"),r={};void 0!==s?r.client_order_id=s:r.id=e;let a=void 0!==s?this.omit(i,["client_order_id","clientOrderId"]):i,o=await this.privatePostOrderStatus(this.extend(r,a));return this.parseOrderStatus(this.safeString(o,"status"))}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let r=this.safeValue2(i,"client_order_id","clientOrderId"),a={};void 0!==r?a.client_order_id=r:a.id=e;let o=void 0!==r?this.omit(i,["client_order_id","clientOrderId"]):i,n=await this.privatePostOrderStatus(this.extend(a,o));return this.parseOrder(n,s)}async fetchMyTrades(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o={};void 0!==e&&(o.pair=(r=this.market(e)).id),void 0!==i&&(o.limit=i),a=void 0!==e?await this.privatePostUserTransactionsPair(this.extend(o,s)):await this.privatePostUserTransactions(this.extend(o,s));let n=this.filterBy(a,"type","2");return this.parseTrades(n,r,t,i)}async fetchFundingRateHistory(e,t,i,s={}){let r,[a,o]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchFundingRateHistory",e,t,i,"8h",o);void 0===this.markets&&await this.loadMarkets();let n={};void 0!==e&&(n.pair=(r=this.market(e)).id),void 0!==t&&(n.since_timestamp=Math.round(t/1e3));let[d,h]=this.handleUntilOption("until_timestamp",n,o,.001);void 0!==i&&(d.limit=i);let c=await this.publicGetFundingRateHistoryPair(this.extend(d,h)),l=this.safeList(c,"funding_rate_history",[]);return this.parseFundingRateHistories(l,r,t,i)}parseFundingRateHistory(e,t){let i=this.safeIntegerProduct(e,"timestamp",.001);return{info:e,symbol:void 0,fundingRate:this.safeNumber(e,"funding_rate"),timestamp:i,datetime:this.iso8601(i)}}async fetchDepositsWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==i&&(a.limit=i);let o=await this.privatePostUserTransactions(this.extend(a,s));void 0!==e&&(r=this.currency(e));let n=this.filterByArray(o,"type",["0","1"],!1);return this.parseTransactions(n,r,t,i)}async fetchWithdrawals(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={};void 0!==t?r.timedelta=this.milliseconds()-t:r.timedelta=5e7;let a=await this.privatePostWithdrawalRequests(this.extend(r,s));return this.parseTransactions(a,void 0,t,i)}parseTransaction(e,t){let i,s,r,a,n=this.parse8601(this.safeString(e,"datetime")),d=this.getCurrencyIdFromTransaction(e),h=this.safeCurrencyCode(d,t),c=this.safeString(e,"fee");"amount"in e?s=this.safeString(e,"amount"):void 0!==t?(s=this.safeString(e,t.id,s),i=t.code):void 0!==h&&void 0!==d&&(s=this.safeString(e,d,s),i=h),void 0!==s&&(s=o.Y.stringAbs(s));let l="ok";if("status"in e&&(l=this.parseTransactionStatus(this.safeString(e,"status"))),"type"in e){let t=this.safeString(e,"type");"0"===t?r="deposit":"1"===t&&(r="withdrawal")}else r="withdrawal";let u=this.safeString(e,"address");if(void 0!==u){let e=u.split("?dt=");e.length>1&&(u=e[0],a=e[1])}let f={currency:void 0,cost:void 0,rate:void 0};return void 0!==c&&(f={currency:i,cost:c,rate:void 0}),{info:e,id:this.safeString(e,"id"),txid:this.safeString(e,"transaction_id"),type:r,currency:h,network:void 0,amount:this.parseNumber(s),status:l,timestamp:n,datetime:this.iso8601(n),address:u,addressFrom:void 0,addressTo:u,tag:a,tagFrom:void 0,tagTo:a,updated:void 0,comment:void 0,internal:void 0,fee:f}}parseTransactionStatus(e){return this.safeString({0:"pending",1:"pending",2:"ok",3:"canceled",4:"failed"},e,e)}parseOrder(e,t){let i=this.safeString2(e,"id","order_id"),s=this.safeString2(e,"client_order_id","orig_client_order_id"),r=this.safeString2(e,"type","order_type");void 0!==r&&(r="1"===r?"sell":"buy");let a=this.parse8601(this.safeString(e,"datetime")),o=this.safeStringLower(e,"currency_pair"),n=this.safeSymbol(o,t,"/"),d=this.parseOrderStatus(this.safeString(e,"status")),h=this.safeString(e,"amount"),c=this.safeList(e,"transactions",[]),l=this.safeString(e,"price");return this.safeOrder({id:i,clientOrderId:s,datetime:this.iso8601(a),timestamp:a,lastTradeTimestamp:void 0,status:d,symbol:n,type:void 0,timeInForce:void 0,postOnly:void 0,side:r,price:l,triggerPrice:void 0,cost:void 0,amount:h,filled:void 0,remaining:void 0,trades:c,fee:void 0,info:e,average:void 0},t)}parseLedgerEntryType(e){return this.safeString({0:"transaction",1:"transaction",2:"trade",14:"transfer"},e,e)}parseLedgerEntry(e,t){let i=this.parseLedgerEntryType(this.safeString(e,"type"));if("trade"===i){let s,r=this.parseTrade(e),a=Object.keys(e);for(let e=0;e<a.length;e++)if(a[e].indexOf("_")>=0){let t=a[e].replace("_","");s=this.safeMarket(t,s)}void 0===s&&(s=this.getMarketFromTrade(e));let o="buy"===r.side?"in":"out";return this.safeLedgerEntry({info:e,id:r.id,timestamp:r.timestamp,datetime:r.datetime,direction:o,account:void 0,referenceId:r.order,referenceAccount:void 0,type:i,currency:this.safeString(s,"base"),amount:r.amount,before:void 0,after:void 0,status:"ok",fee:r.fee},t)}{let s,r=this.parseTransaction(e,t),a=!("amount"in e)&&"currency"in r&&void 0!==r.currency,n=t;if(a&&(n=this.currency(this.safeString(r,"currency"))),"amount"in e){let t=this.safeString(e,"amount");s=o.Y.stringGt(t,"0")?"in":"out"}else if("currency"in r&&void 0!==r.currency){let t=this.safeString(e,this.safeString(n,"id"));s=o.Y.stringGt(t,"0")?"in":"out"}return this.safeLedgerEntry({info:e,id:r.id,timestamp:r.timestamp,datetime:r.datetime,direction:s,account:void 0,referenceId:r.txid,referenceAccount:void 0,type:i,currency:r.currency,amount:r.amount,before:void 0,after:void 0,status:r.status,fee:r.fee},n)}}async fetchLedger(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==i&&(a.limit=i);let o=await this.privatePostUserTransactions(this.extend(a,s));return void 0!==e&&(r=this.currency(e)),this.parseLedger(o,r,t,i)}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={market_symbol:i.id},r=await this.publicGetFundingRateMarketSymbol(this.extend(s,t));return this.parseFundingRate(r,i)}parseFundingRate(e,t){let i=this.safeIntegerProduct(e,"timestamp",1e3),s=this.safeIntegerProduct(e,"next_funding_time",1e3),r=this.safeString(e,"market");return{info:e,symbol:this.safeSymbol(r,t),markPrice:this.safeNumber(e,"mark_price"),indexPrice:this.safeNumber(e,"index_price"),interestRate:void 0,estimatedSettlePrice:void 0,timestamp:i,datetime:this.iso8601(i),previousFundingRate:void 0,nextFundingRate:void 0,previousFundingTimestamp:void 0,nextFundingTimestamp:void 0,previousFundingDatetime:void 0,nextFundingDatetime:void 0,fundingRate:this.safeNumber(e,"funding_rate"),fundingTimestamp:s,fundingDatetime:this.iso8601(s),interval:void 0}}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a=await this.privatePostOpenOrdersAll(s);return this.parseOrders(a,r,t,i,{status:"open",type:"limit"})}getCurrencyName(e){return e.toLowerCase()}isFiat(e){return"USD"===e||"EUR"===e||"GBP"===e}async fetchDepositAddress(e,t={}){if(this.isFiat(e))throw new a.NotSupported(this.id+" fiat fetchDepositAddress() for "+e+" is not supported!");let i=this.getCurrencyName(e),s=await this.request(i+"_address/","private","POST",t),r=this.safeString(s,"address"),o=this.safeString2(s,"memo_id","destination_tag");return this.checkAddress(r),{info:s,currency:e,network:void 0,address:r,tag:o}}async withdraw(e,t,i,s,r={}){let a,o,[n,d]=this.handleWithdrawTagAndParams(s,r);void 0===this.markets&&await this.loadMarkets(),this.checkAddress(i);let h={amount:t};if(this.isFiat(e))a=this.currency(e),h.iban=i,h.account_currency=a.id,o=await this.privatePostWithdrawalOpen(this.extend(h,d));else{let t=this.getCurrencyName(e);"XRP"===e?void 0!==n&&(h.destination_tag=n):("XLM"===e||"HBAR"===e)&&void 0!==n&&(h.memo_id=n),h.address=i,o=await this.request(t+"_withdrawal/","private","POST",this.extend(h,d))}return this.parseTransaction(o,a)}async transfer(e,t,i,s,r={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d={amount:this.parseToNumeric(this.currencyToPrecision(e,t)),currency:n.id.toUpperCase()};if("main"===i)d.subAccount=s,o=await this.privatePostTransferFromMain(this.extend(d,r));else if("main"===s)d.subAccount=i,o=await this.privatePostTransferToMain(this.extend(d,r));else throw new a.BadRequest(this.id+" transfer() only supports from or to main");let h=this.parseTransfer(o,n);return h.amount=t,h.fromAccount=i,h.toAccount=s,h}parseTransfer(e,t){let i=this.safeString(e,"status");if(void 0===t)throw new a.ExchangeError(this.id+" parseTransfer() could not resolve currency");return{info:e,id:void 0,timestamp:void 0,datetime:void 0,currency:t.code,amount:void 0,fromAccount:void 0,toAccount:void 0,status:this.parseTransferStatus(i)}}parseTransferStatus(e){return this.safeString({ok:"ok",error:"failed"},e,e)}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},o,n){let d,h=this.safeString(this.urls.api,t);if(void 0===h)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let c=h+"/";c+=this.version+"/",c+=this.implodeParams(e,r);let l=this.omit(r,this.extractParams(e)),u="public"!==t&&"POST"===i,f=this.urlencode({foo:"bar"});Object.keys(l).length>0&&(f=this.urlencode(l));let p=n;if(u&&(p=f),"public"===t)Object.keys(l).length>0&&(c+="?"+this.urlencode(l));else{this.checkRequiredCredentials();let e="BITSTAMP "+this.apiKey,t=this.uuid(),r=this.milliseconds().toString(),a="";d={"X-Auth":e,"X-Auth-Nonce":t,"X-Auth-Timestamp":r,"X-Auth-Version":"v2"},"POST"===i&&(a="application/x-www-form-urlencoded",d["Content-Type"]=a);let o="";void 0!==p&&""!==p&&(o=p);let n=e+i+c.replace("https://","")+a+t+r+"v2"+o,h=this.hmac(this.encode(n),this.encode(this.secret),s.sc);d["X-Auth-Signature"]=h}return{url:c,method:i,body:p,headers:"public"===t?o:d}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"status"),l=this.safeValue(n,"error");if("error"===c||void 0!==l){let e=[];if("string"==typeof l)e.push(l);else if(void 0!==l){let t=Object.keys(l);for(let i=0;i<t.length;i++){let s=t[i],r=this.safeValue(l,s);Array.isArray(r)?e=this.arrayConcat(e,r):e.push(r)}}let t=this.safeValue(n,"reason",{});if("string"==typeof t)e.push(t);else{let i=this.safeList(t,"__all__",[]);for(let t=0;t<i.length;t++)e.push(i[t])}if("API0005"===this.safeString(n,"code"))throw new a.AuthenticationError(this.id+" invalid signature, use the uid for the main account if you have subaccounts");let i=this.id+" "+o;for(let t=0;t<e.length;t++){let s=e[t];this.throwExactlyMatchedException(this.exceptions.exact,s,i),this.throwBroadlyMatchedException(this.exceptions.broad,s,i)}throw new a.ExchangeError(i)}}}i.d(t,{A:()=>n})},3122(e,t,i){"use strict";var s=i(9385),r=i(1453),a=i(7749);class o extends s.A{describe(){return this.deepExtend(super.describe(),{id:"bitteam",name:"BIT.TEAM",countries:["UK"],version:"v2.0.6",rateLimit:1,certified:!1,pro:!1,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!1,closeAllPositions:!1,closePosition:!1,createDepositAddress:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,deposit:!1,editOrder:!1,fetchAccounts:!1,fetchBalance:!0,fetchBidsAsks:!1,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCanceledOrders:!0,fetchClosedOrder:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:!1,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!1,fetchDepositsWithdrawals:!0,fetchDepositWithdrawFee:!1,fetchDepositWithdrawFees:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchL3OrderBook:!1,fetchLedger:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrder:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrders:!0,fetchOrderTrades:!1,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchStatus:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!1,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTradingLimits:!1,fetchTransactionFee:!1,fetchTransactionFees:!1,fetchTransactions:!0,fetchTransfers:!1,fetchVolatilityHistory:!1,fetchWithdrawal:!1,fetchWithdrawals:!1,fetchWithdrawalWhitelist:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,signIn:!1,transfer:!1,withdraw:!1,ws:!1},timeframes:{"1m":"1","5m":"5","15m":"15","1h":"60","1d":"1D"},urls:{logo:"https://github.com/user-attachments/assets/b41b5e0d-98e5-4bd3-8a6e-aeb230a4a135",api:{history:"https://history.bit.team",public:"https://bit.team",private:"https://bit.team"},www:"https://bit.team/",referral:"https://bit.team/auth/sign-up?ref=bitboy2023",doc:["https://bit.team/trade/api/documentation"]},api:{history:{get:{"api/tw/history/{pairName}/{resolution}":{cost:1}}},public:{get:{"trade/api/asset":{cost:1},"trade/api/currencies":{cost:1},"trade/api/orderbooks/{symbol}":{cost:1},"trade/api/orders":{cost:1},"trade/api/pair/{name}":{cost:1},"trade/api/pairs":{cost:1},"trade/api/pairs/precisions":{cost:1},"trade/api/rates":{cost:1},"trade/api/stats":{cost:1},"trade/api/trade/{id}":{cost:1},"trade/api/trades":{cost:1},"trade/api/ccxt/pairs":{cost:1},"trade/api/cmc/assets":{cost:1},"trade/api/cmc/orderbook/{pair}":{cost:1},"trade/api/cmc/summary":{cost:1},"trade/api/cmc/ticker":{cost:1},"trade/api/cmc/trades/{pair}":{cost:1}}},private:{get:{"trade/api/ccxt/balance":{cost:1},"trade/api/ccxt/order/{id}":{cost:1},"trade/api/ccxt/ordersOfUser":{cost:1},"trade/api/ccxt/tradesOfUser":{cost:1},"trade/api/transactionsOfUser":{cost:1}},post:{"trade/api/ccxt/cancel-all-order":{cost:1},"trade/api/ccxt/cancelorder":{cost:1},"trade/api/ccxt/ordercreate":{cost:1}}}},fees:{trading:{feeSide:"get",tierBased:!1,percentage:!0,taker:this.parseNumber("0.002"),maker:this.parseNumber("0.002")}},precisionMode:4,options:{networksById:{Ethereum:"ERC20",ethereum:"ERC20",Tron:"TRC20",tron:"TRC20",Binance:"BSC",binance:"BSC","Binance Smart Chain":"BSC",bscscan:"BSC",Bitcoin:"BTC",bitcoin:"BTC",Litecoin:"LTC",litecoin:"LTC",Polygon:"POLYGON",polygon:"POLYGON",PRIZM:"PRIZM",Decimal:"Decimal",ufobject:"ufobject",tonchain:"tonchain"},fetchMarkets:{currenciesValuedInUsd:{USDT:!0,BUSD:!0}}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:void 0,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!1,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:100,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!0,limit:100,daysBack:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:100,daysBack:void 0,daysBackCanceled:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:1e3}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},exceptions:{exact:{400002:r.BadSymbol,401e3:r.AuthenticationError,403002:r.BadRequest,404200:r.BadSymbol},broad:{"is not allowed":r.BadRequest,"Insufficient funds":r.InsufficientFunds,"Invalid request params input":r.BadRequest,"must be a number":r.BadRequest,"must be a string":r.BadRequest,"must be of type":r.BadRequest,"must be one of":r.BadRequest,"Order not found":r.OrderNotFound,"Pair with pair name":r.BadSymbol,pairName:r.BadSymbol,"Service Unavailable":r.ExchangeNotAvailable,"Symbol ":r.BadSymbol}}})}async fetchMarkets(e={}){let t=await this.publicGetTradeApiCcxtPairs(e),i=this.safeDict(t,"result",{}),s=this.safeList(i,"pairs",[]);return this.parseMarkets(s)}parseMarket(e){let t,i=this.safeString(e,"name"),s=this.safeInteger(e,"id"),r=i.split("_"),a=this.safeString(r,0),o=this.safeString(r,1),n=this.safeCurrencyCode(a),d=this.safeCurrencyCode(o);if(void 0===n||void 0===d)return;let h=this.safeBool(e,"active"),c=this.safeString(e,"timeStart"),l=this.parse8601(c),u=this.handleOption("fetchMarkets","currenciesValuedInUsd",{});if(!0===this.safeBool(u,d,!1)){let i=this.safeDict(e,"settings",{});t=this.safeNumber(i,"limit_usd")}return this.safeMarketStructure({id:i,numericId:s,symbol:n+"/"+d,base:n,quote:d,settle:void 0,baseId:a,quoteId:o,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:h,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(e,"baseStep"))),price:this.parseNumber(this.parsePrecision(this.safeString(e,"quoteStep")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:t,max:void 0}},created:l,info:e})}async fetchCurrencies(e={}){let t=await this.publicGetTradeApiCurrencies(e),i=this.safeDict(t,"result",{}),s=this.safeList(i,"currencies",[]),r=await this.publicGetTradeApiCmcAssets();r=this.indexBy(r,"unified_cryptoasset_id"),this.options._temp_currencies_statuses=r;let a=this.parseCurrencies(s);return delete this.options._temp_currencies_statuses,a}parseCurrency(e){let t,i=this.safeDict(this.options,"_temp_currencies_statuses",{}),s=this.safeString(e,"symbol"),r=this.safeInteger(e,"id"),a=this.safeCurrencyCode(s),o=this.safeBool(e,"active",!1),n=this.parseNumber(this.parsePrecision(this.safeString(e,"precision"))),d=this.safeDict(e,"txLimits",{}),h=this.safeString(d,"minWithdraw"),c=this.safeString(d,"maxWithdraw"),l=this.safeString(d,"minDeposit"),u=this.safeDict(d,"withdrawCommissionFixed",{}),f={},p=this.safeString(e,"blockChain");void 0!==p&&""!==p?(t=this.parseNumber(u),f[p]=t):f=u;let m=this.safeDict(i,r,{}),g=this.safeBool(m,"depositStatus"),v=this.safeBool(m,"withdrawStatus"),y=Object.keys(f),b={},w=this.parseNumber(this.parsePrecision(this.safeString(e,"decimals"))),k=this.safeString(e,"type");for(let t=0;t<y.length;t++){let i=y[t],s=this.networkIdToCode(i,a),r=this.safeNumber(f,i);void 0!==s&&(b[s]={id:i,network:s,deposit:g,withdraw:v,active:o,fee:r,precision:w,limits:{amount:{min:void 0,max:void 0},withdraw:{min:this.parseNumber(h),max:this.parseNumber(c)},deposit:{min:this.parseNumber(l),max:void 0}},info:e})}return this.safeCurrencyStructure({id:s,numericId:r,code:a,name:a,info:e,active:o,deposit:g,withdraw:v,fee:t,precision:n,limits:{amount:{min:void 0,max:void 0},withdraw:{min:this.parseNumber(h),max:this.parseNumber(c)},deposit:{min:this.parseNumber(l),max:void 0}},type:k,networks:b})}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=this.safeString(this.timeframes,t,t),n={pairName:a.id,resolution:o},d=await this.historyGetApiTwHistoryPairNameResolution(this.extend(n,r)),h=this.safeDict(d,"result",{}),c=this.safeList(h,"data",[]);return this.parseOHLCVs(c,a,t,i,s)}parseOHLCV(e,t){return[this.safeTimestamp(e,"t"),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={pair:this.market(e).id},r=await this.publicGetTradeApiCmcOrderbookPair(this.extend(s,i)),a=this.safeInteger(r,"timestamp");return this.parseOrderBook(r,e,a)}async fetchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={type:this.safeString(s,"type","all")};void 0!==e&&(a.pair=(r=this.market(e)).id),void 0!==i&&(a.limit=i);let o=await this.privateGetTradeApiCcxtOrdersOfUser(this.extend(a,s)),n=this.safeDict(o,"result",{}),d=this.safeList(n,"orders",[]);return this.parseOrders(d,r,t,i)}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let r=await this.privateGetTradeApiCcxtOrderId(this.extend({id:e},i)),a=this.safeDict(r,"result",{});return this.parseOrder(a,s)}async fetchOpenOrders(e,t,i,s={}){return void 0===this.markets&&await this.loadMarkets(),await this.fetchOrders(e,t,i,this.extend({type:"active"},s))}async fetchClosedOrders(e,t,i,s={}){return void 0===this.markets&&await this.loadMarkets(),await this.fetchOrders(e,t,i,this.extend({type:"closed"},s))}async fetchCanceledOrders(e,t,i,s={}){return void 0===this.markets&&await this.loadMarkets(),await this.fetchOrders(e,t,i,this.extend({type:"cancelled"},s))}async createOrder(e,t,i,s,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d={pairId:this.safeString(n,"numericId"),type:t,side:i,amount:this.amountToPrecision(e,s)};if("limit"===t)if(void 0===a)throw new r.ArgumentsRequired(this.id+" createOrder() requires a price argument for a "+t+" order");else d.price=this.priceToPrecision(e,a);let h=await this.privatePostTradeApiCcxtOrdercreate(this.extend(d,o)),c=this.safeDict(h,"result",{});return this.parseOrder(c,n)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privatePostTradeApiCcxtCancelorder(this.extend({id:e},i)),r=this.safeDict(s,"result",{});return this.parseOrder(r)}async cancelAllOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={};void 0!==e?(i=this.market(e),s.pairId=this.safeString(i,"numericId")):s.pairId="0";let r=await this.privatePostTradeApiCcxtCancelAllOrder(this.extend(s,t)),a=this.safeDict(r,"result",{});return this.parseOrders([a],i)}parseOrder(e,t){let i,s,r=this.safeString(e,"id"),a=this.safeString(e,"pair"),o=this.safeMarket(a,t),n=this.safeString(e,"orderCid"),d=this.safeString(e,"createdAt");i=void 0!==d?this.parse8601(d):this.safeTimestamp(e,"timestamp");let h=this.safeString(e,"updatedAt"),c=this.parse8601(h),l=this.parseOrderStatus(this.safeString(e,"status")),u=this.parseOrderType(this.safeString(e,"type")),f=this.safeString(e,"side"),p=this.safeDict(e,"fee"),m=this.safeString(e,"price"),g=this.safeString(e,"quantity"),v=this.safeString(e,"executed");if(void 0!==p){let e=this.safeString(p,"amount"),t=this.safeString(p,"symbol");s={currency:this.safeCurrencyCode(t),cost:e,rate:void 0}}return this.safeOrder({id:r,clientOrderId:n,timestamp:i,datetime:this.iso8601(i),lastTradeTimestamp:void 0,lastUpdateTimestamp:c,status:l,symbol:o.symbol,type:u,timeInForce:"GTC",side:f,price:m,triggerPrice:this.safeString(e,"stopPrice"),average:void 0,amount:g,cost:void 0,filled:v,remaining:void 0,fee:s,trades:void 0,info:e,postOnly:!1},o)}parseOrderStatus(e){return this.safeString({accepted:"open",executed:"closed",cancelled:"canceled",partiallyCancelled:"canceled",delete:"rejected",inactive:"rejected",executing:"open",created:"open"},e,e)}parseOrderType(e){return this.safeString({market:"market",limit:"limit"},e,e)}parseValueToPricision(e,t,i,s){let r=this.safeString(e,t),o=this.safeString(i,s);if(void 0===r||void 0===o)return;let n=this.parsePrecision(o);return a.Y.stringMul(r,n)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetTradeApiCmcSummary(),s=[],r=[];Array.isArray(i)&&(r=i);for(let e=0;e<r.length;e++){let t=r[e],i=this.parseTicker(t);s.push(i)}return this.filterByArrayTickers(s,"symbol",e)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={name:i.id},r=await this.publicGetTradeApiPairName(this.extend(s,t)),a=this.safeDict(r,"result",{}),o=this.safeDict(a,"pair",{});return this.parseTicker(o,i)}parseTicker(e,t){let i,s,r,a,o=this.safeStringLower(e,"trading_pairs"),n=this.safeMarket(o,t),d=this.safeList(e,"bids"),h=this.safeList(e,"asks");if(void 0!==d&&Array.isArray(d)&&void 0!==h&&Array.isArray(h)){let e=this.safeDict(d,0,{});i=this.safeString(e,"price"),r=this.safeString(e,"quantity");let t=this.safeDict(h,0,{});s=this.safeString(t,"price"),a=this.safeString(t,"quantity")}else i=this.safeString(e,"highest_bid"),s=this.safeString(e,"lowest_ask");let c=this.safeString2(e,"volume24","base_volume"),l=this.safeString2(e,"quoteVolume24","quote_volume"),u=this.safeString2(e,"highPrice24","highest_price_24h"),f=this.safeString2(e,"lowPrice24","lowest_price_24h"),p=this.safeString2(e,"lastPrice","last_price"),m=this.safeString2(e,"change24","price_change_percent_24h");return this.safeTicker({symbol:n.symbol,timestamp:void 0,datetime:void 0,open:void 0,high:u,low:f,close:p,bid:i,bidVolume:r,ask:s,askVolume:a,vwap:void 0,previousClose:void 0,change:void 0,percentage:m,average:void 0,baseVolume:c,quoteVolume:l,info:e},n)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={pair:r.id},o=await this.publicGetTradeApiCmcTradesPair(this.extend(a,s));return this.parseTrades(o,r,t,i)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.pairId=(r=this.market(e)).numericId),void 0!==i&&(a.limit=i);let o=await this.privateGetTradeApiCcxtTradesOfUser(this.extend(a,s)),n=this.safeDict(o,"result",{}),d=this.safeList(n,"trades",[]);return this.parseTrades(d,r,t,i)}parseTrade(e,t){let i,s,r=this.safeString(e,"pair"),o=this.safeMarket(r,t),n=o.symbol,d=this.safeString2(e,"id","trade_id"),h=this.safeString(e,"price"),c=this.safeString2(e,"quantity","base_volume"),l=this.safeString(e,"quote_volume"),u=this.safeString(e,"isCurrentSide"),f=this.safeString(e,"timestamp");void 0!==u&&(f=a.Y.stringMul(f,"1000"));let p=this.safeString2(e,"side","type");"maker"===u?("sell"===p?p="buy":"buy"===p&&(p="sell"),s=this.safeString(e,"makerOrderId"),i=this.safeDict(e,"feeMaker",{})):"taker"===u&&(s=this.safeString(e,"takerOrderId"),i=this.safeDict(e,"feeTaker",{}));let m=this.safeString(i,"symbol"),g=this.safeString(i,"amount"),v={currency:this.safeCurrencyCode(m),cost:g},y=this.parseToInt(f);return this.safeTrade({id:d,order:s,timestamp:y,datetime:this.iso8601(y),symbol:n,type:void 0,side:p,takerOrMaker:u,price:h,amount:c,cost:l,fee:v,info:e},o)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetTradeApiCcxtBalance(e);return this.parseBalance(t)}parseBalance(e){let t={info:e,timestamp:void 0,datetime:void 0},i=this.safeDict(e,"result",{}),s=Object.keys(this.omit(i,["free","used","total"]));for(let e=0;e<s.length;e++){let r=s[e],a=this.safeDict(i,r),o=this.safeString(a,"free"),n=this.safeString(a,"used"),d=this.safeString(a,"total"),h=this.safeCurrencyCode(r.toLowerCase());void 0!==h&&(t[h]={free:o,used:n,total:d})}return this.safeBalance(t)}async fetchDepositsWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.currency=(r=this.currency(e)).numericId),void 0!==i&&(a.limit=i);let o=await this.privateGetTradeApiTransactionsOfUser(this.extend(a,s)),n=this.safeDict(o,"result",{}),d=this.safeList(n,"transactions",[]);return this.parseTransactions(d,r,t,i)}parseTransaction(e,t){let i=this.safeDict(e,"currency"),s=this.safeString(i,"symbol"),r=this.safeCurrencyCode(s,t),a=this.safeString(e,"id"),o=this.safeDict(e,"params"),n=this.safeString(o,"tx_id"),d=this.safeInteger(e,"timestamp"),h=this.safeString(e,"blockChain");if(void 0===h){let e=this.safeList(i,"links",[]),t=this.safeDict(e,0,{});h=this.safeString(t,"blockChain")}let c=this.safeString(e,"sender"),l=this.safeString(e,"recipient"),u=this.safeString(e,"message"),f=this.parseTransactionType(this.safeString(e,"type")),p=this.parseValueToPricision(e,"amount",i,"decimals"),m=this.parseTransactionStatus(this.safeString(e,"status"));return{info:e,id:a,txid:n,timestamp:d,datetime:this.iso8601(d),network:this.networkIdToCode(h,r),addressFrom:c,address:void 0,addressTo:l,tagFrom:void 0,tag:u,tagTo:void 0,type:f,amount:this.parseNumber(p),currency:r,status:m,updated:void 0,fee:void 0,comment:this.safeString(e,"description"),internal:!1}}parseTransactionType(e){return this.safeString({deposit:"deposit",withdraw:"withdrawal"},e,e)}parseTransactionStatus(e){return this.safeString({approving:"pending",success:"ok"},e,e)}sign(e,t="public",i="GET",s={},a,o){let n,d,h=this.omit(s,this.extractParams(e)),c="/"+this.implodeParams(e,s),l=this.safeString(this.urls.api,t);if(void 0===l)throw new r.ExchangeError(this.id+" sign() has no API URL for this endpoint");let u=l+c,f=this.urlencode(h);if("private"===t){this.checkRequiredCredentials(),"POST"===i?n=this.json(h):0!==f.length&&(u+="?"+f);let e=this.apiKey+":"+this.secret;d={Authorization:"Basic "+this.stringToBase64(e),"Content-Type":"application/json"}}else 0!==f.length&&(u+="?"+f);return{url:u,method:i,body:void 0===n?o:n,headers:void 0===d?a:d}}handleErrors(e,t,i,s,a,o,n,d,h){if(void 0!==n&&200!==e){if(404===e){if(i.indexOf("/ccxt/order/")>=0&&"GET"===s){let e=i.split("/order/"),t=this.safeString(e,1);throw new r.OrderNotFound(this.id+" order "+t+" not found")}if(i.indexOf("/cmc/orderbook/")>=0){let e=i.split("/cmc/orderbook/"),t=this.safeString(e,1);throw new r.BadSymbol(this.id+" symbolId "+t+" not found")}}let t=this.id+" "+o,a=this.safeString(n,"message"),d=this.safeString(n,"code");throw this.throwBroadlyMatchedException(this.exceptions.broad,a,t),this.throwExactlyMatchedException(this.exceptions.exact,d,t),new r.ExchangeError(t)}}}i.d(t,{A:()=>o})},7081(e,t,i){"use strict";var s=i(4721),r=i(3076),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bittrade",name:"BitTrade",countries:["JP"],rateLimit:100,userAgent:this.userAgents.chrome39,certified:!1,version:"v1",hostname:"api-cloud.bittrade.co.jp",pro:!0,has:{CORS:void 0,spot:!0,margin:void 0,swap:!1,future:!1,option:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createStopLimitOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,fetchAccounts:!0,fetchBalance:!0,fetchClosedOrders:!0,fetchCurrencies:!0,fetchDepositAddress:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchFundingHistory:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchIndexOHLCV:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchOrderTrades:!0,fetchPremiumIndexOHLCV:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingLimits:!0,fetchWithdrawals:!0,withdraw:!0},timeframes:{"1m":"1min","5m":"5min","15m":"15min","30m":"30min","1h":"60min","4h":"4hour","1d":"1day","1w":"1week","1M":"1mon","1y":"1year"},urls:{logo:"https://github.com/user-attachments/assets/c5996ed2-0d56-42d8-ac40-7eaf8116dbae",api:{market:"https://{hostname}",public:"https://{hostname}",private:"https://{hostname}",v2Public:"https://{hostname}",v2Private:"https://{hostname}"},www:"https://www.bittrade.co.jp",referral:"https://www.bittrade.co.jp/register/?invite_code=znnq3",doc:"https://api-doc.bittrade.co.jp",fees:"https://www.bittrade.co.jp/ja-jp/support/fee"},api:{v2Public:{get:{"reference/currencies":{cost:1},"market-status":{cost:1}}},v2Private:{get:{"account/ledger":{cost:1},"account/withdraw/quota":{cost:1},"account/withdraw/address":{cost:1},"account/deposit/address":{cost:1},"account/repayment":{cost:5},"reference/transact-fee-rate":{cost:1},"account/asset-valuation":{cost:.2},"point/account":{cost:5},"sub-user/user-list":{cost:1},"sub-user/user-state":{cost:1},"sub-user/account-list":{cost:1},"sub-user/deposit-address":{cost:1},"sub-user/query-deposit":{cost:1},"user/api-key":{cost:1},"user/uid":{cost:1},"algo-orders/opening":{cost:1},"algo-orders/history":{cost:1},"algo-orders/specific":{cost:1},"c2c/offers":{cost:1},"c2c/offer":{cost:1},"c2c/transactions":{cost:1},"c2c/repayment":{cost:1},"c2c/account":{cost:1},"etp/reference":{cost:1},"etp/transactions":{cost:5},"etp/transaction":{cost:5},"etp/rebalance":{cost:1},"etp/limit":{cost:1}},post:{"account/transfer":{cost:1},"account/repayment":{cost:5},"point/transfer":{cost:5},"sub-user/management":{cost:1},"sub-user/creation":{cost:1},"sub-user/tradable-market":{cost:1},"sub-user/transferability":{cost:1},"sub-user/api-key-generation":{cost:1},"sub-user/api-key-modification":{cost:1},"sub-user/api-key-deletion":{cost:1},"sub-user/deduct-mode":{cost:1},"algo-orders":{cost:1},"algo-orders/cancel-all-after":{cost:1},"algo-orders/cancellation":{cost:1},"c2c/offer":{cost:1},"c2c/cancellation":{cost:1},"c2c/cancel-all":{cost:1},"c2c/repayment":{cost:1},"c2c/transfer":{cost:1},"etp/creation":{cost:5},"etp/redemption":{cost:5},"etp/{transactId}/cancel":{cost:10},"etp/batch-cancel":{cost:50}}},market:{get:{"history/kline":{cost:1},"detail/merged":{cost:1},depth:{cost:1},trade:{cost:1},"history/trade":{cost:1},detail:{cost:1},tickers:{cost:1},etp:{cost:1}}},public:{get:{"common/symbols":{cost:1},"common/currencys":{cost:1},"common/timestamp":{cost:1},"common/exchange":{cost:1},"settings/currencys":{cost:1},"retail/maintain/time":{cost:1}}},private:{get:{"account/accounts":{cost:.2},"account/accounts/{id}/balance":{cost:.2},"account/accounts/{sub-uid}":{cost:1},"account/history":{cost:4},"cross-margin/loan-info":{cost:1},"margin/loan-info":{cost:1},"fee/fee-rate/get":{cost:1},"order/openOrders":{cost:.4},"order/orders":{cost:.4},"order/orders/{id}":{cost:.4},"order/orders/{id}/matchresults":{cost:.4},"order/orders/getClientOrder":{cost:.4},"order/history":{cost:1},"order/matchresults":{cost:1},"query/deposit-withdraw":{cost:1},"margin/loan-orders":{cost:.2},"margin/accounts/balance":{cost:.2},"cross-margin/loan-orders":{cost:1},"cross-margin/accounts/balance":{cost:1},"points/actions":{cost:1},"points/orders":{cost:1},"subuser/aggregate-balance":{cost:10},"stable-coin/exchange_rate":{cost:1},"stable-coin/quote":{cost:1},"retail/order/list":{cost:1}},post:{"account/transfer":{cost:1},"futures/transfer":{cost:1},"order/batch-orders":{cost:.4},"order/orders/place":{cost:.2},"order/orders/submitCancelClientOrder":{cost:.2},"order/orders/batchCancelOpenOrders":{cost:.4},"order/orders/{id}/submitcancel":{cost:.2},"order/orders/batchcancel":{cost:.4},"dw/withdraw/api/create":{cost:1},"dw/withdraw-virtual/{id}/cancel":{cost:1},"dw/transfer-in/margin":{cost:10},"dw/transfer-out/margin":{cost:10},"margin/orders":{cost:10},"margin/orders/{id}/repay":{cost:10},"cross-margin/transfer-in":{cost:1},"cross-margin/transfer-out":{cost:1},"cross-margin/orders":{cost:1},"cross-margin/orders/{id}/repay":{cost:1},"stable-coin/exchange":{cost:1},"subuser/transfer":{cost:10},"retail/order/place":{cost:1}}}},fees:{trading:{feeSide:"get",tierBased:!1,percentage:!0,maker:this.parseNumber("0.002"),taker:this.parseNumber("0.002")}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!1,GTD:!1},hedged:!1,selfTradePrevention:!1,trailing:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:120,untilDays:2,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:void 0,daysBack:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:void 0,daysBack:void 0,daysBackCanceled:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:2e3}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},precisionMode:4,exceptions:{broad:{"contract is restricted of closing positions on API.  Please contact customer service":a.OnMaintenance,maintain:a.OnMaintenance},exact:{"bad-request":a.BadRequest,"base-date-limit-error":a.BadRequest,"api-not-support-temp-addr":a.PermissionDenied,timeout:a.RequestTimeout,"gateway-internal-error":a.ExchangeNotAvailable,"account-frozen-balance-insufficient-error":a.InsufficientFunds,"invalid-amount":a.InvalidOrder,"order-limitorder-amount-min-error":a.InvalidOrder,"order-limitorder-amount-max-error":a.InvalidOrder,"order-marketorder-amount-min-error":a.InvalidOrder,"order-limitorder-price-min-error":a.InvalidOrder,"order-limitorder-price-max-error":a.InvalidOrder,"order-holding-limit-failed":a.InvalidOrder,"order-orderprice-precision-error":a.InvalidOrder,"order-etp-nav-price-max-error":a.InvalidOrder,"order-orderstate-error":a.OrderNotFound,"order-queryorder-invalid":a.OrderNotFound,"order-update-error":a.ExchangeNotAvailable,"api-signature-check-failed":a.AuthenticationError,"api-signature-not-valid":a.AuthenticationError,"base-record-invalid":a.OrderNotFound,"base-symbol-trade-disabled":a.BadSymbol,"base-symbol-error":a.BadSymbol,"system-maintenance":a.OnMaintenance,"invalid symbol":a.BadSymbol,"symbol trade not open now":a.BadSymbol,"invalid-address":a.BadRequest,"base-currency-chain-error":a.BadRequest,"dw-insufficient-balance":a.InsufficientFunds}},options:{defaultNetwork:"ERC20",networks:{ETH:"erc20",TRX:"trc20",HRC20:"hrc20",HECO:"hrc20",HT:"hrc20",ALGO:"algo"},fetchOrdersByStates:{method:"private_get_order_orders"},fetchOpenOrders:{method:"fetch_open_orders_v1"},createOrder:{createMarketBuyOrderRequiresPrice:!0,method:"privatePostOrderOrdersPlace"},fetchMarkets:{method:"publicGetCommonSymbols"},fetchBalance:{method:"privateGetAccountAccountsIdBalance"},currencyToPrecisionRoundingMode:0,fetchCurrencies:{language:"en-US"},broker:{id:"AA03022abc"}},commonCurrencies:{GET:"Themis",GTC:"Game.com",HIT:"HitChain",PNT:"Penta",SBTC:"Super Bitcoin",BIFI:"Bitcoin File"}})}async fetchTime(e={}){let t=await this.publicGetCommonTimestamp(e);return this.safeInteger(t,"data")}async fetchTradingLimits(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=void 0===e?this.symbols:e;if(void 0===i)throw new a.ExchangeError(this.id+" markets not loaded");let s={};for(let e=0;e<i.length;e++){let r=i[e];s[r]=await this.fetchTradingLimitsById(this.marketId(r),t)}return s}async fetchTradingLimitsById(e,t={}){let i=await this.publicGetCommonExchange(this.extend({symbol:e},t));return this.parseTradingLimits(this.safeDict(i,"data",{}))}parseTradingLimits(e,t,i={}){return{info:e,limits:{amount:{min:this.safeNumber(e,"limit-order-must-greater-than"),max:this.safeNumber(e,"limit-order-must-less-than")}}}}costToPrecision(e,t){return this.decimalToPrecision(t,0,this.market(e).precision.cost,this.precisionMode)}async fetchMarkets(e={}){let t,i=this.handleOption("fetchMarkets","method","publicGetCommonSymbols");if("publicGetCommonSymbols"===i)t=await this.publicGetCommonSymbols(e);else throw new a.NotSupported(this.id+" fetchMarkets() does not support the "+i+" method");let s=this.safeList(t,"data",[]);if(s.length<1)throw new a.NetworkError(this.id+" fetchMarkets() returned empty response: "+this.json(s));let r=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.safeString(t,"base-currency"),n=this.safeString(t,"quote-currency"),d=this.safeCurrencyCode(i),h=this.safeCurrencyCode(n);if(void 0===d||void 0===h)continue;let c=this.safeString(t,"state"),l=this.safeString(t,"leverage-ratio","1"),u=this.safeString(t,"super-margin-leverage-ratio","1"),f=o.Y.stringGt(l,"1")||o.Y.stringGt(u,"1"),p="OMG"===d?this.parseNumber("0"):this.parseNumber("0.002");if(void 0===i)throw new a.ExchangeError(this.id+" fetchMarkets() missing baseId");if(void 0===n)throw new a.ExchangeError(this.id+" fetchMarkets() missing quoteId");r.push({id:i+n,symbol:d+"/"+h,base:d,quote:h,settle:void 0,baseId:i,quoteId:n,settleId:void 0,type:"spot",spot:!0,margin:f,swap:!1,future:!1,option:!1,active:"online"===c,contract:!1,linear:void 0,inverse:void 0,taker:p,maker:p,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{price:this.parseNumber(this.parsePrecision(this.safeString(t,"price-precision"))),amount:this.parseNumber(this.parsePrecision(this.safeString(t,"amount-precision"))),cost:this.parseNumber(this.parsePrecision(this.safeString(t,"value-precision")))},limits:{leverage:{min:this.parseNumber("1"),max:this.parseNumber(l),superMax:this.parseNumber(u)},amount:{min:this.safeNumber(t,"min-order-amt"),max:this.safeNumber(t,"max-order-amt")},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(t,"min-order-value"),max:void 0}},created:void 0,info:t})}return r}parseTicker(e,t){let i,s,r,a,o=this.safeSymbol(void 0,t),n=this.safeInteger(e,"ts");"bid"in e&&(Array.isArray(e.bid)?(i=this.safeString(e.bid,0),s=this.safeString(e.bid,1)):(i=this.safeString(e,"bid"),s=this.safeString(e,"bidSize"))),"ask"in e&&(Array.isArray(e.ask)?(r=this.safeString(e.ask,0),a=this.safeString(e.ask,1)):(r=this.safeString(e,"ask"),a=this.safeString(e,"askSize")));let d=this.safeString(e,"open"),h=this.safeString(e,"close"),c=this.safeString(e,"amount"),l=this.safeString(e,"vol");return this.safeTicker({symbol:o,timestamp:n,datetime:this.iso8601(n),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:i,bidVolume:s,ask:r,askVolume:a,vwap:void 0,open:d,close:h,last:h,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:c,quoteVolume:l,info:e},t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={symbol:this.market(e).id,type:"step0"},r=await this.marketGetDepth(this.extend(s,i));if("tick"in r){if(void 0===r.tick||null===r.tick)throw new a.BadSymbol(this.id+" fetchOrderBook() returned empty response: "+this.json(r));let t=this.safeDict(r,"tick"),i=this.safeInteger(t,"ts",this.safeInteger(r,"ts")),s=this.parseOrderBook(t,e,i);return s.nonce=this.safeInteger(t,"version"),s}throw new a.ExchangeError(this.id+" fetchOrderBook() returned unrecognized response: "+this.json(r))}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.marketGetDetailMerged(this.extend(s,t)),a=this.safeDict(r,"tick",{}),o=this.parseTicker(a,i),n=this.safeInteger(r,"ts");return o.timestamp=n,o.datetime=this.iso8601(n),o}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.marketGetTickers(t),r=this.safeList(s,"data",[]),a=this.safeInteger(s,"ts"),o={};for(let e=0;e<r.length;e++){let t=this.safeString(r[e],"symbol"),i=this.safeMarket(t),s=i.symbol,n=this.parseTicker(r[e],i);n.timestamp=a,n.datetime=this.iso8601(a),o[s]=n}return this.filterByArrayTickers(o,"symbol",i)}parseTrade(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeSymbol(s,t),a=this.safeInteger2(e,"ts","created-at"),n=this.safeString(e,"order-id"),d=this.safeString(e,"direction"),h=this.safeString(e,"type");if(void 0!==h){let e=h.split("-");d=e[0],h=e[1]}let c=this.safeString(e,"role"),l=this.safeString(e,"price"),u=this.safeString2(e,"filled-amount","amount"),f=o.Y.stringMul(l,u),p=this.safeString(e,"filled-fees"),m=this.safeCurrencyCode(this.safeString(e,"fee-currency")),g=this.safeString(e,"filled-points");void 0!==g&&(void 0===p||o.Y.stringEq(p,"0.0"))&&(p=g,m=this.safeCurrencyCode(this.safeString(e,"fee-deduct-currency"))),void 0!==p&&(i={cost:p,currency:m});let v=this.safeString2(e,"trade-id","tradeId"),y=this.safeString(e,"id",v);return this.safeTrade({info:e,id:y,symbol:r,order:n,timestamp:a,datetime:this.iso8601(a),type:h,side:d,takerOrMaker:c,price:l,amount:u,cost:f,fee:i})}async fetchOrderTrades(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=await this.privateGetOrderOrdersIdMatchresults(this.extend({id:e},r)),o=this.safeList(a,"data",[]);return this.parseTrades(o,void 0,i,s)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id),void 0!==i&&(a.size=i),void 0!==t&&(a["start-time"]=t);let o=await this.privateGetOrderMatchresults(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTrades(n,r,t,i)}async fetchTrades(e,t,i=1e3,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id};void 0!==i&&(a.size=Math.min(i,2e3));let o=await this.marketGetHistoryTrade(this.extend(a,s)),n=this.safeList(o,"data",[]),d=[];for(let e=0;e<n.length;e++){let t=this.safeList(n[e],"data",[]);for(let e=0;e<t.length;e++){let i=this.parseTrade(t[e],r);d.push(i)}}return d=this.sortBy(d,"timestamp"),this.filterBySymbolSinceLimit(d,this.safeString(r,"symbol"),t,i)}parseOHLCV(e,t){return[this.safeTimestamp(e,"id"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"amount")]}async fetchOHLCV(e,t="1m",i,s=1e3,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={symbol:a.id,period:this.safeString(this.timeframes,t,t)};void 0!==s&&(o.size=Math.min(s,2e3));let n=await this.marketGetHistoryKline(this.extend(o,r)),d=this.safeList(n,"data",[]);return this.parseOHLCVs(d,a,t,i,s)}async fetchAccounts(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetAccountAccounts(e);return this.safeList(t,"data",[])}async fetchCurrencies(e={}){let t={language:this.handleOption("fetchCurrencies","language","en-US")},i=await this.publicGetSettingsCurrencys(this.extend(t,e)),s=this.safeList(i,"data",[]);return this.parseCurrencies(s)}parseCurrency(e){let t=this.safeString(e,"name"),i=this.safeCurrencyCode(t),s=this.safeBool(e,"deposit-enabled"),r=this.safeBool(e,"withdraw-enabled"),a=this.safeBool(e,"country-disabled"),o=this.safeBool(e,"visible",!1),n=this.safeString(e,"state"),d=!0===o&&!0===s&&!0===r&&"online"===n&&!0!==a,h=this.safeString(e,"display-name"),c=this.parseNumber(this.parsePrecision(this.safeString(e,"withdraw-precision")));return this.safeCurrencyStructure({id:t,code:i,type:"crypto",name:h,active:d,deposit:s,withdraw:r,fee:void 0,precision:c,networks:void 0,limits:{amount:{min:c,max:void 0},deposit:{min:this.safeNumber(e,"deposit-min-amount"),max:void 0},withdraw:{min:this.safeNumber(e,"withdraw-min-amount"),max:void 0}},info:e})}parseBalance(e){let t=this.safeList(e.data,"list",[]),i={info:e};for(let e=0;e<t.length;e++){let s,r=t[e],o=this.safeString(r,"currency"),n=this.safeCurrencyCode(o);if(void 0===(s=void 0!==n&&n in i?i[n]:this.account())||("trade"===this.safeString(r,"type")&&(s.free=this.safeString(r,"balance")),void 0===s))throw new a.ExchangeError(this.id+" parseBalance() could not resolve account");"frozen"===this.safeString(r,"type")&&(s.used=this.safeString(r,"balance")),void 0!==n&&(i[n]=s)}return this.safeBalance(i)}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let i=this.handleOption("fetchBalance","method","privateGetAccountAccountsIdBalance"),s={id:this.accounts[0].id};if("privateGetAccountAccountsIdBalance"===i)t=await this.privateGetAccountAccountsIdBalance(this.extend(s,e));else throw new a.NotSupported(this.id+" fetchBalance() does not support the "+i+" method");return this.parseBalance(t)}async fetchOrdersByStates(e,t,i,s,r={}){let a,o;void 0===this.markets&&await this.loadMarkets();let n={states:e};void 0!==t&&(n.symbol=(a=this.market(t)).id);let d=this.handleOption("fetchOrdersByStates","method","private_get_order_orders");return o="private_get_order_history"===d||"privateGetOrderHistory"===d?await this.privateGetOrderHistory(this.extend(n,r)):await this.privateGetOrderOrders(this.extend(n,r)),this.parseOrders(o.data,a,i,s)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateGetOrderOrdersId(this.extend({id:e},i)),r=this.safeDict(s,"data",{});return this.parseOrder(r)}async fetchOrders(e,t,i,s={}){return await this.fetchOrdersByStates("pre-submitted,submitted,partial-filled,filled,partial-canceled,canceled",e,t,i,s)}async fetchOpenOrders(e,t,i,s={}){let r=this.handleOption("fetchOpenOrders","method","fetch_open_orders_v1");return"fetch_open_orders_v2"===r||"fetchOpenOrdersV2"===r?await this.fetchOpenOrdersV2(e,t,i,s):await this.fetchOpenOrdersV1(e,t,i,s)}async fetchOpenOrdersV1(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOpenOrdersV1() requires a symbol argument");return await this.fetchOrdersByStates("pre-submitted,submitted,partial-filled",e,t,i,s)}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrdersByStates("filled,partial-canceled,canceled",e,t,i,s)}async fetchOpenOrdersV2(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id);let o=this.safeString(s,"account-id");if(void 0===o){await this.loadAccounts();for(let e=0;e<this.accounts.length;e++){let t=this.accounts[e];if("spot"===t.type&&void 0!==(o=this.safeString(t,"id")))break}}a["account-id"]=o,void 0!==i&&(a.size=i);let n=this.omit(s,"account-id"),d=await this.privateGetOrderOpenOrders(this.extend(a,n)),h=this.safeList(d,"data",[]);return this.parseOrders(h,r,t,i)}parseOrderStatus(e){return this.safeString({"partial-filled":"open","partial-canceled":"canceled",filled:"closed",canceled:"canceled",submitted:"open"},e,e)}parseOrder(e,t){let i,s,r,a,o=this.safeString(e,"id");if("type"in e){let t=e.type.split("-");i=t[0],s=t[1],r=this.parseOrderStatus(this.safeString(e,"state"))}let n=this.safeString(e,"symbol"),d=this.safeMarket(n,t),h=this.safeInteger(e,"created-at"),c=this.safeString(e,"client-order-id"),l=this.safeString(e,"amount"),u=this.safeString2(e,"filled-amount","field-amount"),f=this.safeString(e,"price"),p=this.safeString2(e,"filled-cash-amount","field-cash-amount"),m=this.safeString2(e,"filled-fees","field-fees");void 0!==m&&(a={cost:m,currency:"sell"===i?d.quote:d.base});return this.safeOrder({info:e,id:o,clientOrderId:c,timestamp:h,datetime:this.iso8601(h),lastTradeTimestamp:void 0,symbol:d.symbol,type:s,timeInForce:void 0,postOnly:void 0,side:i,price:f,triggerPrice:void 0,average:void 0,cost:p,amount:l,filled:u,remaining:void 0,status:r,fee:a,trades:void 0},d)}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new a.NotSupported(this.id+" createMarketBuyOrderWithCost() supports spot orders only");return i.createMarketBuyOrderRequiresPrice=!1,await this.createOrder(e,"market","buy",t,void 0,i)}async createOrder(e,t,i,s,r,n={}){let d;void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let h=this.market(e),c={"account-id":this.accounts[0].id,symbol:h.id,type:i+"-"+t},l=this.safeString2(n,"clientOrderId","client-order-id");if(void 0===l){let e=this.safeDict(this.options,"broker",{}),t=this.safeString(e,"id");c["client-order-id"]=t+this.uuid()}else c["client-order-id"]=l;let u=this.omit(n,["clientOrderId","client-order-id"]),f=u;if("market"===t&&"buy"===i){let t,[i,n]=this.handleOptionBoolAndParams(u,"createOrder","createMarketBuyOrderRequiresPrice",!0),d=this.safeNumber(n,"cost");if(f=this.omit(n,"cost"),void 0!==d)t=this.amountToPrecision(e,d);else if(i)if(void 0===r)throw new a.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument");else{let i=this.numberToString(s),a=this.numberToString(r);t=this.amountToPrecision(e,o.Y.stringMul(i,a))}else t=this.amountToPrecision(e,s);c.amount=t}else c.amount=this.amountToPrecision(e,s);("limit"===t||"ioc"===t||"limit-maker"===t||"stop-limit"===t||"stop-limit-fok"===t)&&(c.price=this.priceToPrecision(e,r));let p=this.handleOption("createOrder","method","privatePostOrderOrdersPlace");if("privatePostOrderOrdersPlace"===p)d=await this.privatePostOrderOrdersPlace(this.extend(c,f));else throw new a.NotSupported(this.id+" createOrder() does not support the "+p+" method");let m=this.safeString(d,"data");return this.safeOrder({info:d,id:m,timestamp:void 0,datetime:void 0,lastTradeTimestamp:void 0,status:void 0,symbol:e,type:t,side:i,price:r,amount:s,filled:void 0,remaining:void 0,cost:void 0,trades:void 0,fee:void 0,clientOrderId:void 0,average:void 0},h)}async cancelOrder(e,t,i={}){let s=await this.privatePostOrderOrdersIdSubmitcancel({id:e});return this.extend(this.parseOrder(s),{id:e,status:"canceled"})}async cancelOrders(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.safeValue2(i,"clientOrderIds","client-order-ids"),r=this.omit(i,["clientOrderIds","client-order-ids"]),a={};void 0===s?a["order-ids"]=e:a["client-order-ids"]=s;let o=await this.privatePostOrderOrdersBatchcancel(this.extend(a,r));return this.parseCancelOrders(o)}parseCancelOrders(e){let t,i=this.safeString(e,"successes");t=void 0!==i?i.split(","):this.safeList(e,"success",[]);let s=this.safeList2(e,"errors","failed",[]),r=[];for(let e=0;e<t.length;e++){let i=t[e];r.push(this.safeOrder({info:i,id:i,status:"canceled"}))}for(let e=0;e<s.length;e++){let t=s[e];r.push(this.safeOrder({info:t,id:this.safeString2(t,"order-id","order_id"),status:"failed",clientOrderId:this.safeString(t,"client-order-id")}))}return r}async cancelAllOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={};void 0!==e&&(i.symbol=this.market(e).id);let s=await this.privatePostOrderOrdersBatchCancelOpenOrders(this.extend(i,t)),r=this.safeDict(s,"data",{});return[this.safeOrder({info:r})]}parseDepositAddress(e,t){let i=this.safeString(e,"address"),s=this.safeString(e,"addressTag"),r=this.safeString(e,"currency"),a=this.safeCurrency(r,t),o=this.safeCurrencyCode(r,a),n=this.safeString(e,"chain"),d=this.safeDict(a,"networks",{}),h=this.indexBy(d,"id"),c=this.safeValue(h,n,n),l=this.safeString(c,"network");return this.checkAddress(i),{currency:o,address:i,tag:s,network:l,info:e}}async fetchDeposits(e,t,i,s={}){let r,a=i;(void 0===i||i>100)&&(a=100),void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.currency(e));let o={type:"deposit",from:0};void 0!==r&&(o.currency=r.id),void 0!==a&&(o.size=a);let n=await this.privateGetQueryDepositWithdraw(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTransactions(d,r,t,a)}async fetchWithdrawals(e,t,i,s={}){let r,a=i;(void 0===i||i>100)&&(a=100),void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.currency(e));let o={type:"withdraw",from:0};void 0!==r&&(o.currency=r.id),void 0!==a&&(o.size=a);let n=await this.privateGetQueryDepositWithdraw(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTransactions(d,r,t,a)}parseTransaction(e,t){let i=this.safeInteger(e,"created-at"),s=this.safeCurrencyCode(this.safeString(e,"currency")),r=this.safeString(e,"type");"withdraw"===r&&(r="withdrawal");let a=this.safeString(e,"fee");return void 0!==a&&(a=o.Y.stringAbs(a)),{info:e,id:this.safeString2(e,"id","data"),txid:this.safeString(e,"tx-hash"),timestamp:i,datetime:this.iso8601(i),network:this.safeStringUpper(e,"chain"),address:this.safeString(e,"address"),addressTo:void 0,addressFrom:void 0,tag:this.safeString(e,"address-tag"),tagTo:void 0,tagFrom:void 0,type:r,amount:this.safeNumber(e,"amount"),currency:s,status:this.parseTransactionStatus(this.safeString(e,"state")),updated:this.safeInteger(e,"updated-at"),comment:void 0,internal:void 0,fee:{currency:s,cost:this.parseNumber(a),rate:void 0}}}parseTransactionStatus(e){return this.safeString({unknown:"failed",confirming:"pending",confirmed:"ok",safe:"ok",orphan:"failed",submitted:"pending",canceled:"canceled",reexamine:"pending",reject:"failed",pass:"pending","wallet-reject":"failed","confirm-error":"failed",repealed:"failed","wallet-transfer":"pending","pre-transfer":"pending"},e,e)}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);void 0===this.markets&&await this.loadMarkets(),this.checkAddress(i);let n=this.currency(e),d={address:i,amount:t,currency:n.id.toLowerCase()};void 0!==a&&(d["addr-tag"]=a);let h=this.safeDict(this.options,"networks",{}),c=this.safeStringUpper(o,"network");void 0!==(c=this.safeStringLower(h,c,c))&&("erc20"===c?d.chain=n.id+c:d.chain=c+n.id);let l=void 0!==c?this.omit(o,"network"):o,u=await this.privatePostDwWithdrawApiCreate(this.extend(d,l));return this.parseTransaction(u,n)}sign(e,t="public",i="GET",r={},o,n){let d,h,c="/";"market"===t?c+="market":"public"===t||"private"===t?c+=this.version:("v2Public"===t||"v2Private"===t)&&(c+="v2"),c+="/"+this.implodeParams(e,r);let l=this.omit(r,this.extractParams(e));if("private"===t||"v2Private"===t){this.checkRequiredCredentials();let e=this.ymdhms(this.milliseconds(),"T"),t={SignatureMethod:"HmacSHA256",SignatureVersion:"2",AccessKeyId:this.apiKey,Timestamp:e};"POST"!==i&&(t=this.extend(t,l));let r=this.keysort(t),a=this.urlencode(r),o=[i,this.hostname,c,a].join("\n"),n=this.hmac(this.encode(o),this.encode(this.secret),s.sc,"base64");a+="&"+this.urlencode({Signature:n}),c+="?"+a,"POST"===i?(h=this.json(l),d={"Content-Type":"application/json"}):d={"Content-Type":"application/x-www-form-urlencoded"}}else Object.keys(r).length>0&&(c+="?"+this.urlencode(r));let u=this.safeString(this.urls.api,t);if(void 0===u)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");return{url:c=this.implodeParams(u,{hostname:this.hostname})+c,method:i,body:void 0!==h?h:n,headers:void 0!==d?d:o}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0!==n&&"status"in n&&"error"===this.safeString(n,"status")){let e=this.safeString(n,"err-code"),t=this.id+" "+o;this.throwBroadlyMatchedException(this.exceptions.broad,o,t),this.throwExactlyMatchedException(this.exceptions.exact,e,t);let i=this.safeString(n,"err-msg");throw this.throwExactlyMatchedException(this.exceptions.exact,i,t),new a.ExchangeError(t)}}}i.d(t,{A:()=>n})},1117(e,t,i){"use strict";var s=i(4721),r=i(8498),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bitvavo",name:"Bitvavo",countries:["NL"],rateLimit:60,version:"v2",certified:!1,pro:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelAllOrdersAfter:!0,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createLimitOrder:!0,createMarketOrder:!0,createMarketOrderWithCost:!0,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createPostOnlyOrder:!0,createReduceOnlyOrder:!1,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,editOrder:!0,fetchAccounts:!0,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLedger:!0,fetchLedgerEntry:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTransactions:!1,fetchTransfer:!0,fetchTransfers:!0,fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!0,withdraw:!0},timeframes:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","8h":"8h","12h":"12h","1d":"1d"},urls:{logo:"https://github.com/user-attachments/assets/35d690b1-5710-47f6-86e9-d638ce38685a",api:{public:"https://api.bitvavo.com",private:"https://api.bitvavo.com"},www:"https://bitvavo.com/",doc:"https://docs.bitvavo.com/",fees:"https://bitvavo.com/en/fees",referral:"https://bitvavo.com/?a=24F34952F7"},api:{public:{get:{"{market}/book":{cost:1},"report/{market}/book":{cost:1},"{market}/trades":{cost:5},"report/{market}/trades":{cost:5},"ticker/price":{cost:1},"ticker/book":{cost:1},"{market}/candles":{cost:1},"ticker/24h":{cost:1,noMarket:25},time:{cost:1},markets:{cost:1},assets:{cost:1}}},private:{get:{order:{cost:1},ordersOpen:{cost:5,noMarket:100},trades:{cost:5},orders:{cost:5},deposit:{cost:1},depositHistory:{cost:5},withdrawalHistory:{cost:5},account:{cost:1},balance:{cost:5},stakingBalance:{cost:1},"account/fees":{cost:1},"account/history":{cost:1},subaccounts:{cost:5},"subaccounts/transfers":{cost:5},"subaccounts/transfers/{transferId}":{cost:5},"institutional/subaccounts/balance":{cost:5},"institutional/subaccounts/history":{cost:5},"institutional/subaccounts/orders/open":{cost:5,noMarket:100}},post:{order:{cost:1},cancelOrdersAfter:{cost:5},withdrawal:{cost:1},"crypto/withdrawal":{cost:25},subaccounts:{cost:5},"subaccounts/transfers":{cost:5}},put:{order:{cost:1}},delete:{order:{cost:1},orders:{cost:25,noMarket:100},"atomic/orders":{cost:100},"institutional/subaccounts/order":{cost:1},"institutional/subaccounts/orders":{cost:25,noMarket:100}}}},fees:{trading:{tierBased:!0,percentage:!0,taker:this.parseNumber("0.0025"),maker:this.parseNumber("0.002"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.0025")],[this.parseNumber("100000"),this.parseNumber("0.0020")],[this.parseNumber("250000"),this.parseNumber("0.0016")],[this.parseNumber("500000"),this.parseNumber("0.0012")],[this.parseNumber("1000000"),this.parseNumber("0.0010")],[this.parseNumber("2500000"),this.parseNumber("0.0008")],[this.parseNumber("5000000"),this.parseNumber("0.0006")],[this.parseNumber("10000000"),this.parseNumber("0.0005")],[this.parseNumber("25000000"),this.parseNumber("0.0004")]],maker:[[this.parseNumber("0"),this.parseNumber("0.0015")],[this.parseNumber("100000"),this.parseNumber("0.0010")],[this.parseNumber("250000"),this.parseNumber("0.0008")],[this.parseNumber("500000"),this.parseNumber("0.0006")],[this.parseNumber("1000000"),this.parseNumber("0.0005")],[this.parseNumber("2500000"),this.parseNumber("0.0004")],[this.parseNumber("5000000"),this.parseNumber("0.0004")],[this.parseNumber("10000000"),this.parseNumber("0.0003")],[this.parseNumber("25000000"),this.parseNumber("0.0003")]]}}},requiredCredentials:{apiKey:!0,secret:!0},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:void 0,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!0,selfTradePrevention:{EXPIRE_MAKER:!1,EXPIRE_TAKER:!1,EXPIRE_BOTH:!0,NONE:!1},iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:1e5,untilDays:1e5,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:{marginMode:!0,limit:1e3,daysBack:1e5,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:void 0,fetchOHLCV:{limit:1440}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},exceptions:{exact:{101:a.ExchangeError,102:a.BadRequest,103:a.RateLimitExceeded,104:a.RateLimitExceeded,105:a.RateLimitExceeded,107:a.ExchangeNotAvailable,108:a.ExchangeNotAvailable,109:a.ExchangeNotAvailable,110:a.BadRequest,200:a.BadRequest,201:a.BadRequest,202:a.BadRequest,203:a.BadSymbol,204:a.BadRequest,205:a.BadRequest,206:a.BadRequest,210:a.InvalidOrder,211:a.InvalidOrder,212:a.InvalidOrder,213:a.InvalidOrder,214:a.InvalidOrder,215:a.InvalidOrder,216:a.InsufficientFunds,217:a.InvalidOrder,230:a.ExchangeError,231:a.ExchangeError,232:a.BadRequest,233:a.OrderNotFound,234:a.InvalidOrder,235:a.ExchangeError,236:a.BadRequest,240:a.OrderNotFound,300:a.AuthenticationError,301:a.AuthenticationError,302:a.AuthenticationError,303:a.AuthenticationError,304:a.AuthenticationError,305:a.AuthenticationError,306:a.AuthenticationError,307:a.PermissionDenied,308:a.AuthenticationError,309:a.AuthenticationError,310:a.PermissionDenied,311:a.PermissionDenied,312:a.PermissionDenied,315:a.BadRequest,317:a.AccountSuspended,400:a.ExchangeError,401:a.ExchangeError,402:a.PermissionDenied,403:a.PermissionDenied,404:a.OnMaintenance,405:a.ExchangeError,406:a.BadRequest,407:a.ExchangeError,408:a.InsufficientFunds,409:a.InvalidAddress,410:a.ExchangeError,411:a.BadRequest,412:a.InvalidAddress,413:a.InvalidAddress,414:a.ExchangeError},broad:{"start parameter is invalid":a.BadRequest,"symbol parameter is invalid":a.BadSymbol,"amount parameter is invalid":a.InvalidOrder,"orderId parameter is invalid":a.InvalidOrder}},options:{mica:!0,currencyToPrecisionRoundingMode:0,recvWindow:1e4,networks:{ERC20:"ETH",TRC20:"TRX"},operatorId:void 0,fetchCurrencies:{fiatCurrencies:["EUR"]}},precisionMode:4,commonCurrencies:{MIOTA:"IOTA"},rollingWindowSize:6e4})}async fetchTime(e={}){let t=await this.publicGetTime(e);return this.safeInteger(t,"time")}async fetchMarkets(e={}){let t=await this.publicGetMarkets(e);return this.parseMarkets(t)}parseMarkets(e){let t=[],i=this.fees;for(let s=0;s<e.length;s++){let r=this.safeDict(e,s),a=this.safeString(r,"market"),o=this.safeString(r,"base"),n=this.safeString(r,"quote"),d=this.safeCurrencyCode(o),h=this.safeCurrencyCode(n);if(void 0===d||void 0===h)continue;let c=this.safeString(r,"status");t.push(this.safeMarketStructure({id:a,symbol:d+"/"+h,base:d,quote:h,settle:void 0,baseId:o,quoteId:n,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:"trading"===c,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,taker:i.trading.taker,maker:i.trading.maker,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(r,"quantityDecimals"))),price:this.safeNumber(r,"tickSize"),cost:this.parseNumber(this.parsePrecision(this.safeString(r,"notionalDecimals")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(r,"minOrderInBaseAsset"),max:this.safeNumber(r,"maxOrderInBaseAsset")},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(r,"minOrderInQuoteAsset"),max:this.safeNumber(r,"maxOrderInQuoteAsset")}},created:void 0,info:r}))}return t}async fetchCurrencies(e={}){let t=await this.publicGetAssets(e);return this.parseCurrencies(t)}parseCurrency(e){let t=this.handleOption("fetchCurrencies","fiatCurrencies",[]),i=this.safeString(e,"symbol"),s=this.safeCurrencyCode(i),r=this.inArray(s,t),a={},o=this.safeList(e,"networks",[]),n="OK"===this.safeString(e,"depositStatus"),d="OK"===this.safeString(e,"withdrawalStatus"),h=n&&d,c=this.safeNumber(e,"withdrawalFee"),l=this.safeString(e,"decimals","8"),u=this.safeNumber(e,"withdrawalMinAmount");for(let t=0;t<o.length;t++){let i=o[t],r=this.networkIdToCode(i,s);void 0!==r&&(a[r]={info:e,id:i,network:r,active:h,deposit:n,withdraw:d,fee:c,precision:this.parseNumber(this.parsePrecision(l)),limits:{withdraw:{min:u,max:void 0}}})}return this.safeCurrencyStructure({info:e,id:i,code:s,name:this.safeString(e,"name"),active:h,deposit:n,withdraw:d,networks:a,fee:c,precision:void 0,type:r?"fiat":"crypto",limits:{amount:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0},withdraw:{min:u,max:void 0}}})}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={market:i.id},r=await this.publicGetTicker24h(this.extend(s,t));return this.parseTicker(r,i)}parseTicker(e,t){let i=this.safeString(e,"market"),s=this.safeSymbol(i,t,"-"),r=this.safeInteger(e,"timestamp"),a=this.safeString(e,"last"),o=this.safeString(e,"volume"),n=this.safeString(e,"volumeQuote"),d=this.safeString(e,"open");return this.safeTicker({symbol:s,timestamp:r,datetime:this.iso8601(r),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"bid"),bidVolume:this.safeString(e,"bidSize"),ask:this.safeString(e,"ask"),askVolume:this.safeString(e,"askSize"),vwap:void 0,open:d,close:a,last:a,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:o,quoteVolume:n,info:e},t)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetTicker24h(t);return this.parseTickers(i,e)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),[a,o]=this.handleOptionBoolAndParams(s,"fetchTrades","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchTrades",e,t,i,o);let n={market:r.id};void 0!==i&&(n.limit=Math.min(i,1e3)),void 0!==t&&(n.start=t);let[d,h]=this.handleUntilOption("end",n,o),c=await this.publicGetMarketTrades(this.extend(d,h));return this.parseTrades(c,r,t,i)}parseTrade(e,t){let i,s,r=this.safeString(e,"price"),a=this.safeString(e,"amount"),o=this.safeInteger(e,"timestamp"),n=this.safeString(e,"side"),d=this.safeString2(e,"id","fillId"),h=this.safeString(e,"market"),c=this.safeSymbol(h,t,"-"),l=this.safeBool(e,"taker");void 0!==l&&(i=!0===l?"taker":"maker");let u=this.safeString(e,"fee");if(void 0!==u){let t=this.safeString(e,"feeCurrency");s={cost:u,currency:this.safeCurrencyCode(t)}}let f=this.safeString(e,"orderId");return this.safeTrade({info:e,id:d,symbol:c,timestamp:o,datetime:this.iso8601(o),order:f,type:void 0,side:n,takerOrMaker:i,price:r,amount:a,cost:void 0,fee:s},t)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetAccount(e);return this.parseTradingFees(t)}parseTradingFees(e,t){let i=this.safeDict(e,"fees"),s=this.safeNumber(i,"maker"),r=this.safeNumber(i,"taker"),a={};for(let t=0;t<this.symbols.length;t++){let i=this.symbols[t];a[i]={info:e,symbol:i,maker:s,taker:r,percentage:!0,tierBased:!0}}return a}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={market:i.id},r=await this.privateGetAccountFees(this.extend(s,t));return this.parseTradingFee(r,i)}parseTradingFee(e,t){return{info:e,symbol:this.safeSymbol(void 0,t),maker:this.safeNumber(e,"maker"),taker:this.safeNumber(e,"taker"),percentage:!0,tierBased:!0}}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={market:s.id};void 0!==t&&(r.depth=t);let a=await this.publicGetMarketBook(this.extend(r,i)),o=this.parseOrderBook(a,s.symbol);return o.nonce=this.safeInteger(a,"nonce"),o}parseOHLCV(e,t){return[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]}fetchOHLCVRequest(e,t="1m",i,s,r={}){let a={market:this.market(e).id,interval:this.safeString(this.timeframes,t,t)};if(void 0!==i){let e=this.parseTimeframe(t);a.start=i;let r=void 0===s?1440:Math.min(s,1440);a.end=this.sum(i,r*e*1e3)}let[o,n]=this.handleUntilOption("end",a,r),d=s;return void 0!==i&&void 0===s&&(d=1440),void 0!==d&&(o.limit=Math.min(d,1440)),this.extend(o,n)}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),[o,n]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(o)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,n,1440);let d=this.fetchOHLCVRequest(e,t,i,s,n),h=await this.publicGetMarketCandles(d);return this.parseOHLCVs(this.toArray(h),a,t,i,s)}parseBalance(e){let t={info:e,timestamp:void 0,datetime:void 0};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"symbol"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(s,"available"),o.used=this.safeString(s,"inOrder"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetBalance(e);return this.parseBalance(t)}async fetchAccounts(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetSubaccounts(e),i=this.safeList(t,"items",[]);return this.parseAccounts(i)}parseAccount(e){return{id:this.safeString(e,"id"),type:this.safeString(e,"type"),code:void 0,info:e}}async transfer(e,t,i,s,r={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d=this.safeString(r,"subaccountId"),h=this.omit(r,"subaccountId");if("master"===i&&"master"===s)throw new a.ArgumentsRequired(this.id+" transfer() requires fromAccount and toAccount to be different (one master and one subaccount id)");if("master"===i)o="masterToSub",void 0===d&&(d=s);else if("master"===s)o="subToMaster",void 0===d&&(d=i);else throw new a.ArgumentsRequired(this.id+" transfer() requires either fromAccount or toAccount to be master");if(void 0===d)throw new a.ArgumentsRequired(this.id+" transfer() requires a subaccount id (provide it as fromAccount/toAccount or params.subaccountId)");let c={subaccountId:d,direction:o,symbol:n.id,amount:this.currencyToPrecision(e,t)},l=await this.privatePostSubaccountsTransfers(this.extend(c,h));return this.parseTransfer(l,n)}async fetchTransfers(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o={};if(void 0!==e&&(o.symbol=(r=this.currency(e)).id),void 0===this.safeString(s,"subaccountId"))throw new a.ArgumentsRequired(this.id+" fetchTransfers() requires a subaccountId parameter");void 0!==t&&(o.start=t),void 0!==i&&(o.limit=i);let[n,d]=this.handleUntilOption("end",o,s),h=await this.privateGetSubaccountsTransfers(this.extend(n,d)),c=this.safeList(h,"items",[]);return this.parseTransfers(c,r,t,i)}async fetchTransfer(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.currency(t));let r=await this.privateGetSubaccountsTransfersTransferId(this.extend({transferId:e},i));return this.parseTransfer(r,s)}parseTransferStatus(e){return this.safeString({completed:"ok",pending:"pending",failed:"failed"},e,e)}parseTransfer(e,t){let i,s,r=this.safeString(e,"symbol"),a=this.safeCurrencyCode(r,t),o=this.safeString(e,"subaccountId"),n=this.safeString(e,"direction");"masterToSub"===n?(i="master",s=o):"subToMaster"===n&&(i=o,s="master");let d=this.safeInteger(e,"createdAt");return void 0===d&&(d=this.parse8601(this.safeString(e,"createdAt"))),{info:e,id:this.safeString(e,"transferId"),timestamp:d,datetime:this.iso8601(d),currency:a,amount:this.safeNumber(e,"amount"),fromAccount:i,toAccount:s,status:this.parseTransferStatus(this.safeString(e,"status"))}}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={symbol:this.currency(e).id},s=await this.privateGetDeposit(this.extend(i,t)),r=this.safeString(s,"address"),a=this.safeString(s,"paymentId");return this.checkAddress(r),{info:s,currency:e,network:void 0,address:r,tag:a}}createOrderRequest(e,t,i,s,r,n={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let d=this.market(e),h={market:d.id,side:i,orderType:t},c="market"===t||"stopLoss"===t||"takeProfit"===t,l="limit"===t||"stopLossLimit"===t||"takeProfitLimit"===t,u=this.safeString(n,"timeInForce"),f=this.safeStringN(n,["triggerPrice","stopPrice","triggerAmount"]),p=this.isPostOnly(c,!1,n),m=this.safeString(n,"stopLossPrice"),g=this.safeString(n,"takeProfitPrice"),v=this.omit(n,["timeInForce","triggerPrice","stopPrice","stopLossPrice","takeProfitPrice"]),y=v;if(c&&(y=this.omit(v,["cost"])),c){let t;if(void 0!==r){let e=this.numberToString(r),i=this.numberToString(s),a=o.Y.stringMul(i,e);t=this.parseNumber(a)}else t=this.safeNumber(v,"cost");if(void 0!==t){let e=this.currency(d.quote).precision;h.amountQuote=this.decimalToPrecision(t,0,e,this.precisionMode)}else h.amount=this.amountToPrecision(e,s)}else l&&(h.price=this.priceToPrecision(e,r),h.amount=this.amountToPrecision(e,s));let b=void 0!==g||"takeProfit"===t||"takeProfitLimit"===t;void 0===m&&(void 0===f||b)&&"stopLoss"!==t&&"stopLossLimit"!==t?b&&(void 0!==g&&(f=g),h.orderType=c?"takeProfit":"takeProfitLimit"):(void 0!==m&&(f=m),h.orderType=c?"stopLoss":"stopLossLimit"),void 0!==f&&(h.triggerAmount=this.priceToPrecision(e,f),h.triggerType="price",h.triggerReference="lastTrade"),void 0!==u&&"PO"!==u&&(h.timeInForce=u),p&&(h.postOnly=!0);let[w,k]=this.handleOptionAndParams(y,"createOrder","operatorId");if(void 0!==w)h.operatorId=this.parseToInt(w);else throw new a.ArgumentsRequired(this.id+" createOrder() requires an operatorId in params or options, eg: exchange.options['operatorId'] = 1234567890");let[S,O]=this.handleOptionStringAndParams(k,"createOrder","selfTradePrevention");return void 0!==S&&("EXPIRE_BOTH"===S?h.selfTradePrevention="cancelBoth":h.selfTradePrevention=S),this.extend(h,O)}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=this.createOrderRequest(e,t,i,s,r,a),d=await this.privatePostOrder(n);return this.parseOrder(d,o)}editOrderRequest(e,t,i,s,r,o,n={}){let d={},h=this.market(t),c=this.safeNumber(n,"amountRemaining"),l=this.safeStringN(n,["triggerPrice","stopPrice","triggerAmount"]),u=this.omit(n,["amountRemaining","triggerPrice","stopPrice","triggerAmount"]);if(void 0!==o&&(d.price=this.priceToPrecision(t,o)),void 0!==r&&(d.amount=this.amountToPrecision(t,r)),void 0!==c&&(d.amountRemaining=this.amountToPrecision(t,c)),void 0!==l&&(d.triggerAmount=this.priceToPrecision(t,l)),d=this.extend(d,u),this.isEmpty(d))throw new a.ArgumentsRequired(this.id+" editOrder() requires an amount argument, or a price argument, or non-empty params");void 0===this.safeString(u,"clientOrderId")&&(d.orderId=e);let f=this.handleOptionAndParams(u,"editOrder","operatorId")[0];if(void 0!==f)d.operatorId=this.parseToInt(f);else throw new a.ArgumentsRequired(this.id+" editOrder() requires an operatorId in params or options, eg: exchange.options['operatorId'] = 1234567890");return d.market=h.id,d}async editOrder(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(t),d=this.editOrderRequest(e,t,i,s,r,a,o),h=await this.privatePutOrder(d);return this.parseOrder(h,n)}cancelOrderRequest(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");let s={market:this.market(t).id};void 0===this.safeString(i,"clientOrderId")&&(s.orderId=e);let[r,o]=this.handleOptionAndParams(i,"cancelOrder","operatorId");if(void 0!==r)s.operatorId=this.parseToInt(r);else throw new a.ArgumentsRequired(this.id+" cancelOrder() requires an operatorId in params or options, eg: exchange.options['operatorId'] = 1234567890");return this.extend(s,o)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r=this.cancelOrderRequest(e,t,i),a=await this.privateDeleteOrder(r);return this.parseOrder(a,s)}async cancelAllOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={};void 0!==e&&(s.market=(i=this.market(e)).id);let[r,o]=this.handleOptionAndParams(t,"cancelAllOrders","operatorId");if(void 0!==r)s.operatorId=this.parseToInt(r);else throw new a.ArgumentsRequired(this.id+" canceAllOrders() requires an operatorId in params or options, eg: exchange.options['operatorId'] = 1234567890");let n=await this.privateDeleteOrders(this.extend(s,o));return this.parseOrders(n,i)}async cancelAllOrdersAfter(e,t={}){if(e>3e5)throw new a.BadRequest(this.id+" cancelAllOrdersAfter() timeout should be less than or equal to 300000 milliseconds");if(e>0&&e<1e4)throw new a.BadRequest(this.id+" cancelAllOrdersAfter() timeout should be 0 or greater than or equal to 10000 milliseconds");void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionIntegerAndParams(t,"cancelAllOrdersAfter","codGroupId",1),r={codGroupId:i,expiryAfterSeconds:e>0?this.parseToInt(e/1e3):0};return await this.privatePostCancelOrdersAfter(this.extend(r,s))}async fetchOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r={market:s.id};void 0===this.safeString(i,"clientOrderId")&&(r.orderId=e);let o=await this.privateGetOrder(this.extend(r,i));return this.parseOrder(o,s)}fetchOrdersRequest(e,t,i,s={}){let r={market:this.market(e).id};void 0!==t&&(r.start=t),void 0!==i&&(r.limit=i);let[a,o]=this.handleUntilOption("end",r,s);return this.extend(a,o)}async fetchOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let[r,o]=this.handleOptionBoolAndParams(s,"fetchOrders","paginate",!1);if(r)return await this.fetchPaginatedCallDynamic("fetchOrders",e,t,i,o);let n=this.market(e),d=this.fetchOrdersRequest(e,t,i,o),h=await this.privateGetOrders(d);return this.parseOrders(h,n,t,i)}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.market=(r=this.market(e)).id);let o=await this.privateGetOrdersOpen(this.extend(a,s));return this.parseOrders(o,r,t,i)}parseOrderStatus(e){return this.safeString({new:"open",canceled:"canceled",canceledAuction:"canceled",canceledSelfTradePrevention:"canceled",canceledIOC:"canceled",canceledFOK:"canceled",canceledMarketProtection:"canceled",canceledPostOnly:"canceled",filled:"closed",partiallyFilled:"open",expired:"canceled",rejected:"canceled",awaitingTrigger:"open"},e,e)}parseOrder(e,t){let i,s=this.safeString(e,"orderId"),r=this.safeInteger(e,"created"),a=this.safeString(e,"market"),n=this.safeMarket(a,t,"-"),d=n.symbol,h=this.parseOrderStatus(this.safeString(e,"status")),c=this.safeString(e,"side"),l=this.safeString(e,"orderType"),u=this.safeString(e,"price"),f=this.safeString(e,"amount"),p=this.safeString(e,"amountRemaining"),m=this.safeString(e,"filledAmount"),g=this.safeString(e,"filledAmountQuote");if(void 0===g){let t=this.safeString(e,"amountQuote"),i=this.safeString(e,"amountQuoteRemaining");g=o.Y.stringSub(t,i)}let v=this.safeNumber(e,"feePaid");if(void 0!==v){let t=this.safeString(e,"feeCurrency");i={cost:v,currency:this.safeCurrencyCode(t)}}let y=this.safeList(e,"fills",[]),b=this.safeString(e,"timeInForce"),w=this.safeBool(e,"postOnly");return this.safeOrder({info:e,id:s,clientOrderId:void 0,timestamp:r,datetime:this.iso8601(r),lastTradeTimestamp:void 0,symbol:d,type:l,timeInForce:b,postOnly:w,side:c,price:u,triggerPrice:this.safeNumber(e,"triggerPrice"),amount:f,cost:g,average:void 0,filled:m,remaining:p,status:h,fee:i,trades:y},n)}fetchMyTradesRequest(e,t,i,s={}){let r={market:this.market(e).id};void 0!==t&&(r.start=t),void 0!==i&&(r.limit=i);let[a,o]=this.handleUntilOption("end",r,s);return this.extend(a,o)}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let[r,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(r)return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,o);let n=this.market(e),d=this.fetchMyTradesRequest(e,t,i,o),h=await this.privateGetTrades(d);return this.parseTrades(h,n,t,i)}async fetchLedger(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(r=this.currency(e)),void 0!==t&&(a.fromDate=t),void 0!==i&&(a.maxItems=Math.min(i,100));let[o,n]=this.handleUntilOption("toDate",a,s),d=await this.privateGetAccountHistory(this.extend(o,n)),h=this.safeList(d,"items",[]);return this.parseLedger(h,r,t,i)}parseLedgerEntryType(e){return this.safeString({buy:"trade",sell:"trade",deposit:"transaction",withdrawal:"transaction",withdrawal_cancelled:"transaction",internal_transfer:"transaction",external_transferred_funds:"transaction"},e,e)}parseLedgerEntry(e,t){let i,s=this.safeString(e,"type"),r=this.parseLedgerEntryType(s),a=this.safeString(e,"receivedCurrency"),o=this.safeString(e,"receivedAmount"),n="in";void 0===o&&(a=this.safeString(e,"sentCurrency"),o=this.safeString(e,"sentAmount"),n="out");let d=this.safeCurrencyCode(a),h=this.safeCurrency(a,t),c=this.parse8601(this.safeString(e,"executedAt")),l=this.safeString(e,"feesAmount");if(void 0!==l){let t=this.safeString(e,"feesCurrency");i={cost:l,currency:this.safeCurrencyCode(t)}}return this.safeLedgerEntry({info:e,id:this.safeString(e,"transactionId"),direction:n,account:void 0,referenceId:this.safeString(e,"transactionId"),referenceAccount:this.safeString(e,"address"),type:r,currency:d,amount:o,timestamp:c,datetime:this.iso8601(c),before:void 0,after:void 0,status:"ok",fee:i},h)}withdrawRequest(e,t,i,s,r={}){let a={symbol:this.currency(e).id,amount:this.currencyToPrecision(e,t),address:i};return void 0!==s&&(a.paymentId=s),this.extend(a,r)}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d=this.withdrawRequest(e,t,i,a,o),h=await this.privatePostWithdrawal(d);return this.parseTransaction(h,n)}fetchWithdrawalsRequest(e,t,i,s={}){let r={};return void 0!==e&&(r.symbol=this.currency(e).id),void 0!==t&&(r.start=t),void 0!==i&&(r.limit=i),this.extend(r,s)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.fetchWithdrawalsRequest(e,t,i,s);void 0!==e&&(r=this.currency(e));let o=await this.privateGetWithdrawalHistory(a);return this.parseTransactions(o,r,t,i,{type:"withdrawal"})}fetchDepositsRequest(e,t,i,s={}){let r={};return void 0!==e&&(r.symbol=this.currency(e).id),void 0!==t&&(r.start=t),void 0!==i&&(r.limit=i),this.extend(r,s)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.fetchDepositsRequest(e,t,i,s);void 0!==e&&(r=this.currency(e));let o=await this.privateGetDepositHistory(a);return this.parseTransactions(o,r,t,i,{type:"deposit"})}parseTransactionStatus(e){return this.safeString({awaiting_processing:"pending",awaiting_email_confirmation:"pending",awaiting_bitvavo_inspection:"pending",approved:"pending",sending:"pending",in_mempool:"pending",processed:"pending",completed:"ok",canceled:"canceled"},e,e)}parseTransaction(e,t){let i,s,r=this.safeInteger(e,"timestamp"),a=this.safeString(e,"symbol"),o=this.safeCurrencyCode(a,t),n=this.parseTransactionStatus(this.safeString(e,"status")),d=this.safeNumber(e,"amount"),h=this.safeString(e,"address"),c=this.safeString(e,"txId"),l=this.safeNumber(e,"fee");void 0!==l&&(i={cost:l,currency:o}),s="success"in e||"address"in e?"withdrawal":"deposit";let u=this.safeString(e,"paymentId");return{info:e,id:void 0,txid:c,timestamp:r,datetime:this.iso8601(r),addressFrom:void 0,address:h,addressTo:h,tagFrom:void 0,tag:u,tagTo:u,type:s,amount:d,currency:o,status:n,updated:void 0,fee:i,network:void 0,comment:void 0,internal:void 0}}parseDepositWithdrawFee(e,t){let i={info:e,withdraw:{fee:this.safeNumber(e,"withdrawalFee"),percentage:!1},deposit:{fee:this.safeNumber(e,"depositFee"),percentage:!1},networks:{}},s=this.safeList(e,"networks"),r=this.safeString(s,0),a=this.safeString(t,"code");"Mainnet"===r&&(r=a);let o=this.networkIdToCode(r,a);return void 0!==o&&(i.networks[o]={deposit:i.deposit,withdraw:i.withdraw}),i}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetAssets(t);return this.parseDepositWithdrawFees(i,e,"symbol")}sign(e,t="public",i="GET",r={},o,n){let d=o,h=n,c=this.omit(r,this.extractParams(e)),l="/"+this.version+"/"+this.implodeParams(e,r),u="GET"===i||"DELETE"===i;if(u&&Object.keys(c).length>0&&(l+="?"+this.urlencode(c)),"private"===t){this.checkRequiredCredentials();let e="";!u&&Object.keys(c).length>0&&(e=h=this.json(c));let t=this.milliseconds().toString(),r=t+i+l+e,a=this.hmac(this.encode(r),this.encode(this.secret),s.sc),o=this.safeString2(this.options,"recvWindow","BITVAVO-ACCESS-WINDOW","10000");d={"BITVAVO-ACCESS-KEY":this.apiKey,"BITVAVO-ACCESS-SIGNATURE":a,"BITVAVO-ACCESS-TIMESTAMP":t,"BITVAVO-ACCESS-WINDOW":o},u||(d["Content-Type"]="application/json")}let f=this.safeString(this.urls.api,t);if(void 0===f)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");return{url:f+l,method:i,body:h,headers:d}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"errorCode"),l=this.safeString(n,"error");if(void 0!==c){let e=this.id+" "+o;throw this.throwBroadlyMatchedException(this.exceptions.broad,l,e),this.throwExactlyMatchedException(this.exceptions.exact,c,e),new a.ExchangeError(e)}}calculateRateLimiterCost(e,t,i,s,r={}){return"noMarket"in r&&!("market"in s)?r.noMarket:this.safeValue(r,"cost",1)}}i.d(t,{A:()=>n})},3427(e,t,i){"use strict";var s=i(7156),r=i(1453),a=i(7749);class o extends s.A{describe(){return this.deepExtend(super.describe(),{id:"blockchaincom",secret:void 0,name:"Blockchain.com",countries:["LX"],rateLimit:500,version:"v3",pro:!0,has:{CORS:!1,spot:!0,margin:void 0,swap:!1,future:!1,option:!1,cancelAllOrders:!0,cancelOrder:!0,createOrder:!0,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,fetchBalance:!0,fetchCanceledOrders:!0,fetchClosedOrders:!0,fetchCurrencies:!1,fetchDeposit:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchFundingHistory:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchIndexOHLCV:!1,fetchL2OrderBook:!0,fetchL3OrderBook:!0,fetchLedger:!1,fetchMarginMode:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyTrades:!0,fetchOHLCV:!1,fetchOpenInterestHistory:!1,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchPositionMode:!1,fetchPremiumIndexOHLCV:!1,fetchTicker:!0,fetchTickers:!0,fetchTrades:!1,fetchTradingFee:!1,fetchTradingFees:!0,fetchTransfer:!1,fetchTransfers:!1,fetchWithdrawal:!0,fetchWithdrawals:!0,fetchWithdrawalWhitelist:!0,transfer:!1,withdraw:!0},timeframes:void 0,urls:{logo:"https://github.com/user-attachments/assets/975e3054-3399-4363-bcee-ec3c6d63d4e8",test:{public:"https://testnet-api.delta.exchange",private:"https://testnet-api.delta.exchange"},api:{public:"https://api.blockchain.com/v3/exchange",private:"https://api.blockchain.com/v3/exchange"},www:"https://blockchain.com",doc:["https://api.blockchain.com/v3"],fees:"https://exchange.blockchain.com/fees"},api:{public:{get:{tickers:{cost:1},"tickers/{symbol}":{cost:1},symbols:{cost:1},"symbols/{symbol}":{cost:1},"l2/{symbol}":{cost:1},"l3/{symbol}":{cost:1}}},private:{get:{fees:{cost:1},"internal/orders":{cost:1},orders:{cost:1},"orders/{orderId}":{cost:1},trades:{cost:1},fills:{cost:1},deposits:{cost:1},"deposits/{depositId}":{cost:1},accounts:{cost:1},"accounts/{account}/{currency}":{cost:1},whitelist:{cost:1},"whitelist/{currency}":{cost:1},withdrawals:{cost:1},"withdrawals/{withdrawalId}":{cost:1}},post:{orders:{cost:1},"deposits/{currency}":{cost:1},withdrawals:{cost:1}},delete:{orders:{cost:1},"orders/{orderId}":{cost:1}}}},fees:{trading:{feeSide:"get",tierBased:!0,percentage:!0,tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.0045")],[this.parseNumber("10000"),this.parseNumber("0.0035")],[this.parseNumber("50000"),this.parseNumber("0.0018")],[this.parseNumber("100000"),this.parseNumber("0.0018")],[this.parseNumber("500000"),this.parseNumber("0.0018")],[this.parseNumber("1000000"),this.parseNumber("0.0018")],[this.parseNumber("2500000"),this.parseNumber("0.0018")],[this.parseNumber("5000000"),this.parseNumber("0.0016")],[this.parseNumber("25000000"),this.parseNumber("0.0014")],[this.parseNumber("100000000"),this.parseNumber("0.0011")],[this.parseNumber("500000000"),this.parseNumber("0.0008")],[this.parseNumber("1000000000"),this.parseNumber("0.0006")]],maker:[[this.parseNumber("0"),this.parseNumber("0.004")],[this.parseNumber("10000"),this.parseNumber("0.0017")],[this.parseNumber("50000"),this.parseNumber("0.0015")],[this.parseNumber("100000"),this.parseNumber("0.0008")],[this.parseNumber("500000"),this.parseNumber("0.0007")],[this.parseNumber("1000000"),this.parseNumber("0.0006")],[this.parseNumber("2500000"),this.parseNumber("0.0005")],[this.parseNumber("5000000"),this.parseNumber("0.0004")],[this.parseNumber("25000000"),this.parseNumber("0.0003")],[this.parseNumber("100000000"),this.parseNumber("0.0002")],[this.parseNumber("500000000"),this.parseNumber("0.0001")],[this.parseNumber("1000000000"),this.parseNumber("0")]]}}},requiredCredentials:{apiKey:!1,secret:!0},options:{networks:{ERC20:"ETH",TRC20:"TRX",ALGO:"ALGO",ADA:"ADA",AR:"AR",ATOM:"ATOM",AVAXC:"AVAX",BCH:"BCH",BSV:"BSV",BTC:"BTC",DCR:"DCR",DESO:"DESO",DASH:"DASH",CELO:"CELO",CHZ:"CHZ",MATIC:"MATIC",SOL:"SOL",DOGE:"DOGE",DOT:"DOT",EOS:"EOS",ETC:"ETC",FIL:"FIL",KAVA:"KAVA",LTC:"LTC",IOTA:"MIOTA",NEAR:"NEAR",STX:"STX",XLM:"XLM",XMR:"XMR",XRP:"XRP",XTZ:"XTZ",ZEC:"ZEC",ZIL:"ZIL"}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!1,GTD:!0},hedged:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,trailing:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:1e5,untilDays:1e5,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,symbolRequired:!1,trailing:!1},fetchOpenOrders:{marginMode:!1,limit:1e3,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:1e3,daysBack:1e5,daysBackCanceled:1,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:void 0},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},precisionMode:4,exceptions:{exact:{401:r.AuthenticationError,404:r.OrderNotFound},broad:{}}})}async fetchMarkets(e={}){let t=await this.publicGetSymbols(e),i=Object.keys(t),s=[];for(let e=0;e<i.length;e++){let r,o,n=i[e],d=this.safeDict(t,n),h=this.safeString(d,"base_currency"),c=this.safeString(d,"counter_currency"),l=this.safeCurrencyCode(h),u=this.safeCurrencyCode(c);if(void 0===l||void 0===u)continue;let f=this.safeNumber(d,"id");r="open"===this.safeString(d,"status");let p=this.safeString(d,"min_price_increment"),m=this.safeString(d,"min_price_increment_scale"),g=this.parsePrecision(m),v=a.Y.stringMul(p,g),y=this.safeString(d,"lot_size"),b=this.safeString(d,"lot_size_scale"),w=this.parsePrecision(b),k=a.Y.stringMul(y,w),S=this.safeString(d,"min_order_size"),O=this.safeString(d,"min_order_size_scale"),T=this.parsePrecision(O),P=a.Y.stringMul(S,T),I=this.parseNumber(P),A=this.safeString(d,"max_order_size");if("0"!==A){let e=this.safeString(d,"max_order_size_scale"),t=this.parsePrecision(e),i=a.Y.stringMul(A,t);o=this.parseNumber(i)}s.push({info:d,id:n,numericId:f,symbol:l+"/"+u,base:l,quote:u,settle:void 0,baseId:h,quoteId:c,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:r,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(k),price:this.parseNumber(v)},limits:{leverage:{min:void 0,max:void 0},amount:{min:I,max:o},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0})}return s}async fetchOrderBook(e,t,i={}){return await this.fetchL3OrderBook(e,t,i)}async fetchL3OrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};void 0!==t&&(r.depth=t);let a=await this.publicGetL3Symbol(this.extend(r,i));return this.parseOrderBook(a,s.symbol,void 0,"bids","asks","px","qty")}async fetchL2OrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};void 0!==t&&(r.depth=t);let a=await this.publicGetL2Symbol(this.extend(r,i));return this.parseOrderBook(a,s.symbol,void 0,"bids","asks","px","qty")}parseTicker(e,t){let i=this.safeString(e,"symbol"),s=this.safeSymbol(i,t,"-"),r=this.safeString(e,"last_trade_price"),a=this.safeString(e,"volume_24h"),o=this.safeString(e,"price_24h");return this.safeTicker({symbol:s,timestamp:void 0,datetime:void 0,high:void 0,low:void 0,bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:o,close:void 0,last:r,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:a,quoteVolume:void 0,info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetTickersSymbol(this.extend(s,t));return this.parseTicker(r,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetTickers(t);return this.parseTickers(i,e)}parseOrderState(e){return this.safeString({OPEN:"open",REJECTED:"rejected",FILLED:"closed",CANCELED:"canceled",PART_FILLED:"open",EXPIRED:"expired"},e,e)}parseOrder(e,t){let i=this.safeString(e,"clOrdId"),s=this.safeStringLower(e,"ordType"),r=this.safeString(e,"ordStatus"),a=this.parseOrderState(r),o=this.safeStringLower(e,"side"),n=this.safeString(e,"symbol"),d=this.safeSymbol(n,t,"-"),h=this.safeString(e,"exOrdId"),c="market"!==s?this.safeString(e,"price"):void 0,l=this.safeNumber(e,"avgPx"),u=this.safeInteger(e,"timestamp"),f=this.iso8601(u),p=this.safeString(e,"cumQty"),m=this.safeString(e,"leavesQty");return this.safeOrder({id:h,clientOrderId:i,datetime:f,timestamp:u,lastTradeTimestamp:void 0,status:a,symbol:d,type:s,timeInForce:void 0,side:o,price:c,average:l,amount:void 0,filled:p,remaining:m,cost:void 0,trades:[],fees:[],info:e})}async createOrder(e,t,i,s,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=this.safeString(o,"ordType",t).toUpperCase(),h=this.safeString2(o,"clientOrderId","clOrdId",this.uuid16()),c=this.omit(o,["ordType","clientOrderId","clOrdId"]);this.checkRequiredArgument("createOrder",i,"side");let l={ordType:d,symbol:n.id,side:i.toUpperCase(),orderQty:this.amountToPrecision(e,s),clOrdId:h},u=this.safeValueN(c,["triggerPrice","stopPx","stopPrice"]),f=this.omit(c,["triggerPrice","stopPx","stopPrice"]);if(("STOP"===d||"STOPLIMIT"===d)&&void 0===u)throw new r.ArgumentsRequired(this.id+" createOrder() requires a stopPx or triggerPrice param for a "+d+" order");void 0!==u&&("MARKET"===d?l.ordType="STOP":"LIMIT"===d&&(l.ordType="STOPLIMIT"));let p=this.safeString(l,"ordType"),m=!1,g=!1;("LIMIT"===p||"STOPLIMIT"===p)&&(m=!0),("STOP"===p||"STOPLIMIT"===p)&&(g=!0),m&&(l.price=this.priceToPrecision(e,a)),g&&(l.stopPx=this.priceToPrecision(e,u));let v=await this.privatePostOrders(this.extend(l,f));return this.parseOrder(v,n)}async cancelOrder(e,t,i={}){let s=await this.privateDeleteOrdersOrderId(this.extend({orderId:e},i));return this.safeOrder({id:e,info:s})}async cancelAllOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={};void 0!==e&&(i.symbol=this.marketId(e));let s=await this.privateDeleteOrders(this.extend(i,t));return[this.safeOrder({info:s})]}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetFees(e),i=this.safeNumber(t,"makerRate"),s=this.safeNumber(t,"takerRate"),r={},a=this.symbols;for(let e=0;e<a.length;e++){let o=a[e];r[o]={info:t,symbol:o,maker:i,taker:s}}return r}async fetchCanceledOrders(e,t,i,s={}){return await this.fetchOrdersByState("CANCELED",e,t,i,s)}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrdersByState("FILLED",e,t,i,s)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrdersByState("OPEN",e,t,i,s)}async fetchOrdersByState(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o={status:e,limit:100};void 0!==t&&(o.symbol=(a=this.market(t)).id);let n=await this.privateGetOrders(this.extend(o,r));return this.parseOrders(n,a,i,s)}parseTrade(e,t){let i,s=this.safeString(e,"exOrdId"),r=this.safeString(e,"tradeId"),a=this.safeStringLower(e,"side"),o=this.safeString(e,"symbol"),n=this.safeString(e,"price"),d=this.safeString(e,"qty"),h=this.safeInteger(e,"timestamp"),c=this.iso8601(h),l=this.safeMarket(o,t,"-"),u=l.symbol,f=this.safeString(e,"fee");return void 0!==f&&(i={cost:f,currency:l.quote}),this.safeTrade({id:r,timestamp:h,datetime:c,symbol:u,order:s,type:void 0,side:a,takerOrMaker:void 0,price:n,amount:d,cost:void 0,fee:i,info:e},l)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==i&&(a.limit=i),void 0!==e&&(a.symbol=this.marketId(e),r=this.market(e));let o=await this.privateGetFills(this.extend(a,s));return this.parseTrades(o,r,t,i,s)}async fetchDepositAddress(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),a={currency:r.id},o=await this.privatePostDepositsCurrency(this.extend(a,t)),n=this.safeString(o,"address");if(void 0!==n){let e=n.split(";");i=this.safeString(e,0),s=this.safeString(e,1)}return{info:o,currency:r.code,network:void 0,address:s,tag:i}}parseTransactionState(e){return this.safeString({COMPLETED:"ok",REJECTED:"failed",PENDING:"pending",FAILED:"failed",REFUNDED:"refunded"},e,e)}parseTransaction(e,t){let i,s,r,a=this.safeNumber(e,"amount"),o=this.safeInteger(e,"timestamp"),n=this.safeString(e,"currency"),d=this.safeCurrencyCode(n,t),h=this.safeString(e,"state");"depositId"in e?(i="deposit",s=this.safeString(e,"depositId")):"withdrawalId"in e&&(i="withdrawal",s=this.safeString(e,"withdrawalId"));let c="withdrawal"===i?this.safeNumber(e,"fee"):void 0;void 0!==c&&(r={currency:d,cost:c});let l=this.safeString(e,"address"),u=this.safeString(e,"txhash");return{info:e,id:s,txid:u,timestamp:o,datetime:this.iso8601(o),network:void 0,addressFrom:void 0,address:l,addressTo:l,tagFrom:void 0,tag:void 0,tagTo:void 0,type:i,amount:a,currency:d,status:this.parseTransactionState(h),updated:void 0,comment:void 0,internal:void 0,fee:r}}async withdraw(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(e),o={amount:t,currency:a.id,beneficiary:i,sendMax:!1},n=await this.privatePostWithdrawals(this.extend(o,r));return this.parseTransaction(n,a)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==t&&(a.from=t),void 0!==e&&(r=this.currency(e));let o=await this.privateGetWithdrawals(this.extend(a,s));return this.parseTransactions(o,r,t,i)}async fetchWithdrawal(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateGetWithdrawalsWithdrawalId(this.extend({withdrawalId:e},i));return this.parseTransaction(s)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==t&&(a.from=t),void 0!==e&&(r=this.currency(e));let o=await this.privateGetDeposits(this.extend(a,s));return this.parseTransactions(o,r,t,i)}async fetchDeposit(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.safeString(i,"depositId",e),r=await this.privateGetDepositsDepositId(this.extend({depositId:s},i));return this.parseTransaction(r)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=this.safeString(e,"account","primary"),i=this.omit(e,"account"),s=await this.privateGetAccounts(this.extend({account:t},i)),a=this.safeList(s,t);if(void 0===a)throw new r.ExchangeError(this.id+' fetchBalance() could not find the "'+t+'" account');let o={info:s};for(let e=0;e<a.length;e++){let t=this.safeDict(a,e),i=this.safeString(t,"currency"),s=this.safeCurrencyCode(i),r=this.account();r.free=this.safeString(t,"available"),r.total=this.safeString(t,"balance"),o[s]=r}return this.safeBalance(o)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateGetOrdersOrderId(this.extend({orderId:e},i));return this.parseOrder(s)}sign(e,t="public",i="GET",s={},a,o){let n="/"+this.implodeParams(e,s),d=this.safeString(this.urls.api,t);if(void 0===d)throw new r.ExchangeError(this.id+" sign() has no API URL for this endpoint");let h=d+n,c=this.omit(s,this.extractParams(e)),l="private"===t,u={"X-API-Token":this.secret},f=a;l&&(f=u);let p=o;return l&&"GET"!==i&&(p=this.json(c)),"public"===t?Object.keys(c).length>0&&(h+="?"+this.urlencode(c)):l&&(this.checkRequiredCredentials(),"GET"===i?Object.keys(c).length>0&&(h+="?"+this.urlencode(c)):u["Content-Type"]="application/json"),{url:h,method:i,body:p,headers:f}}handleErrors(e,t,i,s,a,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"text");if(void 0!==c&&"Insufficient Balance"===c)throw new r.InsufficientFunds(this.id+" "+o);let l=this.safeString(n,"status"),u=this.safeString(n,"error");if(void 0!==e){let e=this.id+" "+this.json(n);this.throwExactlyMatchedException(this.exceptions.exact,l,e),this.throwBroadlyMatchedException(this.exceptions.broad,u,e)}}}i.d(t,{A:()=>o})},2114(e,t,i){"use strict";var s=i(4721),r=i(5331),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"blofin",name:"BloFin",countries:["US"],version:"v1",rateLimit:200,pro:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!1,option:!1,addMargin:!1,borrowMargin:!1,cancelAllOrders:!1,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!1,closePosition:!0,createDepositAddress:!1,createMarketBuyOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!0,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopLossOrder:!0,createStopMarketOrder:!1,createStopOrder:!1,createTakeProfitOrder:!0,createTriggerOrder:!0,editOrder:!1,fetchAccounts:!1,fetchBalance:!0,fetchBidsAsks:void 0,fetchBorrowInterest:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchCanceledOrders:!1,fetchClosedOrder:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!1,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!0,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchL3OrderBook:!1,fetchLedger:!0,fetchLedgerEntry:void 0,fetchLeverage:!0,fetchLeverages:!0,fetchLeverageTiers:!1,fetchMarginMode:!0,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenOrder:void 0,fetchOpenOrders:!0,fetchOrder:void 0,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrders:!1,fetchOrderTrades:!0,fetchPosition:!0,fetchPositionADLRank:!0,fetchPositionMode:!0,fetchPositions:!0,fetchPositionsADLRank:!0,fetchPositionsForSymbol:!1,fetchPositionsHistory:!0,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchStatus:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!1,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTradingLimits:!1,fetchTransactionFee:!1,fetchTransactionFees:!1,fetchTransactions:!1,fetchTransfer:!1,fetchTransfers:!1,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,fetchWithdrawal:!0,fetchWithdrawals:!0,fetchWithdrawalWhitelist:!1,reduceMargin:!1,repayCrossMargin:!1,setLeverage:!0,setMargin:!1,setMarginMode:!0,setPositionMode:!0,signIn:!1,transfer:!0,withdraw:!0},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1H","2h":"2H","4h":"4H","6h":"6H","8h":"8H","12h":"12H","1d":"1D","3d":"3D","1w":"1W","1M":"1M"},urls:{logo:"https://github.com/user-attachments/assets/67edf117-6217-4cb8-95e7-9b03f314b1b1",api:{rest:"https://openapi.blofin.com"},test:{rest:"https://demo-trading-openapi.blofin.com"},referral:{url:"https://blofin.com/register?referral_code=f79EsS",discount:.05},www:"https://www.blofin.com",doc:"https://blofin.com/docs"},api:{public:{get:{"market/instruments":{cost:1},"market/instruments-history":{cost:1},"market/tickers":{cost:1},"market/books":{cost:1},"market/trades":{cost:1},"market/mark-price":{cost:1},"market/funding-rate":{cost:1},"market/funding-rate-history":{cost:1},"market/candles":{cost:1},"market/index-candles":{cost:1},"market/mark-price-candles":{cost:1},"market/position-tiers":{cost:1},"spot/market/instruments":{cost:1},"spot/market/tickers":{cost:1},"spot/market/books":{cost:1},"spot/market/trades":{cost:1},"spot/market/candles":{cost:1}}},private:{get:{"asset/balances":{cost:1},"asset/bills":{cost:1},"asset/withdrawal-history":{cost:1},"asset/deposit-history":{cost:1},"asset/deposit-address":{cost:1},"account/config":{cost:1},"asset/currencies":{cost:1},"account/balance":{cost:1},"account/positions":{cost:1},"account/positions-history":{cost:1},"account/funding-fees":{cost:1},"account/margin-mode":{cost:1},"account/position-mode":{cost:1},"account/leverage-info":{cost:1},"account/batch-leverage-info":{cost:1},"trade/orders-pending":{cost:1.67},"trade/order-detail":{cost:1.67},"trade/orders-tpsl-pending":{cost:1.67},"trade/order-tpsl-detail":{cost:1.67},"trade/orders-algo-pending":{cost:1.67},"trade/orders-history":{cost:1.67},"trade/orders-tpsl-history":{cost:1.67},"trade/orders-algo-history":{cost:1.67},"trade/fills-history":{cost:1.67},"trade/order/price-range":{cost:1.67},"affiliate/basic":{cost:1},"affiliate/referral-code":{cost:1},"affiliate/invitees":{cost:1},"affiliate/sub-invitees":{cost:1},"affiliate/sub-affiliates":{cost:1},"affiliate/invitees/daily/info":{cost:1},"copytrading/instruments":{cost:1},"copytrading/config":{cost:1},"copytrading/account/balance":{cost:1},"copytrading/account/positions-by-order":{cost:1},"copytrading/account/positions-details-by-order":{cost:1},"copytrading/account/positions-by-contract":{cost:1},"copytrading/account/position-mode":{cost:1},"copytrading/account/leverage-info":{cost:1},"copytrading/trade/orders-pending":{cost:1.67},"copytrading/trade/pending-tpsl-by-contract":{cost:1.67},"copytrading/trade/position-history-by-order":{cost:1.67},"copytrading/trade/orders-history":{cost:1.67},"copytrading/trade/pending-tpsl-by-order":{cost:1.67},"user/query-apikey":{cost:1},"spot/trade/fills-history":{cost:1},"spot/trade/orders-pending":{cost:1.67},"spot/trade/order-detail":{cost:1.67},"spot/trade/orders-algo-pending":{cost:1.67},"spot/trade/orders-history":{cost:1.67},"spot/trade/orders-algo-history":{cost:1.67},"spot/trade/order/price-range":{cost:1.67}},post:{"asset/transfer":{cost:1},"asset/demo-apply-money":{cost:1},"asset/withdrawal-apply":{cost:1},"account/set-margin-mode":{cost:1.67},"account/set-position-mode":{cost:1.67},"account/set-leverage":{cost:1.67},"trade/order":{cost:1.67},"trade/batch-orders":{cost:1.67},"trade/order-tpsl":{cost:1.67},"trade/order-algo":{cost:1.67},"trade/cancel-order":{cost:1.67},"trade/cancel-batch-orders":{cost:1.67},"trade/cancel-tpsl":{cost:1.67},"trade/cancel-algo":{cost:1.67},"trade/amend-order":{cost:1.67},"trade/amend-batch-orders":{cost:1.67},"trade/amend-tpsl":{cost:1.67},"trade/amend-algo":{cost:1.67},"trade/close-position":{cost:1.67},"spot/trade/order":{cost:1.67},"spot/trade/batch-orders":{cost:1.67},"spot/trade/order-algo":{cost:1.67},"spot/trade/cancel-order":{cost:1.67},"spot/trade/cancel-batch-orders":{cost:1.67},"spot/trade/cancel-algo":{cost:1.67},"copytrading/account/set-position-mode":{cost:1.67},"copytrading/account/set-leverage":{cost:1.67},"copytrading/trade/place-order":{cost:1.67},"copytrading/trade/cancel-order":{cost:1.67},"copytrading/trade/place-tpsl-by-contract":{cost:1.67},"copytrading/trade/cancel-tpsl-by-contract":{cost:1.67},"copytrading/trade/place-tpsl-by-order":{cost:1.67},"copytrading/trade/cancel-tpsl-by-order":{cost:1.67},"copytrading/trade/close-position-by-order":{cost:1.67},"copytrading/trade/close-position-by-contract":{cost:1.67}}}},fees:{swap:{taker:this.parseNumber("0.00060"),maker:this.parseNumber("0.00020")}},requiredCredentials:{apiKey:!0,secret:!0,password:!0},features:{default:{sandbox:!1,createOrder:{timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,trailing:!1,iceberg:!1},createOrders:{max:10},fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,symbolRequired:!1},fetchOrder:void 0,fetchOpenOrders:{marginMode:!1,limit:100,trigger:!0,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:1e3,daysBack:1e5,daysBackCanceled:1,untilDays:1e5,trigger:!0,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:1440}},spot:{extends:"default",fetchCurrencies:{private:!0},createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,hedged:!1}},forDerivatives:{extends:"default",createOrder:{marginMode:!0,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:{triggerPriceType:void 0,price:!0},hedged:!0}},swap:{linear:{extends:"forDerivatives"},inverse:void 0},future:{linear:void 0,inverse:void 0}},exceptions:{exact:{400:a.BadRequest,401:a.AuthenticationError,500:a.ExchangeError,404:a.BadRequest,405:a.BadRequest,406:a.BadRequest,429:a.RateLimitExceeded,152001:a.BadRequest,152002:a.BadRequest,152003:a.BadRequest,152004:a.BadRequest,152005:a.BadRequest,152006:a.InvalidOrder,152007:a.InvalidOrder,152008:a.InvalidOrder,152009:a.InvalidOrder,150003:a.InvalidOrder,150004:a.InvalidOrder,542:a.InvalidOrder,102002:a.InvalidOrder,102005:a.InvalidOrder,102014:a.InvalidOrder,102015:a.InvalidOrder,102022:a.InvalidOrder,102037:a.InvalidOrder,102038:a.InvalidOrder,102039:a.InvalidOrder,102040:a.InvalidOrder,102047:a.InvalidOrder,102048:a.InvalidOrder,102049:a.InvalidOrder,102050:a.InvalidOrder,102051:a.InvalidOrder,102052:a.InvalidOrder,102053:a.InvalidOrder,102054:a.InvalidOrder,102055:a.InvalidOrder,102064:a.BadRequest,102065:a.BadRequest,102068:a.BadRequest,103013:a.ExchangeError,102067:a.OrderNotFound,102089:a.BadRequest,102148:a.DuplicateOrderId,103003:a.InsufficientFunds,110006:a.InvalidOrder,110019:a.InvalidOrder,148082:a.BadRequest,148083:a.BadRequest,152011:a.PermissionDenied,152012:a.BadRequest,152013:a.PermissionDenied,152014:a.BadRequest,152015:a.BadRequest,152020:a.InvalidAddress,152022:a.BadRequest,152023:a.PermissionDenied,152024:a.PermissionDenied,152025:a.PermissionDenied,152026:a.BadRequest,152027:a.BadRequest,152028:a.InsufficientFunds,152029:a.PermissionDenied,152030:a.DuplicateOrderId,152031:a.InvalidAddress,152032:a.PermissionDenied,152401:a.AuthenticationError,152402:a.AuthenticationError,152404:a.PermissionDenied,152405:a.InvalidNonce,152406:a.PermissionDenied,152407:a.InvalidNonce,152408:a.AuthenticationError,152409:a.AuthenticationError,152410:a.InvalidNonce,152420:a.DuplicateOrderId,152421:a.DuplicateOrderId,152422:a.BadRequest,152423:a.InvalidOrder,152428:a.BadRequest,152429:a.BadRequest,"Order failed. Insufficient USDT margin in account":a.InsufficientFunds},broad:{"Internal Server Error":a.ExchangeNotAvailable,"server error":a.ExchangeNotAvailable}},httpExceptions:{429:a.ExchangeNotAvailable},precisionMode:4,options:{accountsByType:{swap:"futures",funding:"funding",future:"futures",copy_trading:"copy_trading",earn:"earn",spot:"spot"},accountsById:{funding:"funding",futures:"swap",copy_trading:"copy_trading",earn:"earn",spot:"spot"},defaultNetwork:"ERC20",defaultNetworks:{ETH:"ERC20",BTC:"BTC",USDT:"TRC20"},networks:{BTC:"Bitcoin",SOL:"Solana",MATIC:"Polygon POS",AVAXC:"AVAX C-Chain",ARBITRUM:"Arbitrum One",OPTIMISM:"Optimism",KAIA:"KAIA",PLASMA:"Plasma"},networkCodeAliases:{OP:"OPTIMISM"},networkPrefixes:{TRC20:"Tron",ERC20:"Ethereum",BEP20:"BNB Smart Chain",APT:"APT",TON:"TON"},networkSuffixes:{TON:"Toncoin"},networkCodesBySuffix:{Toncoin:"TON"},networksById:{Bitcoin:"BTC",Solana:"SOL","Polygon POS":"MATIC","AVAX C-Chain":"AVAXC","Arbitrum One":"ARBITRUM",Optimism:"OPTIMISM",BSC:"BEP20",Plasma:"PLASMA"},fetchOpenInterestHistory:{timeframes:{"5m":"5m","1h":"1H","8h":"8H","1d":"1D","5M":"5m","1H":"1H","8H":"8H","1D":"1D"}},defaultType:"swap",brokerId:"ec6dd3a7dd982d0b",fetchOpenOrders:{method:"privateGetTradeOrdersPending"},cancelOrders:{method:"privatePostTradeCancelBatchOrders"},fetchClosedOrders:{method:"privateGetTradeOrdersHistory"},withdraw:{password:void 0,pwd:void 0},exchangeType:{spot:"SPOT",swap:"SWAP",SPOT:"SPOT",SWAP:"SWAP"}}})}async fetchMarkets(e={}){let t=await this.publicGetMarketInstruments(e),i=this.safeList(t,"data",[]);return this.parseMarkets(i)}parseMarket(e){let t=this.safeString(e,"instId"),i=this.safeStringLower(e,"instType"),s="spot"===i,r="future"===i,a="swap"===i,n="option"===i,d=a||r,h=this.safeString(e,"baseCurrency"),c=this.safeString(e,"quoteCurrency"),l=this.safeString(e,"settleCurrency",c),u=this.safeCurrencyCode(l),f=this.safeCurrencyCode(h),p=this.safeCurrencyCode(c);if(void 0===f||void 0===p)return;let m=f+"/"+p;a&&(m=m+":"+u);let g,v=this.safeString(e,"tickSize"),y=this.safeDict2(this.fees,i,"trading",{}),b=this.safeNumber(y,"taker"),w=this.safeNumber(y,"maker"),k=this.safeString(e,"maxLeverage","100");k=o.Y.stringMax(k,"1");let S="live"===this.safeString(e,"state"),O=s&&o.Y.stringGt(k,"1"),T=this.safeString(e,"contractType"),P=this.safeNumber(e,"maxLimitSize"),I=this.safeNumber(e,"maxMarketSize");return this.safeMarketStructure({id:t,symbol:m,base:f,quote:p,baseId:h,quoteId:c,settle:u,settleId:l,type:i,spot:s,option:n,margin:O,swap:a,future:r,active:S,taker:b,maker:w,contract:d,linear:d?"linear"===T:void 0,inverse:d?"inverse"===T:void 0,contractSize:d?this.safeNumber(e,"contractValue"):void 0,expiry:g,expiryDatetime:g,strike:void 0,optionType:void 0,created:this.safeInteger(e,"listTime"),precision:{amount:this.safeNumber(e,"lotSize"),price:this.parseNumber(v)},limits:{leverage:{min:this.parseNumber("1"),max:this.parseNumber(k)},amount:{min:this.safeNumber(e,"minSize"),max:P},price:{min:void 0,max:void 0},cost:{min:void 0,max:d?void 0:I}},info:e})}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={instId:this.market(e).id},r=void 0===t?50:t;void 0!==r&&(s.size=r);let a=await this.publicGetMarketBooks(this.extend(s,i)),o=this.safeList(a,"data",[]),n=this.safeDict(o,0,{}),d=this.safeInteger(n,"ts");return this.parseOrderBook(n,e,d)}parseTicker(e,t){let i=this.safeInteger(e,"ts"),s=this.safeString(e,"instId"),r=this.safeMarket(s,t,"-"),a=r.symbol,o=this.safeString(e,"last"),n=this.safeString(e,"open24h"),d=!0===this.safeBool(r,"spot",!1)?this.safeString(e,"volCurrency24h"):void 0,h=this.safeString(e,"vol24h"),c=this.safeString(e,"high24h"),l=this.safeString(e,"low24h");return this.safeTicker({symbol:a,timestamp:i,datetime:this.iso8601(i),high:c,low:l,bid:this.safeString(e,"bidPrice"),bidVolume:this.safeString(e,"bidSize"),ask:this.safeString(e,"askPrice"),askVolume:this.safeString(e,"askSize"),vwap:void 0,open:n,close:o,last:o,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:h,quoteVolume:d,indexPrice:this.safeString(e,"indexPrice"),markPrice:this.safeString(e,"markPrice"),info:e},r)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instId:i.id},r=await this.publicGetMarketTickers(this.extend(s,t)),a=this.safeList(r,"data",[]),o=this.safeDict(a,0,{});return this.parseTicker(o,i)}async fetchMarkPrice(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetMarketMarkPrice(this.extend(s,t)),a=this.safeList(r,"data",[]),o=this.safeDict(a,0,{});return this.parseTicker(o,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetMarketTickers(t),r=this.safeList(s,"data",[]);return this.parseTickers(r,i)}parseTrade(e,t){let i,s=this.safeString(e,"tradeId"),r=this.safeString(e,"instId"),a=this.safeMarket(r,t,"-"),n=a.symbol,d=this.safeInteger(e,"ts"),h=this.safeString2(e,"price","fillPrice"),c=this.safeString2(e,"size","fillSize"),l=this.safeString(e,"side"),u=this.safeString(e,"orderId"),f=this.safeString(e,"fee"),p=this.safeString(e,"feeCurrency"),m=void 0!==p;if(void 0===p?p=this.safeString(a,"settle"):"base_currency"===p?p=this.safeString(a,"base"):"quote_currency"===p&&(p=this.safeString(a,"quote")),void 0!==f&&(i={cost:f,currency:p}),!m)return this.safeTrade({info:e,timestamp:d,datetime:this.iso8601(d),symbol:n,id:s,order:u,type:void 0,takerOrMaker:void 0,side:l,price:h,amount:c,cost:void 0,fee:i},a);{let t=a.base+"/"+a.quote,i=this.parseNumber(o.Y.stringMul(h,c));return{info:e,timestamp:d,datetime:this.iso8601(d),symbol:t,id:s,order:u,type:void 0,takerOrMaker:void 0,side:l,price:this.parseNumber(h),amount:this.parseNumber(c),cost:i,fee:{cost:this.parseNumber(f),currency:p}}}}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchTrades","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchTrades",e,t,i,o,"tradeId","after",void 0,100);let n=this.market(e),d={instId:n.id};void 0!==i&&(d.limit=i);let[h,c]=this.handleOptionStringAndParams(o,"fetchTrades","method","publicGetMarketTrades");"publicGetMarketTrades"===h&&(r=await this.publicGetMarketTrades(this.extend(d,c)));let l=this.safeList(r,"data",[]);return this.parseTrades(l,n,t,i)}parseOHLCV(e,t){return[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,6)]}async fetchOHLCV(e,t="1m",i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=!1;if([n,a]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1),n)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,a,100);let d=void 0===s?100:s,h={instId:o.id,bar:this.safeString(this.timeframes,t,t),limit:d},c=this.safeInteger(a,"until");void 0!==c&&(h.after=c,a=this.omit(a,"until"));let l=await this.publicGetMarketCandles(this.extend(h,a)),u=this.safeList(l,"data",[]);return this.parseOHLCVs(u,o,t,i,d)}async fetchFundingRateHistory(e,t,i,s={}){let r;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let o=!1;if([o,r]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1),o)return await this.fetchPaginatedCallDeterministic("fetchFundingRateHistory",e,t,i,"8h",r,100);let n=this.market(e),d={instId:n.id};void 0!==t&&(d.before=Math.max(t-1,0)),void 0!==i&&(d.limit=i);let h=this.safeInteger(r,"until");void 0!==h&&(d.after=h,r=this.omit(r,"until"));let c=await this.publicGetMarketFundingRateHistory(this.extend(d,r)),l=[],u=this.safeList(c,"data",[]);for(let e=0;e<u.length;e++){let t=u[e],i=this.safeInteger(t,"fundingTime");l.push({info:t,symbol:n.symbol,fundingRate:this.safeNumber(t,"fundingRate"),timestamp:i,datetime:this.iso8601(i)})}let f=this.sortBy(l,"timestamp");return this.filterBySymbolSinceLimit(f,this.safeString(n,"symbol"),t,i)}parseFundingRate(e,t){let i=this.safeString(e,"instId"),s=this.safeSymbol(i,t),r=this.safeInteger(e,"fundingTime");return{info:e,symbol:s,markPrice:void 0,indexPrice:void 0,interestRate:this.parseNumber("0"),estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:this.safeNumber(e,"fundingRate"),fundingTimestamp:r,fundingDatetime:this.iso8601(r),nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:void 0}}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new a.ExchangeError(this.id+" fetchFundingRate() is only valid for swap markets");let s={instId:i.id},r=await this.publicGetMarketFundingRate(this.extend(s,t)),o=this.safeList(r,"data",[]),n=this.safeDict(o,0,{});return this.parseFundingRate(n,i)}parseBalanceByType(e){let t=this.safeList(e,"data");return void 0!==t&&Array.isArray(t)?this.parseFundingBalance(e):this.parseBalance(e)}parseBalance(e){let t={info:e},i=this.safeDict(e,"data",{}),s=this.safeInteger(i,"ts"),r=this.safeList(i,"details",[]);for(let e=0;e<r.length;e++){let i=this.safeDict(r,e),s=this.safeString(i,"currency"),a=this.safeCurrencyCode(s),o=this.account(),n=this.safeString(i,"equity"),d=this.safeString(i,"available");void 0===n||void 0===d?(o.free=this.safeString(i,"availableEquity"),o.used=this.safeString(i,"frozen")):(o.total=n,o.free=d),t[a]=o}return t.timestamp=s,t.datetime=this.iso8601(s),this.safeBalance(t)}parseFundingBalance(e){let t={info:e},i=this.safeList(e,"data",[]);for(let e=0;e<i.length;e++){let s=this.safeDict(i,e),r=this.safeString(s,"currency"),a=this.safeCurrencyCode(r),o=this.account();o.total=this.safeString(s,"balance"),o.free=this.safeString(s,"available"),o.used=this.safeString(s,"frozen"),t[a]=o}return this.safeBalance(t)}parseTradingFee(e,t){return{info:e,symbol:this.safeSymbol(void 0,t),maker:this.parseNumber(o.Y.stringNeg(this.safeString2(e,"maker","makerU"))),taker:this.parseNumber(o.Y.stringNeg(this.safeString2(e,"taker","takerU"))),percentage:void 0,tierBased:void 0}}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionStringAndParams2(e,"fetchBalance","accountType","type"),r={};if(void 0!==i&&"swap"!==i){let e=this.safeDict(this.options,"accountsByType",{});r.accountType=this.safeString(e,i,i),t=await this.privateGetAssetBalances(this.extend(r,s))}else t=await this.privateGetAccountBalance(this.extend(r,s));return this.parseBalanceByType(t)}createOrderRequest(e,t,i,s,r,o={}){let n,d;if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let h={instId:this.market(e).id,side:i,orderType:t,size:this.amountToPrecision(e,s),brokerId:this.safeString(this.options,"brokerId","ec6dd3a7dd982d0b")};[n,d]=this.handleMarginModeAndParams("createOrder",o,"cross"),h.marginMode=n;let c=this.safeStringN(d,["triggerPrice","stopLossPrice","takeProfitPrice"]),l=this.safeString2(d,"stopLossPrice","takeProfitPrice"),u=this.safeString(d,"timeInForce","GTC");!0===this.safeBool(d,"hedged",!1)&&(h.positionSide="buy"===i?"long":"short");let f="market"===t;d=this.omit(d,["timeInForce"]);let p="IOC"===u||"ioc"===t,m=f&&p;if(f||m)h.orderType="market";else{let t="price";void 0!==c&&(t="orderPrice"),h[t]=this.priceToPrecision(e,r)}let g=!1;[g,d]=this.handlePostOnly(f,"post_only"===t,d),g&&(h.type="post_only");let v=this.safeDict(d,"stopLoss"),y=this.safeDict(d,"takeProfit");d=this.omit(d,["stopLoss","takeProfit","hedged"]);let b=void 0!==v,w=void 0!==y;if(b||w){if(b){let t=this.safeString2(v,"triggerPrice","stopPrice");h.slTriggerPrice=this.priceToPrecision(e,t);let i=this.safeString(v,"price","-1");h.slOrderPrice=this.priceToPrecision(e,i)}if(w){let t=this.safeString2(y,"triggerPrice","stopPrice");h.tpTriggerPrice=this.priceToPrecision(e,t);let i=this.safeString(y,"price","-1");h.tpOrderPrice=this.priceToPrecision(e,i)}}else void 0!==c&&(h.orderType="trigger",h.triggerPrice=this.priceToPrecision(e,c),f&&(h.orderPrice="-1"),void 0!==l&&(h.reduceOnly=!0),d=this.omit(d,["stopLossPrice","takeProfitPrice","triggerPrice"]));return this.extend(h,d)}parseOrderStatus(e){return this.safeString({canceled:"canceled",order_failed:"canceled",live:"open",partially_filled:"open",filled:"closed",effective:"closed"},e,e)}parseOrder(e,t){let i,s,r,a,n=this.safeStringN(e,["tpslId","orderId","algoId"]),d=this.safeInteger(e,"createTime"),h=this.safeInteger(e,"updateTime"),c=this.safeInteger(e,"fillTime"),l=this.safeString(e,"side"),u=this.safeString(e,"orderType");"post_only"===u?(i=!0,u="limit"):"fok"===u?(s="FOK",u="limit"):"ioc"===u?(s="IOC",u="limit"):"conditional"===u&&(u="trigger");let f=this.safeString(e,"instId"),p=this.safeMarket(f,t),m=this.safeSymbol(f,p,"-"),g=this.safeString(e,"filledSize"),v=this.safeStringN(e,["px","price","orderPrice"]),y=this.safeString(e,"averagePrice"),b=this.parseOrderStatus(this.safeString(e,"state")),w=this.safeString(e,"fee"),k=this.safeString(e,"size"),S=this.safeString(p,"contractSize"),O=o.Y.stringMul(S,g);if(void 0!==y&&(r=o.Y.stringMul(y,O)),void 0!==w){let t=o.Y.stringAbs(w),i=this.safeString(e,"feeCcy","USDT"),s=this.safeCurrencyCode(i);a={cost:this.parseNumber(t),currency:s}}let T=this.safeString(e,"clientOrderId");void 0!==T&&T.length<1&&(T=void 0);let P=this.safeNumber(e,"slTriggerPrice"),I=this.safeNumber(e,"tpTriggerPrice"),A=this.safeString(e,"reduceOnly");return this.safeOrder({info:e,id:n,clientOrderId:T,timestamp:d,datetime:this.iso8601(d),lastTradeTimestamp:c,lastUpdateTimestamp:h,symbol:m,type:u,timeInForce:s,postOnly:i,side:l,price:v,stopLossPrice:P,takeProfitPrice:I,average:y,cost:r,amount:k,filled:g,remaining:void 0,status:b,fee:a,trades:void 0,reduceOnly:"true"===A},p)}async createOrder(e,t,i,s,r,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=void 0!==this.safeString(a,"stopLossPrice"),h=void 0!==this.safeString(a,"takeProfitPrice"),c=void 0!==this.safeString(a,"triggerPrice"),[l,u]=this.handleOptionBoolAndParams(a,"createOrder","tpsl",!1),f=d&&h||l,p=d||h,m=this.safeBool(u,"reduceOnly");if(void 0!==m&&(u.reduceOnly=m?"true":"false"),f){let a=this.createTpslOrderRequest(e,t,i,s,r,u);o=await this.privatePostTradeOrderTpsl(a)}else if(c||p){let a=this.createOrderRequest(e,t,i,s,r,u);o=await this.privatePostTradeOrderAlgo(a)}else{let a=this.createOrderRequest(e,t,i,s,r,u);o=await this.privatePostTradeOrder(a)}if(f||p||c){let e=this.safeDict(o,"data",{});return this.parseOrder(e,n)}let g=this.safeList(o,"data",[]),v=this.safeDict(g,0),y=this.parseOrder(v,n);return y.type=t,y.side=i,y}createTpslOrderRequest(e,t,i,s,r,o={}){let n=this.market(e),d=this.safeBool(o,"hedged",!1),h="net";!0===d&&(h="buy"===i?"short":"long");let c={instId:n.id,side:i,positionSide:h,brokerId:this.safeString(this.options,"brokerId","ec6dd3a7dd982d0b"),reduceOnly:this.safeBool(o,"reduceOnly",!0)};void 0!==s&&(c.size=this.amountToPrecision(e,s));let l=this.safeString(o,"marginMode","cross");if("cross"!==l&&"isolated"!==l)throw new a.BadRequest(this.id+" createTpslOrder() requires a marginMode parameter that must be either cross or isolated");let u=this.safeString(o,"stopLossPrice"),f=this.safeString(o,"takeProfitPrice");if(void 0!==u)if(c.slTriggerPrice=this.priceToPrecision(e,u),"market"===t)c.slOrderPrice="-1";else{let t=this.safeString(o,"stopLossLimitPrice");if(void 0===t)throw new a.ArgumentsRequired(this.id+' createTpslOrder() requires a "stopLossLimitPrice" parameter (instead of "price" argument) for stop loss orders when the order type is not market');c.slOrderPrice=this.priceToPrecision(e,t)}if(void 0!==f)if(c.tpTriggerPrice=this.priceToPrecision(e,f),"market"===t)c.tpOrderPrice="-1";else{let t=this.safeString(o,"takeProfitLimitPrice");if(void 0===t)throw new a.ArgumentsRequired(this.id+' createTpslOrder() requires a "takeProfitLimitPrice" parameter (instead of "price" argument) for take profit orders when the order type is not market');c.tpOrderPrice=this.priceToPrecision(e,t)}c.marginMode=l;let p=["stopLossPrice","takeProfitPrice","reduceOnly","hedged"];return void 0!==u&&"market"!==t&&p.push("stopLossLimitPrice"),void 0!==f&&"market"!==t&&p.push("takeProfitLimitPrice"),this.extend(c,this.omit(o,p))}async cancelOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r={instId:s.id},o=this.safeBool(i,"trigger",!1),n=this.safeBool2(i,"tpsl","TPSL",!1),d=this.safeString(i,"clientOrderId");void 0!==d?r.clientOrderId=d:!0!==o&&!0!==n?r.orderId=e.toString():!0===n?r.tpslId=e.toString():!0===o&&(r.algoId=e.toString());let h=this.omit(i,["orderId","clientOrderId","stop","trigger","tpsl"]);if(!0===n){let s=await this.cancelOrders([e],t,i);return this.safeDict(s,0)}if(!0===o){let e=await this.privatePostTradeCancelAlgo(this.extend(r,h)),t=this.safeDict(e,"data");return this.parseOrder(t,s)}let c=await this.privatePostTradeCancelOrder(this.extend(r,h)),l=this.safeList(c,"data",[]),u=this.safeDict(l,0);return this.parseOrder(u,s)}async createOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=[];for(let s=0;s<e.length;s++){let r=this.safeDict(e,s),a=this.safeString(r,"symbol"),o=this.safeString(r,"type"),n=this.safeString(r,"side"),d=this.safeValue(r,"amount"),h=this.safeValue(r,"price"),c=this.safeDict(r,"params",{}),l=this.extend(c,t),u=this.createOrderRequest(a,o,n,d,h,l);i.push(u)}let s=await this.privatePostTradeBatchOrders(i),r=this.safeList(s,"data",[]);return this.parseOrders(r)}async fetchOpenOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(s,"fetchOpenOrders","paginate",!1);if(o)return await this.fetchPaginatedCallDynamic("fetchOpenOrders",e,t,i,n);let d={};void 0!==e&&(d.instId=(a=this.market(e)).id),void 0!==i&&(d.limit=i);let h=this.safeBoolN(n,["stop","trigger"],!1),c=this.safeBool2(n,"tpsl","TPSL",!1),[l,u]=this.handleOptionStringAndParams(n,"fetchOpenOrders","method","privateGetTradeOrdersPending"),f=this.omit(u,["method","stop","trigger","tpsl","TPSL"]);!0===c||"privateGetTradeOrdersTpslPending"===l?r=await this.privateGetTradeOrdersTpslPending(this.extend(d,f)):!0===h||"privateGetTradeOrdersAlgoPending"===l?(d.orderType="trigger",r=await this.privateGetTradeOrdersAlgoPending(this.extend(d,f))):r=await this.privateGetTradeOrdersPending(this.extend(d,f));let p=this.safeList(r,"data",[]);return this.parseOrders(p,a,t,i)}async fetchMyTrades(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(o)return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,n);let d={};void 0!==e&&(d.instId=(a=this.market(e)).id);let[h,c]=this.handleUntilOption("end",d,n);void 0!==i&&(h.limit=i);let[l,u]=this.handleMarketTypeAndParams("fetchMyTrades",a,c,"swap");"spot"===l?(h.instType="SPOT",r=await this.privateGetSpotTradeFillsHistory(this.extend(h,u))):r=await this.privateGetTradeFillsHistory(this.extend(h,u));let f=this.safeList(r,"data",[]);return this.parseTrades(f,a,t,i)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchDeposits","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchDeposits",e,t,i,o);let n={};void 0!==e&&(n.currency=(r=this.currency(e)).id),void 0!==t&&(n.before=Math.max(t-1,0)),void 0!==i&&(n.limit=i);let[d,h]=this.handleUntilOption("after",n,o),c=await this.privateGetAssetDepositHistory(this.extend(d,h)),l=this.safeList(c,"data",[]);return this.parseTransactions(l,r,t,i,h)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchWithdrawals","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchWithdrawals",e,t,i,o);let n={};void 0!==e&&(n.currency=(r=this.currency(e)).id),void 0!==t&&(n.before=Math.max(t-1,0)),void 0!==i&&(n.limit=i);let[d,h]=this.handleUntilOption("after",n,o),c=await this.privateGetAssetWithdrawalHistory(this.extend(d,h)),l=this.safeList(c,"data",[]);return this.parseTransactions(l,r,t,i,h)}networkCodeToChainId(e,t){let i=this.safeDict(this.options,"networkCodeAliases",{}),s=this.safeString(i,e,e);if(void 0!==t){let e=this.safeDict(t,"networks",{}),i=this.safeDict(e,s),r=this.safeString(i,"id");if(void 0!==r)return r}let r=this.safeDict(this.options,"networks",{}),a=this.safeString(r,s);if(void 0!==a)return a;let o=this.safeDict(this.options,"networkPrefixes",{}),n=this.safeString(o,s);if(void 0!==n){let e=this.safeDict(this.options,"networkSuffixes",{});return n+" ("+this.safeString(e,s,s)+")"}return s}chainIdToNetworkCode(e){if(void 0!==e){if(e.indexOf("(")>-1){let t=e.split("("),i=this.safeString(t,1,"").split(")"),s=this.safeString(i,0),r=this.safeDict(this.options,"networkCodesBySuffix",{}),a=this.safeString(r,s);if(void 0!==a)return a;let o=this.safeDict(this.options,"networkPrefixes",{});if(void 0!==s&&s in o)return s;let n=this.safeString(t,0,"");return this.networkIdToCode(n.trim())}return this.networkIdToCode(e)}}async fetchCurrencies(e={}){if(!this.checkRequiredCredentials(!1)||this.isSandboxModeEnabled)return{};let t=await this.privateGetAssetCurrencies(e),i=this.safeList(t,"data",[]),s=Object.values(this.groupBy(i,"currency"));return this.parseCurrencies(s)}parseCurrency(e){let t=this.safeDict(e,0,{}),i=this.safeString(t,"currency"),s=this.safeCurrencyCode(i),r={},a=e.length;for(let t=0;t<a;t++){let i=this.safeDict(e,t),s=this.safeString(i,"chain"),a=this.chainIdToNetworkCode(s);void 0!==a&&(r[a]={id:s,network:a,active:void 0,deposit:1===this.safeInteger(i,"isDepositAvailable"),withdraw:1===this.safeInteger(i,"isWithdrawAvailable"),fee:this.safeNumber(i,"withdrawFee"),precision:this.parseNumber(this.parsePrecision(this.safeString(i,"withdrawPrecision"))),limits:{deposit:{min:this.safeNumber(i,"depositMinAmount"),max:void 0},withdraw:{min:this.safeNumber(i,"withdrawMinAmount"),max:void 0}},info:i})}return this.safeCurrencyStructure({info:e,code:s,id:i,name:void 0,active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,precision:void 0,limits:{amount:{min:void 0,max:void 0}},type:"crypto",networks:r})}async fetchDepositAddress(e,t={}){let i,s;await this.loadMarkets();let r=this.currency(e),o={currency:r.id};[i,s]=this.handleNetworkCodeAndParams(t);let n=this.safeString(s,"chain");if(void 0===n){if(void 0===i){let e=Object.keys(this.safeDict(r,"networks",{}));if(1===e.length)i=this.safeString(e,0);else{let e=this.safeDict(this.options,"defaultNetworks",{});i=this.safeString(e,r.code)}}if(void 0===i)throw new a.ArgumentsRequired(this.id+' fetchDepositAddress() requires a params["network"] or params["chain"] for '+e);o.chain=this.networkCodeToChainId(i,r)}let d=await this.privateGetAssetDepositAddress(this.extend(o,s)),h=this.safeList(d,"data",[]),c=this.safeDict(h,0);if(void 0===c)throw new a.InvalidAddress(this.id+" fetchDepositAddress() returned no address for "+e+" on "+this.safeString(o,"chain",n));return this.parseDepositAddress(c,r)}parseDepositAddress(e,t){let i=this.safeString(e,"address"),s=this.safeString(e,"currency"),r=this.safeString(e,"chain"),a=this.safeString(e,"tag");return""===a&&(a=void 0),this.checkAddress(i),{info:e,currency:this.safeCurrencyCode(s,t),network:this.chainIdToNetworkCode(r),address:i,tag:a}}async fetchDepositWithdrawFees(e,t={}){await this.loadMarkets();let i=await this.privateGetAssetCurrencies(t),s=this.safeList(i,"data",[]),r=this.groupBy(s,"currency");return this.parseDepositWithdrawFees(r,e)}parseDepositWithdrawFee(e,t){let i=this.depositWithdrawFee(e),s=e.length;for(let t=0;t<s;t++){let s=this.safeDict(e,t),r=this.chainIdToNetworkCode(this.safeString(s,"chain"));void 0!==r&&(i.networks[r]={withdraw:{fee:this.safeNumber(s,"withdrawFee"),percentage:!1},deposit:{fee:void 0,percentage:void 0}})}if(1===s){let e=Object.keys(i.networks),t=this.safeString(e,0);void 0!==t&&(i.withdraw=i.networks[t].withdraw)}return i}async fetchDeposit(e,t,i={}){let s;await this.loadMarkets();let r={depositId:e};void 0!==t&&(r.currency=(s=this.currency(t)).id);let o=await this.privateGetAssetDepositHistory(this.extend(r,i)),n=this.safeList(o,"data",[]),d=n.length;for(let t=0;t<d;t++){let i=n[t];if(this.safeString(i,"depositId")===e)return this.parseTransaction(i,s)}throw new a.ExchangeError(this.id+" fetchDeposit() could not find deposit "+e)}async fetchWithdrawal(e,t,i={}){let s,r=this.safeString(i,"clientId");if(void 0===e&&void 0===r)throw new a.ArgumentsRequired(this.id+' fetchWithdrawal() requires an id argument or a params["clientId"]');await this.loadMarkets();let o={};void 0!==e&&(o.withdrawId=e),void 0!==t&&(o.currency=(s=this.currency(t)).id);let n=await this.privateGetAssetWithdrawalHistory(this.extend(o,i)),d=this.safeList(n,"data",[]),h=d.length;for(let t=0;t<h;t++){let i=d[t];if(void 0!==e?this.safeString(i,"withdrawId")===e:this.safeString(i,"clientId")===r)return this.parseTransaction(i,s)}let c=void 0!==e?e:r;throw new a.ExchangeError(this.id+" fetchWithdrawal() could not find withdrawal "+c)}async withdraw(e,t,i,s,r={}){let o,n,d;[o,n]=this.handleWithdrawTagAndParams(s,r),await this.loadMarkets();let h=this.currency(e),c={currency:h.id,address:i,amount:this.numberToString(t)},l=this.safeString(n,"dest","onchain");if(c.dest=l,n=this.omit(n,"dest"),"onchain"===l&&(this.checkAddress(i),c.addrType=this.safeString(n,"addrType","1"),n=this.omit(n,"addrType")),void 0!==o&&(c.tag=o),[d,n]=this.handleNetworkCodeAndParams(n),void 0===this.safeString(n,"chain")){if(void 0!==d)c.chain=this.networkCodeToChainId(d,h);else if("onchain"===l)throw new a.ArgumentsRequired(this.id+' withdraw() requires a params["network"] or params["chain"] for on-chain withdrawals')}let u=await this.privatePostAssetWithdrawalApply(this.extend(c,n)),f=this.safeDict(u,"data",{});return this.parseTransaction(this.extend(c,f),h)}async fetchLedger(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchLedger","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchLedger",e,t,i,o);let n={};void 0!==i&&(n.limit=i),void 0!==e&&(n.currency=(r=this.currency(e)).id);let[d,h]=this.handleUntilOption("end",n,o),c=await this.privateGetAssetBills(this.extend(d,h)),l=this.safeList(c,"data",[]);return this.parseLedger(l,r,t,i)}parseTransaction(e,t){let i,s,r,a=this.safeString(e,"withdrawId"),o=this.safeString(e,"depositId"),n=this.safeString(e,"address"),d=this.safeString(e,"tag");void 0!==a?(i="withdrawal",s=a,r=this.parseTransactionWithdrawalStatus(this.safeString(e,"state"))):(s=o,i="deposit",r=this.parseTransactionDepositStatus(this.safeString(e,"state")));let h=this.safeString(e,"currency"),c=this.safeCurrencyCode(h),l=this.safeNumber(e,"amount"),u=this.safeString(e,"chain"),f=this.chainIdToNetworkCode(u),p=this.safeString(e,"txId"),m=this.safeInteger(e,"ts"),g=this.safeString(e,"feeCurrency"),v=this.safeCurrencyCode(g),y=this.safeNumber(e,"fee");return{info:e,id:s,currency:c,amount:l,network:f,addressFrom:void 0,addressTo:n,address:n,tagFrom:void 0,tagTo:d,tag:d,status:r,type:i,updated:void 0,txid:p,timestamp:m,datetime:this.iso8601(m),internal:void 0,comment:void 0,fee:{currency:v,cost:y}}}parseTransactionWithdrawalStatus(e){return this.safeString({0:"pending",2:"failed",3:"ok",4:"failed",6:"pending",7:"pending"},e,e)}parseTransactionDepositStatus(e){return this.safeString({0:"pending",1:"ok",2:"failed",3:"pending"},e,e)}parseLedgerEntryType(e){return this.safeString({1:"transfer",2:"trade",3:"trade",4:"rebate",5:"trade",6:"transfer",7:"trade",8:"fee",9:"trade",10:"trade",11:"trade"},e,e)}parseLedgerEntry(e,t){let i=this.safeString(e,"currency"),s=this.safeCurrencyCode(i,t),r=this.safeCurrency(i,t),a=this.safeInteger(e,"ts");return this.safeLedgerEntry({info:e,id:this.safeString(e,"transferId"),direction:void 0,account:void 0,referenceId:this.safeString(e,"clientId"),referenceAccount:void 0,type:this.parseLedgerEntryType(this.safeString(e,"type")),currency:s,amount:this.safeNumber(e,"amount"),timestamp:a,datetime:this.iso8601(a),before:void 0,after:void 0,status:"ok",fee:void 0},r)}parseIds(e){return"string"==typeof e?e.split(","):e}async cancelOrders(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),o=[],n=this.handleOption("cancelOrders","method","privatePostTradeCancelBatchOrders"),d=this.parseIds(this.safeValue(i,"clientOrderId")),h=this.parseIds(this.safeValue(i,"tpslId")),c=this.safeBoolN(i,["stop","trigger","tpsl"]);if(!0===c&&(n="privatePostTradeCancelTpsl"),void 0===d){let t=this.parseIds(e);if(void 0!==h)for(let e=0;e<h.length;e++)o.push({tpslId:h[e],instId:r.id});for(let e=0;e<t.length;e++)!0===c?o.push({tpslId:t[e],instId:r.id}):o.push({orderId:t[e],instId:r.id})}else for(let e=0;e<d.length;e++)o.push({instId:r.id,clientOrderId:d[e]});s="privatePostTradeCancelTpsl"===n?await this.privatePostTradeCancelTpsl(o):await this.privatePostTradeCancelBatchOrders(o);let l=this.safeList(s,"data",[]);return this.parseOrders(l,r,void 0,void 0,i)}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(e),o=this.safeDict(this.options,"accountsByType",{}),n=this.safeString(o,i,i),d=this.safeString(o,s,s),h={currency:a.id,amount:this.currencyToPrecision(e,t),fromAccount:n,toAccount:d},c=await this.privatePostAssetTransfer(this.extend(h,r)),l=this.safeDict(c,"data",{});return this.parseTransfer(l,a)}parseTransfer(e,t){let i=this.safeString(e,"transferId");return{info:e,id:i,timestamp:void 0,datetime:void 0,currency:void 0,amount:void 0,fromAccount:void 0,toAccount:void 0,status:void 0}}async fetchPosition(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instId:i.id},r=await this.privateGetAccountPositions(this.extend(s,t)),o=this.safeList(r,"data",[]),n=this.safeDict(o,0);if(void 0===n)throw new a.NullResponse(this.id+" fetchPosition() returned empty position");return this.parsePosition(n,i)}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.privateGetAccountPositions(t),r=this.safeList(s,"data",[]),a=this.parsePositions(r);return this.filterByArrayPositions(a,"symbol",i)}async fetchPositionsHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={};void 0!==e&&0===e.length&&(r.instId=this.market(e[0]).id),void 0!==i&&(r.limit=Math.min(i,100)),void 0!==t&&(r.begin=t);let[a,o]=this.handleUntilOption("end",r,s),n=await this.privateGetAccountPositionsHistory(this.extend(a,o)),d=this.safeList(n,"data",[]),h=this.parsePositions(d,e,o);return this.filterBySinceLimit(h,t,i)}parsePosition(e,t){let i,s,r,a=this.safeString(e,"instId"),n=this.safeMarket(a,t),d=n.symbol,h=this.safeString(e,"positions"),c=o.Y.stringAbs(h),l=this.safeString(e,"positionSide"),u="net"!==l,f=this.parseNumber(c);void 0!==h&&"net"===l&&(l=o.Y.stringGt(h,"0")?"long":o.Y.stringLt(h,"0")?"short":void 0);let p=this.safeNumber(n,"contractSize"),m=this.numberToString(p),g=this.safeString(e,"markPrice"),v=this.safeString(e,"notionalUsd");!0===n.inverse&&(v=o.Y.stringDiv(o.Y.stringMul(c,m),g));let y=this.parseNumber(v),b=this.safeString(e,"marginMode"),w=this.safeString2(e,"averagePrice","openAveragePrice"),k=this.safeString(e,"unrealizedPnl"),S=this.safeString(e,"leverage");"cross"===b?(i=this.safeString(e,"initialMargin"),r=o.Y.stringAdd(i,k)):"isolated"===b&&(s=o.Y.stringDiv("1",S),r=this.safeString(e,"margin"));let O=this.safeString(e,"maintenanceMargin"),T=this.parseNumber(O),P=o.Y.stringDiv(O,v);if(void 0===s)s=this.parseNumber(o.Y.stringDiv(i,v,4));else if(void 0===i){let e=this.numberToString(s);i=o.Y.stringMul(e,v)}let I=this.parseNumber(o.Y.stringDiv(o.Y.stringAdd(P,"0.00005"),"1",4)),A=this.safeNumber(e,"liquidationPrice"),x=this.safeString(e,"unrealizedPnlRatio"),M=this.parseNumber(o.Y.stringMul(x,"100")),_=this.safeInteger(e,"updateTime"),C=this.parseNumber(o.Y.stringDiv(O,r,4));return this.safePosition({info:e,id:void 0,symbol:d,notional:y,marginMode:b,liquidationPrice:A,entryPrice:this.parseNumber(w),exitPrice:this.safeNumber(e,"closeAveragePrice"),unrealizedPnl:this.parseNumber(k),realizedPnl:this.safeNumber(e,"realizedPnl"),percentage:M,contracts:f,contractSize:p,markPrice:this.parseNumber(g),lastPrice:void 0,side:l,hedged:u,timestamp:_,datetime:this.iso8601(_),lastUpdateTimestamp:void 0,maintenanceMargin:T,maintenanceMarginPercentage:I,collateral:this.parseNumber(r),initialMargin:this.parseNumber(i),initialMarginPercentage:this.parseNumber(s),leverage:this.parseNumber(S),marginRatio:C,stopLossPrice:void 0,takeProfitPrice:void 0})}async fetchLeverages(e,t={}){let i,s;if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ArgumentsRequired(this.id+" fetchLeverages() requires a symbols argument");if([i,s]=this.handleMarginModeAndParams("fetchLeverages",t),void 0===i&&(i=this.safeString(s,"marginMode","cross")),"cross"!==i&&"isolated"!==i)throw new a.BadRequest(this.id+" fetchLeverages() requires a marginMode parameter that must be either cross or isolated");let r=this.marketSymbols(e),o="";for(let e=0;e<r.length;e++){let t=r[e],i=this.market(t);e>0?o=o+","+i.id:o+=i.id}let n={instId:o,marginMode:i},d=await this.privateGetAccountBatchLeverageInfo(this.extend(n,s)),h=this.safeList(d,"data",[]);return this.parseLeverages(h,r,"instId")}async fetchLeverage(e,t={}){let i,s;if(void 0===this.markets&&await this.loadMarkets(),[i,s]=this.handleMarginModeAndParams("fetchLeverage",t),void 0===i&&(i=this.safeString(s,"marginMode","cross")),"cross"!==i&&"isolated"!==i)throw new a.BadRequest(this.id+" fetchLeverage() requires a marginMode parameter that must be either cross or isolated");let r=this.market(e),o={instId:r.id,marginMode:i},n=await this.privateGetAccountLeverageInfo(this.extend(o,s)),d=this.safeDict(n,"data",{});return this.parseLeverage(d,r)}parseLeverage(e,t){let i=this.safeString(e,"instId"),s=this.safeInteger(e,"leverage");return{info:e,symbol:this.safeSymbol(i,t),marginMode:this.safeStringLower(e,"marginMode"),longLeverage:s,shortLeverage:s}}async setLeverage(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");if(e<1||e>125)throw new a.BadRequest(this.id+" setLeverage() leverage should be between 1 and 125");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),[r,o]=this.handleMarginModeAndParams("setLeverage",i,"cross");if("cross"!==r&&"isolated"!==r)throw new a.BadRequest(this.id+" setLeverage() requires a marginMode parameter that must be either cross or isolated");let n={leverage:e,marginMode:r,instId:s.id};return await this.privatePostAccountSetLeverage(this.extend(n,o))}async closePosition(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=this.safeString(i,"clientOrderId"),[a,o]=this.handleMarginModeAndParams("closePosition",i,"cross"),n={instId:s.id,marginMode:a};void 0!==r&&(n.clientOrderId=r);let d=await this.privatePostTradeClosePosition(this.extend(n,o));return this.safeDict(d,"data")}async fetchClosedOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(s,"fetchClosedOrders","paginate",!1);if(o)return await this.fetchPaginatedCallDynamic("fetchClosedOrders",e,t,i,n);let d={};void 0!==e&&(d.instId=(a=this.market(e)).id),void 0!==i&&(d.limit=i),void 0!==t&&(d.begin=t);let h=this.safeBoolN(n,["stop","trigger","tpsl","TPSL"],!1),[c,l]=this.handleOptionStringAndParams(n,"fetchClosedOrders","method","privateGetTradeOrdersHistory"),u=this.omit(l,["method","stop","trigger","tpsl","TPSL"]);r=!0===h||"privateGetTradeOrdersTpslHistory"===c?await this.privateGetTradeOrdersTpslHistory(this.extend(d,u)):await this.privateGetTradeOrdersHistory(this.extend(d,u));let f=this.safeList(r,"data",[]);return this.parseOrders(f,a,t,i)}async fetchMarginMode(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=await this.privateGetAccountMarginMode(t),r=this.safeDict(s,"data",{});return this.parseMarginMode(r,i)}parseMarginMode(e,t){return{info:e,symbol:this.safeString(t,"symbol"),marginMode:this.safeString(e,"marginMode")}}async setMarginMode(e,t,i={}){let s;this.checkRequiredArgument("setMarginMode",e,"marginMode",["cross","isolated"]),void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let r=await this.privatePostAccountSetMarginMode(this.extend({marginMode:e},i)),a=this.safeDict(r,"data",{});return this.parseMarginMode(a,s)}async fetchPositionMode(e,t={}){let i=await this.privateGetAccountPositionMode(t),s=this.safeDict(i,"data",{}),r=this.safeString(s,"positionMode");return{info:s,hedged:"long_short_mode"===r}}async setPositionMode(e,t,i={}){return await this.privatePostAccountSetPositionMode(this.extend({positionMode:e?"long_short_mode":"net_mode"},i))}async fetchPositionsADLRank(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s=await this.privateGetAccountPositions(t),r=this.safeList(s,"data",[]);return this.parseADLRanks(r,i)}parseADLRank(e,t){let i=this.safeString(e,"instId"),s=this.safeIntegerOmitZero(e,"createTime");return{info:e,symbol:this.safeSymbol(i,t,void 0,"contract"),rank:this.safeInteger(e,"adl"),rating:void 0,percentage:void 0,timestamp:s,datetime:this.iso8601(s)}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"code"),l=this.safeString(n,"msg"),u=this.id+" "+o;if(void 0!==c&&"0"!==c)throw this.throwExactlyMatchedException(this.exceptions.exact,l,u),this.throwExactlyMatchedException(this.exceptions.exact,c,u),this.throwBroadlyMatchedException(this.exceptions.broad,l,u),new a.ExchangeError(u);let f=this.safeList(n,"data"),p=this.safeDict(f,0),m=this.safeString(p,"msg"),g=this.safeString(p,"code");void 0!==g&&"0"!==g&&(this.throwExactlyMatchedException(this.exceptions.exact,g,u),this.throwExactlyMatchedException(this.exceptions.exact,m,u),this.throwBroadlyMatchedException(this.exceptions.broad,m,u))}sign(e,t="public",i="GET",r={},o,n){let d="/api/"+this.version+"/"+this.implodeParams(e,r),h=this.omit(r,this.extractParams(e)),c=this.safeString(this.urls.api,"rest");if(void 0===c)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let l=c+d;if("public"===t)this.isEmpty(h)||(l+="?"+this.urlencode(h));else if("private"===t){let e;this.checkRequiredCredentials();let t=this.milliseconds().toString(),r={"ACCESS-KEY":this.apiKey,"ACCESS-PASSPHRASE":this.password,"ACCESS-TIMESTAMP":t,"ACCESS-NONCE":t},a="";if("GET"===i){if(!this.isEmpty(h)){let e="?"+this.urlencode(h);l+=e,d+=e}}else this.isEmpty(h)||(a=e=this.json(h)),r["Content-Type"]="application/json";let o=d+i+t+t+a,c=this.stringToBase64(this.hmac(this.encode(o),this.encode(this.secret),s.sc));return r["ACCESS-SIGN"]=c,{url:l,method:i,body:void 0===e?n:e,headers:r}}return{url:l,method:i,body:n,headers:o}}}i.d(t,{A:()=>n})},6514(e,t,i){"use strict";var s=i(4721),r=i(8858),a=i(7567),o=i(1453),n=i(7749);class d extends a.A{describe(){return this.deepExtend(super.describe(),{id:"btcbox",name:"BtcBox",countries:["JP"],rateLimit:1e3,version:"v1",pro:!1,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchTransfer:!1,fetchTransfers:!1,fetchVolatilityHistory:!1,fetchWithdrawal:!1,fetchWithdrawals:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,withdraw:!1,ws:!1},urls:{logo:"https://github.com/user-attachments/assets/1e2cb499-8d0f-4f8f-9464-3c015cfbc76b",api:{rest:"https://www.btcbox.co.jp/api"},www:"https://www.btcbox.co.jp/",doc:"https://blog.btcbox.jp/en/archives/8762",fees:"https://support.btcbox.co.jp/hc/en-us/articles/360001235694-Fees-introduction"},api:{public:{get:{depth:{cost:1},orders:{cost:1},ticker:{cost:1},tickers:{cost:1}}},private:{post:{balance:{cost:1},order_history:{cost:1},trade_add:{cost:1},trade_cancel:{cost:1},trade_list:{cost:1},trade_view:{cost:1},wallet:{cost:1}}},webApi:{get:{"ajax/coin/coinInfo":{cost:1}}}},options:{fetchMarkets:{webApiEnable:!0,webApiRetries:3}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!1,GTD:!1},hedged:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,trailing:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:void 0,fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:100,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:{marginMode:!1,limit:100,daysBack:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:void 0,fetchOHLCV:void 0},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},precisionMode:4,exceptions:{104:o.AuthenticationError,105:o.PermissionDenied,106:o.InvalidNonce,107:o.InvalidOrder,200:o.InsufficientFunds,201:o.InvalidOrder,202:o.InvalidOrder,203:o.OrderNotFound,401:o.OrderNotFound,402:o.DDoSProtection}})}async fetchMarkets(e={}){let t=this.publicGetTickers(),i=this.fetchWebEndpoint("fetchMarkets","webApiGetAjaxCoinCoinInfo",!0),[s,r]=await Promise.all([t,i]),a=this.safeDict(r,"data",{}),o=Object.keys(s),n=[];for(let e=0;e<o.length;e++){let t=o[e],i=t.split("_"),r=this.safeString(i,0,""),d=this.safeString(i,1,""),h=d.toLowerCase(),c=r.toLowerCase(),l=this.safeDict(s,t,{}),u=r+"/"+d,f="BTC"===c?this.parseNumber("0.0005"):this.parseNumber("0.0010"),p=this.safeDict(a,c,{}),m=this.safeDict(p,"trade",{});n.push(this.safeMarketStructure({id:c,uppercaseId:void 0,symbol:u,base:r,baseId:c,quote:d,quoteId:h,settle:void 0,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,taker:f,maker:f,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,limits:{amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0},leverage:{min:void 0,max:void 0}},precision:{price:this.parseNumber(this.parsePrecision(this.safeString(m,"pricedecimal"))),amount:void 0},active:"1"===this.safeString(m,"enable"),created:void 0,info:l}))}return n}parseMarket(e){let t=this.safeString(e,"base"),i=this.safeCurrencyCode(t),s=this.safeString(e,"quote"),r=this.safeCurrencyCode(s);if(void 0!==i&&void 0!==r)return this.safeMarketStructure({id:this.safeString(e,"symbol"),uppercaseId:void 0,symbol:i+"/"+r,base:i,baseId:t,quote:r,quoteId:s,settle:void 0,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,limits:{amount:{min:this.safeNumber(e,"minLimitBaseAmount"),max:this.safeNumber(e,"maxLimitBaseAmount")},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0},leverage:{min:void 0,max:void 0}},precision:{price:this.parseNumber(this.parsePrecision(this.safeString(e,"quotePrecision"))),amount:this.parseNumber(this.parsePrecision(this.safeString(e,"basePrecision")))},active:void 0,created:void 0,info:e})}parseBalance(e){let t={info:e},i=Object.keys(this.currencies);for(let s=0;s<i.length;s++){let r=i[s],a=this.currency(r).id,o=a+"_balance";if(o in e){let i=this.account(),s=a+"_lock";i.free=this.safeString(e,o),i.used=this.safeString(e,s),t[r]=i}}return this.safeBalance(t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostBalance(e);return this.parseBalance(t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={};this.symbols.length>1&&(r.coin=s.baseId);let a=await this.publicGetDepth(this.extend(r,i));return this.parseOrderBook(a,s.symbol)}parseTicker(e,t){let i=this.safeSymbol(void 0,t),s=this.safeString(e,"last");return this.safeTicker({symbol:i,timestamp:void 0,datetime:void 0,high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"buy"),bidVolume:void 0,ask:this.safeString(e,"sell"),askVolume:void 0,vwap:void 0,open:void 0,close:s,last:s,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"vol"),quoteVolume:this.safeString(e,"volume"),info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={};this.symbols.length>1&&(s.coin=i.baseId);let r=await this.publicGetTicker(this.extend(s,t));return this.parseTicker(r,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetTickers(t);return this.parseTickers(i,e)}parseTrade(e,t){let i=this.safeTimestamp(e,"date"),s=this.safeMarket(void 0,t),r=this.safeString(e,"tid"),a=this.safeString(e,"price"),o=this.safeString(e,"amount"),n=this.safeString(e,"type");return this.safeTrade({info:e,id:r,order:void 0,timestamp:i,datetime:this.iso8601(i),symbol:s.symbol,type:void 0,side:n,takerOrMaker:void 0,price:a,amount:o,cost:void 0,fee:void 0},s)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={};this.symbols.length>1&&(a.coin=r.baseId);let o=await this.publicGetOrders(this.extend(a,s));return this.parseTrades(o,r,t,i)}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={amount:s,price:r,type:i,coin:o.baseId},d=await this.privatePostTradeAdd(this.extend(n,a));return this.parseOrder(d,o)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(void 0===t?"BTC/JPY":t),r={id:e,coin:s.baseId},a=await this.privatePostTradeCancel(this.extend(r,i));return this.parseOrder(a,s)}parseOrderStatus(e){if(void 0!==e)return this.safeString({part:"open",all:"closed",cancelled:"canceled",closed:"closed",no:"closed"},e,e)}parseOrder(e,t){let i,s=this.safeString(e,"id"),r=this.safeString(e,"datetime");void 0!==r&&(i=this.parse8601(r+"+09:00"));let a=this.safeString(e,"amount_original"),o=this.safeString(e,"amount_outstanding"),d=this.safeString(e,"price"),h=this.parseOrderStatus(this.safeString(e,"status"));void 0===h&&n.Y.stringEquals(o,"0")&&(h="closed");let c=this.safeMarket(void 0,t),l=this.safeString(e,"type");return this.safeOrder({id:s,clientOrderId:void 0,timestamp:i,datetime:this.iso8601(i),lastTradeTimestamp:void 0,amount:a,remaining:o,filled:void 0,side:l,type:void 0,timeInForce:void 0,postOnly:void 0,status:h,symbol:c.symbol,price:d,triggerPrice:void 0,cost:void 0,trades:void 0,fee:void 0,info:e,average:void 0},c)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(void 0===t?"BTC/JPY":t),r=this.extend({id:e,coin:s.baseId},i),a=await this.privatePostTradeView(this.extend(r,i));return this.parseOrder(a,s)}async fetchOrdersByType(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(void 0===t?"BTC/JPY":t),o={type:e,coin:a.baseId},n=await this.privatePostTradeList(this.extend(o,r)),d=this.parseOrders(n,a,i,s);if("open"===e)for(let e=0;e<d.length;e++)d[e].status="open";return d}async fetchOrders(e,t,i,s={}){return await this.fetchOrdersByType("all",e,t,i,s)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrdersByType("open",e,t,i,s)}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",a={},n,d){let h=this.safeString(this.urls.api,"rest");if(void 0===h)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let c=h+"/"+this.version+"/"+e;if("public"===t)Object.keys(a).length>0&&(c+="?"+this.urlencode(a));else if("webApi"===t)c=this.urls.www+"/"+e;else{this.checkRequiredCredentials();let e=this.nonce().toString(),t=this.extend({key:this.apiKey,nonce:e},a),o=this.urlencode(t),n=this.hash(this.encode(this.secret),r.Fx);return t.signature=this.hmac(this.encode(o),this.encode(n),s.sc),{url:c,method:i,body:this.urlencode(t),headers:{"Content-Type":"application/x-www-form-urlencoded"}}}return{url:c,method:i,body:d,headers:n}}handleErrors(e,t,i,s,r,a,n,d,h){if(void 0===n||e>=400)return;let c=this.safeBool(n,"result");if(void 0===c||!0===c)return;let l=this.safeString(n,"code"),u=this.id+" "+a;throw this.throwExactlyMatchedException(this.exceptions,l,u),new o.ExchangeError(u)}async request(e,t="public",i="GET",s={},r,a,n={}){let d=await this.fetch2(e,t,i,s,r,a,n);if("string"==typeof d){if(d=this.strip(d),!this.isJsonEncodedObject(d))throw new o.ExchangeError(this.id+" "+d);d=JSON.parse(d)}return d}}i.d(t,{A:()=>d})},6222(e,t,i){"use strict";var s=i(4721),r=i(227),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"btcmarkets",name:"BTC Markets",countries:["AU"],rateLimit:1e3,version:"v3",has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!1,closePosition:!1,createDepositAddress:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,createTriggerOrder:!0,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrders:"emulated",fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTime:!0,fetchTrades:!0,fetchTransactions:"emulated",fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,withdraw:!0},urls:{logo:"https://github.com/user-attachments/assets/8c8d6907-3873-4cc4-ad20-e22fba28247e",api:{public:"https://api.btcmarkets.net",private:"https://api.btcmarkets.net"},www:"https://btcmarkets.net",doc:["https://api.btcmarkets.net/doc/v3","https://github.com/BTCMarkets/API"]},api:{public:{get:{markets:{cost:1},"markets/{marketId}/ticker":{cost:1},"markets/{marketId}/trades":{cost:1},"markets/{marketId}/orderbook":{cost:1},"markets/{marketId}/candles":{cost:1},"markets/tickers":{cost:1},"markets/orderbooks":{cost:1},time:{cost:1}}},private:{get:{orders:{cost:1},"orders/{id}":{cost:1},"batchorders/{ids}":{cost:1},trades:{cost:1},"trades/{id}":{cost:1},withdrawals:{cost:1},"withdrawals/{id}":{cost:1},deposits:{cost:1},"deposits/{id}":{cost:1},transfers:{cost:1},"transfers/{id}":{cost:1},addresses:{cost:1},"withdrawal-fees":{cost:1},assets:{cost:1},"accounts/me/trading-fees":{cost:1},"accounts/me/withdrawal-limits":{cost:1},"accounts/me/balances":{cost:1},"accounts/me/transactions":{cost:1},"reports/{id}":{cost:1}},post:{orders:{cost:1},batchorders:{cost:1},withdrawals:{cost:1},reports:{cost:1}},delete:{orders:{cost:1},"orders/{id}":{cost:1},"batchorders/{ids}":{cost:1}},put:{"orders/{id}":{cost:1}}}},timeframes:{"1m":"1m","1h":"1h","1d":"1d"},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!0,trailing:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:100,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:100,daysBack:1e5,daysBackCanceled:1,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:1e3}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},precisionMode:4,exceptions:{exact:{InsufficientFund:a.InsufficientFunds,InvalidPrice:a.InvalidOrder,InvalidAmount:a.InvalidOrder,MissingArgument:a.BadRequest,OrderAlreadyCancelled:a.InvalidOrder,OrderNotFound:a.OrderNotFound,OrderStatusIsFinal:a.InvalidOrder,InvalidPaginationParameter:a.BadRequest},broad:{}},fees:{percentage:!0,tierBased:!0,maker:this.parseNumber("-0.0005"),taker:this.parseNumber("0.0020")},options:{fees:{AUD:{maker:this.parseNumber("0.0085"),taker:this.parseNumber("0.0085")}}}})}async fetchTransactionsWithMethod(e,t,i,s,r={}){let a,o;void 0===this.markets&&await this.loadMarkets();let n={};return void 0!==s&&(n.limit=s),void 0!==i&&(n.after=i),void 0!==t&&(a=this.currency(t)),o="privateGetTransfers"===e?await this.privateGetTransfers(this.extend(n,r)):"privateGetDeposits"===e?await this.privateGetDeposits(this.extend(n,r)):await this.privateGetWithdrawals(this.extend(n,r)),this.parseTransactions(o,a,i,s)}async fetchDepositsWithdrawals(e,t,i,s={}){return await this.fetchTransactionsWithMethod("privateGetTransfers",e,t,i,s)}async fetchDeposits(e,t,i,s={}){return await this.fetchTransactionsWithMethod("privateGetDeposits",e,t,i,s)}async fetchWithdrawals(e,t,i,s={}){return await this.fetchTransactionsWithMethod("privateGetWithdrawals",e,t,i,s)}parseTransactionStatus(e){return this.safeString({Accepted:"pending","Pending Authorization":"pending",Complete:"ok",Cancelled:"cancelled",Failed:"failed"},e,e)}parseTransactionType(e){return this.safeString({Withdraw:"withdrawal",Deposit:"deposit"},e,e)}parseTransaction(e,t){let i,s=this.parse8601(this.safeString(e,"creationTime")),r=this.parse8601(this.safeString(e,"lastUpdate")),a=this.parseTransactionType(this.safeStringLower(e,"type"));"withdraw"===a&&(a="withdrawal");let n=this.safeDict(e,"paymentDetail",{}),d=this.safeString(n,"txId"),h=this.safeString(n,"address");if(void 0!==h){let e=h.split("?dt=");e.length>1&&(h=e[0],i=e[1])}let c=h,l=i,u=this.safeString(e,"fee"),f=this.parseTransactionStatus(this.safeString(e,"status")),p=this.safeString(e,"assetName"),m=this.safeCurrencyCode(p),g=this.safeString(e,"amount");return void 0!==u&&""!==u&&(g=o.Y.stringSub(g,u)),{id:this.safeString(e,"id"),txid:d,timestamp:s,datetime:this.iso8601(s),network:void 0,address:h,addressTo:c,addressFrom:void 0,tag:i,tagTo:l,tagFrom:void 0,type:a,amount:this.parseNumber(g),currency:m,status:f,updated:r,comment:this.safeString(e,"description"),internal:void 0,fee:{currency:m,cost:this.parseNumber(u),rate:void 0},info:e}}async fetchMarkets(e={}){let t=await this.publicGetMarkets(e);return this.parseMarkets(t)}parseMarket(e){let t,i=this.safeString(e,"baseAssetName"),s=this.safeString(e,"quoteAssetName"),r=this.safeString(e,"marketId"),a=this.safeCurrencyCode(i),o=this.safeCurrencyCode(s);if(void 0===a||void 0===o)return;let n=a+"/"+o,d=this.safeDict(this.safeDict(this.options,"fees",{}),o,this.fees),h=this.parseNumber(this.parsePrecision(this.safeString(e,"priceDecimals"))),c=this.safeNumber(e,"minOrderAmount"),l=this.safeNumber(e,"maxOrderAmount"),u=this.safeString(e,"status");return"AUD"===o&&(t=h),this.safeMarketStructure({id:r,symbol:n,base:a,quote:o,settle:void 0,baseId:i,quoteId:s,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:"Online"===u,contract:!1,linear:void 0,inverse:void 0,taker:d.taker,maker:d.maker,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(e,"amountDecimals"))),price:h},limits:{leverage:{min:void 0,max:void 0},amount:{min:c,max:l},price:{min:t,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:e})}async fetchTime(e={}){let t=await this.publicGetTime(e);return this.parse8601(this.safeString(t,"timestamp"))}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"assetName"),a=this.safeCurrencyCode(r),o=this.account();o.used=this.safeString(s,"locked"),o.total=this.safeString(s,"balance"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetAccountsMeBalances(e);return this.parseBalance(t)}parseOHLCV(e,t){return[this.parse8601(this.safeString(e,0)),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={marketId:a.id,timeWindow:this.safeString(this.timeframes,t,t)};void 0!==i&&(o.from=this.iso8601(i)),void 0!==s&&(o.limit=Math.min(s,200));let n=await this.publicGetMarketsMarketIdCandles(this.extend(o,r));return this.parseOHLCVs(this.toArray(n),a,t,i,s)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={marketId:this.market(e).id},r=await this.publicGetMarketsMarketIdOrderbook(this.extend(s,i)),a=this.safeIntegerProduct(r,"snapshotId",.001),o=this.parseOrderBook(r,e,a);return o.nonce=this.safeInteger(r,"snapshotId"),o}parseTicker(e,t){let i=this.safeString(e,"marketId"),s=this.safeMarket(i,t,"-"),r=s.symbol,a=this.parse8601(this.safeString(e,"timestamp")),o=this.safeString(e,"lastPrice"),n=this.safeString(e,"volume24h"),d=this.safeString(e,"volumeQte24h"),h=this.safeString(e,"price24h"),c=this.safeString(e,"pricePct24h");return this.safeTicker({symbol:r,timestamp:a,datetime:this.iso8601(a),high:this.safeString(e,"high24h"),low:this.safeString(e,"low"),bid:this.safeString(e,"bestBid"),bidVolume:void 0,ask:this.safeString(e,"bestAsk"),askVolume:void 0,vwap:void 0,open:void 0,close:o,last:o,previousClose:void 0,change:h,percentage:c,average:void 0,baseVolume:n,quoteVolume:d,info:e},s)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={marketId:i.id},r=await this.publicGetMarketsMarketIdTicker(this.extend(s,t));return this.parseTicker(r,i)}async fetchTicker2(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={id:i.id},r=await this.publicGetMarketsMarketIdTicker(this.extend(s,t));return this.parseTicker(r,i)}parseTrade(e,t){let i,s,r=this.parse8601(this.safeString(e,"timestamp")),a=this.safeString(e,"marketId"),o=this.safeMarket(a,t,"-");i="AUD"===o.quote?o.quote:o.base;let n=this.safeString(e,"side");"Bid"===n?n="buy":"Ask"===n&&(n="sell");let d=this.safeString(e,"id"),h=this.safeString(e,"price"),c=this.safeString(e,"amount"),l=this.safeString(e,"orderId"),u=this.safeString(e,"fee");void 0!==u&&(s={cost:u,currency:i});let f=this.safeStringLower(e,"liquidityType");return this.safeTrade({info:e,id:d,timestamp:r,datetime:this.iso8601(r),order:l,symbol:o.symbol,type:void 0,side:n,price:h,amount:c,cost:void 0,takerOrMaker:f,fee:s},o)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={marketId:r.id},o=await this.publicGetMarketsMarketIdTrades(this.extend(a,s));return this.parseTrades(o,r,t,i)}async createOrder(e,t,i,s,r,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d={marketId:n.id,amount:this.amountToPrecision(e,s),side:"buy"===i?"Bid":"Ask"},h=t.toLowerCase(),c=this.safeDict(this.options,"orderTypes",{limit:"Limit",market:"Market",stop:"Stop","stop limit":"Stop Limit","take profit":"Take Profit"});d.type=this.safeString(c,h,t);let l=!1,u=!1;if("limit"===h?l=!0:"stop limit"===h?(u=!0,l=!0):"take profit"===h?u=!0:"stop"===h&&(u=!0),l)if(void 0===r)throw new a.ArgumentsRequired(this.id+" createOrder() requires a price argument for a "+t+"order");else d.price=this.priceToPrecision(e,r);if(u){let i=this.safeNumber(o,"triggerPrice");if(void 0===i)throw new a.ArgumentsRequired(this.id+" createOrder() requires a triggerPrice parameter for a "+t+"order");d.triggerPrice=this.priceToPrecision(e,i)}let f=this.safeString(o,"clientOrderId");void 0!==f&&(d.clientOrderId=f);let p=o;u&&(p=this.omit(o,"triggerPrice"));let m=this.omit(p,"clientOrderId"),g=await this.privatePostOrders(this.extend(d,m));return this.parseOrder(g,n)}async cancelOrders(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=[];for(let t=0;t<e.length;t++)s.push(parseInt(e[t]));let r=await this.privateDeleteBatchordersIds(this.extend({ids:s},i)),a=this.safeList(r,"cancelOrders",[]),o=this.safeList(r,"unprocessedRequests",[]),n=this.arrayConcat(a,o);return this.parseOrders(n)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateDeleteOrdersId(this.extend({id:e},i));return this.parseOrder(s)}calculateFee(e,t,i,s,r,a="taker",n={}){let d,h,c=this.market(e);if("AUD"===c.quote){d=this.safeString(c,"quote");let t=this.numberToString(s),i=this.numberToString(r),a=o.Y.stringMul(t,i);h=this.costToPrecision(e,a)}else d=this.safeString(c,"base"),h=this.amountToPrecision(e,s);let l=this.safeValue(c,a),u=o.Y.stringMul(this.numberToString(l),h),f=this.feeToPrecision(e,u);return void 0===f&&(f="0"),{type:a,currency:d,rate:l,cost:parseFloat(f)}}parseOrderStatus(e){return this.safeString({Accepted:"open",Placed:"open","Partially Matched":"open","Fully Matched":"closed",Cancelled:"canceled","Partially Cancelled":"canceled",Failed:"rejected"},e,e)}parseOrder(e,t){let i=this.parse8601(this.safeString(e,"creationTime")),s=this.safeString(e,"marketId"),r=this.safeMarket(s,t,"-"),a=this.safeString(e,"side");"Bid"===a?a="buy":"Ask"===a&&(a="sell");let o=this.safeStringLower(e,"type"),n=this.safeString(e,"price"),d=this.safeString(e,"amount"),h=this.safeString(e,"openAmount"),c=this.parseOrderStatus(this.safeString(e,"status")),l=this.safeString(e,"orderId"),u=this.safeString(e,"clientOrderId"),f=this.safeString(e,"timeInForce"),p=this.safeBool(e,"postOnly");return this.safeOrder({info:e,id:l,clientOrderId:u,timestamp:i,datetime:this.iso8601(i),lastTradeTimestamp:void 0,symbol:r.symbol,type:o,timeInForce:f,postOnly:p,side:a,price:n,triggerPrice:this.safeNumber(e,"triggerPrice"),cost:void 0,amount:d,filled:void 0,remaining:h,average:void 0,status:c,trades:void 0,fee:void 0},r)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateGetOrdersId(this.extend({id:e},i));return this.parseOrder(s)}async fetchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={status:"all"};void 0!==e&&(a.marketId=(r=this.market(e)).id),void 0!==t&&(a.after=t),void 0!==i&&(a.limit=i);let o=await this.privateGetOrders(this.extend(a,s));return this.parseOrders(o,r,t,i)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({status:"open"},s))}async fetchClosedOrders(e,t,i,s={}){let r=await this.fetchOrders(e,t,i,s);return this.filterBy(r,"status","closed")}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.marketId=(r=this.market(e)).id),void 0!==t&&(a.after=t),void 0!==i&&(a.limit=i);let o=await this.privateGetTrades(this.extend(a,s));return this.parseTrades(o,r,t,i)}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d={assetName:n.id,amount:this.currencyToPrecision(e,t)};"AUD"!==e&&(this.checkAddress(i),d.toAddress=i),void 0!==a&&(d.toAddress=i+"?dt="+a);let h=await this.privatePostWithdrawals(this.extend(d,o));return this.parseTransaction(h,n)}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},o,n){let d,h,c="/"+this.version+"/"+this.implodeParams(e,r),l=this.keysort(this.omit(r,this.extractParams(e)));if("private"===t){this.checkRequiredCredentials();let e=this.nonce().toString(),t=this.base64ToBinary(this.secret),r=i+c+e;"GET"===i||"DELETE"===i?Object.keys(l).length>0&&(c+="?"+this.urlencode(l)):r+=h=this.json(l);let a=this.hmac(this.encode(r),t,s.Zf,"base64");d={Accept:"application/json","Accept-Charset":"UTF-8","Content-Type":"application/json","BM-AUTH-APIKEY":this.apiKey,"BM-AUTH-TIMESTAMP":e,"BM-AUTH-SIGNATURE":a}}else"public"===t&&Object.keys(l).length>0&&(c+="?"+this.urlencode(l));let u=this.safeString(this.urls.api,t);if(void 0===u)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");return{url:u+c,method:i,body:void 0!==h?h:n,headers:void 0!==d?d:o}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"code"),l=this.safeString(n,"message");if(void 0!==c){let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,l,e),this.throwExactlyMatchedException(this.exceptions.exact,c,e),this.throwBroadlyMatchedException(this.exceptions.broad,l,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>n})},1679(e,t,i){"use strict";var s=i(4721),r=i(9980),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"btcturk",name:"BTCTurk",countries:["TR"],rateLimit:100,pro:!1,has:{CORS:!0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createDepositAddress:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchVolatilityHistory:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,ws:!1},timeframes:{"1m":1,"15m":15,"30m":30,"1h":60,"4h":240,"1d":"1 d","1w":"1 w","1y":"1 y"},urls:{logo:"https://github.com/user-attachments/assets/710711ff-1278-4e7a-9b03-b5503dd85b59",api:{public:"https://api.btcturk.com/api/v2",private:"https://api.btcturk.com/api/v1",graph:"https://graph-api.btcturk.com/v1"},www:"https://www.btcturk.com",doc:"https://github.com/BTCTrader/broker-api-docs"},api:{public:{get:{orderbook:{cost:1},ticker:{cost:.1},"ticker/currency":{cost:.1},trades:{cost:1},ohlc:{cost:1},"server/exchangeinfo":{cost:1}}},private:{get:{"users/balances":{cost:1},openOrders:{cost:1},allOrders:{cost:1},"order/{orderId}":{cost:1},"users/transactions/trade":{cost:1},"users/transactions/crypto":{cost:1},"users/transactions/fiat":{cost:1},"crypto-deposit-declarations":{cost:1}},post:{"users/transactions/crypto":{cost:1},"users/transactions/fiat":{cost:1},order:{cost:1},cancelOrder:{cost:1},"crypto-deposit-declarations/confirm":{cost:1}},delete:{order:{cost:1}}},graph:{get:{ohlcs:{cost:1},"klines/history":{cost:1}}}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!1,GTD:!1},hedged:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,trailing:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:30,symbolRequired:!0},fetchOrder:void 0,fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:{marginMode:!1,limit:1e3,daysBack:1e5,untilDays:30,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:void 0,fetchOHLCV:{limit:void 0}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},fees:{trading:{maker:this.parseNumber("0.0005"),taker:this.parseNumber("0.0009")}},exceptions:{exact:{FAILED_ORDER_WITH_OPEN_ORDERS:a.InsufficientFunds,FAILED_LIMIT_ORDER:a.InvalidOrder,FAILED_MARKET_ORDER:a.InvalidOrder}},precisionMode:4})}async fetchMarkets(e={}){let t=await this.publicGetServerExchangeinfo(e),i=this.safeDict(t,"data",{}),s=this.safeList(i,"symbols",[]);return this.parseMarkets(s)}parseMarket(e){let t,i,s,r,a,o=this.safeString(e,"name"),n=this.safeString(e,"numerator"),d=this.safeString(e,"denominator"),h=this.safeCurrencyCode(n),c=this.safeCurrencyCode(d);if(void 0===h||void 0===c)return;let l=this.safeList(e,"filters",[]);for(let e=0;e<l.length;e++){let o=this.safeDict(l,e);"PRICE_FILTER"===this.safeString(o,"filterType")&&(t=this.safeNumber(o,"minPrice"),i=this.safeNumber(o,"maxPrice"),s=this.safeNumber(o,"minAmount"),r=this.safeNumber(o,"maxAmount"),a=this.safeNumber(o,"minExchangeValue"))}let u=this.safeString(e,"status");return this.safeMarketStructure({id:o,symbol:h+"/"+c,base:h,quote:c,settle:void 0,baseId:n,quoteId:d,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:"TRADING"===u,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(e,"numeratorScale"))),price:this.parseNumber(this.parsePrecision(this.safeString(e,"denominatorScale")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:s,max:r},price:{min:t,max:i},cost:{min:a,max:void 0}},created:void 0,info:e})}parseBalance(e){let t=this.safeList(e,"data",[]),i={info:e,timestamp:void 0,datetime:void 0};for(let e=0;e<t.length;e++){let s=this.safeDict(t,e),r=this.safeString(s,"asset"),a=this.safeCurrencyCode(r),o=this.account();o.total=this.safeString(s,"balance"),o.free=this.safeString(s,"free"),o.used=this.safeString(s,"locked"),void 0!==a&&(i[a]=o)}return this.safeBalance(i)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetUsersBalances(e);return this.parseBalance(t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={pairSymbol:s.id},a=await this.publicGetOrderbook(this.extend(r,i)),o=this.safeDict(a,"data",{}),n=this.safeInteger(o,"timestamp");return this.parseOrderBook(o,s.symbol,n,"bids","asks",0,1)}parseTicker(e,t){let i=this.safeString(e,"pair"),s=this.safeMarket(i,t),r=s.symbol,a=this.safeInteger(e,"timestamp"),n=this.safeString(e,"last"),d=this.safeString(e,"open"),h=this.safeString(e,"daily"),c=this.safeString(e,"dailyPercent"),l=this.safeString(e,"average");return void 0===d||void 0===n||o.Y.stringEq(d,"0")||(h=void 0,c=void 0,l=void 0),this.safeTicker({symbol:r,timestamp:a,datetime:this.iso8601(a),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"bid"),bidVolume:void 0,ask:this.safeString(e,"ask"),askVolume:void 0,vwap:void 0,open:d,close:n,last:n,previousClose:void 0,change:h,percentage:c,average:l,baseVolume:this.safeString(e,"volume"),quoteVolume:void 0,info:e},s)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetTicker(t),s=this.safeList(i,"data");return this.parseTickers(s,e)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.fetchTickers([e],t);return this.safeDict(i,e)}parseTrade(e,t){let i,s=this.safeInteger2(e,"date","timestamp"),r=this.safeString2(e,"tid","id"),a=this.safeString(e,"orderId"),n=this.safeString(e,"price"),d=o.Y.stringAbs(this.safeString(e,"amount")),h=this.safeString(e,"pair"),c=this.safeSymbol(h,t),l=this.safeString2(e,"side","orderType"),u=this.safeString(e,"fee");if(void 0!==u){let t=this.safeString(e,"denominatorSymbol");i={cost:o.Y.stringAbs(u),currency:this.safeCurrencyCode(t)}}return this.safeTrade({info:e,id:r,order:a,timestamp:s,datetime:this.iso8601(s),symbol:c,type:void 0,side:l,takerOrMaker:void 0,price:n,amount:d,cost:void 0,fee:i},t)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={pairSymbol:r.id};void 0!==i&&(a.last=i);let o=await this.publicGetTrades(this.extend(a,s)),n=this.safeList(o,"data"),d=[];return void 0!==n&&(d=n),this.parseTrades(d,r,t,i)}parseOHLCV(e,t){return[this.safeTimestamp(e,"timestamp"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchOHLCV(e,t="1h",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={symbol:o.id,resolution:this.safeString(this.timeframes,t,t)},d=this.safeInteger(r,"until",this.milliseconds());n.to=this.parseToInt(d/1e3),void 0!==i&&(n.from=this.parseToInt(i/1e3));let h=s;void 0===i&&void 0===s&&(h=100);let c=void 0!==h?Math.min(h,11e3):void 0;if(void 0!==c){if("1y"===t)throw new a.BadRequest(this.id+' fetchOHLCV () does not accept a limit parameter when timeframe == "1y"');let e=this.parseTimeframe(t)*(c-1);if(void 0!==i){let t=this.parseToInt(i/1e3)+e;n.to=Math.min(n.to,t)}else n.from=this.parseToInt(0)-e}let l=await this.graphGetKlinesHistory(this.extend(n,r));return this.parseOHLCVs(l,o,t,i,c)}parseOHLCVs(e,t,i="1m",s,r,a=!1){let o=[],n=this.safeList(e,"t",[]),d=this.safeList(e,"h",[]),h=this.safeList(e,"o",[]),c=this.safeList(e,"l",[]),l=this.safeList(e,"c",[]),u=this.safeList(e,"v",[]);for(let e=0;e<n.length;e++){let i={timestamp:this.safeInteger(n,e),high:this.safeNumber(d,e),open:this.safeNumber(h,e),low:this.safeNumber(c,e),close:this.safeNumber(l,e),volume:this.safeNumber(u,e)};o.push(this.parseOHLCV(i,t))}let f=this.sortBy(o,0);return this.filterBySinceLimit(f,s,r,0,a)}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={orderType:i,orderMethod:t,pairSymbol:o.id,quantity:this.amountToPrecision(e,s)};"market"!==t&&(n.price=this.priceToPrecision(e,r)),"clientOrderId"in a?n.newClientOrderId=a.clientOrderId:"newClientOrderId"in a||(n.newClientOrderId=this.uuid());let d=await this.privatePostOrder(this.extend(n,a)),h=this.safeDict(d,"data",{});return this.parseOrder(h,o)}async cancelOrder(e,t,i={}){let s=await this.privateDeleteOrder(this.extend({id:e},i));return this.safeOrder({info:s})}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.pairSymbol=(r=this.market(e)).id);let o=await this.privateGetOpenOrders(this.extend(a,s)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"bids",[]),h=this.safeList(n,"asks",[]);return this.parseOrders(this.arrayConcat(d,h),r,t,i)}async fetchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={pairSymbol:r.id};void 0!==i&&(a.last=i),void 0!==t&&(a.startTime=Math.floor(t/1e3));let o=await this.privateGetAllOrders(this.extend(a,s)),n=this.safeList(o,"data");return this.parseOrders(n,r,t,i)}parseOrderStatus(e){return this.safeString({Untouched:"open",Partial:"open",Canceled:"canceled",Closed:"closed"},e,e)}parseOrder(e,t){let i=this.safeString(e,"id"),s=this.safeString(e,"price"),r=this.safeString2(e,"amount","quantity"),a=o.Y.stringAbs(r),n=this.safeString(e,"leftAmount"),d=this.safeString(e,"pairSymbol"),h=this.safeSymbol(d,t),c=this.safeString(e,"type"),l=this.safeString(e,"method"),u=this.safeString(e,"orderClientId"),f=this.safeInteger2(e,"updateTime","datetime"),p=this.safeString(e,"status"),m=this.parseOrderStatus(p);return this.safeOrder({info:e,id:i,price:s,amount:a,remaining:n,filled:void 0,cost:void 0,average:void 0,status:m,side:c,type:l,clientOrderId:u,timestamp:f,datetime:this.iso8601(f),symbol:h,fee:void 0},t)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a=await this.privateGetUsersTransactionsTrade(),o=this.safeList(a,"data"),n=[];return void 0!==o&&(n=o),this.parseTrades(n,r,t,i)}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},o,n){let d,h;if("btctrader"===this.id)throw new a.ExchangeError(this.id+" is an abstract base API for BTCExchange, BTCTurk");let c=this.safeString(this.urls.api,t);if(void 0===c)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let l=c+"/"+e,u="GET"===i||"DELETE"===i;if(u&&Object.keys(r).length>0&&(l+="?"+this.urlencode(r)),d=u?n:this.json(r),"private"===t){this.checkRequiredCredentials();let e=this.nonce().toString(),t=this.base64ToBinary(this.secret),i=this.apiKey+e;h={"X-PCK":this.apiKey,"X-Stamp":e,"X-Signature":this.hmac(this.encode(i),t,s.sc,"base64"),"Content-Type":"application/json"}}return{url:l,method:i,body:d,headers:void 0!==h?h:o}}handleErrors(e,t,i,s,r,o,n,d,h){let c=this.safeString(n,"code","0"),l=this.safeString(n,"message"),u=l;if(void 0===l&&(u=o),this.throwExactlyMatchedException(this.exceptions.exact,l,this.id+" "+u),"0"!==c&&"SUCCESS"!==c)throw new a.ExchangeError(this.id+" "+u)}}i.d(t,{A:()=>n})},1624(e,t,i){"use strict";var s=i(2517),r=i(1453),a=i(4721),o=i(7749);class n extends s.A{describe(){return this.deepExtend(super.describe(),{id:"btse",name:"BTSE",countries:["VG"],rateLimit:1e3/75,version:"v3",certified:!1,pro:!1,has:{CORS:void 0,spot:!0,margin:!1,swap:!0,future:!0,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelAllOrdersAfter:!0,cancelOrder:!0,cancelOrders:!1,cancelOrdersWithClientOrderId:!1,cancelOrderWithClientOrderId:!0,closeAllPositions:!1,closePosition:!0,createDepositAddress:!1,createLimitBuyOrder:!0,createLimitOrder:!0,createLimitSellOrder:!0,createMarketBuyOrder:!0,createMarketBuyOrderWithCost:!1,createMarketOrder:!0,createMarketOrderWithCost:!1,createMarketSellOrder:!0,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!1,createOrderWithTakeProfitAndStopLoss:!0,createPostOnlyOrder:!0,createReduceOnlyOrder:!0,createStopLimitOrder:!1,createStopLossOrder:!1,createStopMarketOrder:!0,createStopOrder:!0,createTakeProfitOrder:!0,createTrailingAmountOrder:!0,createTrailingPercentOrder:!1,createTriggerOrder:!0,deposit:!1,editOrder:!0,editOrders:!1,editOrderWithClientOrderId:!0,fetchAccounts:!1,fetchBalance:!0,fetchBidsAsks:!1,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCanceledAndClosedOrders:!1,fetchCanceledOrders:!1,fetchClosedOrder:!1,fetchClosedOrders:!1,fetchConvertCurrencies:!1,fetchConvertQuote:!1,fetchConvertTrade:!1,fetchConvertTradeHistory:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDeposit:!1,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!0,fetchDepositWithdrawFee:!1,fetchDepositWithdrawFees:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchL2OrderBook:!1,fetchL3OrderBook:!1,fetchLastPrices:!1,fetchLedger:!0,fetchLedgerEntry:!1,fetchLeverage:!0,fetchLeverages:!1,fetchLeverageTiers:!0,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!0,fetchMarginModes:!1,fetchMarketLeverageTiers:!0,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!1,fetchOpenInterests:!0,fetchOpenOrder:!0,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!1,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrders:!1,fetchOrdersByStatus:!1,fetchOrderTrades:!0,fetchOrderWithClientOrderId:!1,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!0,fetchPositions:!0,fetchPositionsForSymbol:!0,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchStatus:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTradingLimits:!1,fetchTransactionFee:!1,fetchTransactionFees:!1,fetchTransactions:!1,fetchTransfer:!1,fetchTransfers:!1,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,fetchWithdrawAddresses:!1,fetchWithdrawal:!1,fetchWithdrawals:!0,fetchWithdrawalWhitelist:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,sandbox:!0,setLeverage:!0,setMargin:!1,setMarginMode:!0,setPositionMode:!0,signIn:!1,transfer:!1,watchMyLiquidationsForSymbols:!1,withdraw:!1,ws:!1},urls:{logo:"https://github.com/user-attachments/assets/879ce771-6db1-4d8f-868a-77c9621635dc",api:{public:"https://api.btse.com",private:"https://api.btse.com"},test:{public:"https://testapi.btse.io",private:"https://testapi.btse.io"},www:"https://www.btse.com",doc:"https://support.btse.com/en/support/solutions/articles/43000044751-btse-api",referral:"https://www.btse.com/referral/o2tjIXx5",fees:"https://support.btse.com/en/support/solutions/articles/43000064283"},api:{public:{get:{"spot/api/v3.3/market_summary":{cost:5},"spot/api/v3.3/ohlcv":{cost:5},"spot/api/v3.3/price":5,"spot/api/v3.3/orderbook":5,"spot/api/v3.3/orderbook/L2":5,"spot/api/v3.3/trades":{cost:5},"spot/api/v3.3/time":{cost:5},"futures/api/v2.3/market_summary":{cost:5},"futures/api/v2.3/ohlcv":{cost:5},"futures/api/v2.3/price":5,"futures/api/v2.3/orderbook":5,"futures/api/v2.3/orderbook/L2":5,"futures/api/v2.3/trades":{cost:5},"futures/api/v2.3/funding_history":5,"futures/api/v2.3/market/risk_limit":5,"spot/api/v3.2/availableCurrencyNetworks":15,"spot/api/v3.2/exchangeRate":15,"public-api/wallet/v1/crypto/networks":15,"public-api/wallet/v1/assets/exchangeRate":15,"public-api/market/v1/markets":{cost:3},"public-api/market/v1/exchangeInfo":3,"public-api/market/v1/orderbook":{cost:3},"public-api/market/v1/trades":{cost:3},"public-api/market/v1/klines":{cost:3},"public-api/market/v1/ticker/24hr":{cost:3},"public-api/market/v1/ticker/price":3,"public-api/market/v1/ticker/indices":3,"public-api/market/v1/ticker/l1":3,"public-api/market/v1/recentFundingHistory":{cost:3},"public-api/market/v1/riskLimits":{cost:3},"public-api/wallet/v1/crypto/list":15,"public-api/otc/v1/markets":1}},private:{get:{"spot/api/v3.3/order":1,"spot/api/v3.3/user/open_orders":5,"spot/api/v3.3/user/trade_history":{cost:5},"spot/api/v3.3/user/fees":{cost:5},"spot/api/v3.3/invest/products":5,"spot/api/v3.3/invest/orders":5,"spot/api/v3.3/invest/history":5,"futures/api/v2.3/order":1,"futures/api/v2.3/user/open_orders":1,"futures/api/v2.3/user/trade_history":{cost:5},"futures/api/v2.3/user/positions":{cost:5},"futures/api/v2.3/risk_limit":5,"futures/api/v2.3/leverage":5,"futures/api/v2.3/user/fees":{cost:5},"futures/api/v2.3/position_mode":{cost:5},"futures/api/v2.3/user/margin_setting":5,"futures/api/v2.3/user/wallet":{cost:5},"futures/api/v2.3/user/wallet_history":5,"futures/api/v2.3/user/unifiedWallet/margin":5,"futures/api/v2.3/user/margin":5,"otc/api/v1/getMarket":1,"spot/api/v3.2/user/wallet":{cost:15},"spot/api/v3.2/user/wallet_history":{cost:15},"spot/api/v3.3/user/wallet/address":15,"spot/api/v3.2/availableCurrencies":15,"spot/api/v3.2/subaccount/wallet/history":15,"spot/api/v4/trade/orders":{cost:5},"spot/api/v4/trade/order":{cost:5},"spot/api/v4/trade/trade_history":5,"spot/api/v4/trade/fees":{cost:5},"futures/api/v3/trade/orders":{cost:5},"futures/api/v3/trade/risk_limit":5,"futures/api/v3/trade/position_mode":{cost:5},"futures/api/v3/trade/leverage":{cost:5},"futures/api/v3/trade/trade_history":{cost:5},"futures/api/v3/trade/positions":{cost:5},"futures/api/v3/trade/margin_setting":5,"public-api/wallet/v1/assets":15,"public-api/wallet/v1/user/assets":{cost:15},"public-api/wallet/v1/user/walletHistory":15,"public-api/wallet/v1/user/crypto/address":15,"public-api/otc/v1/quotes":1},post:{"spot/api/v3.3/order":1,"spot/api/v3.3/order/peg":1,"spot/api/v3.3/order/cancelAllAfter":{cost:1},"spot/api/v3.3/invest/deposit":5,"spot/api/v3.3/invest/renew":5,"spot/api/v3.3/invest/redeem":5,"futures/api/v2.3/order":1,"futures/api/v2.3/order/peg":1,"futures/api/v2.3/order/cancelAllAfter":{cost:1},"futures/api/v2.3/order/close_position":1,"futures/api/v2.3/risk_limit":5,"futures/api/v2.3/leverage":5,"futures/api/v2.3/settle_in":5,"futures/api/v2.3/order/bind/tpsl":1,"futures/api/v2.3/position_mode":{cost:5},"futures/api/v2.3/user/wallet/transfer":5,"futures/api/v2.3/subaccount/wallet/transfer":5,"otc/api/v1/quote":1,"otc/api/v1/accept/{quoteId}":1,"otc/api/v1/reject/{quoteId}":1,"otc/api/v1/queryOrder/{quoteId}":1,"spot/api/v3.3/user/wallet/address":15,"spot/api/v3.3/user/wallet/withdraw":15,"spot/api/v3.2/user/wallet/convert":15,"spot/api/v3.3/user/wallet/transfer":15,"spot/api/v4/trade/orders":{cost:1},"spot/api/v4/trade/orders/cancel_all_after":{cost:1},"spot/api/v4/trade/orders/algo":{cost:1},"futures/api/v3/trade/orders":{cost:1},"futures/api/v3/trade/orders/cancel_all_after":{cost:1},"futures/api/v3/trade/orders/algo":{cost:1},"futures/api/v3/trade/settle_in":5,"futures/api/v3/trade/risk_limit":5,"futures/api/v3/trade/positions/tpsl":1,"futures/api/v3/trade/position_mode":{cost:1},"futures/api/v3/trade/leverage":{cost:1},"public-api/wallet/v1/user/crypto/address":15,"public-api/wallet/v1/user/crypto/withdraw":15,"public-api/wallet/v1/user/assets/sendTo":15,"public-api/wallet/v1/user/assets/convert":15,"public-api/otc/v1/quotes":1,"public-api/otc/v1/quotes/accept":1},put:{"spot/api/v3.3/order":1,"futures/api/v2.3/order":1,"spot/api/v4/trade/orders":{cost:1},"futures/api/v3/trade/orders":{cost:1}},delete:{"spot/api/v3.3/order":1,"futures/api/v2.3/order":1,"spot/api/v3.3/user/wallet/address":15,"spot/api/v4/trade/orders":{cost:1},"spot/api/v4/trade/orders/all":{cost:1},"futures/api/v3/trade/orders":{cost:1},"futures/api/v3/trade/positions":1,"public-api/wallet/v1/user/crypto/address":15}}},features:{contract:{sandbox:!0,createOrder:{marginMode:!0,triggerPrice:!0,triggerPriceType:{mark:!0,last:!0,index:!1},stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:{triggerPriceType:{last:!0,mark:!0,index:!1},price:!1},timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!0,selfTradePrevention:!1,trailing:!0,iceberg:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,daysBack:void 0,limit:void 0,untilDays:7,symbolRequired:!1},fetchOrder:void 0,fetchOpenOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchCanceledAndClosedOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:{limit:300}},spot:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:{mark:!1,last:!0,index:!0},stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,selfTradePrevention:!1,trailing:!0,iceberg:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,daysBack:void 0,limit:void 0,untilDays:7,symbolRequired:!1},fetchOrder:void 0,fetchOpenOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchCanceledAndClosedOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:{limit:300}},swap:{linear:{extends:"contract"},inverse:void 0},future:{linear:{extends:"contract"},inverse:void 0}},timeframes:{"1m":"1","5m":"5","15m":"15","30m":"30","1h":"60","4h":"240","6h":"360","1d":"1440","1w":"10080","1M":"43200"},precisionMode:4,fees:{trading:{tierBased:!0,percentage:!0,maker:this.parseNumber("0.0002"),taker:this.parseNumber("0.0002")},spot:{tierBased:!0,percentage:!0,maker:this.parseNumber("0.0002"),taker:this.parseNumber("0.0002")},contract:{tierBased:!0,percentage:!0,maker:this.parseNumber("0.0002"),taker:this.parseNumber("0.00055")}},exceptions:{exact:{"-2":r.BadRequest,"-7":r.AuthenticationError,"-7006":r.BadSymbol,"-11":r.ExchangeNotAvailable,1:r.ExchangeNotAvailable,8:r.InsufficientFunds,11:r.BadRequest,12:r.BadRequest,13:r.BadRequest,15:r.InvalidOrder,16:r.OrderNotFound,17:r.ExchangeError,28:r.ExchangeError,41:r.BadRequest,64:r.ExchangeError,101:r.InvalidOrder,133:r.InvalidOrder,134:r.BadRequest,135:r.BadRequest,300:r.InvalidOrder,301:r.InvalidOrder,302:r.InvalidOrder,303:r.RateLimitExceeded,304:r.InvalidOrder,305:r.InvalidOrder,1003:r.InvalidOrder,1004:r.InvalidOrder,4003:r.InvalidOrder,4005:r.InvalidOrder,4051:r.InvalidOrder,10002:r.AuthenticationError,0x98bd94:r.BadRequest,0xa7d8c1:r.BadRequest,51523:r.InsufficientFunds,0x1f78e29:r.InvalidOrder,0x1f78e2b:r.InvalidOrder,0x1fa93fd:r.InsufficientFunds,0x1fa9410:r.InvalidOrder},broad:{"Order not found":r.OrderNotFound,"Insufficient wallet balance":r.InsufficientFunds,"Insufficient balance":r.InsufficientFunds,"Authentication Failed":r.AuthenticationError,"Authenticate failed":r.AuthenticationError,"Signature verification failed":r.AuthenticationError,"api parameter is mandatory":r.AuthenticationError,"Invalid nonce":r.InvalidNonce,"Invalid order size":r.InvalidOrder,"Invalid order price":r.InvalidOrder,"Maximum open orders exceeded":r.InvalidOrder,"Rate limit exceeded":r.RateLimitExceeded,"auto-deleveraging":r.InvalidOrder,BADREQUEST:r.BadRequest}},commonCurrencies:{},options:{timeDifference:0,adjustForTimeDifference:!1,networks:{},timeInForce:{GTC:"GTC",IOC:"IOC",FOK:"FOK",HALFSEC:"HALFSEC",HALFMIN:"HALFMIN",FIVEMIN:"FIVEMIN",HOUR:"HOUR",TWELVEHOUR:"TWELVEHOUR",DAY:"DAY",WEEK:"WEEK",MONTH:"MONTH"},accountsByType:{},accountsById:{}}})}async fetchTime(e={}){let t=await this.publicGetSpotApiV33Time(e);return this.safeTimestamp(t,"epoch")}async fetchMarkets(e={}){this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference();let t=await this.publicGetPublicApiMarketV1Markets(e),i=this.safeDict(t,"data",{}),s=this.safeList(i,"symbols",[]);return this.parseMarkets(s)}parseMarket(e){let t,i,s=this.safeString(e,"type"),r="Spot"===s,a="FuturesTimeBased"===s,o="FuturesPerpetual"===s,n=this.safeString(e,"symbol"),d=this.safeString(e,"baseCurrency"),h=this.safeString(e,"quoteCurrency"),c=this.safeCurrencyCode(d),l=this.safeCurrencyCode(h);if(void 0===c||void 0===l)return;let u=c+"/"+l,f=this.safeString(e,"maxOrderSize"),p=this.safeString(e,"minOrderSize"),m=this.safeString(e,"minOrderPrice"),g=this.safeString(e,"minPriceIncrement"),v=this.safeString(e,"minSizeIncrement"),y=this.safeBool(e,"active"),b="spot";r||(u+=":"+l,i=this.safeString(e,"contractSize"),a?(t=this.safeInteger(e,"contractEndTime"),u+="-"+this.yymmdd(t),b="future"):b="swap");let w=this.safeDict(this.fees,"contract",{});return r&&(w=this.safeDict(this.fees,"spot",{})),this.safeMarketStructure({id:n,symbol:u,base:c,quote:l,settle:r?void 0:l,baseId:d,quoteId:h,settleId:r?void 0:h,type:b,spot:r,margin:!r&&void 0,swap:o,future:a,option:!1,active:y,contract:o||a,linear:!r||void 0,inverse:!!r&&void 0,taker:w.taker,maker:w.maker,contractSize:this.parseNumber(i),expiry:t,expiryDatetime:this.iso8601(t),strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(v),price:this.parseNumber(g)},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.parseNumber(p),max:this.parseNumber(f)},price:{min:this.parseNumber(m),max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:e})}async fetchOHLCV(e,t="1m",i,s,r={}){await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(a)return this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,o,300);let n=this.market(e),d=this.safeString(this.timeframes,t,t),h={symbol:n.id,resolution:d};void 0!==s?h.limit=Math.min(s,300):h.limit=300,void 0!==i&&(h.start=this.parseToInt(i/1e3));let[c,l]=this.handleOptionIntegerAndParams(o,"fetchOHLCV","until");void 0!==c&&(void 0!==i?c-i<300*this.parseTimeframe(t)*1e3&&(h.end=this.parseToInt(c/1e3)):h.end=this.parseToInt(c/1e3));let u=await this.publicGetPublicApiMarketV1Klines(this.extend(h,l)),f=this.safeList(u,"data",[]);return this.parseOHLCVs(f,n,t,i,s)}parseOHLCV(e,t){return[this.safeTimestamp(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]}async fetchOrderBook(e,t,i={}){await this.loadMarkets();let s=this.market(e),r={symbol:s.id};void 0!==t&&(r.depth=Math.min(t,50));let a=await this.publicGetPublicApiMarketV1Orderbook(this.extend(r,i)),o=this.safeDict(a,"data",{}),n=this.safeInteger(o,"timestamp");return this.parseOrderBook(o,s.symbol,n,"bids","asks")}async fetchFundingRateHistory(e,t,i,s={}){let a,o;if(void 0===e)throw new r.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");await this.loadMarkets();let n=this.market(e);if(!0!==n.contract)throw new r.BadRequest(this.id+" fetchFundingRateHistory() supports contract markets only");if([a,o]=this.handleOptionStringAndParams(s,"fetchFundingRateHistory","period"),void 0===a&&(a="7D",void 0!==t)){let e=this.milliseconds()-t;e>12096e5?a="1M":e>6048e5&&(a="2W")}let d={symbol:n.id,period:a},[h,c]=this.handleOptionIntegerAndParams(o,"fetchFundingRateHistory","until"),l=await this.publicGetPublicApiMarketV1RecentFundingHistory(this.extend(d,c)),u=this.safeList(l,"data",[]),f=this.parseFundingRateHistories(u,n,t,i);if(void 0===h)return f;let p=[];for(let e=0;e<f.length;e++){let t=f[e],i=this.safeInteger(t,"timestamp");(void 0===i||i<=h)&&p.push(t)}return p}parseFundingRateHistory(e,t){let i=this.safeInteger(e,"timestamp");return{info:e,symbol:this.safeSymbol(void 0,t),fundingRate:this.safeNumber(e,"rate"),timestamp:i,datetime:this.iso8601(i)}}async fetchBalance(e={}){let t;await this.loadMarkets();let[i,s]=this.handleMarketTypeAndParams("fetchBalance",void 0,e,"spot");if("spot"===i){let e=await this.privateGetPublicApiWalletV1UserAssets(s);t=this.safeList(e,"data",[])}else{let[e,i]=this.handleOptionStringAndParams(s,"fetchBalance","wallet","CROSS@");t=await this.privateGetFuturesApiV23UserWallet(this.extend({wallet:e},i))}return this.parseBalance(t)}parseBalance(e){let t={info:e},i={},s={},r={};for(let t=0;t<e.length;t++){let a=this.safeDict(e,t),n=this.safeList(a,"assets");if(void 0!==n){let e=this.safeList(a,"assetsInUse",[]);for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s=this.safeCurrencyCode(this.safeString(i,"currency"));void 0!==s&&(r[s]=o.Y.stringAdd(this.safeString(r,s,"0"),this.safeString(i,"balance")))}for(let e=0;e<n.length;e++){let t=this.safeDict(n,e),s=this.safeCurrencyCode(this.safeString(t,"currency"));void 0!==s&&(i[s]=o.Y.stringAdd(this.safeString(i,s,"0"),this.safeString(t,"balance")),r[s]=this.safeString(r,s,"0"))}}else{let e=this.safeCurrencyCode(this.safeString2(a,"asset","currency"));if(void 0===e)continue;i[e]=o.Y.stringAdd(this.safeString(i,e,"0"),this.safeString2(a,"totalAmount","total")),s[e]=o.Y.stringAdd(this.safeString(s,e,"0"),this.safeString2(a,"availableAmount","available"))}}let a=Object.keys(i);for(let e=0;e<a.length;e++){let o=a[e],n=this.account();n.total=this.safeString(i,o),n.free=this.safeString(s,o),n.used=this.safeString(r,o),t[o]=n}return this.safeBalance(t)}async fetchLeverageTiers(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e),s={};if(void 0!==i&&1===i.length){let e=this.safeString(i,0);s.symbol=this.market(e).id}let r=await this.publicGetPublicApiMarketV1RiskLimits(this.extend(s,t)),a=this.safeList(r,"data");void 0===a&&(a=[this.safeDict(r,"data",{})]);let o={};for(let e=0;e<a.length;e++){let t=this.safeDict(a,e),s=this.safeString(t,"symbol"),r=this.safeMarket(s),n=r.symbol;if(void 0===i||this.inArray(n,i)){let e=this.safeList(t,"riskLimits",[]),i=[];for(let t=0;t<e.length;t++){let s=e[t];i.push({tier:this.safeInteger(s,"level"),symbol:n,currency:r.settle,minNotional:void 0,maxNotional:this.safeNumber(s,"value"),maintenanceMarginRate:void 0,maxLeverage:void 0,info:s})}o[n]=i}}let n=Object.keys(o);for(let e=0;e<n.length;e++){let t=n[e],i=o[t];for(let e=0;e<i.length;e++)0===e?i[e].minNotional=0:i[e].minNotional=i[e-1].maxNotional;o[t]=i}return o}async fetchMarketLeverageTiers(e,t={}){if(await this.loadMarkets(),!0!==this.market(e).contract)throw new r.BadRequest(this.id+" fetchMarketLeverageTiers() supports contract markets only");return(await this.fetchLeverageTiers([e],t))[e]}async fetchTickers(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0),s=this.omit(t,"type"),r=await this.publicGetPublicApiMarketV1Ticker24hr(s),a=this.safeList(r,"data",[]);return this.parseTickers(a,i)}async fetchTicker(e,t={}){await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetPublicApiMarketV1Ticker24hr(this.extend(s,t)),a=this.safeDict(r,"data");if(void 0===a){let e=this.safeList(r,"data",[]);a=this.safeDict(e,0,{})}return this.parseTicker(a,i)}parseTicker(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeString(e,"lastPrice"),a=this.safeString(e,"amount");if(void 0!==a&&void 0!==s&&!0===s.contract){let e=this.numberToString(s.contractSize);void 0!==e&&(a=o.Y.stringMul(a,e))}let n=this.safeTimestamp(e,"closeTime");return this.safeTicker({symbol:this.safeSymbol(i,s),timestamp:n,datetime:this.iso8601(n),high:this.safeString(e,"highPrice"),low:this.safeString(e,"lowPrice"),bid:this.safeString(e,"bidPrice"),bidVolume:this.safeString(e,"bidQty"),ask:this.safeString(e,"askPrice"),askVolume:this.safeString(e,"askQty"),vwap:void 0,open:this.safeString(e,"openPrice"),close:r,last:r,previousClose:this.safeString(e,"prevClosePrice"),change:this.safeString(e,"priceChange"),percentage:void 0,average:void 0,baseVolume:a,quoteVolume:this.safeString(e,"volume"),markPrice:void 0,indexPrice:void 0,info:e},s)}async fetchOpenInterest(e,t={}){await this.loadMarkets();let i=this.market(e);if(!0===i.spot)throw new r.BadRequest(this.id+" fetchOpenInterest() symbol does not support market "+e);let s={symbol:i.id},a=await this.publicGetPublicApiMarketV1Ticker24hr(this.extend(s,t)),o=this.safeDict(a,"data");if(void 0===o){let e=this.safeList(a,"data",[]);o=this.safeDict(e,0,{})}return this.parseOpenInterest(o,i)}async fetchOpenInterests(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetPublicApiMarketV1Ticker24hr(t),r=this.safeList(s,"data",[]),a=[];for(let e=0;e<r.length;e++){let t=r[e];void 0!==this.safeString(t,"openInterest")&&a.push(t)}return this.parseOpenInterests(a,i)}parseOpenInterest(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeTimestamp(e,"closeTime");return this.safeOpenInterest({symbol:s.symbol,openInterestAmount:this.safeNumber(e,"openInterest"),openInterestValue:this.safeNumber(e,"openInterestUSD"),timestamp:r,datetime:this.iso8601(r),info:e},s)}async fetchFundingRate(e,t={}){await this.loadMarkets();let i=this.market(e);if(!0===i.spot)throw new r.BadRequest(this.id+" fetchFundingRate() symbol does not support spot markets");let s={symbol:i.id},a=await this.publicGetPublicApiMarketV1Ticker24hr(this.extend(s,t)),o=this.safeDict(a,"data");if(void 0===o){let e=this.safeList(a,"data",[]);o=this.safeDict(e,0,{})}return this.parseFundingRate(o,i)}async fetchFundingRates(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetPublicApiMarketV1Ticker24hr(t),r=this.safeList(s,"data",[]),a=[];for(let e=0;e<r.length;e++){let t=r[e];void 0!==this.safeString(t,"fundingRate")&&a.push(t)}return this.parseFundingRates(a,i)}parseFundingRate(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=this.safeTimestamp(e,"closeTime"),o=this.safeIntegerOmitZero(e,"nextFundingTime"),n=this.safeInteger(e,"fundingIntervalMinutes");return void 0!==n&&n>=60&&(i=this.parseToInt(n/60).toString()+"h"),{info:e,symbol:r.symbol,markPrice:void 0,indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:a,datetime:this.iso8601(a),fundingRate:this.safeNumber(e,"fundingRate"),fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:void 0,nextFundingTimestamp:o,nextFundingDatetime:this.iso8601(o),previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:i}}async fetchTrades(e,t,i,s={}){await this.loadMarkets();let r=this.market(e),a={symbol:r.id};void 0!==i&&(a.limit=Math.min(i,500));let[o,n]=this.handleOptionIntegerAndParams(s,"fetchTrades","until"),d=await this.publicGetPublicApiMarketV1Trades(this.extend(a,n)),h=this.safeList(d,"data",[]),c=this.parseTrades(h,r,t,i);if(void 0===o)return c;let l=[];for(let e=0;e<c.length;e++){let t=c[e],i=this.safeInteger(t,"timestamp");(void 0===i||i<=o)&&l.push(t)}return l}async fetchMyTrades(e,t,i,s={}){let a,o,n;if(await this.loadMarkets(),!0===this.safeBool(s,"paginate",!1))return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,this.omit(s,"paginate"));let d={};void 0!==e&&(a=this.market(e),d.symbol=a.id),void 0!==t&&(d.startTime=t),void 0!==i&&(d.count=i),[d,o]=this.handleUntilOption("endTime",d,s);let[h,c]=this.handleMarketTypeAndParams("fetchMyTrades",a,o,"spot");if("spot"===h){if(void 0===e)throw new r.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument for spot markets");n=await this.privateGetSpotApiV4TradeTradeHistory(this.extend(d,c))}else d=this.omit(d,"count"),void 0!==a&&(d.symbol=this.futuresRequestId(a)),n=await this.privateGetFuturesApiV3TradeTradeHistory(this.extend(d,c));let l=this.safeList(n,"data");return void 0===l&&(l=n),this.parseTrades(l,a,t,i)}async fetchOrderTrades(e,t,i,s,a={}){await this.loadMarkets();let o=this.safeString(a,"clientOrderId");if(void 0===o&&void 0===e)throw new r.ArgumentsRequired(this.id+" fetchOrderTrades() requires an id argument or a clientOrderId parameter");let n={};return n=void 0===o?{orderID:e}:{clOrderID:o},await this.fetchMyTrades(t,i,s,this.extend(a,n))}parseTrade(e,t){let i,s=this.safeString2(e,"positionId","symbol"),r=this.safeMarket(s,t),a=this.safeInteger(e,"timestamp"),o=this.safeNumber(e,"feeAmount");return void 0!==o&&(i={cost:o,currency:this.safeCurrencyCode(this.safeString(e,"feeCurrency"))}),this.safeTrade({info:e,timestamp:a,datetime:this.iso8601(a),symbol:r.symbol,id:this.safeStringN(e,["tradeId","serialId","id"]),order:this.safeString(e,"orderId"),type:this.parseOrderType(this.safeString2(e,"orderType","type")),side:this.safeStringLower2(e,"side","orderSide"),takerOrMaker:void 0,price:this.safeStringN(e,["filledPrice","avgFilledPrice","price"]),amount:this.safeString2(e,"filledSize","size"),cost:void 0,fee:i},r)}async createOrder(e,t,i,s,r,a={}){return(await this.loadMarkets(),!0===this.market(e).spot)?await this.createSpotOrder(e,t,i,s,r,a):await this.createContractOrder(e,t,i,s,r,a)}async createSpotOrder(e,t,i,s,a,n={}){let d;await this.loadMarkets();let h=this.market(e),c=t.toUpperCase(),l=i.toUpperCase(),u={symbol:h.id,orderSide:l},f=this.safeString(n,"clientOrderId");void 0!==f&&(u.clOrderId=f);let p=this.omit(n,"clientOrderId"),m="MARKET"===c,g="LIMIT"===c,v=!1;[v,p]=this.handlePostOnly(m,v,p),v&&(u.postOnly=!0);let y=this.handleTimeInForce(p);void 0!==y&&(u.timeInForce=y);let b=this.safeString(p,"triggerPrice"),w=this.safeString(p,"takeProfitPrice"),k=this.safeString(p,"stopLossPrice"),S=void 0!==k,O=(void 0!==b||void 0!==w||S)&&(m||g),T=O||!m&&!g;if((g||"PEG"===c||"OCO"===c)&&void 0===a)throw new r.InvalidOrder(this.id+" createOrder() requires a price argument for "+c+" orders");if((m||"TRAILING"===c)&&"BUY"===l){let t,i=!0;[i,p]=this.handleOptionBoolAndParams(p,"createOrder","createMarketBuyOrderRequiresPrice",!0);let n=this.safeString(p,"cost");if(p=this.omit(p,"cost"),void 0!==n)t=this.costToPrecision(e,n);else if(i)if(void 0===a)throw new r.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend, alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument");else{let i=this.numberToString(s),r=this.numberToString(a);t=this.costToPrecision(e,o.Y.stringMul(i,r))}else t=this.costToPrecision(e,this.numberToString(s));u.quoteOrderSize=t}else u.orderSize=this.amountToPrecision(e,s);if(T){if(O){let t,i;u.orderType="CONDITIONAL",S?(t="STOP_LOSS",i=k):(t="TAKE_PROFIT",void 0===(i=b)&&(i=w)),g&&(t+="_LIMIT",u.orderPrice=this.priceToPrecision(e,a)),u.triggerOrderType=t,u.triggerPrice=this.priceToPrecision(e,i);let s=this.safeString(p,"triggerPriceType","last");u.triggerPriceType=this.encodeTriggerPriceType(s),p=this.omit(p,["triggerPrice","takeProfitPrice","stopLossPrice","triggerPriceType"])}else if(u.orderType=c,"OCO"===c){u.takeProfitOrderPrice=this.priceToPrecision(e,a);let t=this.safeString(p,"stopPrice");void 0!==t&&(u.stopLossOrderPrice=this.priceToPrecision(e,t)),void 0!==b&&(u.stopLossTriggerPrice=this.priceToPrecision(e,b));let i=this.safeString(p,"triggerPriceType","last");u.stopLossTriggerPriceType=this.encodeTriggerPriceType(i),p=this.omit(p,["stopPrice","triggerPrice","triggerPriceType"])}else if("PEG"===c)u.orderPrice=this.priceToPrecision(e,a);else if("TRAILING"===c){let t=this.safeString(p,"trailingAmount"),i=this.safeString(p,"trailingPercent");void 0!==t?(u.trailValue=this.priceToPrecision(e,t),u.trailValueType="DISTANCE"):void 0!==i&&(u.trailValue=i,u.trailValueType="PERCENTAGE");let s=this.safeString(p,"triggerPriceType","last");u.triggerPriceType=this.encodeTriggerPriceType(s),p=this.omit(p,["trailingAmount","trailingPercent","triggerPriceType"])}d=await this.privatePostSpotApiV4TradeOrdersAlgo(this.extend(u,p))}else u.orderType=c,g&&(u.orderPrice=this.priceToPrecision(e,a)),d=await this.privatePostSpotApiV4TradeOrders(this.extend(u,p));let P=this.safeDict(d,0,{});return this.parseOrder(P,h)}async createContractOrder(e,t,i,s,a,o={}){let n;await this.loadMarkets();let d=this.market(e),h=t.toUpperCase(),c={symbol:this.futuresRequestId(d),orderSide:i.toUpperCase(),orderSize:this.amountToPrecision(e,s)},l=this.safeString(o,"clientOrderId");void 0!==l&&(c.clOrderId=l);let u=this.omit(o,"clientOrderId");if(void 0===this.safeString(u,"positionMode")){let e=!1;[e,u]=this.handleOptionBoolAndParams(u,"createOrder","hedged",e);let t="cross";if([t,u]=this.handleOptionStringAndParams(u,"createOrder","marginMode",t),"isolated"===t){if(e)throw new r.BadRequest(this.id+" createOrder() cannot use isolated margin with hedged positions");c.positionMode="ISOLATED"}else e&&(c.positionMode="HEDGE")}let f="MARKET"===h,p="LIMIT"===h,m=!1;[m,u]=this.handlePostOnly(f,m,u),m&&(c.postOnly=!0);let g=this.handleTimeInForce(u);void 0!==g&&(c.timeInForce=g);let v=this.safeString(u,"triggerPrice"),y=this.safeString(u,"takeProfitPrice"),b=this.safeString(u,"stopLossPrice"),w=void 0!==b,k=(void 0!==v||void 0!==y||w)&&(f||p),S=k||!f&&!p;if((p||"OCO"===h)&&void 0===a)throw new r.InvalidOrder(this.id+" createOrder() requires a price argument for "+h+" orders");let O=this.safeDict(u,"takeProfit"),T=this.safeDict(u,"stopLoss");if(void 0!==O||void 0!==T){let t=this.safeString(O,"triggerPrice"),i=this.safeString(T,"triggerPrice");if(void 0!==t){c.takeProfitTriggerPrice=this.priceToPrecision(e,t);let i=this.safeString(O,"priceType");void 0!==i&&(c.takeProfitTriggerType=this.encodeTriggerPriceType(i))}if(void 0!==i){c.stopLossTriggerPrice=this.priceToPrecision(e,i);let t=this.safeString(T,"priceType");void 0!==t&&(c.stopLossTriggerType=this.encodeTriggerPriceType(t))}u=this.omit(u,["takeProfit","stopLoss"])}if(S){if(k){c.orderType="CONDITIONAL";let t=v;void 0===t&&(t=y),void 0===t&&(t=b),c.triggerPrice=this.priceToPrecision(e,t);let i=this.safeString(u,"triggerPriceType","mark");c.triggerType=this.encodeTriggerPriceType(i),p&&(c.orderPrice=this.priceToPrecision(e,a)),u=this.omit(u,["triggerPrice","takeProfitPrice","stopLossPrice","triggerPriceType"])}else if(c.orderType=h,"OCO"===h){c.takeProfitOrderPrice=this.priceToPrecision(e,a);let t=this.safeString(u,"stopPrice");void 0!==t&&(c.stopLossOrderPrice=this.priceToPrecision(e,t)),void 0!==v&&(c.stopLossTriggerPrice=this.priceToPrecision(e,v));let i=this.safeString(u,"triggerPriceType","mark");c.stopLossTriggerType=this.encodeTriggerPriceType(i),u=this.omit(u,["stopPrice","triggerPrice","triggerPriceType"])}else if("PEG"===h)void 0!==a&&(c.orderPrice=this.priceToPrecision(e,a));else if("TRAILING"===h){let t=this.safeString(u,"trailingAmount"),i=this.safeString(u,"trailingPercent");void 0!==t?(c.trailValue=this.priceToPrecision(e,t),c.trailValueType="DISTANCE"):void 0!==i&&(c.trailValue=i,c.trailValueType="PERCENTAGE");let s=this.safeString(u,"triggerPriceType","mark");c.trailTriggerPriceType=this.encodeTriggerPriceType(s),u=this.omit(u,["trailingAmount","trailingPercent","triggerPriceType"])}n=await this.privatePostFuturesApiV3TradeOrdersAlgo(this.extend(c,u))}else c.orderType=h,p&&(c.orderPrice=this.priceToPrecision(e,a)),n=await this.privatePostFuturesApiV3TradeOrders(this.extend(c,u));let P=n;return Array.isArray(n)&&(P=this.safeDict(n,0,{})),this.parseOrder(P,d)}encodeTriggerPriceType(e){return this.safeString({last:"LAST_PRICE",mark:"MARK_PRICE",index:"INDEX_PRICE",lastPrice:"LAST_PRICE",markPrice:"MARK_PRICE",indexPrice:"INDEX_PRICE"},e,e)}async fetchOpenOrder(e,t,i={}){let s,a;await this.loadMarkets();let o={},n=this.safeString(i,"clientOrderId");if(void 0!==n)o.clOrderId=n;else if(void 0===e)throw new r.ArgumentsRequired(this.id+" fetchOpenOrder() requires an id argument or a clientOrderId parameter");else o.orderId=e;let d=void 0!==n?this.omit(i,"clientOrderId"):i;void 0!==t&&(s=this.market(t));let[h,c]=this.handleMarketTypeAndParams("fetchOrder",s,d,"spot");a="spot"===h?await this.privateGetSpotApiV4TradeOrder(this.extend(o,c)):await this.privateGetFuturesApiV3TradeOrders(this.extend(o,c));let l=this.safeValue(a,"data",a);return Array.isArray(l)&&(l=this.safeDict(l,0,{})),this.parseOrder(l,s)}async editOrder(e,t,i,s,a,o,n={}){let d;await this.loadMarkets();let h=this.market(t),c={},l=this.safeString(n,"clientOrderId");if(void 0!==l)c.clOrderId=l;else if(void 0===e)throw new r.ArgumentsRequired(this.id+" editOrder() requires an id argument or a clientOrderId parameter");else c.orderId=e;let u=void 0!==l?this.omit(n,"clientOrderId"):n,f=this.safeString(u,"triggerPrice");void 0!==f&&(c.triggerPrice=this.priceToPrecision(t,f));let p=void 0!==f?this.omit(u,"triggerPrice"):u;void 0!==a&&(c.orderSize=this.amountToPrecision(t,a)),void 0!==o&&(c.orderPrice=this.priceToPrecision(t,o));let m=this.safeBool(p,"slide",!1);if(void 0===a&&void 0===o&&void 0===f&&!0!==m)throw new r.ArgumentsRequired(this.id+" editOrder() requires an amount argument, a price argument or a triggerPrice parameter");if(!0===h.spot)c.symbol=h.id,d=await this.privatePutSpotApiV4TradeOrders(this.extend(c,p));else{if(c.symbol=this.futuresRequestId(h),void 0!==f){if(void 0!==a||void 0!==o)throw new r.BadRequest(this.id+" editOrder() can not amend the trigger price together with the price or the amount on contract markets");c.amendType="TRIGGER_PRICE"}else void 0!==a&&void 0!==o?c.amendType="ALL":void 0!==a?c.amendType="SIZE":c.amendType="PRICE";d=await this.privatePutFuturesApiV3TradeOrders(this.extend(c,p))}let g=this.safeDict(d,0,{});return this.parseOrder(g,h)}async cancelOrder(e,t,i={}){let s;if(void 0===t)throw new r.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");await this.loadMarkets();let a=this.market(t),o={},n=this.safeString(i,"clientOrderId");if(void 0!==n)o.clOrderId=n;else if(void 0===e)throw new r.ArgumentsRequired(this.id+" cancelOrder() requires an id argument or a clientOrderId parameter");else o.orderId=e;let d=void 0!==n?this.omit(i,"clientOrderId"):i;!0===a.spot?(o.symbol=a.id,s=await this.privateDeleteSpotApiV4TradeOrders(this.extend(o,d))):(o.symbol=this.futuresRequestId(a),s=await this.privateDeleteFuturesApiV3TradeOrders(this.extend(o,d)));let h=this.safeDict(s,0,{});return this.parseOrder(h,a)}async cancelAllOrders(e,t={}){let i,s;await this.loadMarkets(),void 0!==e&&(i=this.market(e));let[a,o]=this.handleMarketTypeAndParams("cancelAllOrders",i,t,"spot"),n={};if("spot"===a)n.symbol=void 0!==i?i.id:"ALL",s=await this.privateDeleteSpotApiV4TradeOrdersAll(this.extend(n,o));else{if(void 0===i)throw new r.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument for contract markets");n.symbol=this.futuresRequestId(i),s=await this.privateDeleteFuturesApiV23Order(this.extend(n,o))}return this.parseOrders(s,i)}async cancelAllOrdersAfter(e,t={}){let i;await this.loadMarkets();let s={},[r,a]=this.handleMarketTypeAndParams("cancelAllOrdersAfter",void 0,t,"spot");return"spot"===r?(s.timeout=e,i=await this.privatePostSpotApiV4TradeOrdersCancelAllAfter(this.extend(s,a))):(s.timeoutMs=e,i=await this.privatePostFuturesApiV3TradeOrdersCancelAllAfter(this.extend(s,a))),i}async fetchOpenOrders(e,t,i,s={}){let r,a;await this.loadMarkets();let o={};void 0!==e&&(r=this.market(e));let[n,d]=this.handleMarketTypeAndParams("fetchOpenOrders",r,s,"spot");"spot"===n?(void 0!==r&&(o.symbol=r.id),a=await this.privateGetSpotApiV4TradeOrders(this.extend(o,d))):(void 0!==r&&(o.symbol=this.futuresRequestId(r)),a=await this.privateGetFuturesApiV3TradeOrders(this.extend(o,d)));let h=this.safeList(a,"data",a);return this.parseOrders(h,r,t,i)}parseOrder(e,t){let i=this.safeString2(e,"symbol","market"),s=this.safeMarket(i,t),r=this.safeInteger(e,"timestamp"),a=this.safeString2(e,"status","orderState"),o=this.safeString2(e,"orderType","type"),n=this.parseOrderStatus(a),d=this.parseOrderType(o);"market"===d&&"open"===n&&(n="closed");let h=this.safeString2(e,"time_in_force","timeInForce");return this.safeOrder({info:e,id:this.safeString2(e,"orderID","orderId"),clientOrderId:this.safeString2(e,"clOrderID","clOrderId"),timestamp:r,datetime:this.iso8601(r),lastTradeTimestamp:void 0,lastUpdateTimestamp:void 0,status:n,symbol:s.symbol,type:d,timeInForce:this.parseTimeInForce(h),postOnly:this.safeBool(e,"postOnly"),reduceOnly:this.safeBool(e,"reduceOnly"),side:this.safeStringLower2(e,"side","orderSide"),price:this.safeString2(e,"price","orderPrice"),triggerPrice:this.omitZero(this.safeString2(e,"triggerOriginalPrice","triggerPrice")),stopLossPrice:void 0,takeProfitPrice:void 0,amount:this.safeStringN(e,["currentOrderBaseSize","currentOrderSize","orderSize"]),filled:this.safeStringN(e,["totalFilledBaseSize","totalFilledSize","filledSize"]),remaining:this.safeString2(e,"remainingOrderBaseSize","remainingSize"),cost:void 0,trades:void 0,fee:void 0,average:this.omitZero(this.safeString2(e,"avgFilledPrice","averageFillPrice"))},s)}parseOrderStatus(e){return this.safeString({2:"open",3:"closed",4:"closed",5:"open",6:"canceled",7:"refunded",8:"rejected",9:"open",10:"open",15:"rejected",16:"rejected",17:"rejected",123:"open",STATUS_ACTIVE:"open",STATUS_INACTIVE:"canceled",ORDER_INSERTED:"open",ORDER_PARTIALLY_TRANSACTED:"open",ORDER_FULLY_TRANSACTED:"closed",ORDER_CANCELLED:"canceled"},e,e)}parseOrderType(e){return this.safeString({76:"limit",77:"market",80:"limit"},e,e)}parseTimeInForce(e){return this.safeString({GTC:"GTC",IOC:"IOC",FOK:"FOK",HALFSEC:"GTD",HALFMIN:"GTD",FIVEMIN:"GTD",HOUR:"GTD",TWELVEHOUR:"GTD",DAY:"GTD",WEEK:"GTD",MONTH:"GTD"},e,e)}async fetchTradingFees(e={}){let t;await this.loadMarkets();let[i,s]=this.handleMarketTypeAndParams("fetchTradingFees",void 0,e,"spot");t="spot"===i?await this.privateGetSpotApiV4TradeFees(s):await this.privateGetFuturesApiV23UserFees(s);let r=this.safeList(t,"data",t),a=this.arrayConcat([],r),o={};for(let e=0;e<a.length;e++){let t=a[e],i=this.safeString(t,"symbol"),s=this.safeMarket(i).symbol,r=this.safeNumber(t,"makerFee"),n=this.safeNumber(t,"takerFee");o[s]={info:t,symbol:s,maker:r,taker:n,percentage:!0,tierBased:!0}}return o}async requestWalletHistoryRows(e,t,i,s,a,o={}){let n,d=this.safeList({types:t},"types",[]);await this.loadMarkets();let h=this.safeString(o,"walletType","SPOT"),c={walletType:h};c.historyTypes=this.json(d);let l=this.omit(o,"walletType");if(void 0!==i)c.asset=(n=this.currency(i)).id;else if("SPOT"===h)throw new r.ArgumentsRequired(this.id+" "+e+"() requires a code argument for the spot wallet history");void 0!==s&&(c.startTime=s),void 0!==a&&(c.pageSize=a);let[u,f]=this.handleOptionIntegerAndParams(l,e,"until");void 0!==u&&(c.endTime=u);let p=await this.privateGetPublicApiWalletV1UserWalletHistory(this.extend(c,f)),m=this.safeList(p,"data",p),g={};for(let e=0;e<d.length;e++){let t=d[e];g[t]=!0,g[this.capitalize(t.toLowerCase())]=!0}let v=[];for(let e=0;e<m.length;e++){let t=m[e];this.safeString(t,"type","")in g&&v.push(t)}return[v,n]}async fetchDepositsWithdrawals(e,t,i,s={}){let[r,a]=await this.requestWalletHistoryRows("fetchDepositsWithdrawals",["DEPOSIT","WITHDRAW"],e,t,i,s);return this.parseTransactions(r,a,t,i)}async fetchDeposits(e,t,i,s={}){let[r,a]=await this.requestWalletHistoryRows("fetchDeposits",["DEPOSIT"],e,t,i,s);return this.parseTransactions(r,a,t,i)}async fetchWithdrawals(e,t,i,s={}){let[r,a]=await this.requestWalletHistoryRows("fetchWithdrawals",["WITHDRAW"],e,t,i,s);return this.parseTransactions(r,a,t,i)}parseTransaction(e,t){let i=this.safeString2(e,"currency","asset"),s=this.safeCurrencyCode(i,t),r=this.safeInteger2(e,"timestamp","transactionTime"),a=this.safeString2(e,"currencyNetwork","cryptoNetwork");return{info:e,id:this.safeString2(e,"orderId","transactionRef"),txid:this.safeString(e,"txId"),timestamp:r,datetime:this.iso8601(r),network:this.networkIdToCode(a,s),address:this.safeString(e,"toAddress"),addressTo:this.safeString(e,"toAddress"),addressFrom:void 0,tag:void 0,tagTo:void 0,tagFrom:void 0,type:this.parseTransactionType(this.safeString(e,"type")),amount:this.safeNumber(e,"amount"),currency:s,status:this.parseTransactionStatus(this.safeString(e,"status")),updated:void 0,internal:void 0,comment:this.safeString(e,"description"),fee:{currency:s,cost:this.safeNumber2(e,"fees","fee")}}}parseTransactionType(e){return this.safeString({Deposit:"deposit",Withdraw:"withdrawal",DEPOSIT:"deposit",WITHDRAW:"withdrawal"},e,e)}parseTransactionStatus(e){return this.safeString({PROCESSING:"pending",PENDING:"pending",COMPLETED:"ok",CANCELLED:"canceled",EXPIRED:"canceled",FAILURE:"failed"},e,e)}async fetchLedger(e,t,i,s={}){let a;await this.loadMarkets();let o={},n=this.safeString(s,"walletType","SPOT");o.walletType=n;let d=this.omit(s,"walletType");if(void 0!==e)o.asset=(a=this.currency(e)).id;else if("SPOT"===n)throw new r.ArgumentsRequired(this.id+" fetchLedger() requires a code argument for the spot wallet history");void 0!==t&&(o.startTime=t),void 0!==i&&(o.pageSize=i);let[h,c]=this.handleOptionIntegerAndParams(d,"fetchLedger","until");void 0!==h&&(o.endTime=h);let l=await this.privateGetPublicApiWalletV1UserWalletHistory(this.extend(o,c)),u=this.safeList(l,"data",l);return this.parseLedger(u,a,t,i)}parseLedgerEntry(e,t){let i=this.safeString2(e,"currency","asset"),s=this.safeCurrencyCode(i,t),r=this.safeInteger2(e,"timestamp","transactionTime"),a=this.safeString(e,"type");return{info:e,id:this.safeString2(e,"orderId","transactionRef"),timestamp:r,datetime:this.iso8601(r),direction:this.parseLedgerEntryDirection(a),account:this.safeString2(e,"wallet","walletName"),referenceId:this.safeString(e,"txId"),referenceAccount:void 0,type:this.parseLedgerEntryType(a),currency:s,amount:this.safeNumber(e,"amount"),before:void 0,after:void 0,status:this.parseTransactionStatus(this.safeString(e,"status")),fee:{currency:s,cost:this.safeNumber2(e,"fees","fee")}}}parseLedgerEntryType(e){return this.safeString({Deposit:"transaction",Withdraw:"transaction","Convert fiat":"trade",Transfer_Out:"transfer",Transfer_In:"transfer",ReferralEarning:"referral","Sub Account Transfer In":"transfer","Sub Account Transfer Out":"transfer","express buy":"trade","spot trading fee rebate":"rebate","futures trading fee rebate":"rebate","general trading fee rebate":"rebate",DEPOSIT:"transaction",WITHDRAW:"transaction",CONVERT:"trade",ASSET_CONVERSION:"trade",SEND:"transfer",RECEIVE:"transfer",REFERRAL:"referral",TRANSFER_IN:"transfer",TRANSFER_OUT:"transfer",SUB_ACCOUNT_TRANSFER_IN:"transfer",SUB_ACCOUNT_TRANSFER_OUT:"transfer",REALIZED_PNL:"trade",FUNDING:"fee"},e,e)}parseLedgerEntryDirection(e){return this.safeString({Deposit:"in",Withdraw:"out",Transfer_Out:"out",Transfer_In:"in",ReferralEarning:"in","Sub Account Transfer In":"in","Sub Account Transfer Out":"out","spot trading fee rebate":"in","futures trading fee rebate":"in","general trading fee rebate":"in","trial fund":"in","token voucher in":"in","token voucher out":"out","Strategy Income":"in","Strategy Pay":"out",DEPOSIT:"in",WITHDRAW:"out",RECEIVE:"in",SEND:"out",REFERRAL:"in",GET_PAID:"in",PAID:"out",TRANSFER_IN:"in",TRANSFER_OUT:"out",SUB_ACCOUNT_TRANSFER_IN:"in",SUB_ACCOUNT_TRANSFER_OUT:"out",INVEST:"out",REDEEM:"in"},e)}async fetchTradingFee(e,t={}){let i;await this.loadMarkets();let s=this.market(e),r={symbol:s.id};i=!0===s.spot?await this.privateGetSpotApiV4TradeFees(this.extend(r,t)):await this.privateGetFuturesApiV23UserFees(this.extend(r,t));let a=this.safeList(i,"data",i),o=this.safeDict(a,0,{}),n=this.safeNumber(o,"makerFee"),d=this.safeNumber(o,"takerFee");return{info:o,symbol:e,maker:n,taker:d,percentage:!0,tierBased:!0}}async fetchPositions(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e),s=await this.privateGetFuturesApiV3TradePositions(t),r=this.safeList(s,"data");return void 0===r&&(r=s),this.parsePositions(r,i)}async fetchPositionsForSymbol(e,t={}){await this.loadMarkets();let i=this.market(e),s=this.extend({symbol:this.futuresRequestId(i)},t);return await this.fetchPositions([e],s)}parsePosition(e,t){let i=this.safeString(e,"positionId");if(void 0!==i){let e=i.split("|");i=this.safeString(e,0)}else i=this.safeString(e,"symbol");let s=this.safeMarket(i,t),r=this.safeInteger(e,"timestamp"),a=this.safeString(e,"marginType"),o=this.safeStringLower2(e,"positionDirection","side"),n=this.safeString(e,"positionMode"),d=this.safeDict(e,"takeProfitOrder",{}),h=this.safeString(d,"triggerPrice"),c=this.safeDict(e,"stopLossOrder",{}),l=this.safeString(c,"triggerPrice");return this.safePosition({info:e,id:this.safeString(e,"positionId"),symbol:s.symbol,entryPrice:this.parseNumber(this.safeString(e,"entryPrice")),markPrice:this.parseNumber(this.safeString(e,"markPrice")),lastPrice:void 0,takeProfitPrice:this.parseNumber(h),stopLossPrice:this.parseNumber(l),notional:this.parseNumber(this.safeString2(e,"notionalValue","orderValue")),collateral:void 0,unrealizedPnl:this.parseNumber(this.safeString(e,"unrealizedProfitLoss")),realizedPnl:void 0,side:this.parsePositionSide(o),contracts:this.parseNumber(this.safeString(e,"size")),contractSize:this.parseNumber(this.safeString(e,"contractSize")),timestamp:r,datetime:this.iso8601(r),lastUpdateTimestamp:void 0,hedged:"HEDGE"===n||"ISOLATED"===n,maintenanceMargin:this.parseNumber(this.safeString(e,"totalMaintenanceMargin")),maintenanceMarginPercentage:void 0,initialMargin:void 0,initialMarginPercentage:void 0,leverage:this.parseNumber(this.safeString(e,"currentLeverage")),liquidationPrice:this.parseNumber(this.safeString(e,"liquidationPrice")),marginRatio:void 0,marginMode:this.parseMarginModeType(a),percentage:void 0})}parseMarginModeType(e){return this.safeString({91:"cross",92:"isolated",CROSS:"cross",ISOLATED:"isolated"},e,e)}parsePositionSide(e){return this.safeString({buy:"long",sell:"short"},e,e)}async fetchPositionMode(e,t={}){if(void 0===e)throw new r.ArgumentsRequired(this.id+" fetchPositionMode() requires a symbol argument");await this.loadMarkets();let i=this.market(e),s={symbol:this.futuresRequestId(i)},a=await this.privateGetFuturesApiV3TradePositionMode(this.extend(s,t)),o=this.safeDict(a,0,{}),n=this.safeString(o,"positionMode");return{info:o,hedged:"HEDGE"===n||"ISOLATED"===n}}async setPositionMode(e,t,i={}){if(void 0===t)throw new r.ArgumentsRequired(this.id+" setPositionMode() requires a symbol argument");await this.loadMarkets();let s=this.market(t),a="ONE_WAY";e&&(a="HEDGE");let o={symbol:this.futuresRequestId(s),positionMode:a};return await this.privatePostFuturesApiV3TradePositionMode(this.extend(o,i))}async fetchMarginMode(e,t={}){await this.loadMarkets();let i=this.market(e),s={symbol:this.futuresRequestId(i)},r=await this.privateGetFuturesApiV3TradeLeverage(this.extend(s,t)),a=this.safeDict(r,0,{});return this.parseMarginMode(a,i)}parseMarginMode(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeStringLower(e,"marginMode"),a="cross";return"isolated"===r&&(a="isolated"),{info:e,symbol:s.symbol,marginMode:a}}async setMarginMode(e,t,i={}){if(void 0===t)throw new r.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");await this.loadMarkets();let s=this.market(t),a=e.toLowerCase(),o="ONE_WAY";if("cross"!==a&&"isolated"!==a)throw new r.BadRequest(this.id+" setMarginMode() marginMode argument should be either cross or isolated");let n=this.safeBool(i,"hedged");if("cross"===a)if("hedged"in i)!0===n&&(o="HEDGE");else throw new r.ArgumentsRequired(this.id+" setMarginMode() requires a hedged parameter for cross margin mode");else if("hedged"in i&&!0!==n)throw new r.BadRequest(this.id+" setMarginMode() hedged parameter cannot be false for isolated margin mode");else o="ISOLATED";let d=this.omit(i,"hedged"),h={symbol:this.futuresRequestId(s),positionMode:o};return await this.privatePostFuturesApiV3TradePositionMode(this.extend(h,d))}async closePosition(e,t,i={}){await this.loadMarkets();let s=this.market(e);if(void 0===this.safeString(i,"positionId"))throw new r.ArgumentsRequired(this.id+" closePosition() requires a positionId parameter");let a={symbol:this.futuresRequestId(s)},[o,n]=this.handleOptionStringAndParams(i,"closePosition","type","market"),d=o.toUpperCase();if(a.orderType=d,"LIMIT"===d){let t=this.safeString(n,"price");if(void 0===t)throw new r.ArgumentsRequired(this.id+" closePosition() requires a price parameter for limit orders");a.orderPrice=this.priceToPrecision(e,t)}let h="LIMIT"===d?this.omit(n,"price"):n,c=await this.privateDeleteFuturesApiV3TradePositions(this.extend(a,h)),l=this.safeDict(c,0);return void 0===l&&(l=c),this.parseOrder(l,s)}async fetchLeverage(e,t={}){let i,s,r;await this.loadMarkets();let a=this.market(e),o={symbol:this.futuresRequestId(a)},n=await this.privateGetFuturesApiV3TradeLeverage(this.extend(o,t)),d=[];Array.isArray(n)&&(d=n);let h={info:n,symbol:e};for(let e=0;e<d.length;e++){let t=this.safeDict(d,e),a=this.safeInteger(t,"leverage"),o=this.safeString(t,"positionDirection");r=this.safeStringLower(t,"marginMode"),"LONG"===o?i=a:"SHORT"===o?s=a:void 0===o&&(i=a,s=a)}return h.marginMode=r,h.longLeverage=i,h.shortLeverage=s,h}async setLeverage(e,t,i={}){if(void 0===t)throw new r.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");await this.loadMarkets();let s=this.market(t),a={symbol:this.futuresRequestId(s),leverage:e},[o,n]=this.handleMarginModeAndParams("setLeverage",i);return void 0!==o&&(a.marginMode=o.toUpperCase()),await this.privatePostFuturesApiV3TradeLeverage(this.extend(a,n))}handleErrors(e,t,i,s,a,o,n,d,h){if(null==n)return;if(!0!==this.safeBool(n,"success",!0)){let e=this.safeString(n,"code"),t=this.safeString(n,"msg"),i=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,e,i),this.throwBroadlyMatchedException(this.exceptions.broad,t,i),new r.ExchangeError(i)}let c=this.safeString(n,"errorCode");if(void 0!==c){let e=this.safeString(n,"message"),t=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,c,t),this.throwBroadlyMatchedException(this.exceptions.broad,e,t),new r.ExchangeError(t)}let l=this.safeString(n,"error"),u=this.safeString(n,"code");if(void 0!==l&&void 0!==u){let e=this.safeString(n,"message"),t=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,u,t),this.throwBroadlyMatchedException(this.exceptions.broad,e,t),new r.ExchangeError(t)}let f=[];f=Array.isArray(n)?n:[n];for(let e=0;e<f.length;e++){let t=this.safeDict(f,e),i=this.safeString(t,"status");if(void 0!==i){let e=this.safeString(t,"message"),s=this.parseJson(e);void 0!==s&&(e=this.safeString(s,"default_msg",e));let r=this.id+" "+o;this.throwExactlyMatchedException(this.exceptions.exact,i,r),this.throwBroadlyMatchedException(this.exceptions.broad,e,r)}}}sign(e,t="public",i="GET",s={},o,n){let d,h,c=this.safeString(this.urls.api,t);if(void 0===c)throw new r.ExchangeError(this.id+" sign() has no API URL for this endpoint");let l=c+"/"+this.implodeParams(e,s),u=this.omit(s,this.extractParams(e)),f="DELETE"===i&&!0===e.startsWith("futures/api/v3/");if(("GET"===i||"DELETE"===i)&&!f&&Object.keys(u).length>0&&(l+="?"+this.urlencode(u)),"private"===t){this.checkRequiredCredentials();let t=this.nonce(),s=this.json(u);"GET"!==i&&"DELETE"!==i||f?d=s:s="";let r=(!0===e.startsWith("public-api/")?"/"+e:this.cleanPath(e))+t.toString()+s,o=this.hmac(this.encode(r),this.encode(this.secret),a.qt);h={"request-api":this.apiKey,"request-nonce":t.toString(),"request-sign":o,"Content-Type":"application/json","BROKER-ID":"ccxt"}}return{url:l,method:i,body:void 0===d?n:d,headers:void 0===h?o:h}}futuresRequestId(e){return this.safeString(e.info,"tradeCurrency",e.id)}cleanPath(e){let t=e.replace("spot","");return(t=t.replace("futures","")).replace("otc","")}nonce(){return this.milliseconds()-this.safeInteger(this.options,"timeDifference",0)}}i.d(t,{A:()=>n})},3935(e,t,i){"use strict";var s=i(4721),r=i(9156),a=i(1453);class o extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bullish",name:"Bullish",countries:["DE"],version:"v3",rateLimit:20,pro:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!0,future:!0,option:!0,addMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!1,createDepositAddress:!1,createLimitBuyOrder:!0,createLimitOrder:!0,createLimitSellOrder:!0,createMarketBuyOrder:!0,createMarketOrder:!0,createMarketSellOrder:!0,createOrder:!0,createPostOnlyOrder:!0,createTriggerOrder:!0,deposit:!1,editOrder:!0,fetchAccounts:!0,fetchBalance:!0,fetchBidsAsks:!1,fetchBorrowInterest:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!0,fetchCanceledAndClosedOrders:!0,fetchCanceledOrders:!0,fetchClosedOrder:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:!1,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!1,fetchDepositsWithdrawals:!0,fetchDepositWithdrawFee:!1,fetchDepositWithdrawFees:!1,fetchFundingHistory:!1,fetchFundingRate:!1,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchL3OrderBook:!1,fetchLedger:!1,fetchLeverage:!1,fetchLeverageTiers:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrder:!1,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrders:!0,fetchOrderTrades:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchStatus:!1,fetchTicker:!0,fetchTickers:!1,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTradingLimits:!1,fetchTransactionFee:!1,fetchTransactionFees:!1,fetchTransactions:!1,fetchTransfers:!0,fetchWithdrawal:!1,fetchWithdrawals:!1,fetchWithdrawalWhitelist:!1,reduceMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,signIn:!0,transfer:!0,withdraw:!0,ws:!0},timeframes:{"1m":"1m","5m":"5m","30m":"30m","1h":"1h","6h":"6h","12h":"12h","1d":"1d"},urls:{logo:"https://github.com/user-attachments/assets/68f0686b-84f0-4da9-a751-f7089af3a9ed",api:{public:"https://api.exchange.bullish.com/trading-api",private:"https://api.exchange.bullish.com/trading-api"},test:{public:"https://api.simnext.bullish-test.com/trading-api",private:"https://api.simnext.bullish-test.com/trading-api"},www:"https://bullish.com/",referral:"",doc:["https://api.exchange.bullish.com/docs/api/rest/"]},api:{public:{get:{"v1/nonce":{cost:1},"v1/time":{cost:1},"v1/assets":{cost:1},"v1/assets/{symbol}":{cost:1},"v1/vol-grids":{cost:1},"v1/assets/{symbol}/vol-grid":{cost:1},"v1/markets":{cost:1},"v1/markets/{symbol}":{cost:1},"v1/history/markets":{cost:1},"v1/history/markets/{symbol}":{cost:1},"v1/markets/{symbol}/orderbook/hybrid":{cost:1},"v1/markets/{symbol}/trades":{cost:1},"v1/markets/{symbol}/tick":{cost:1},"v1/markets/{symbol}/candle":{cost:1},"v1/markets/{symbol}/auctions":{cost:1},"v1/markets/{symbol}/auctions/noii":{cost:1},"v1/history/markets/{symbol}/trades":{cost:1},"v1/history/markets/{symbol}/funding-rate":{cost:1},"v1/history/markets/{symbol}/auctions":{cost:1},"v1/history/option-trades":{cost:1},"v1/index-prices":{cost:1},"v1/index-prices/{assetSymbol}":{cost:1},"v1/expiry-prices/{symbol}":{cost:1},"v1/option-ladder":{cost:1},"v1/option-ladder/{symbol}":{cost:1}}},private:{get:{"v2/orders":{cost:1},"v2/history/orders":{cost:1},"v2/orders/{orderId}":{cost:1},"v2/orders/client-order-id/{clientOrderId}":{cost:1},"v2/amm-instructions":{cost:1},"v2/amm-instructions/{instructionId}":{cost:1},"v1/wallets/transactions":{cost:1},"v1/wallets/limits/{symbol}":{cost:1},"v1/wallets/deposit-instructions/crypto/{symbol}":{cost:1},"v1/wallets/withdrawal-instructions/crypto/{symbol}":{cost:1},"v1/wallets/deposit-instructions/fiat/{symbol}":{cost:1},"v1/wallets/withdrawal-instructions/fiat/{symbol}":{cost:1},"v1/wallets/self-hosted/verification-attempts":{cost:1},"v1/trades":{cost:5},"v1/history/trades":{cost:5},"v1/trades/{tradeId}":{cost:5},"v1/trades/client-order-id/{clientOrderId}":{cost:1},"v1/accounts/asset":{cost:1},"v1/accounts/asset/{symbol}":{cost:1},"v1/users/logout":{cost:1},"v1/users/hmac/login":{cost:1},"v1/accounts/trading-accounts":{cost:1},"v1/accounts/trading-accounts/{tradingAccountId}":{cost:1},"v1/derivatives-positions":{cost:1},"v1/history/derivatives-settlement":{cost:1},"v1/history/transfer":{cost:1},"v1/history/borrow-interest":{cost:1},"v2/mmp-configuration":{cost:1},"v2/otc-trades":{cost:1},"v2/otc-trades/{otcTradeId}":{cost:1},"v2/otc-trades/unconfirmed-trade":{cost:1},"v2/otc-trades/delegated-accounts":{cost:1},"v2/idb/delegated-accounts":{cost:1},"v2/idb/otc-trades":{cost:1}},post:{"v2/orders":{cost:5},"v2/command":{cost:5},"v2/amm-instructions":{cost:1},"v1/wallets/withdrawal":{cost:1},"v2/users/login":{cost:1},"v1/simulate-portfolio-margin":{cost:1},"v1/bulk-simulate-portfolio-margin":{cost:1},"v1/wallets/self-hosted/initiate":{cost:1},"v2/mmp-configuration":{cost:1},"v2/otc-trades":{cost:1},"v2/otc-command":{cost:1},"v2/idb/otc-trades":{cost:1},"v2/idb/otc-command":{cost:1}}}},fees:{trading:{tierBased:!1,percentage:!0,taker:this.parseNumber("0.001"),maker:this.parseNumber("0.001")}},precisionMode:4,options:{timeDifference:0,adjustForTimeDifference:!1,networks:{BTC:"BTC",EOS:"EOS",ERC20:"ETH"},defaultNetwork:"ERC20",defaultNetworks:{USDC:"ERC20"},tradingAccountId:void 0},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:90,symbolRequired:!1,untilDays:90},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:100,daysBack:90,untilDays:90,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:100,daysBack:90,untilDays:90,trigger:!1,trailing:!1,symbolRequired:!1},fetchCanceledAndClosedOrders:{marginMode:!1,limit:100,daysBack:90,untilDays:90,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:100,daysBack:1,daysBackCanceled:1,untilDays:1,trigger:!1,trailing:!1,symbolRequired:!1},fetchCanceledOrders:{marginMode:!1,limit:100,daysBack:1,untilDays:1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:1e3}},spot:{extends:"default"},swap:{linear:{extends:"default"},inverse:void 0},future:{linear:{extends:"default"},inverse:void 0}},exceptions:{exact:{1:a.BadRequest,5:a.InvalidOrder,6:a.DuplicateOrderId,13:a.BadRequest,15:a.BadRequest,18:a.BadRequest,1002:a.BadRequest,2001:a.BadRequest,2002:a.BadRequest,2003:a.BadRequest,2004:a.BadRequest,2005:a.ExchangeError,2006:a.BadRequest,2007:a.BadRequest,2008:a.BadRequest,2009:a.BadSymbol,2010:a.AuthenticationError,2011:a.AuthenticationError,2012:a.BadRequest,2013:a.InvalidOrder,2015:a.OperationRejected,2016:a.BadRequest,2017:a.BadRequest,2018:a.BadRequest,2020:a.PermissionDenied,2021:a.OperationRejected,2029:a.InvalidNonce,2035:a.InvalidNonce,3001:a.InsufficientFunds,3002:a.OrderNotFound,3003:a.PermissionDenied,3004:a.InsufficientFunds,3005:a.InsufficientFunds,3006:a.InsufficientFunds,3007:a.DuplicateOrderId,3031:a.BadRequest,3032:a.BadRequest,3033:a.PermissionDenied,3034:a.RateLimitExceeded,3035:a.RateLimitExceeded,3047:a.OperationRejected,3048:a.OperationRejected,3049:a.OperationRejected,3051:a.InsufficientFunds,3052:a.InsufficientFunds,3063:a.BadRequest,3064:a.OrderNotFillable,3065:a.MarketClosed,3066:a.ExchangeError,3067:a.MarketClosed,6007:a.InvalidOrder,6011:a.InvalidOrder,6012:a.InvalidOrder,6013:a.InvalidOrder,8301:a.ExchangeError,8305:a.ExchangeError,8306:a.ExchangeError,8307:a.ExchangeError,8310:a.InvalidAddress,8311:a.BadRequest,8313:a.BadRequest,8315:a.OperationRejected,8316:a.OperationRejected,8317:a.OperationRejected,8318:a.NotSupported,8319:a.NotSupported,8320:a.InvalidAddress,8322:a.BadRequest,8327:a.AuthenticationError,8329:a.ExchangeError,8331:a.InvalidAddress,8332:a.BadRequest,8333:a.BadRequest,8334:a.BadRequest,8335:a.InvalidAddress,8336:a.InvalidAddress,8399:a.ExchangeError},broad:{HttpInvalidParameterException:a.BadRequest,UNAUTHORIZED_COMMAND:a.AuthenticationError,QUERY_FILTER_ERROR:a.BadRequest,INVALID_SYMBOL:a.BadSymbol}}})}async fetchTime(e={}){let t=await this.publicGetV1Time(e);return this.safeInteger(t,"timestamp")}async fetchCurrencies(e={}){let t=await this.publicGetV1Assets(e);return this.parseCurrencies(t)}parseCurrency(e){let t=this.safeString(e,"symbol"),i=this.safeCurrencyCode(t),s=this.safeString(e,"name"),r=this.safeString(e,"precision");return this.safeCurrencyStructure({id:t,code:i,name:s,active:void 0,deposit:void 0,withdraw:void 0,fee:this.safeNumber(e,"minFee"),precision:this.parseNumber(this.parsePrecision(r)),limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}},networks:{},type:"crypto",info:e})}async fetchMarkets(e={}){this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference();let t=await this.publicGetV1Markets(e);return this.parseMarkets(t)}parseMarket(e){let t,i,s,r,a,o,n=this.safeString(e,"symbol"),d=this.safeString(e,"baseSymbol"),h=this.safeString(e,"quoteSymbol"),c=this.safeCurrencyCode(d),l=this.safeCurrencyCode(h);if(void 0===c||void 0===l)return;let u=c+"/"+l,f=this.safeString(e,"basePrecision"),p=this.safeString(e,"quotePrecision"),m=this.safeString(e,"quantityPrecision"),g=this.safeString(e,"pricePrecision"),v=this.safeString(e,"costPrecision"),y=this.safeString(e,"minQuantityLimit"),b=this.safeString(e,"maxQuantityLimit"),w=this.safeString(e,"minPriceLimit"),k=this.safeString(e,"maxPriceLimit"),S=this.safeString(e,"minCostLimit"),O=this.safeString(e,"maxCostLimit"),T=this.safeString(e,"settlementAssetSymbol"),P=this.safeCurrencyCode(T),I=this.parseMarketType(this.safeString(e,"marketType"),"spot"),A=!1,x=!1,M=!1,_=!1,C=!0,B=!1;if("spot"===I)A=!0,C=!1,B=this.safeBool(e,"marginTradingEnabled");else if(r=this.safeNumber(e,"contractMultiplier"),u+=":"+P,i=!(t=P===l),"swap"===I)x=!0;else{s=this.safeString(e,"expiryDatetime");let t=n.split("-");u+="-"+this.safeString(t,2).slice(2),"future"===I?M=!0:"option"===I&&(_=!0,a=this.safeStringLower(e,"optionType"),o=this.parseToNumeric(this.safeString(e,"optionStrikePrice")),u+="-"+this.numberToString(o)+"-"+this.safeString(t,4))}return this.safeMarketStructure({id:n,symbol:u,base:c,baseId:d,quote:l,quoteId:h,settle:P,settleId:T,type:I,spot:A,margin:B,swap:x,future:M,option:_,contract:C,linear:t,inverse:i,taker:this.fees.trading.taker,maker:this.fees.trading.maker,contractSize:r,expiry:this.parse8601(s),expiryDatetime:s,strike:o,optionType:a,limits:{amount:{min:this.parseNumber(y),max:this.parseNumber(b)},price:{min:this.parseNumber(w),max:this.parseNumber(k)},cost:{min:this.parseNumber(S),max:this.parseNumber(O)},leverage:{min:void 0,max:void 0}},precision:{amount:this.parseNumber(this.parsePrecision(m)),price:this.parseNumber(this.parsePrecision(g)),cost:this.parseNumber(this.parsePrecision(v)),base:this.parseNumber(this.parsePrecision(f)),quote:this.parseNumber(this.parsePrecision(p))},active:this.safeBool(e,"marketEnabled"),created:void 0,info:e})}parseMarketType(e,t){return this.safeString({SPOT:"spot",PERPETUAL:"swap",DATED_FUTURE:"future",OPTION:"option"},e,t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={symbol:this.market(e).id},r=await this.publicGetV1MarketsSymbolOrderbookHybrid(this.extend(s,i)),a=this.safeInteger(r,"timestamp");return this.parseOrderBook(r,e,a,"bids","asks","price","priceLevelQuantity")}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchTrades","paginate",!1);if(r){let s=this.handlePaginationParams("fetchTrades",t,a);return await this.fetchPaginatedCallDynamic("fetchTrades",e,t,i,s,100)}let o=this.market(e),n={symbol:o.id},d=this.handleSinceAndUntil(t,a);void 0!==i&&(n._pageSize=this.getClosestLimit(i));let h=await this.publicGetV1HistoryMarketsSymbolTrades(this.extend(n,d));return this.parseTrades(h,o,t,i)}async fetchMyTrades(e,t,i,s={}){let r,a;await Promise.all([this.loadMarkets(),this.handleToken()]);let o={tradingAccountId:await this.loadAccount(s)};if(void 0!==e&&(o.symbol=(a=this.market(e)).id),void 0!==this.safeString(s,"clientOrderId"))r=await this.privateGetV1TradesClientOrderIdClientOrderId(this.extend(o,s));else{let[a,n]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(a){let s=this.handlePaginationParams("fetchMyTrades",t,n);return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,s,100)}let d=this.handleSinceAndUntil(t,n);void 0!==i&&(o._pageSize=this.getClosestLimit(i)),r=await this.privateGetV1HistoryTrades(this.extend(o,d))}return this.parseTrades(r,a,t,i)}async fetchOrderTrades(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.safeString(r,"clientOrderId"),o=r;return void 0===a&&(o=this.extend({orderId:e},r)),await this.fetchMyTrades(t,i,s,o)}parseTrade(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=r.symbol,o=this.safeInteger(e,"createdAtTimestamp"),n=this.safeString(e,"price"),d=this.safeString(e,"quantity"),h=this.safeStringLower(e,"side"),c=this.safeBool(e,"isTaker"),l=r.quote,u=this.safeCurrencyCode(l),f=this.safeNumber(e,"quoteFee");void 0!==f&&(i={currency:u,cost:f});let p=this.safeString(e,"orderId");return this.safeTrade({info:e,timestamp:o,datetime:this.iso8601(o),symbol:a,id:this.safeString(e,"tradeId"),order:p,type:void 0,takerOrMaker:!0===c?"taker":"maker",side:h,price:n,amount:d,cost:void 0,fee:i},r)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetV1MarketsSymbolTick(this.extend(s,t));return this.parseTicker(r,i)}parseTicker(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeInteger(e,"createdAtTimestamp");return this.safeTicker({symbol:s.symbol,timestamp:r,datetime:this.iso8601(r),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString2(e,"bid","bestBid"),bidVolume:this.safeString(e,"bidVolume"),ask:this.safeString2(e,"ask","bestAsk"),askVolume:this.safeString(e,"askVolume"),vwap:this.safeString(e,"vwap"),open:this.safeString(e,"open"),close:this.safeString(e,"close"),last:this.safeString(e,"last"),previousClose:void 0,change:this.safeString(e,"change"),percentage:this.safeString(e,"percentage"),average:this.safeString(e,"average"),baseVolume:this.safeString(e,"baseVolume"),quoteVolume:this.safeString(e,"quoteVolume"),markPrice:this.safeString(e,"markPrice"),info:e},s)}async safeDeterministicCall(e,t,i,s,r,o={}){let[n,d]=this.handleOptionIntegerAndParams(o,e,"maxRetries",3);if("fetchOHLCV"!==e&&"fetchFundingRateHistory"!==e&&"fetchTrades"!==e)throw new a.NotSupported(this.id+" safeDeterministicCall() does not support the "+e+" method");let h=0,c=this.omit(d,"until");for(;h<=n;)try{if("fetchOHLCV"===e)return await this.fetchOHLCV(t,r,i,s,c);if("fetchFundingRateHistory"===e)return await this.fetchFundingRateHistory(t,i,s,c);return await this.fetchTrades(t,i,s,c)}catch(e){if(e instanceof a.RateLimitExceeded||(h+=1)>n)throw e}return[]}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),[o,n]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(o)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,n,100);let d={symbol:a.id,timeBucket:this.safeString(this.timeframes,t,t),_pageSize:100},[h,c]=this.handleUntilOption("createdAtDatetime[lte]",d,n),l=this.safeInteger(h,"createdAtDatetime[lte]"),u=1e3*this.parseTimeframe(t)*100,f=i;void 0===f&&void 0===l?f=(l=this.milliseconds())-u:void 0===f?f=l-u:void 0===l&&(l=this.sum(f,u)),h["createdAtDatetime[gte]"]=this.iso8601(f),h["createdAtDatetime[lte]"]=this.iso8601(l);let p=await this.publicGetV1MarketsSymbolCandle(this.extend(h,c)),m=this.toArray(p);return this.parseOHLCVs(m,a,t,i,s)}parseOHLCV(e,t){return[this.safeInteger(e,"createdAtTimestamp"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let[r,o]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(r){let s=this.handlePaginationParams("fetchFundingRateHistory",t,o);return await this.fetchPaginatedCallDynamic("fetchFundingRateHistory",e,t,i,s,100)}let n=this.market(e);if(!0!==n.swap)throw new a.BadRequest(this.id+" fetchFundingRateHistory() supports swap markets only");let d={symbol:n.id};void 0!==i&&(d._pageSize=this.getClosestLimit(i));let h=this.handleSinceAndUntil(t,o,"updatedAtDatetime[gte]","updatedAtDatetime[lte]"),c=await this.publicGetV1HistoryMarketsSymbolFundingRate(this.extend(d,h)),l=[],u=this.toArray(c);for(let t=0;t<u.length;t++){let i=u[t],s=this.safeString(i,"updatedAtDatetime");l.push({info:i,symbol:e,fundingRate:this.safeNumber(i,"fundingRate"),timestamp:this.parse8601(s),datetime:s})}let f=this.sortBy(l,"timestamp");return this.filterBySymbolSinceLimit(f,this.safeString(n,"symbol"),t,i)}async fetchOrders(e,t,i,s={}){let r,o;await Promise.all([this.loadMarkets(),this.handleToken()]);let n=await this.loadAccount(s);if(!0===this.safeBool(s,"paginate",!1)){let r=this.handlePaginationParams("fetchOrders",t,s);return await this.fetchPaginatedCallDynamic("fetchOrders",e,t,i,r,100)}let d={tradingAccountId:n};void 0!==e&&(d.symbol=(r=this.market(e)).id);let h=this.handleSinceAndUntil(t,s);void 0!==i&&(d._pageSize=this.getClosestLimit(i));let c="privateGetV2HistoryOrders";[c,o]=this.handleOptionStringAndParams(h,"fetchOrders","method",c);let l=[];if("privateGetV2Orders"===c)l=await this.privateGetV2Orders(this.extend(d,o));else if("privateGetV2HistoryOrders"===c)l=await this.privateGetV2HistoryOrders(this.extend(d,o));else throw new a.BadRequest(this.id+' fetchOrders() method parameter must be either "privateGetV2Orders" or "privateGetV2HistoryOrders"');return this.parseOrders(l,r,t,i)}handlePaginationParams(e,t,i={}){let s=this.milliseconds(),r=s-7776e6;if(void 0!==t&&t<r)throw new a.BadRequest(this.id+" "+e+"() only allows fetching entries up to 90 days in the past");let o=this.omit(i,"paginate"),n=this.extend(o,{paginationDirection:"backward"});return void 0===this.safeInteger(n,"until")?this.extend(n,{until:s}):n}handleSinceAndUntil(e,t={},i="createdAtDatetime[gte]",s="createdAtDatetime[lte]"){let r=this.safeInteger(t,"until"),a=t;if(void 0===e&&void 0!==r&&(a=this.omit(t,"until")),void 0!==e||void 0!==r){let t=e;if(void 0===e&&(t=r-6048e5),void 0!==e&&void 0===r){r=this.sum(e,6048e5);let t=this.milliseconds();r>t&&(r=t)}let o=this.iso8601(t),n=this.iso8601(r);a[i]=o,a[s]=n}return a}getClosestLimit(e){let t=5;return e>5&&e<26?t=25:e>25&&e<51?t=50:e>50&&(t=100),t}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({status:"OPEN"},s))}async fetchCanceledOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({status:"CANCELLED",method:"privateGetV2Orders"},s))}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({status:"CLOSED",method:"privateGetV2Orders"},s))}async fetchCanceledAndClosedOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({status:"CLOSED",method:"privateGetV2HistoryOrders"},s))}async fetchOrder(e,t,i={}){let s;await Promise.all([this.loadMarkets(),this.handleToken()]);let r=await this.loadAccount(i);void 0!==t&&(s=this.market(t));let a=await this.privateGetV2OrdersOrderId(this.extend({orderId:e,tradingAccountId:r},i));return this.parseOrder(a,s)}async createOrder(e,t,i,s,r,o={}){await Promise.all([this.loadMarkets(),this.handleToken()]);let n=await this.loadAccount(o),d=this.market(e),h={commandType:"V3CreateOrder",symbol:d.id,side:i.toUpperCase(),quantity:this.amountToPrecision(e,s),tradingAccountId:n},c="market"===t||"MARKET"===t,[l,u]=this.handlePostOnly(c,"POST_ONLY"===t,o),f=t;l&&(f="POST_ONLY");let[p,m]=this.handleOptionStringAndParams(u,"createOrder","timeInForce","GTC");m.timeInForce=p.toUpperCase(),c||(h.price=this.priceToPrecision(e,r));let g=this.safeString(m,"triggerPrice");if(void 0!==g){if(c)throw new a.NotSupported(this.id+" createOrder() does not support market trigger orders");h.stopPrice=this.priceToPrecision(e,g),f="STOP_LIMIT"}let v=void 0!==g?this.omit(m,"triggerPrice"):m;h.type=f.toUpperCase();let y=await this.privatePostV2Orders(this.extend(h,v));return this.parseOrder(y,d)}async editOrder(e,t,i,s,r,a,o={}){await Promise.all([this.loadMarkets(),this.handleToken()]);let n=await this.loadAccount(o),d=this.market(t),h={commandType:"V1AmendOrder",symbol:d.id,tradingAccountId:n};void 0===this.safeString(o,"clientOrderId")&&(h.orderId=e),void 0!==i&&(h.type=i.toUpperCase());let c=this.safeBool(o,"postOnly",!1);!0===c&&(h.type="POST_ONLY"),void 0!==r&&(h.quantity=this.amountToPrecision(t,r)),void 0!==a&&(h.price=this.priceToPrecision(t,a));let l=!0===c?this.omit(o,"postOnly"):o,u=await this.privatePostV2Command(this.extend(h,l));return this.parseOrder(u,d)}async cancelOrder(e,t,i={}){await Promise.all([this.loadMarkets(),this.handleToken()]);let s=await this.loadAccount(i);if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");let r=this.market(t),o={symbol:r.id,tradingAccountId:s,commandType:this.safeString(i,"commandType","V3CancelOrder"),orderId:e},n=await this.privatePostV2Command(this.extend(o,i));return this.parseOrder(n,r)}async cancelAllOrders(e,t={}){let i;await Promise.all([this.loadMarkets(),this.handleToken()]);let s={tradingAccountId:await this.loadAccount(t)};void 0!==e?(s.symbol=(i=this.market(e)).id,s.commandType="V1CancelAllOrdersByMarket"):s.commandType="V1CancelAllOrders";let r=await this.privatePostV2Command(this.extend(s,t));return this.parseOrders([r],i)}parseOrder(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(void 0===t?i:void 0,t),r=this.safeSymbol(i,s),a=this.safeString(e,"orderId"),o=this.safeInteger(e,"createdAtTimestamp"),n=this.safeString(e,"type"),d=this.safeStringLower(e,"side"),h=this.safeString(e,"price"),c=this.safeString(e,"quantity"),l=this.safeString(e,"quantityFilled"),u=this.parseOrderStatus(this.safeString(e,"status"));"closed"===u&&"User cancelled"===this.safeString(e,"statusReason")&&(u="canceled");let f=this.safeString(e,"timeInForce"),p=this.safeString(e,"stopPrice"),m=this.safeString(e,"quoteAmount"),g={},v=this.safeNumber(e,"quoteFee");void 0!==v&&(g.cost=v,g.currency=s.quote);let y=this.safeString(e,"averageFillPrice");return this.safeOrder({id:a,clientOrderId:this.safeString(e,"clientOrderId"),timestamp:o,datetime:this.iso8601(o),lastTradeTimestamp:void 0,status:u,symbol:r,type:this.parseOrderType(n),timeInForce:f,postOnly:"POST_ONLY"===n,side:d,price:h,triggerPrice:p,amount:c,filled:l,remaining:void 0,cost:m,trades:void 0,fee:g,info:e,average:y},s)}parseOrderStatus(e){return this.safeString({OPEN:"open",CLOSED:"closed",CANCELLED:"canceled",REJECTED:"rejected"},e,e)}parseOrderType(e){return this.safeString({LMT:"limit",MKT:"market",POST_ONLY:"limit",STOP_LIMIT:"limit"},e,e)}async fetchDepositsWithdrawals(e,t,i,s={}){let r;await Promise.all([this.loadMarkets(),this.handleToken()]);let[a,o]=this.handleUntilOption("createdAtDatetime[lte]",{},s),n=this.safeInteger(a,"createdAtDatetime[lte]");void 0!==n&&(a["createdAtDatetime[lte]"]=this.iso8601(n)),void 0!==t&&(a["createdAtDatetime[gte]"]=this.iso8601(t));let d=await this.privateGetV1WalletsTransactions(this.extend(a,o)),h=this.safeList(d,"data",[]);return void 0!==e&&(r=this.currency(e)),this.parseTransactions(h,r,t,i)}async withdraw(e,t,i,s,r={}){await Promise.all([this.loadMarkets(),this.handleToken()]);let o=this.currency(e),n={command:{commandType:"V1Withdraw",destinationId:i,symbol:o.id,quantity:this.currencyToPrecision(e,t)}},[d,h]=this.handleNetworkCodeAndParams(r);if(void 0!==d)n.network=this.networkCodeToId(d,e);else throw new a.ArgumentsRequired(this.id+" withdraw() requires a network parameter");let c=await this.privatePostV1WalletsWithdrawal(this.extend(n,h));return this.parseTransaction(c,o)}parseTransaction(e,t){let i=this.safeString(e,"custodyTransactionId"),s=this.safeString(e,"direction"),r=this.parse8601(this.safeString(e,"createdAtDateTime")),a=this.parse8601(this.safeString(e,"updatedAtDateTime")),o=this.safeString(e,"network"),n=this.safeDict(e,"transactionDetails"),d=this.safeString(n,"blockchainTxId"),h=this.safeString(n,"address"),c=this.safeNumber(e,"quantity"),l=this.safeString(e,"symbol"),u=this.safeCurrencyCode(l,t),f=this.safeString(e,"status"),p=this.safeList(n,"sources",[]),m=this.safeDict(p,0,{}),g=this.safeString(m,"address"),v={currency:void 0,cost:void 0,rate:void 0},y=this.safeNumber(e,"fee");return void 0!==y&&(v.cost=y,v.currency=u),{id:i,txid:d,timestamp:r,datetime:this.iso8601(r),network:this.networkIdToCode(o,u),addressFrom:g,address:h,addressTo:h,amount:c,type:this.parseTransactionType(s),currency:u,status:this.parseTransactionStatus(f),updated:a,tagFrom:void 0,tag:void 0,tagTo:void 0,comment:void 0,internal:void 0,fee:v,info:e}}parseTransactionType(e){return this.safeString({DEPOSIT:"deposit",WITHDRAW:"withdrawal"},e,e)}parseTransactionStatus(e){return this.safeString({COMPLETE:"ok",FAILED:"failed",PENDING:"pending",CANCELLED:"canceled"},e,e)}async loadAccount(e={}){let t,i;if([t,i]=this.handleOptionStringAndParams(e,"loadAccount","tradingAccountId"),void 0===t){let e=await this.privateGetV1AccountsTradingAccounts(i),s=this.toArray(e);for(let e=0;e<s.length;e++){let i=this.safeDict(s,e);if("Primary Account"===this.safeString(i,"tradingAccountName")){t=this.safeString(i,"tradingAccountId");break}}}if(void 0===t)throw new a.ArgumentsRequired(this.id+' loadAccount() requires a tradingAccountId parameter in options["tradingAccountId"] or params["tradingAccountId"], fetchAccounts() was not able to find the Primary account');return this.options.tradingAccountId=t,t}async fetchAccounts(e={}){await Promise.all([this.loadMarkets(),this.handleToken()]);let t=await this.privateGetV1AccountsTradingAccounts(e);return this.parseAccounts(t,e)}parseAccount(e){return{id:this.safeString(e,"tradingAccountId"),type:void 0,code:void 0,info:e}}async fetchDepositAddress(e,t={}){let i;await Promise.all([this.loadMarkets(),this.handleToken()]);let s=this.currency(e),r={symbol:s.id},a=await this.privateGetV1WalletsDepositInstructionsCryptoSymbol(this.extend(r,t)),o=this.toArray(a),n=o.length,d=this.safeDict(o,0,{}),h=void 0!==(i=this.handleNetworkCodeAndParams(t)[0]);if((n>1||h)&&(void 0===i&&(i=this.defaultNetworkCode(e)),void 0!==i)){for(let t=0;t<o.length;t++){let s=this.safeDict(o,t,{}),r=this.safeString(s,"network");if(i===this.networkIdToCode(r,e)){d=s;break}}h&&(d={})}return this.parseDepositAddress(d,s)}parseDepositAddress(e,t){let i=this.safeString(e,"symbol"),s=this.safeString(e,"network"),r=this.safeCurrencyCode(i,t);return{info:e,currency:r,network:this.networkIdToCode(s,r),address:this.safeString(e,"address"),tag:void 0}}async fetchBalance(e={}){let t;await Promise.all([this.loadMarkets(),this.handleToken()]);let i={tradingAccountId:await this.loadAccount(e)},s=this.safeString(e,"code");return void 0!==s?(i.symbol=this.currency(s).id,t=await this.privateGetV1AccountsAssetSymbol(this.extend(i,e)),this.parseBalanceForSingleCurrency(t,s)):(t=await this.privateGetV1AccountsAsset(this.extend(i,e)),this.parseBalance(t))}parseBalanceForSingleCurrency(e,t){let i={info:e},s=this.account();return s.free=this.safeString(e,"availableQuantity"),s.used=this.safeString(e,"lockedQuantity"),i[t]=s,this.safeBalance(i)}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"assetSymbol"),a=this.safeCurrencyCode(r),o=this.account();o.total=this.safeString(s,"availableQuantity"),o.used=this.safeString(s,"lockedQuantity"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async fetchPositions(e,t={}){await Promise.all([this.loadMarkets(),this.handleToken()]);let i=await this.loadAccount(t),s=await this.privateGetV1DerivativesPositions(this.extend({tradingAccountId:i},t)),r=this.parsePositions(s,e);return this.filterByArrayPositions(r,"symbol",e)}parsePosition(e,t){let i=this.safeMarket(this.safeString(e,"symbol"),t).symbol,s=this.safeInteger(e,"createdAtTimestamp"),r=this.safeString(e,"side");return this.safePosition({info:e,id:void 0,symbol:i,timestamp:s,datetime:this.iso8601(s),lastUpdateTimestamp:this.safeInteger(e,"updatedAtTimestamp"),hedged:void 0,side:this.parsePositionSide(r),contracts:this.safeNumber(e,"quantity"),contractSize:void 0,entryPrice:void 0,markPrice:void 0,lastPrice:void 0,notional:this.safeNumber(e,"notional"),leverage:void 0,collateral:void 0,initialMargin:void 0,initialMarginPercentage:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,unrealizedPnl:void 0,liquidationPrice:void 0,marginMode:void 0,marginRatio:void 0,percentage:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}parsePositionSide(e){return this.safeString({BUY:"long",SELL:"short"},e,e)}async fetchTransfers(e,t,i,s={}){let r;await Promise.all([this.loadMarkets(),this.handleToken()]);let a=await this.loadAccount(s),[o,n]=this.handleOptionBoolAndParams(s,"fetchTransfers","paginate",!1);if(o){let s=this.handlePaginationParams("fetchTransfers",t,n);return await this.fetchPaginatedCallDynamic("fetchTransfers",e,t,i,s,100)}let d={tradingAccountId:a};void 0!==e&&(d.assetSymbol=(r=this.currency(e)).id);let h=this.safeInteger(n,"until"),c=n;void 0===t&&void 0===h&&(c=this.extend(n,{until:this.milliseconds()}));let l=this.handleSinceAndUntil(t,c);void 0!==i&&(d._pageSize=this.getClosestLimit(i));let u=await this.privateGetV1HistoryTransfer(this.extend(d,l));return this.parseTransfers(u,r,t,i)}async transfer(e,t,i,s,r={}){await Promise.all([this.loadMarkets(),this.handleToken()]);let a=this.currency(e),o={commandType:"V2TransferAsset",assetSymbol:a.id,quantity:this.currencyToPrecision(e,t),fromTradingAccountId:i,toTradingAccountId:s},n=await this.privatePostV2Command(this.extend(o,r)),d=this.safeDict(this.options,"transfer",{}),h=this.safeBool(d,"fillResponseFromRequest",!0),c=this.parseTransfer(n,a);return!0===h&&(c.fromAccount=i,c.toAccount=s,c.amount=t,c.currency=e),c}parseTransfer(e,t){let i=this.safeInteger(e,"createdAtTimestamp"),s=this.safeString(e,"assetSymbol"),r=this.safeString(e,"status");return void 0===r&&(r=this.safeString(e,"message")),{id:this.safeString(e,"requestId"),timestamp:i,datetime:this.iso8601(i),currency:this.safeCurrencyCode(s,t),amount:this.safeNumber(e,"quantity"),fromAccount:this.safeString(e,"fromTradingAccountId"),toAccount:this.safeString(e,"toTradingAccountId"),status:this.parseTransferStatus(r),info:e}}parseTransferStatus(e){return this.safeString({CLOSED:"ok",OPEN:"pending",REJECTED:"failed","Command acknowledged - TransferAsset":"ok"},e,e)}async fetchBorrowRateHistory(e,t,i,s={}){await Promise.all([this.loadMarkets(),this.handleToken()]);let r=await this.loadAccount(s),a={assetSymbol:this.currency(e).id,tradingAccountId:r},o=this.milliseconds(),n=t,[d,h]=this.handleUntilOption("createdAtDatetime[lte]",a,s),c=this.safeInteger(d,"createdAtDatetime[lte]");void 0===n&&(n=o-7776e6),void 0===c&&(c=o),d["createdAtDatetime[gte]"]=this.iso8601(n),d["createdAtDatetime[lte]"]=this.iso8601(c);let l=await this.privateGetV1HistoryBorrowInterest(this.extend(d,h));return this.parseBorrowRateHistory(l,e,t,i)}parseBorrowRate(e,t){let i=this.safeInteger(e,"createdAtTimestamp"),s=this.safeString(e,"assetSymbol");return{currency:this.safeCurrencyCode(s,t),rate:this.safeNumber(e,"borrowedQuantity"),period:864e5,timestamp:i,datetime:this.iso8601(i),info:e}}getTimestamp(){return this.milliseconds()-this.safeInteger(this.options,"timeDifference",0)}async fetchOpenInterest(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetV1MarketsSymbolTick(this.extend(s,t));return this.parseOpenInterest(r,i)}parseOpenInterest(e,t){let i=this.safeString(e,"openInterest");return this.safeOpenInterest({info:e,symbol:this.safeString(t,"symbol"),openInterestAmount:i,openInterestValue:void 0,timestamp:this.safeString(e,"createdAtTimestamp"),datetime:this.safeString(e,"createdAtDatetime"),baseVolume:i,quoteVolume:void 0},t)}sign(e,t="public",i="GET",r={},o,n){let d=o,h=n,c=this.omit(r,this.extractParams(e)),l="/"+this.implodeParams(e,r),u=this.safeString(this.urls.api,t);if(void 0===u)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let f=u+l;if("private"===t){this.checkRequiredCredentials();let t=this.microseconds().toString(),o=this.getTimestamp().toString();if("GET"===i){let r=o+t+i+"/trading-api/"+e;d={"BX-TIMESTAMP":o,"BX-NONCE":t,"BX-SIGNATURE":this.hmac(this.encode(r),this.encode(this.secret),s.sc,"hex")}}else if("POST"===i){let a=o+t+i+"/trading-api/"+e+(h=this.json(r)),n=this.hash(this.encode(a),s.sc,"hex");(d={"BX-TIMESTAMP":o,"BX-NONCE":t,"BX-SIGNATURE":this.hmac(this.encode(n),this.encode(this.secret),s.sc,"hex"),"Content-Type":"application/json"})["Content-Type"]="application/json";let l=this.safeString(c,"rateLimitToken");void 0!==l&&(d["BX-RATE-LIMIT-TOKEN"]=l)}if("v1/users/hmac/login"===e)(d=void 0===d?{}:d)["BX-PUBLIC-KEY"]=this.apiKey;else{let e=this.token;if(void 0===e)throw new a.AuthenticationError(this.id+" requires a token, please call signIn() first");(d=void 0===d?{}:d).Authorization="Bearer "+e}}if("GET"===i){let e=this.urlencode(c);e.length>0&&(f+="?"+e)}return{url:f,method:i,body:h,headers:d}}async signIn(e={}){let t=await this.privateGetV1UsersHmacLogin(e),i=this.safeString(t,"token"),s=this.safeString(t,"authorizer");return this.options.authorizer=s,this.token=i,this.options.tokenExpires=this.sum(this.milliseconds(),864e5),i}async handleToken(e={}){let t=this.milliseconds(),i=this.token,s=this.safeInteger(this.options,"tokenExpires");return void 0===i||void 0===s||t>s?await this.signIn():this.token}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"errorCode"),l=this.safeString(n,"type");if(void 0!==c&&"0"!==c&&"1001"!==c||void 0!==l&&"HttpInvalidParameterException"===l){let e="",t=this.safeString(n,"errorCodeName");e=void 0!==t?t:l;let i=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,e,i),this.throwBroadlyMatchedException(this.exceptions.broad,e,i),this.throwExactlyMatchedException(this.exceptions.exact,c,i),new a.ExchangeError(i)}}}i.d(t,{A:()=>o})},1484(e,t,i){"use strict";var s=i(4721),r=i(1355),a=i(1453),o=i(7749),n=i(8748);class d extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bybit",name:"Bybit",countries:["VG"],version:"v5",userAgent:void 0,rateLimit:20,hostname:"bybit.com",pro:!0,certified:!0,has:{CORS:!0,spot:!0,margin:!0,swap:!0,future:!0,option:!0,borrowCrossMargin:!0,cancelAllOrders:!0,cancelAllOrdersAfter:!0,cancelOrder:!0,cancelOrders:!0,cancelOrdersForSymbols:!0,closeAllPositions:!1,closePosition:!1,createConvertTrade:!0,createMarketBuyOrderWithCost:!0,createMarketSellOrderWithCost:!0,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!0,createPostOnlyOrder:!0,createReduceOnlyOrder:!0,createStopLimitOrder:!0,createStopLossOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,createTakeProfitOrder:!0,createTrailingAmountOrder:!0,createTriggerOrder:!0,editOrder:!0,editOrders:!0,fetchAllGreeks:!0,fetchBalance:!0,fetchBidsAsks:"emulated",fetchBorrowInterest:!0,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!0,fetchCanceledAndClosedOrders:!0,fetchCanceledOrders:!0,fetchClosedOrder:!0,fetchClosedOrders:!0,fetchConvertCurrencies:!0,fetchConvertQuote:!0,fetchConvertTrade:!0,fetchConvertTradeHistory:!0,fetchCrossBorrowRate:!0,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:!1,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!0,fetchDeposits:!0,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!0,fetchFundingRate:"emulated",fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchGreeks:!0,fetchIndexOHLCV:!0,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLedger:!0,fetchLeverage:!0,fetchLeverageTiers:!0,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!0,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!0,fetchMarketLeverageTiers:!0,fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMyLiquidations:!0,fetchMySettlementHistory:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!0,fetchOpenOrder:!0,fetchOpenOrders:!0,fetchOption:!0,fetchOptionChain:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrderTrades:!0,fetchPosition:!0,fetchPositionADLRank:!0,fetchPositionHistory:"emulated",fetchPositions:!0,fetchPositionsADLRank:!0,fetchPositionsHistory:!0,fetchPremiumIndexOHLCV:!0,fetchSettlementHistory:!0,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTransactions:!1,fetchTransfers:!0,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!0,fetchWithdrawals:!0,repayCrossMargin:!0,sandbox:!0,setLeverage:!0,setMarginMode:!0,setPositionMode:!0,transfer:!0,withdraw:!0},timeframes:{"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","1h":"60","2h":"120","4h":"240","6h":"360","12h":"720","1d":"D","1w":"W","1M":"M"},urls:{test:{spot:"https://api-testnet.{hostname}",futures:"https://api-testnet.{hostname}",v2:"https://api-testnet.{hostname}",public:"https://api-testnet.{hostname}",private:"https://api-testnet.{hostname}"},logo:"https://github.com/user-attachments/assets/97a5d0b3-de10-423d-90e1-6620960025ed",api:{spot:"https://api.{hostname}",futures:"https://api.{hostname}",v2:"https://api.{hostname}",public:"https://api.{hostname}",private:"https://api.{hostname}"},demotrading:{spot:"https://api-demo.{hostname}",futures:"https://api-demo.{hostname}",v2:"https://api-demo.{hostname}",public:"https://api-demo.{hostname}",private:"https://api-demo.{hostname}"},www:"https://www.bybit.com",doc:["https://bybit-exchange.github.io/docs/inverse/","https://bybit-exchange.github.io/docs/linear/","https://github.com/bybit-exchange"],fees:"https://help.bybit.com/hc/en-us/articles/360039261154",referral:"https://www.bybit.com/invite?ref=XDK12WP"},api:{public:{get:{"spot/v3/public/symbols":{cost:1},"spot/v3/public/quote/depth":{cost:1},"spot/v3/public/quote/depth/merged":{cost:1},"spot/v3/public/quote/trades":{cost:1},"spot/v3/public/quote/kline":{cost:1},"spot/v3/public/quote/ticker/24hr":{cost:1},"spot/v3/public/quote/ticker/price":{cost:1},"spot/v3/public/quote/ticker/bookTicker":{cost:1},"spot/v3/public/server-time":{cost:1},"spot/v3/public/infos":{cost:1},"spot/v3/public/margin-product-infos":{cost:1},"spot/v3/public/margin-ensure-tokens":{cost:1},"v3/public/time":{cost:1},"contract/v3/public/copytrading/symbol/list":{cost:1},"derivatives/v3/public/order-book/L2":{cost:1},"derivatives/v3/public/kline":{cost:1},"derivatives/v3/public/tickers":{cost:1},"derivatives/v3/public/instruments-info":{cost:1},"derivatives/v3/public/mark-price-kline":{cost:1},"derivatives/v3/public/index-price-kline":{cost:1},"derivatives/v3/public/funding/history-funding-rate":{cost:1},"derivatives/v3/public/risk-limit/list":{cost:1},"derivatives/v3/public/delivery-price":{cost:1},"derivatives/v3/public/recent-trade":{cost:1},"derivatives/v3/public/open-interest":{cost:1},"derivatives/v3/public/insurance":{cost:1},"v5/announcements/index":{cost:5},"v5/system/status":{cost:5},"v5/market/time":{cost:5},"v5/market/kline":{cost:5},"v5/market/mark-price-kline":{cost:5},"v5/market/index-price-kline":{cost:5},"v5/market/premium-index-price-kline":{cost:5},"v5/market/instruments-info":{cost:5},"v5/market/orderbook":{cost:5},"v5/market/rpi_orderbook":{cost:5},"v5/market/full_orderbook":{cost:5},"v5/market/tickers":{cost:5},"v5/market/funding/history":{cost:5},"v5/market/recent-trade":{cost:5},"v5/market/open-interest":{cost:5},"v5/market/historical-volatility":{cost:5},"v5/market/insurance":{cost:5},"v5/market/risk-limit":{cost:5},"v5/market/delivery-price":{cost:5},"v5/market/new-delivery-price":{cost:5},"v5/market/account-ratio":{cost:5},"v5/market/index-price-components":{cost:5},"v5/market/price-limit":{cost:5},"v5/market/adlAlert":{cost:5},"v5/market/fee-group-info":{cost:5},"v5/spot-lever-token/info":{cost:5},"v5/spot-lever-token/reference":{cost:5},"v5/spot-margin-trade/data":{cost:5},"v5/spot-margin-trade/collateral":{cost:5},"v5/spot-cross-margin-trade/data":{cost:5},"v5/spot-cross-margin-trade/pledge-token":{cost:5},"v5/spot-cross-margin-trade/borrow-token":{cost:5},"v5/crypto-loan/collateral-data":{cost:5},"v5/crypto-loan/loanable-data":{cost:5},"v5/crypto-loan-common/loanable-data":{cost:5},"v5/crypto-loan-common/collateral-data":{cost:5},"v5/crypto-loan-fixed/supply-order-quote":{cost:5},"v5/crypto-loan-fixed/borrow-order-quote":{cost:5},"v5/ins-loan/product-infos":{cost:5},"v5/ins-loan/ensure-tokens-convert":{cost:5},"v5/earn/product":{cost:5},"v5/spot-x/launchpool/project/list":{cost:5},"v5/spot-x/puzzle/project/list":{cost:5},"v5/spot-x/token-splash/project/list":{cost:5},"v5/event/instruments-info":{cost:5},"v5/event/orderbook":{cost:5}}},private:{get:{"v5/market/instruments-info":{cost:5},"v2/private/wallet/fund/records":{cost:25},"spot/v3/private/order":{cost:2.5},"spot/v3/private/open-orders":{cost:2.5},"spot/v3/private/history-orders":{cost:2.5},"spot/v3/private/my-trades":{cost:2.5},"spot/v3/private/account":{cost:2.5},"spot/v3/private/reference":{cost:2.5},"spot/v3/private/record":{cost:2.5},"spot/v3/private/cross-margin-orders":{cost:10},"spot/v3/private/cross-margin-account":{cost:10},"spot/v3/private/cross-margin-loan-info":{cost:10},"spot/v3/private/cross-margin-repay-history":{cost:10},"spot/v3/private/margin-loan-infos":{cost:10},"spot/v3/private/margin-repaid-infos":{cost:10},"spot/v3/private/margin-ltv":{cost:10},"asset/v3/private/transfer/inter-transfer/list/query":{cost:50},"asset/v3/private/transfer/sub-member/list/query":{cost:50},"asset/v3/private/transfer/sub-member-transfer/list/query":{cost:50},"asset/v3/private/transfer/universal-transfer/list/query":{cost:25},"asset/v3/private/coin-info/query":{cost:25},"asset/v3/private/deposit/address/query":{cost:10},"contract/v3/private/copytrading/order/list":{cost:30},"contract/v3/private/copytrading/position/list":{cost:40},"contract/v3/private/copytrading/wallet/balance":{cost:25},"contract/v3/private/position/limit-info":{cost:25},"contract/v3/private/order/unfilled-orders":{cost:1},"contract/v3/private/order/list":{cost:1},"contract/v3/private/position/list":{cost:1},"contract/v3/private/execution/list":{cost:1},"contract/v3/private/position/closed-pnl":{cost:1},"contract/v3/private/account/wallet/balance":{cost:1},"contract/v3/private/account/fee-rate":{cost:1},"contract/v3/private/account/wallet/fund-records":{cost:1},"unified/v3/private/order/unfilled-orders":{cost:1},"unified/v3/private/order/list":{cost:1},"unified/v3/private/position/list":{cost:1},"unified/v3/private/execution/list":{cost:1},"unified/v3/private/delivery-record":{cost:1},"unified/v3/private/settlement-record":{cost:1},"unified/v3/private/account/wallet/balance":{cost:1},"unified/v3/private/account/transaction-log":{cost:1},"unified/v3/private/account/borrow-history":{cost:1},"unified/v3/private/account/borrow-rate":{cost:1},"unified/v3/private/account/info":{cost:1},"user/v3/private/frozen-sub-member":{cost:10},"user/v3/private/query-sub-members":{cost:5},"user/v3/private/query-api":{cost:5},"user/v3/private/get-member-type":{cost:1},"asset/v3/private/transfer/transfer-coin/list/query":{cost:50},"asset/v3/private/transfer/account-coin/balance/query":{cost:50},"asset/v3/private/transfer/account-coins/balance/query":{cost:25},"asset/v3/private/transfer/asset-info/query":{cost:50},"asset/v3/public/deposit/allowed-deposit-list/query":{cost:.17},"asset/v3/private/deposit/record/query":{cost:10},"asset/v3/private/withdraw/record/query":{cost:10},"v5/order/realtime":{cost:5},"v5/order/history":{cost:5},"v5/order/spot-borrow-check":{cost:1},"v5/position/list":{cost:5},"v5/execution/list":{cost:5},"v5/position/closed-pnl":{cost:5},"v5/position/get-closed-positions":{cost:5},"v5/position/move-history":{cost:5},"v5/position/symbol-info":{cost:5},"v5/pre-upgrade/order/history":{cost:5},"v5/pre-upgrade/execution/list":{cost:5},"v5/pre-upgrade/position/closed-pnl":{cost:5},"v5/pre-upgrade/account/transaction-log":{cost:5},"v5/pre-upgrade/asset/delivery-record":{cost:5},"v5/pre-upgrade/asset/settlement-record":{cost:5},"v5/account/wallet-balance":{cost:1},"v5/account/borrow-history":{cost:1},"v5/account/instruments-info":{cost:1},"v5/account/collateral-info":{cost:1},"v5/account/option-asset-info":{cost:1},"v5/asset/coin-greeks":{cost:1},"v5/account/fee-rate":{cost:10},"v5/account/info":{cost:5},"v5/account/transaction-log":{cost:1.66},"v5/account/contract-transaction-log":{cost:1},"v5/account/query-dcp-info":{cost:5},"v5/account/user-setting-config":{cost:5},"v5/account/pay-info":{cost:5},"v5/account/trade-info-for-analysis":{cost:5},"v5/account/smp-group":{cost:1},"v5/account/mmp-state":{cost:5},"v5/account/withdrawal":{cost:5},"v5/asset/asset-overview":{cost:5},"v5/asset/exchange/query-coin-list":{cost:.5},"v5/asset/exchange/convert-result-query":{cost:.5},"v5/asset/exchange/query-convert-history":{cost:.5},"v5/asset/exchange/order-record":{cost:5},"v5/asset/fundinghistory":{cost:5},"v5/asset/portfolio-margin":{cost:5},"v5/asset/total-members-assets":{cost:5},"v5/asset/delivery-record":{cost:5},"v5/asset/settlement-record":{cost:5},"v5/asset/transfer/query-asset-info":{cost:50},"v5/asset/transfer/query-account-coins-balance":{cost:25},"v5/asset/transfer/query-account-coin-balance":{cost:50},"v5/asset/transfer/query-transfer-coin-list":{cost:50},"v5/asset/transfer/query-inter-transfer-list":{cost:50},"v5/asset/transfer/query-sub-member-list":{cost:50},"v5/asset/transfer/query-universal-transfer-list":{cost:25},"v5/asset/deposit/query-allowed-list":{cost:5},"v5/asset/deposit/query-record":{cost:10},"v5/asset/deposit/query-sub-member-record":{cost:10},"v5/asset/deposit/query-internal-record":{cost:5},"v5/asset/deposit/query-address":{cost:10},"v5/asset/deposit/query-sub-member-address":{cost:10},"v5/asset/coin/query-info":{cost:28},"v5/asset/withdraw/query-address":{cost:10},"v5/asset/withdraw/query-record":{cost:10},"v5/asset/withdraw/withdrawable-amount":{cost:5},"v5/asset/withdraw/vasp/list":{cost:5},"v5/asset/covert/small-balance-list":{cost:5},"v5/asset/covert/small-balance-history":{cost:5},"v5/asset/convert/small-balance-list":{cost:5},"v5/asset/convert/small-balance-history":{cost:5},"v5/fiat/query-coin-list":{cost:5},"v5/fiat/reference-price":{cost:5},"v5/fiat/trade-query":{cost:5},"v5/fiat/query-trade-history":{cost:5},"v5/fiat/balance-query":{cost:5},"v5/user/query-sub-members":{cost:5},"v5/user/query-api":{cost:5},"v5/user/sub-apikeys":{cost:5},"v5/user/get-member-type":{cost:5},"v5/user/aff-customer-info":{cost:5},"v5/user/del-submember":{cost:5},"v5/user/submembers":{cost:5},"v5/user/escrow_sub_members":{cost:5},"v5/user/invitation/referrals":{cost:5},"v5/user/invitation/code":{cost:5},"v5/affiliate/aff-user-list":{cost:5},"v5/affiliate/affiliate-sub-list":{cost:5},"v5/spot-lever-token/order-record":{cost:1},"v5/spot-margin-trade/flexible-available-inventory":{cost:5},"v5/spot-margin-trade/fixed-available-inventory":{cost:5},"v5/spot-margin-trade/interest-rate-history":{cost:5},"v5/spot-margin-trade/state":{cost:5},"v5/spot-margin-trade/max-borrowable":{cost:5},"v5/spot-margin-trade/position-tiers":{cost:5},"v5/spot-margin-trade/coinstate":{cost:5},"v5/spot-margin-trade/currency-data":{cost:5},"v5/spot-margin-trade/fixedborrow-contract-info":{cost:5},"v5/spot-margin-trade/fixedborrow-order-info":{cost:5},"v5/spot-margin-trade/fixedborrow-order-quote":{cost:5},"v5/spot-margin-trade/liability":{cost:5},"v5/spot-margin-trade/repayment-available-amount":{cost:5},"v5/spot-margin-trade/get-auto-repay-mode":{cost:5},"v5/spot-cross-margin-trade/loan-info":{cost:1},"v5/spot-cross-margin-trade/account":{cost:1},"v5/spot-cross-margin-trade/orders":{cost:1},"v5/spot-cross-margin-trade/repay-history":{cost:1},"v5/crypto-loan/borrowable-collateralisable-number":{cost:5},"v5/crypto-loan/ongoing-orders":{cost:5},"v5/crypto-loan/repayment-history":{cost:5},"v5/crypto-loan/borrow-history":{cost:5},"v5/crypto-loan/max-collateral-amount":{cost:5},"v5/crypto-loan/adjustment-history":{cost:5},"v5/crypto-loan-common/max-collateral-amount":{cost:10},"v5/crypto-loan-common/adjustment-history":{cost:10},"v5/crypto-loan-common/position":{cost:10},"v5/crypto-loan-flexible/ongoing-coin":{cost:10},"v5/crypto-loan-flexible/borrow-history":{cost:10},"v5/crypto-loan-flexible/repayment-history":{cost:10},"v5/crypto-loan-fixed/borrow-contract-info":{cost:10},"v5/crypto-loan-fixed/supply-contract-info":{cost:10},"v5/crypto-loan-fixed/borrow-order-info":{cost:10},"v5/crypto-loan-fixed/renew-info":{cost:10},"v5/crypto-loan-fixed/supply-order-info":{cost:10},"v5/crypto-loan-fixed/repayment-history":{cost:10},"v5/crypto-loan-fixed/available-inventory":{cost:10},"v5/crypto-loan-flexible/available-inventory":{cost:10},"v5/ins-loan/product-infos":{cost:5},"v5/ins-loan/ensure-tokens":{cost:5},"v5/ins-loan/ensure-tokens-convert":{cost:5},"v5/ins-loan/loan-order":{cost:5},"v5/ins-loan/repaid-history":{cost:5},"v5/ins-loan/ltv":{cost:5},"v5/ins-loan/ltv-convert":{cost:5},"v5/ins-loan/coin-delta-amount":{cost:5},"v5/lending/info":{cost:5},"v5/lending/history-order":{cost:5},"v5/lending/account":{cost:5},"v5/broker/earning-record":{cost:5},"v5/broker/earnings-info":{cost:5},"v5/broker/account-info":{cost:5},"v5/broker/asset/query-sub-member-deposit-record":{cost:10},"v5/earn/product":{cost:5},"v5/earn/order":{cost:5},"v5/earn/position":{cost:5},"v5/earn/yield":{cost:5},"v5/earn/hourly-yield":{cost:5},"v5/event/order-realtime":{cost:5},"v5/event/order-list":{cost:5},"v5/event/positions":{cost:5},"v5/event/trades":{cost:5},"v5/event/settlements":{cost:5},"v5/spot-x/launchpool/user/current-staking":{cost:5},"v5/spot-x/token-splash/user/activity-params":{cost:5},"v5/rfq/rfq-detail-list":{cost:5},"v5/alpha/prediction/engine-status":{cost:5},"v5/alpha/prediction/pay-token-list":{cost:5},"v5/alpha/prediction/sports/timeline-stages":{cost:5}},post:{"spot/v3/private/order":{cost:2.5},"spot/v3/private/cancel-order":{cost:2.5},"spot/v3/private/cancel-orders":{cost:2.5},"spot/v3/private/cancel-orders-by-ids":{cost:2.5},"spot/v3/private/purchase":{cost:2.5},"spot/v3/private/redeem":{cost:2.5},"spot/v3/private/cross-margin-loan":{cost:10},"spot/v3/private/cross-margin-repay":{cost:10},"asset/v3/private/transfer/inter-transfer":{cost:150},"asset/v3/private/withdraw/create":{cost:300},"asset/v3/private/withdraw/cancel":{cost:50},"asset/v3/private/transfer/sub-member-transfer":{cost:150},"asset/v3/private/transfer/transfer-sub-member-save":{cost:150},"asset/v3/private/transfer/universal-transfer":{cost:10},"user/v3/private/create-sub-member":{cost:10},"user/v3/private/create-sub-api":{cost:10},"user/v3/private/update-api":{cost:10},"user/v3/private/delete-api":{cost:10},"user/v3/private/update-sub-api":{cost:10},"user/v3/private/delete-sub-api":{cost:10},"contract/v3/private/copytrading/order/create":{cost:30},"contract/v3/private/copytrading/order/cancel":{cost:30},"contract/v3/private/copytrading/order/close":{cost:30},"contract/v3/private/copytrading/position/close":{cost:40},"contract/v3/private/copytrading/position/set-leverage":{cost:40},"contract/v3/private/copytrading/wallet/transfer":{cost:25},"contract/v3/private/copytrading/order/trading-stop":{cost:2.5},"contract/v3/private/order/create":{cost:1},"contract/v3/private/order/cancel":{cost:1},"contract/v3/private/order/cancel-all":{cost:1},"contract/v3/private/order/replace":{cost:1},"contract/v3/private/position/set-auto-add-margin":{cost:1},"contract/v3/private/position/switch-isolated":{cost:1},"contract/v3/private/position/switch-mode":{cost:1},"contract/v3/private/position/switch-tpsl-mode":{cost:1},"contract/v3/private/position/set-leverage":{cost:1},"contract/v3/private/position/trading-stop":{cost:1},"contract/v3/private/position/set-risk-limit":{cost:1},"contract/v3/private/account/setMarginMode":{cost:1},"unified/v3/private/order/create":{cost:30},"unified/v3/private/order/replace":{cost:30},"unified/v3/private/order/cancel":{cost:30},"unified/v3/private/order/create-batch":{cost:30},"unified/v3/private/order/replace-batch":{cost:30},"unified/v3/private/order/cancel-batch":{cost:30},"unified/v3/private/order/cancel-all":{cost:30},"unified/v3/private/position/set-leverage":{cost:2.5},"unified/v3/private/position/tpsl/switch-mode":{cost:2.5},"unified/v3/private/position/set-risk-limit":{cost:2.5},"unified/v3/private/position/trading-stop":{cost:2.5},"unified/v3/private/account/upgrade-unified-account":{cost:2.5},"unified/v3/private/account/setMarginMode":{cost:2.5},"fht/compliance/tax/v3/private/registertime":{cost:50},"fht/compliance/tax/v3/private/create":{cost:50},"fht/compliance/tax/v3/private/status":{cost:50},"fht/compliance/tax/v3/private/url":{cost:50},"v5/order/create":{cost:2.5},"v5/order/amend":{cost:5},"v5/order/cancel":{cost:2.5},"v5/order/cancel-all":{cost:50},"v5/order/create-batch":{cost:5},"v5/order/amend-batch":{cost:5},"v5/order/cancel-batch":{cost:5},"v5/order/disconnected-cancel-all":{cost:5},"v5/order/pre-check":{cost:5},"v5/position/set-leverage":{cost:5},"v5/position/switch-isolated":{cost:5},"v5/position/set-tpsl-mode":{cost:5},"v5/position/switch-mode":{cost:5},"v5/position/set-risk-limit":{cost:5},"v5/position/trading-stop":{cost:5},"v5/position/set-auto-add-margin":{cost:5},"v5/position/add-margin":{cost:5},"v5/position/move-positions":{cost:5},"v5/position/confirm-pending-mmr":{cost:5},"v5/account/upgrade-to-uta":{cost:5},"v5/account/quick-repayment":{cost:5},"v5/account/set-margin-mode":{cost:5},"v5/account/set-hedging-mode":{cost:5},"v5/account/mmp-modify":{cost:5},"v5/account/mmp-reset":{cost:5},"v5/account/borrow":{cost:5},"v5/account/repay":{cost:5},"v5/account/no-convert-repay":{cost:5},"v5/account/set-limit-px-action":{cost:5},"v5/account/set-delta-mode":{cost:5},"v5/asset/exchange/quote-apply":{cost:1},"v5/asset/exchange/convert-execute":{cost:1},"v5/asset/transfer/inter-transfer":{cost:50},"v5/asset/transfer/save-transfer-sub-member":{cost:150},"v5/asset/transfer/universal-transfer":{cost:10},"v5/asset/deposit/deposit-to-account":{cost:5},"v5/asset/travel-rule/deposit/submit":{cost:5},"v5/asset/withdraw/create":{cost:50},"v5/asset/withdraw/cancel":{cost:50},"v5/asset/covert/get-quote":{cost:10},"v5/asset/covert/small-balance-execute":{cost:10},"v5/fiat/quote-apply":{cost:10},"v5/fiat/trade-execute":{cost:10},"v5/user/create-sub-member":{cost:10},"v5/user/create-sub-api":{cost:10},"v5/user/frozen-sub-member":{cost:10},"v5/user/update-api":{cost:10},"v5/user/update-sub-api":{cost:10},"v5/user/delete-api":{cost:10},"v5/user/delete-sub-api":{cost:10},"v5/user/agreement":{cost:10},"v5/user/create-demo-member":{cost:10},"v5/spot-lever-token/purchase":{cost:2.5},"v5/spot-lever-token/redeem":{cost:2.5},"v5/spot-margin-trade/switch-mode":{cost:5},"v5/spot-margin-trade/set-leverage":{cost:5},"v5/spot-margin-trade/set-auto-repay-mode":{cost:5},"v5/spot-margin-trade/fixedborrow":{cost:5},"v5/spot-margin-trade/fixedborrow-renew":{cost:5},"v5/spot-cross-margin-trade/loan":{cost:2.5},"v5/spot-cross-margin-trade/repay":{cost:2.5},"v5/spot-cross-margin-trade/switch":{cost:2.5},"v5/crypto-loan/borrow":{cost:5},"v5/crypto-loan/repay":{cost:5},"v5/crypto-loan/adjust-ltv":{cost:5},"v5/crypto-loan-common/adjust-ltv":{cost:50},"v5/crypto-loan-common/max-loan":{cost:10},"v5/crypto-loan-flexible/borrow":{cost:50},"v5/crypto-loan-flexible/repay":{cost:50},"v5/crypto-loan-flexible/repay-collateral":{cost:50},"v5/crypto-loan-fixed/borrow":{cost:50},"v5/crypto-loan-fixed/renew":{cost:50},"v5/crypto-loan-fixed/supply":{cost:50},"v5/crypto-loan-fixed/borrow-order-cancel":{cost:50},"v5/crypto-loan-fixed/supply-order-cancel":{cost:50},"v5/crypto-loan-fixed/fully-repay":{cost:50},"v5/crypto-loan-fixed/repay-collateral":{cost:50},"v5/ins-loan/association-uid":{cost:5},"v5/ins-loan/repay-loan":{cost:5},"v5/lending/purchase":{cost:5},"v5/lending/redeem":{cost:5},"v5/lending/redeem-cancel":{cost:5},"v5/account/set-collateral-switch":{cost:5},"v5/account/set-collateral-switch-batch":{cost:5},"v5/account/demo-apply-money":{cost:5},"v5/broker/award/info":{cost:5},"v5/broker/award/distribute-award":{cost:5},"v5/broker/award/distribution-record":{cost:5},"v5/earn/place-order":{cost:5},"v5/event/quotes":{cost:5},"v5/event/cancel":{cost:5},"v5/spot-x/launchpool/user/activity-log":{cost:5},"v5/spot-x/launchpool/user/history":{cost:5},"v5/alpha/prediction/event-detail":{cost:5},"v5/alpha/prediction/order-estimate":{cost:5},"v5/alpha/prediction/buy":{cost:5},"v5/alpha/prediction/sell":{cost:5},"v5/alpha/prediction/order-list":{cost:5},"v5/alpha/prediction/order-book":{cost:5},"v5/alpha/prediction/token-price":{cost:5},"v5/alpha/prediction/price-history":{cost:5},"v5/alpha/prediction/position-list":{cost:5},"v5/alpha/prediction/position-history":{cost:5},"v5/alpha/prediction/portfolio-summary":{cost:5},"v5/alpha/prediction/side-market-list":{cost:5},"v5/alpha/prediction/sports/match-list":{cost:5},"v5/alpha/prediction/sports/group-stage-detail":{cost:5}}}},httpExceptions:{403:a.RateLimitExceeded},exceptions:{exact:{"-10009":a.BadRequest,"-1004":a.BadRequest,"-1021":a.BadRequest,"-1103":a.BadRequest,"-1140":a.InvalidOrder,"-1197":a.InvalidOrder,"-2013":a.InvalidOrder,"-2015":a.AuthenticationError,"-6017":a.BadRequest,"-6025":a.BadRequest,"-6029":a.BadRequest,5004:a.ExchangeError,7001:a.BadRequest,10001:a.BadRequest,10002:a.InvalidNonce,10003:a.AuthenticationError,10004:a.AuthenticationError,10005:a.PermissionDenied,10006:a.RateLimitExceeded,10007:a.AuthenticationError,10008:a.AccountSuspended,10009:a.AuthenticationError,10010:a.PermissionDenied,10014:a.BadRequest,10016:a.ExchangeError,10017:a.BadRequest,10018:a.RateLimitExceeded,10020:a.PermissionDenied,10024:a.PermissionDenied,10027:a.PermissionDenied,10028:a.PermissionDenied,10029:a.PermissionDenied,12137:a.InvalidOrder,12201:a.BadRequest,12141:a.BadRequest,100028:a.PermissionDenied,110001:a.OrderNotFound,110003:a.InvalidOrder,110004:a.InsufficientFunds,110005:a.InvalidOrder,110006:a.InsufficientFunds,110007:a.InsufficientFunds,110008:a.InvalidOrder,110009:a.InvalidOrder,110010:a.InvalidOrder,110011:a.InvalidOrder,110012:a.InsufficientFunds,110013:a.BadRequest,110014:a.InsufficientFunds,110015:a.BadRequest,110016:a.InvalidOrder,110017:a.InvalidOrder,110018:a.BadRequest,110019:a.InvalidOrder,110020:a.InvalidOrder,110021:a.InvalidOrder,110022:a.InvalidOrder,110023:a.InvalidOrder,110024:a.BadRequest,110025:a.NoChange,110026:a.MarginModeAlreadySet,110027:a.NoChange,110028:a.BadRequest,110029:a.BadRequest,110030:a.InvalidOrder,110031:a.InvalidOrder,110032:a.InvalidOrder,110033:a.InvalidOrder,110034:a.InvalidOrder,110035:a.InvalidOrder,110036:a.InvalidOrder,110037:a.InvalidOrder,110038:a.InvalidOrder,110039:a.InvalidOrder,110040:a.InvalidOrder,110041:a.InvalidOrder,110042:a.InvalidOrder,110043:a.BadRequest,110044:a.InsufficientFunds,110045:a.InsufficientFunds,110046:a.BadRequest,110047:a.BadRequest,110048:a.BadRequest,110049:a.BadRequest,110050:a.BadRequest,110051:a.InsufficientFunds,110052:a.InsufficientFunds,110053:a.InsufficientFunds,110054:a.InvalidOrder,110055:a.InvalidOrder,110056:a.InvalidOrder,110057:a.InvalidOrder,110058:a.InvalidOrder,110059:a.InvalidOrder,110060:a.BadRequest,110061:a.BadRequest,110062:a.BadRequest,110063:a.ExchangeError,110064:a.InvalidOrder,110065:a.PermissionDenied,110066:a.ExchangeError,110067:a.PermissionDenied,110068:a.PermissionDenied,110069:a.PermissionDenied,110070:a.InvalidOrder,110071:a.ExchangeError,110072:a.InvalidOrder,110073:a.ExchangeError,110092:a.InvalidOrder,110093:a.InvalidOrder,110094:a.InvalidOrder,130006:a.InvalidOrder,130021:a.InsufficientFunds,130074:a.InvalidOrder,131001:a.InsufficientFunds,131084:a.ExchangeError,131200:a.ExchangeError,131201:a.ExchangeError,131202:a.BadRequest,131203:a.BadRequest,131204:a.BadRequest,131205:a.BadRequest,131206:a.ExchangeError,131207:a.BadRequest,131208:a.ExchangeError,131209:a.BadRequest,131210:a.BadRequest,131211:a.BadRequest,131212:a.InsufficientFunds,131213:a.BadRequest,131214:a.BadRequest,131215:a.BadRequest,131216:a.ExchangeError,131217:a.ExchangeError,131231:a.NotSupported,131232:a.NotSupported,131002:a.BadRequest,131003:a.ExchangeError,131004:a.AuthenticationError,131085:a.InsufficientFunds,131086:a.BadRequest,131088:a.BadRequest,131089:a.BadRequest,131090:a.ExchangeError,131091:a.ExchangeError,131092:a.ExchangeError,131093:a.ExchangeError,131094:a.BadRequest,131095:a.BadRequest,131096:a.BadRequest,131097:a.ExchangeError,131098:a.ExchangeError,131099:a.ExchangeError,140001:a.OrderNotFound,140003:a.InvalidOrder,140004:a.InsufficientFunds,140005:a.InvalidOrder,140006:a.InsufficientFunds,140007:a.InsufficientFunds,140008:a.InvalidOrder,140009:a.InvalidOrder,140010:a.InvalidOrder,140011:a.InvalidOrder,140012:a.InsufficientFunds,140013:a.BadRequest,140014:a.InsufficientFunds,140015:a.InvalidOrder,140016:a.InvalidOrder,140017:a.InvalidOrder,140018:a.BadRequest,140019:a.InvalidOrder,140020:a.InvalidOrder,140021:a.InvalidOrder,140022:a.InvalidOrder,140023:a.InvalidOrder,140024:a.BadRequest,140025:a.BadRequest,140026:a.BadRequest,140027:a.BadRequest,140028:a.InvalidOrder,140029:a.BadRequest,140030:a.InvalidOrder,140031:a.BadRequest,140032:a.InvalidOrder,140033:a.InvalidOrder,140034:a.InvalidOrder,140035:a.InvalidOrder,140036:a.BadRequest,140037:a.InvalidOrder,140038:a.BadRequest,140039:a.BadRequest,140040:a.InvalidOrder,140041:a.InvalidOrder,140042:a.InvalidOrder,140043:a.BadRequest,140044:a.InsufficientFunds,140045:a.InsufficientFunds,140046:a.BadRequest,140047:a.BadRequest,140048:a.BadRequest,140049:a.BadRequest,140050:a.InvalidOrder,140051:a.InsufficientFunds,140052:a.InsufficientFunds,140053:a.InsufficientFunds,140054:a.InvalidOrder,140055:a.InvalidOrder,140056:a.InvalidOrder,140057:a.InvalidOrder,140058:a.InvalidOrder,140059:a.InvalidOrder,140060:a.BadRequest,140061:a.BadRequest,140062:a.BadRequest,140063:a.ExchangeError,140064:a.InvalidOrder,140065:a.PermissionDenied,140066:a.ExchangeError,140067:a.PermissionDenied,140068:a.PermissionDenied,140069:a.PermissionDenied,140070:a.InvalidOrder,170001:a.ExchangeError,170005:a.InvalidOrder,170007:a.RequestTimeout,170010:a.InvalidOrder,170011:a.InvalidOrder,170019:a.InvalidOrder,170031:a.ExchangeError,170032:a.ExchangeError,170033:a.InsufficientFunds,170034:a.InsufficientFunds,170035:a.BadRequest,170036:a.BadRequest,170037:a.BadRequest,170105:a.BadRequest,170115:a.InvalidOrder,170116:a.InvalidOrder,170117:a.InvalidOrder,170121:a.InvalidOrder,170124:a.InvalidOrder,170130:a.BadRequest,170131:a.InsufficientFunds,170132:a.InvalidOrder,170133:a.InvalidOrder,170134:a.InvalidOrder,170135:a.InvalidOrder,170136:a.InvalidOrder,170137:a.InvalidOrder,170139:a.InvalidOrder,170140:a.InvalidOrder,170141:a.InvalidOrder,170142:a.InvalidOrder,170143:a.InvalidOrder,170144:a.InvalidOrder,170145:a.InvalidOrder,170146:a.InvalidOrder,170147:a.InvalidOrder,170148:a.InvalidOrder,170149:a.ExchangeError,170150:a.ExchangeError,170151:a.InvalidOrder,170157:a.InvalidOrder,170159:a.InvalidOrder,170190:a.InvalidOrder,170191:a.InvalidOrder,170192:a.InvalidOrder,170193:a.InvalidOrder,170194:a.InvalidOrder,170195:a.InvalidOrder,170196:a.InvalidOrder,170197:a.InvalidOrder,170198:a.InvalidOrder,170199:a.InvalidOrder,170200:a.InvalidOrder,170201:a.PermissionDenied,170202:a.InvalidOrder,170203:a.InvalidOrder,170204:a.InvalidOrder,170206:a.InvalidOrder,170209:a.RestrictedLocation,170210:a.InvalidOrder,170213:a.OrderNotFound,170217:a.InvalidOrder,170218:a.InvalidOrder,170221:a.BadRequest,170222:a.RateLimitExceeded,170223:a.InsufficientFunds,170224:a.PermissionDenied,170226:a.InsufficientFunds,170227:a.ExchangeError,170228:a.InvalidOrder,170229:a.InvalidOrder,170234:a.ExchangeError,170241:a.ManualInteractionNeeded,170371:a.InvalidOrder,170372:a.InvalidOrder,175e3:a.InvalidOrder,175001:a.InvalidOrder,175002:a.InvalidOrder,175003:a.InsufficientFunds,175004:a.InvalidOrder,175005:a.InvalidOrder,175006:a.InsufficientFunds,175007:a.InvalidOrder,175008:a.InvalidOrder,175009:a.InvalidOrder,175010:a.PermissionDenied,175012:a.InvalidOrder,175013:a.InvalidOrder,175014:a.InvalidOrder,175015:a.InvalidOrder,175016:a.InvalidOrder,175017:a.InvalidOrder,175027:a.ExchangeError,176002:a.BadRequest,176004:a.BadRequest,176003:a.BadRequest,176006:a.BadRequest,176005:a.BadRequest,176008:a.BadRequest,176007:a.BadRequest,176010:a.BadRequest,176009:a.BadRequest,176012:a.BadRequest,176011:a.BadRequest,176014:a.BadRequest,176013:a.BadRequest,176015:a.InsufficientFunds,176016:a.BadRequest,176017:a.BadRequest,176018:a.BadRequest,176019:a.BadRequest,176020:a.BadRequest,176021:a.BadRequest,176022:a.BadRequest,176023:a.BadRequest,176024:a.BadRequest,176025:a.BadRequest,176026:a.BadRequest,176027:a.BadRequest,176028:a.BadRequest,176029:a.BadRequest,176030:a.BadRequest,176031:a.BadRequest,176034:a.BadRequest,176035:a.PermissionDenied,176036:a.PermissionDenied,176037:a.PermissionDenied,176038:a.BadRequest,176039:a.BadRequest,176040:a.BadRequest,181e3:a.BadRequest,181001:a.BadRequest,181002:a.InvalidOrder,181003:a.InvalidOrder,181004:a.InvalidOrder,182e3:a.InvalidOrder,181017:a.BadRequest,20001:a.OrderNotFound,20003:a.InvalidOrder,20004:a.InvalidOrder,20005:a.InvalidOrder,20006:a.InvalidOrder,20007:a.InvalidOrder,20008:a.InvalidOrder,20009:a.InvalidOrder,20010:a.InvalidOrder,20011:a.InvalidOrder,20012:a.InvalidOrder,20013:a.InvalidOrder,20014:a.InvalidOrder,20015:a.InvalidOrder,20016:a.InvalidOrder,20017:a.InvalidOrder,20018:a.InvalidOrder,20019:a.InvalidOrder,20020:a.InvalidOrder,20021:a.InvalidOrder,20022:a.BadRequest,20023:a.BadRequest,20031:a.BadRequest,20070:a.BadRequest,20071:a.BadRequest,20084:a.BadRequest,30001:a.BadRequest,30003:a.InvalidOrder,30004:a.InvalidOrder,30005:a.InvalidOrder,30007:a.InvalidOrder,30008:a.InvalidOrder,30009:a.ExchangeError,30010:a.InsufficientFunds,30011:a.PermissionDenied,30012:a.PermissionDenied,30013:a.PermissionDenied,30014:a.InvalidOrder,30015:a.InvalidOrder,30016:a.ExchangeError,30017:a.InvalidOrder,30018:a.InvalidOrder,30019:a.InvalidOrder,30020:a.InvalidOrder,30021:a.InvalidOrder,30022:a.InvalidOrder,30023:a.InvalidOrder,30024:a.InvalidOrder,30025:a.InvalidOrder,30026:a.InvalidOrder,30027:a.InvalidOrder,30028:a.InvalidOrder,30029:a.InvalidOrder,30030:a.InvalidOrder,30031:a.InsufficientFunds,30032:a.InvalidOrder,30033:a.RateLimitExceeded,30034:a.OrderNotFound,30035:a.RateLimitExceeded,30036:a.ExchangeError,30037:a.InvalidOrder,30041:a.ExchangeError,30042:a.InsufficientFunds,30043:a.InvalidOrder,30044:a.InvalidOrder,30045:a.InvalidOrder,30049:a.InsufficientFunds,30050:a.ExchangeError,30051:a.ExchangeError,30052:a.ExchangeError,30054:a.ExchangeError,30057:a.ExchangeError,30063:a.ExchangeError,30067:a.InsufficientFunds,30068:a.ExchangeError,30074:a.InvalidOrder,30075:a.InvalidOrder,30078:a.ExchangeError,33004:a.AuthenticationError,34026:a.ExchangeError,34036:a.BadRequest,35015:a.BadRequest,340099:a.ExchangeError,3400045:a.ExchangeError,3100116:a.BadRequest,3100198:a.BadRequest,3200300:a.InsufficientFunds},broad:{"Not supported symbols":a.BadSymbol,"Request timeout":a.RequestTimeout,"unknown orderInfo":a.OrderNotFound,"invalid api_key":a.AuthenticationError,oc_diff:a.InsufficientFunds,new_oc:a.InsufficientFunds,"openapi sign params error!":a.AuthenticationError}},precisionMode:4,options:{enableDemoTrading:!1,fetchMarkets:{usePrivateInstrumentsInfo:!1,types:["spot","linear","inverse","option"],options:["BTC","ETH","SOL","XRP","MNT","DOGE"],loadAllOptions:!1,loadExpiredOptions:!1},enableUnifiedMargin:void 0,enableUnifiedAccount:void 0,unifiedMarginStatus:void 0,createOrder:{createMarketBuyOrderRequiresPrice:!1},createUnifiedMarginAccount:!1,defaultType:"swap",defaultSubType:"linear",defaultSettle:"USDT",code:"BTC",recvWindow:5e3,timeDifference:0,adjustForTimeDifference:!1,brokerId:"CCXT",accountsByType:{spot:"SPOT",margin:"SPOT",future:"CONTRACT",swap:"CONTRACT",option:"OPTION",investment:"INVESTMENT",unified:"UNIFIED",funding:"FUND",fund:"FUND",contract:"CONTRACT"},accountsById:{SPOT:"spot",MARGIN:"spot",CONTRACT:"contract",OPTION:"option",INVESTMENT:"investment",UNIFIED:"unified",FUND:"fund"},networks:{BTC:"BTC",BRC20:"BTC",ETH:"ETH",ERC20:"ETH",TRX:"TRX",TRC20:"TRX",BSC:"BSC",BEP20:"BSC",SOL:"SOL",ACA:"ACA",ADA:"ADA",ALGO:"ALGO",APT:"APTOS",ARBITRUM:"ARBI",ARBITRUM_NOVA:"ARBINOVA",AVAXC:"CAVAX",AVAXX:"XAVAX",COSMOS:"ATOM",ATOM:"ATOM",BCH:"BCH",BEP2:"BNB",DOGE:"DOGE",DOT:"DOT",EGLD:"EGLD",EOS:"EOS",ETC:"ETC",ETHW:"ETHW",FIL:"FIL",STEP:"FITFI",SONIC:"SONIC",GLMR:"GLMR",HBAR:"HBAR",ICP:"ICP",KLAY:"KLAY",LTC:"LTC",POLYGON:"MATIC",MATIC:"MATIC",NEAR:"NEAR",OASYS:"OAS",OASIS:"ROSE",ONE:"ONE",OP:"OP",SCRT:"SCRT",STX:"STX",TON:"TON",WAX:"WAXP",XEC:"XEC",XLM:"XLM",XRP:"XRP",XTZ:"XTZ",ZIL:"ZIL",ZKSYNCLITE:"ZKSYNC",ZKSYNCERA:"ZKV2","0G":"ZEROGRAVITY",MANTLE:"MANTLE",CHZ:"CHILIZ",BASE:"BASE",CELO:"CELO",SCROLL:"SCROLL",SUI:"SUI",DYDX:"DYDX",HUMANITY:"HUMANITY",HYPER:"HYPEREVM",MONAD:"MONAD",MOVE:"MOVE"},networksById:{ETH:"ERC20",TRX:"TRC20",BSC:"BEP20",OP:"OP",MATIC:"MATIC",SPL:"SOL"},defaultNetwork:"ERC20",defaultNetworks:{USDT:"TRC20"},intervals:{"5m":"5min","15m":"15min","30m":"30min","1h":"1h","4h":"4h","1d":"1d"},useMarkPriceForPositionCollateral:!1},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:{last:!0,mark:!0,index:!0},triggerDirection:!0,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:{triggerPriceType:{last:!0,mark:!0,index:!0},price:!0},timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!0,selfTradePrevention:!0,trailing:!0,iceberg:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!0},createOrders:{max:10},fetchMyTrades:{marginMode:!1,limit:100,daysBack:730,untilDays:7,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!0,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:50,trigger:!0,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:50,daysBack:730,daysBackCanceled:1,untilDays:7,trigger:!0,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:1e3},editOrders:{max:10}},spot:{extends:"default",fetchCurrencies:{private:!0},createOrder:{triggerPriceType:void 0,triggerDirection:!1,attachedStopLossTakeProfit:{triggerPriceType:void 0,price:!0},marketBuyRequiresPrice:!0}},swap:{linear:{extends:"default"},inverse:{extends:"default"}},future:{linear:{extends:"default"},inverse:{extends:"default"}}},fees:{trading:{feeSide:"get",tierBased:!0,percentage:!0,taker:75e-5,maker:1e-4},funding:{tierBased:!1,percentage:!1,withdraw:{},deposit:{}}},rollingWindowSize:5e3})}enableDemoTrading(e){if(this.isSandboxModeEnabled)throw new a.NotSupported(this.id+" demo trading does not support in sandbox environment");if(e)this.urls.apiBackupDemoTrading=this.urls.api,this.urls.api=this.urls.demotrading;else if("apiBackupDemoTrading"in this.urls){this.urls.api=this.urls.apiBackupDemoTrading;let e=this.omit(this.urls,"apiBackupDemoTrading");this.urls=e}this.options.enableDemoTrading=e}nonce(){return this.milliseconds()-this.safeInteger(this.options,"timeDifference",0)}addPaginationCursorToResult(e){let t=this.safeDict(e,"result",{}),i=this.safeListN(t,["list","rows","data","dataList"],[]),s=this.safeString2(t,"nextPageCursor","cursor"),r=i.length;if(void 0!==s&&r>0){let e=i[0];e.nextPageCursor=s,i[0]=e}return i}async isUnifiedEnabled(e={}){let t=this.safeBool(this.options,"enableUnifiedMargin"),i=this.safeBool(this.options,"enableUnifiedAccount");if(void 0===t||void 0===i){if(this.safeBool(this.options,"enableDemoTrading",!1))return this.options.enableUnifiedMargin=!1,this.options.enableUnifiedAccount=!0,this.options.unifiedMarginStatus=6,[this.options.enableUnifiedMargin,this.options.enableUnifiedAccount];let t=[this.privateGetV5UserQueryApi(e),this.privateGetV5AccountInfo(e)],i=await Promise.all(t),s=this.safeDict(i,0),r=this.safeDict(i,1),a=this.safeDict(s,"result",{}),o=this.safeDict(r,"result",{});this.options.enableUnifiedMargin=1===this.safeInteger(a,"unified"),this.options.enableUnifiedAccount=1===this.safeInteger(a,"uta"),this.options.unifiedMarginStatus=this.safeInteger(o,"unifiedMarginStatus",6)}return[this.options.enableUnifiedMargin,this.options.enableUnifiedAccount]}async upgradeUnifiedTradeAccount(e={}){return await this.privatePostV5AccountUpgradeToUta(e)}createExpiredOptionMarket(e){let t,i,s,r,o,n,d=e.split("-"),h=e.split("/");if(e.indexOf("/")>-1){s=this.safeString(h,0),r=this.safeString(d,1);let e=this.safeString(h,1);if(void 0===e)throw new a.ExchangeError(this.id+" createExpiredOptionMarket() missing symbolQuoteAndSettle");let o=e.split(":"),n=this.safeString(o,0);t=n,i=n}else s=this.safeString(d,0),r=this.convertMarketIdExpireDate(this.safeString(d,1)),e.endsWith("-USDT")?(t="USDT",i="USDT"):(t="USDC",i="USDC");let c=this.safeString(d,2),l=this.safeString(d,3),u=this.convertExpireDate(r),f=this.parse8601(u);return"BTC"===s?(o=this.parseNumber("0.01"),n=this.parseNumber("5")):"ETH"===s?(o=this.parseNumber("0.1"),n=this.parseNumber("0.1")):"SOL"===s&&(o=this.parseNumber("1"),n=this.parseNumber("0.01")),{id:s+"-"+this.convertExpireDateToMarketIdDate(r)+"-"+c+"-"+l,symbol:s+"/"+t+":"+i+"-"+r+"-"+c+"-"+l,base:s,quote:t,settle:i,baseId:s,quoteId:t,settleId:i,active:!1,type:"option",subType:s===i?"inverse":"linear",linear:s!==i,inverse:s===i,spot:!1,swap:!1,future:!1,option:!0,margin:!1,contract:!0,contractSize:this.parseNumber("1"),expiry:f,expiryDatetime:u,optionType:"C"===l?"call":"put",strike:this.parseNumber(c),precision:{amount:o,price:n},limits:{amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},info:void 0}}safeMarket(e,t,i,s){return void 0!==e&&(e.indexOf("-C")>-1||e.indexOf("-P")>-1)&&(void 0===this.markets_by_id||!(e in this.markets_by_id))?this.createExpiredOptionMarket(e):super.safeMarket(e,t,i,s)}getBybitType(e,t,i={}){let[s,r]=this.handleMarketTypeAndParams(e,t,i),[a,o]=this.handleSubTypeAndParams(e,t,r);return"option"===s||"spot"===s?[s,o]:[a,o]}getAmount(e,t){let i=void 0===this.market(e).precision.amount,s=this.numberToString(t);return i||"0"===s?s:this.amountToPrecision(e,t)}getPrice(e,t){return void 0===t?t:void 0!==this.market(e).precision.price?this.priceToPrecision(e,t):t}getCost(e,t){return void 0!==this.market(e).precision.price?this.costToPrecision(e,t):t}async fetchStatus(e={}){let t,i,s=await this.publicGetV5SystemStatus(e),r=this.safeDict(s,"result",{}),a=this.safeList(r,"list",[]),o="ok";for(let e=0;e<a.length;e++){let s=this.safeDict(a,e),r=this.safeString(s,"state");if("ongoing"===r){o="maintenance",t=this.safeInteger(s,"end"),i=this.safeString(s,"href");break}"scheduled"===r&&(t=this.safeInteger(s,"begin"),i=this.safeString(s,"href"))}return{status:o,updated:void 0,eta:t,url:i,info:s}}async fetchTime(e={}){let t=await this.publicGetV5MarketTime(e);return this.safeInteger(t,"time")}async fetchCurrencies(e={}){if(!this.checkRequiredCredentials(!1)||this.safeBool(this.options,"enableDemoTrading",!1))return{};let t=await this.privateGetV5AssetCoinQueryInfo(e),i=this.safeDict(t,"result",{}),s=this.safeList(i,"rows",[]);return this.parseCurrencies(s)}parseCurrency(e){let t=this.safeString(e,"coin"),i=this.safeCurrencyCode(t),s=this.safeString(e,"name"),r=this.safeList(e,"chains",[]),a={};for(let e=0;e<r.length;e++){let t=r[e],s=this.safeString(t,"chain"),o=this.networkIdToCode(s,i);void 0!==o&&(a[o]={info:t,id:s,network:o,active:void 0,deposit:1===this.safeInteger(t,"chainDeposit"),withdraw:1===this.safeInteger(t,"chainWithdraw"),fee:this.safeNumber(t,"withdrawFee"),precision:this.parseNumber(this.parsePrecision(this.safeString(t,"minAccuracy"))),limits:{withdraw:{min:this.safeNumber(t,"withdrawMin"),max:void 0},deposit:{min:this.safeNumber(t,"depositMin"),max:void 0}}})}return this.safeCurrencyStructure({info:e,code:i,id:t,name:s,active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,precision:void 0,limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},networks:a,type:"crypto"})}async fetchMarkets(e={}){let t;this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference();let i=[],s=["spot","linear","inverse","option"],r=this.safeDict(this.options,"fetchMarkets");t=void 0!==r?this.safeList(r,"types",s):this.safeList(this.options,"fetchMarkets",s);for(let s=0;s<t.length;s++){let o=t[s];if("spot"===o)i.push(this.fetchSpotMarkets(e));else if("linear"===o)i.push(this.fetchFutureMarkets({category:"linear"}));else if("inverse"===o)i.push(this.fetchFutureMarkets({category:"inverse"}));else if("option"===o){let e=this.safeList(r,"options",["BTC","ETH","SOL"]);for(let t=0;t<e.length;t++){let s=e[t];i.push(this.fetchOptionMarkets({baseCoin:s}))}}else throw new a.ExchangeError(this.id+' fetchMarkets() this.options fetchMarkets "'+o+'" is not a supported market type')}let o=await Promise.all(i),n=[];for(let e=0;e<o.length;e++){let t=o[e];n=this.arrayConcat(n,t)}return n}async fetchSpotMarkets(e){let t,i={category:"spot"};t=!0===this.handleOption("fetchMarkets","usePrivateInstrumentsInfo",!1)?await this.privateGetV5MarketInstrumentsInfo(this.extend(i,e)):await this.publicGetV5MarketInstrumentsInfo(this.extend(i,e));let s=this.safeDict(t,"result",{}),r=this.safeList(s,"list",[]),a=[],o=this.parseNumber("0.001"),n=this.parseNumber("0.001");for(let e=0;e<r.length;e++){let t=r[e],i=this.safeString(t,"symbol"),s=this.safeString(t,"baseCoin"),d=this.safeString(t,"quoteCoin"),h=this.safeCurrencyCode(s),c=this.safeCurrencyCode(d);if(void 0===h||void 0===c)continue;let l=h+"/"+c,u="Trading"===this.safeString(t,"status"),f=this.safeDict(t,"lotSizeFilter"),p=this.safeDict(t,"priceFilter"),m=this.safeNumber(f,"quotePrecision"),g="none"!==this.safeString(t,"marginTrading","none");a.push(this.safeMarketStructure({id:i,symbol:l,base:h,quote:c,settle:void 0,baseId:s,quoteId:d,settleId:void 0,type:"spot",spot:!0,margin:g,swap:!1,future:!1,option:!1,active:u,contract:!1,linear:void 0,inverse:void 0,taker:o,maker:n,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(f,"basePrecision"),price:this.safeNumber(p,"tickSize",m)},limits:{leverage:{min:this.parseNumber("1"),max:void 0},amount:{min:this.safeNumber(f,"minOrderQty"),max:this.safeNumber(f,"maxOrderQty")},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(f,"minOrderAmt"),max:this.safeNumber(f,"maxOrderAmt")}},created:void 0,info:t}))}return a}async fetchFutureMarkets(e={}){let t,i=this.extend(e,{});i.limit=1e3;let s=[],r=this.handleOption("fetchMarkets","usePrivateInstrumentsInfo",!1);if(!0===r)t=await this.privateGetV5MarketInstrumentsInfo(i);else{let e=[this.publicGetV5MarketInstrumentsInfo(i),this.publicGetV5MarketInstrumentsInfo(this.extend(i,{status:"PreLaunch"}))],r=await Promise.all(e);t=this.safeDict(r,0,{}),s=this.safeDict(r,1,{})}let a=this.safeDict(t,"result",{}),o=this.safeList(a,"list",[]),n=this.safeString(a,"nextPageCursor");if(void 0!==n)for(;void 0!==n;){let e;i.cursor=n,e=!0===r?await this.privateGetV5MarketInstrumentsInfo(i):await this.publicGetV5MarketInstrumentsInfo(i);let t=this.safeDict(e,"result",{}),s=this.safeList(t,"list",[]);if(0===s.length)break;o=this.arrayConcat(s,o),n=this.safeString(t,"nextPageCursor")}let d=this.safeDict(s,"result",{}),h=this.safeList(d,"list",[]);o=this.arrayConcat(o,h);let c=[],l=this.safeString(a,"category");for(let e=0;e<o.length;e++){let t,i,s,r=o[e];void 0===l&&(l=this.safeString(r,"category"));let a="linear"===l,n="inverse"===l,d=this.safeString(r,"contractType"),h="InverseFutures"===d,u="LinearFutures"===d,f="LinearPerpetual"===d,p="InversePerpetual"===d,m=this.safeString(r,"symbol"),g=this.safeString(r,"baseCoin"),v=this.safeString(r,"quoteCoin"),y=g;a&&(y=v);let b=this.safeString(r,"settleCoin",y),w=this.safeCurrencyCode(g),k=this.safeCurrencyCode(v);if(void 0===w||void 0===k)continue;t=f&&"USD"===b?"USDC":this.safeCurrencyCode(b);let S=w+"/"+k,O=this.safeDict(r,"lotSizeFilter",{}),T=this.safeDict(r,"priceFilter",{}),P=this.safeDict(r,"leverageFilter",{}),I=this.safeString(r,"status"),A=f||p,x=h||u;A?i="swap":x&&(i="future"),A||void 0!==(s=this.omitZero(this.safeString(r,"deliveryTime")))&&(s=parseInt(s));let M=this.iso8601(s);S=S+":"+t,void 0!==s&&(S=S+"-"+this.yymmdd(s));let _=n?this.safeNumber2(O,"minTradingQty","minOrderQty"):this.parseNumber("1"),C=this.safeMarketStructure({id:m,symbol:S,base:w,quote:k,settle:t,baseId:g,quoteId:v,settleId:b,type:i,spot:!1,margin:void 0,swap:A,future:x,option:!1,active:"Trading"===I,contract:!0,linear:a,inverse:n,taker:this.safeNumber(r,"takerFee",this.parseNumber("0.0006")),maker:this.safeNumber(r,"makerFee",this.parseNumber("0.0001")),contractSize:_,expiry:s,expiryDatetime:M,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(O,"qtyStep"),price:this.safeNumber(T,"tickSize")},limits:{leverage:{min:this.safeNumber(P,"minLeverage"),max:this.safeNumber(P,"maxLeverage")},amount:{min:this.safeNumber2(O,"minTradingQty","minOrderQty"),max:this.safeNumber2(O,"maxTradingQty","maxOrderQty")},price:{min:this.safeNumber(T,"minPrice"),max:this.safeNumber(T,"maxPrice")},cost:{min:a?this.safeNumber(O,"minNotionalValue"):void 0,max:void 0}},created:this.safeInteger(r,"launchTime"),info:r});c.push(C)}return c}async fetchOptionMarkets(e){let t,i={category:"option"},s=this.handleOption("fetchMarkets","usePrivateInstrumentsInfo",!1);t=!0===s?await this.privateGetV5MarketInstrumentsInfo(this.extend(i,e)):await this.publicGetV5MarketInstrumentsInfo(this.extend(i,e));let r=this.safeDict(t,"result",{}),o=this.safeList(r,"list",[]),n=this.handleOption("fetchMarkets","loadAllOptions");if(!0===n){i.limit=1e3;let t=this.safeString(r,"nextPageCursor");if(void 0!==t)for(;void 0!==t;){let r;i.cursor=t,r=!0===s?await this.privateGetV5MarketInstrumentsInfo(this.extend(i,e)):await this.publicGetV5MarketInstrumentsInfo(this.extend(i,e));let a=this.safeDict(r,"result",{}),n=this.safeList(a,"list",[]);if(0===n.length)break;o=this.arrayConcat(n,o),t=this.safeString(a,"nextPageCursor")}}let d=[];for(let e=0;e<o.length;e++){let t=o[e],i=this.safeString(t,"symbol"),s=this.safeString(t,"baseCoin"),r=this.safeString(t,"quoteCoin"),h=this.safeString(t,"settleCoin"),c=this.safeCurrencyCode(s),l=this.safeCurrencyCode(r);if(void 0===c||void 0===l)continue;let u=this.safeCurrencyCode(h),f=this.safeDict(t,"lotSizeFilter",{}),p=this.safeDict(t,"priceFilter",{}),m=this.safeString(t,"status"),g=this.safeInteger(t,"deliveryTime");if(void 0===i)throw new a.ExchangeError(this.id+" method() missing id");let v=i.split("-"),y=this.safeString(v,2),b=this.safeString(v,3),w="Trading"===m,k=c===u,S=this.handleOption("fetchMarkets","loadExpiredOptions");(w||!0===n||!0===S)&&d.push(this.safeMarketStructure({id:i,symbol:c+"/"+l+":"+u+"-"+this.yymmdd(g)+"-"+y+"-"+b,base:c,quote:l,settle:u,baseId:s,quoteId:r,settleId:h,type:"option",subType:void 0,spot:!1,margin:!1,swap:!1,future:!1,option:!0,active:w,contract:!0,linear:!k,inverse:k,taker:this.safeNumber(t,"takerFee",this.parseNumber("0.0006")),maker:this.safeNumber(t,"makerFee",this.parseNumber("0.0001")),contractSize:this.parseNumber("1"),expiry:g,expiryDatetime:this.iso8601(g),strike:this.parseNumber(y),optionType:this.safeStringLower(t,"optionsType"),precision:{amount:this.safeNumber(f,"qtyStep"),price:this.safeNumber(p,"tickSize")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(f,"minOrderQty"),max:this.safeNumber(f,"maxOrderQty")},price:{min:this.safeNumber(p,"minPrice"),max:this.safeNumber(p,"maxPrice")},cost:{min:void 0,max:void 0}},created:this.safeInteger(t,"launchTime"),info:t}))}return d}parseTicker(e,t){let i=void 0===this.safeString(e,"openInterestValue"),s=this.safeInteger(e,"time"),r=this.safeString(e,"symbol"),a="contract";i&&(a="spot");let n=this.safeMarket(r,t,void 0,a),d=this.safeSymbol(r,n,void 0,a),h=this.safeString(e,"lastPrice"),c=this.safeString(e,"prevPrice24h"),l=this.safeString(e,"price24hPcnt");l=o.Y.stringMul(l,"100");let u=this.safeString(e,"turnover24h"),f=this.safeString(e,"volume24h"),p=this.safeString(e,"bid1Price"),m=this.safeString(e,"ask1Price"),g=this.safeString(e,"highPrice24h"),v=this.safeString(e,"lowPrice24h");return this.safeTicker({symbol:d,timestamp:s,datetime:this.iso8601(s),high:g,low:v,bid:p,bidVolume:this.safeString2(e,"bidSize","bid1Size"),ask:m,askVolume:this.safeString2(e,"askSize","ask1Size"),vwap:void 0,open:c,close:h,last:h,previousClose:void 0,change:void 0,percentage:l,average:void 0,baseVolume:f,quoteVolume:u,markPrice:this.safeString(e,"markPrice"),indexPrice:this.safeString(e,"indexPrice"),info:e},n)}async fetchTicker(e,t={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchTicker() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},[r,o]=this.getBybitType("fetchTicker",i,t);s.category=r;let n=await this.publicGetV5MarketTickers(this.extend(s,o)),d=this.safeDict(n,"result",{}),h=this.safeList(d,"list",[]),c=this.safeDict(h,0,{});return this.parseTicker(c,i)}async fetchTickers(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.safeStringN(t,["code","currency","baseCoin"]),o=!1;if(void 0!==e){let n;s=[];let d=this.handleMarketTypeAndParams("fetchTickers",void 0,t)[0];for(let t=0;t<e.length;t++){let h=e[t];if(i=-1===h.indexOf("/")?this.safeMarket(h,void 0,void 0,d):this.market(h),void 0===n)n=this.safeString(i,"type");else if(i.type!==n)throw new a.BadRequest(this.id+" fetchTickers can only accept a list of symbols of the same type");if(!0===i.option){if(void 0!==r&&r!==i.base)throw new a.BadRequest(this.id+" fetchTickers the base currency must be the same for all symbols, this endpoint only supports one base currency at a time. Read more about it here: https://bybit-exchange.github.io/docs/v5/market/tickers");void 0===r&&(r=this.safeString(i,"base")),o=!0}s.push(i.symbol)}}let n={},d=t;o&&(d=this.omit(t,["code","currency"]));let[h,c]=this.getBybitType("fetchTickers",i,d);n.category=h,"option"===h&&(n.category="option",void 0===r&&(r="BTC"),n.baseCoin=r);let l=await this.publicGetV5MarketTickers(this.extend(n,c)),u=this.safeDict(l,"result",{}),f=this.safeList(u,"list",[]);return this.parseTickers(f,s)}async fetchBidsAsks(e,t={}){return await this.fetchTickers(e,t)}parseOHLCV(e,t){let i=this.safeBool(t,"inverse");return[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,!0===i?6:5)]}async fetchOHLCV(e,t="1m",i,s,r={}){let o,n;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOHLCV() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let[d,h]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(d)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,h,1e3);let c=this.market(e),l={symbol:c.id},u=s;if(void 0===u&&(u=200),void 0!==i){let e=1e3*this.parseTimeframe(t);l.start=this.parseToInt(Math.ceil(i/e))*e}if(l.limit=u,[l,n]=this.handleUntilOption("end",l,h),l.interval=this.safeString(this.timeframes,t,t),!0===c.spot)l.category="spot",o=await this.publicGetV5MarketKline(this.extend(l,n));else{let e=this.safeString(n,"price"),t=this.omit(n,"price");if(!0===c.linear)l.category="linear";else if(!0===c.inverse)l.category="inverse";else throw new a.NotSupported(this.id+" fetchOHLCV() is not supported for option markets");o="mark"===e?await this.publicGetV5MarketMarkPriceKline(this.extend(l,t)):"index"===e?await this.publicGetV5MarketIndexPriceKline(this.extend(l,t)):"premiumIndex"===e?await this.publicGetV5MarketPremiumIndexPriceKline(this.extend(l,t)):await this.publicGetV5MarketKline(this.extend(l,t))}let f=this.safeDict(o,"result",{}),p=this.safeList(f,"list",[]);return this.parseOHLCVs(p,c,t,i,u)}parseFundingRate(e,t){let i,s=this.safeInteger(e,"timestamp"),r=this.omit(e,"timestamp"),a=this.safeString(r,"symbol"),o=this.safeSymbol(a,t,void 0,"swap"),n=this.safeNumber(r,"fundingRate"),d=this.safeInteger(r,"nextFundingTime"),h=this.safeNumber(r,"markPrice"),c=this.safeNumber(r,"indexPrice"),l=this.safeDict(this.safeMarket(a,t,void 0,"swap"),"info"),u=this.safeInteger(l,"fundingInterval");return void 0!==u&&(i=this.parseToInt(u/60).toString()+"h"),{info:r,symbol:o,markPrice:h,indexPrice:c,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:s,datetime:this.iso8601(s),fundingRate:n,fundingTimestamp:d,fundingDatetime:this.iso8601(d),nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:i}}async fetchFundingRates(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={},r=this.marketSymbols(e);void 0!==r&&(i=this.market(r[0]),1===r.length&&(s.symbol=i.id));let[o,n]=this.handleMarketTypeAndParams("fetchFundingRates",i,t);if("swap"!==o)throw new a.NotSupported(this.id+" fetchFundingRates() does not support "+o+" markets");let[d,h]=this.handleSubTypeAndParams("fetchFundingRates",i,n,"linear");s.category=d;let c=await this.publicGetV5MarketTickers(this.extend(s,h)),l=this.safeDict(c,"result",{}),u=this.safeList(l,"list",[]),f=this.safeInteger(c,"time");for(let e=0;e<u.length;e++)u[e].timestamp=f;return this.parseFundingRates(u,r)}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let[r,o]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(r)return await this.fetchPaginatedCallDynamic("fetchFundingRateHistory",e,t,i,o,200);let n=void 0===i?200:i,d={limit:n},h=this.market(e),c=this.safeInteger(h.info,"fundingInterval"),l=h.symbol;d.symbol=h.id;let[u,f]=this.getBybitType("fetchFundingRateHistory",h,o);if("spot"===u||"option"===u)throw new a.NotSupported(this.id+" fetchFundingRateHistory() only support linear and inverse market");d.category=u,void 0!==t&&(d.startTime=t);let p=this.safeInteger(f,"until"),m=this.safeInteger(f,"endTime",p),g=this.omit(f,["endTime","until"]);if(void 0!==m)d.endTime=m;else if(void 0!==t){let e=288e5;void 0!==c&&(e=60*c*1e3),d.endTime=this.sum(t,n*e)}let v=await this.publicGetV5MarketFundingHistory(this.extend(d,g)),y=[],b=this.safeDict(v,"result"),w=this.safeList(b,"list",[]);for(let e=0;e<w.length;e++){let t=w[e],i=this.safeInteger(t,"fundingRateTimestamp");y.push({info:t,symbol:this.safeSymbol(this.safeString(t,"symbol"),void 0,void 0,"swap"),fundingRate:this.safeNumber(t,"fundingRate"),timestamp:i,datetime:this.iso8601(i)})}let k=this.sortBy(y,"timestamp");return this.filterBySymbolSinceLimit(k,l,t,n)}parseTrade(e,t){let i,s,r=this.safeStringN(e,["execId","id","tradeId"]),a=this.safeString(e,"symbol"),n="spot";"createType"in e&&(n="contract");let d=this.safeString(e,"category");void 0!==d&&(n="spot"===d?"spot":"contract"),void 0!==t&&(n=this.safeString(t,"type"));let h=this.safeMarket(a,t,void 0,n),c=h.symbol,l=this.safeStringN(e,["execQty","orderQty","size"]),u=this.safeStringN(e,["execPrice","orderPrice","price"]),f=this.safeString(e,"execValue"),p=this.safeIntegerN(e,["time","execTime","tradeTime"]),m=this.safeStringLower(e,"side");if(void 0===m){let t=this.safeInteger(e,"isBuyer");void 0!==t&&(m=0!==t?"buy":"sell")}let g=this.safeBool(e,"isMaker");if(void 0!==g)i=g?"maker":"taker";else{let t=this.safeString(e,"lastLiquidityInd");"UNKNOWN"===t&&(t=void 0),void 0!==t&&(i="TAKER"===t||"MAKER"===t?t.toLowerCase():"AddedLiquidity"===t?"maker":"taker")}let v=this.safeStringLower(e,"orderType");"unknown"===v&&(v=void 0);let y=this.safeString(e,"execFee");if(void 0!==y){let t,i=this.safeString(e,"feeRate");t=!0===h.spot?o.Y.stringGt(y,"0")?"buy"===m?h.base:h.quote:"buy"===m?h.quote:h.base:!0===h.inverse?h.base:h.settle,s={cost:y,currency:this.safeString(e,"feeCoin",t),rate:i}}return this.safeTrade({id:r,info:e,timestamp:p,datetime:this.iso8601(p),symbol:c,order:this.safeString(e,"orderId"),type:v,side:m,takerOrMaker:i,price:u,amount:l,cost:f,fee:s},h)}async fetchTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={symbol:r.id};void 0!==i&&(o.limit=i);let[n,d]=this.getBybitType("fetchTrades",r,s);o.category=n;let h=await this.publicGetV5MarketRecentTrade(this.extend(o,d)),c=this.safeDict(h,"result",{}),l=this.safeList(c,"list",[]);return this.parseTrades(l,r,t,i)}async fetchOrderBook(e,t,i={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrderBook() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id},o=25;!0===s.spot?(o=50,r.category="spot"):!0===s.option?r.category="option":!0===s.linear?r.category="linear":!0===s.inverse&&(r.category="inverse"),r.limit=void 0!==t?t:o;let n=await this.publicGetV5MarketOrderbook(this.extend(r,i)),d=this.safeDict(n,"result",{}),h=this.safeInteger(d,"ts");return this.parseOrderBook(d,e,h,"b","a")}parseBalance(e){let t=this.safeInteger(e,"time"),i={info:e,timestamp:t,datetime:this.iso8601(t)},s=this.safeDict(e,"result",{}),r=this.safeListN(s,["loanAccountList","list","balance"]);if(void 0===r){let e=this.account();e.free=this.safeString(s,"availableBalance"),e.total=this.safeString(s,"walletBalance"),i.USDC=e}else for(let e=0;e<r.length;e++){let t=this.safeDict(r,e),s=this.safeString(t,"accountType");if("UNIFIED"===s||"CONTRACT"===s||"SPOT"===s){let e=this.safeList(t,"coin",[]);for(let t=0;t<e.length;t++){let s=this.account(),r=this.safeDict(e,t),a=this.safeString(r,"borrowAmount"),n=this.safeString(r,"accruedInterest");void 0!==a&&void 0!==n&&(s.debt=o.Y.stringAdd(a,n)),s.total=this.safeString(r,"walletBalance");let d=this.safeString2(r,"availableToWithdraw","free");if(void 0!==d)s.free=d;else{let e=this.safeString(r,"locked","0"),t=this.safeString(r,"totalPositionIM","0"),i=this.safeString(r,"totalOrderIM","0"),a=o.Y.stringAdd(e,t);s.used=a=o.Y.stringAdd(a,i)}let h=this.safeString(r,"coin"),c=this.safeCurrencyCode(h);void 0!==c&&(i[c]=s)}}else{let e=this.account(),s=this.safeString(t,"loan"),r=this.safeString(t,"interest");void 0!==s&&void 0!==r&&(e.debt=o.Y.stringAdd(s,r)),e.total=this.safeString2(t,"total","walletBalance"),e.free=this.safeStringN(t,["free","availableBalanceWithoutConvert","availableBalance","transferBalance"]),e.used=this.safeString(t,"locked");let a=this.safeStringN(t,["tokenId","coin","currencyCoin"]),n=this.safeCurrencyCode(a);void 0!==n&&(i[n]=e)}}return this.safeBalance(i)}async fetchBalance(e={}){let t,i,s;void 0===this.markets&&await this.loadMarkets();let r={},[a,o]=await this.isUnifiedEnabled();[i,s]=this.handleMarketTypeAndParams("fetchBalance",void 0,e);let[n,d]=this.handleSubTypeAndParams("fetchBalance",void 0,s);("swap"===i||"future"===i)&&(i=n);let h=void 0!==i?i.toLowerCase():void 0,c="spot"===i,l="linear"===i,u="inverse"===i;!0===a||!0===o?i=5>this.safeInteger(this.options,"unifiedMarginStatus",6)&&u?"contract":"unified":(l||u)&&(i="contract");let f=this.safeDict(this.options,"accountsByType",{}),p=this.safeStringUpper(f,i,i),[m,g]=this.handleMarginModeAndParams("fetchBalance",d);return c&&void 0!==m?t=await this.privateGetV5SpotCrossMarginTradeAccount(this.extend(r,g)):"fund"===h||"funding"===h?(r.accountType="FUND",t=await this.privateGetV5AssetTransferQueryAccountCoinsBalance(this.extend(r,g))):(r.accountType=p,t=await this.privateGetV5AccountWalletBalance(this.extend(r,g))),this.parseBalance(t)}parseOrderStatus(e){return this.safeString({NEW:"open",PARTIALLY_FILLED:"open",FILLED:"closed",CANCELED:"canceled",PENDING_CANCEL:"open",PENDING_NEW:"open",REJECTED:"rejected",PARTIALLY_FILLED_CANCELLED:"closed",Created:"open",New:"open",Rejected:"rejected",PartiallyFilled:"open",PartiallyFilledCanceled:"closed",Filled:"closed",PendingCancel:"open",Cancelled:"canceled",Untriggered:"open",Deactivated:"canceled",Triggered:"open",Active:"open"},e,e)}parseTimeInForce(e){return this.safeString({GoodTillCancel:"GTC",ImmediateOrCancel:"IOC",FillOrKill:"FOK",PostOnly:"PO"},e,e)}parseOrder(e,t){let i,s,r,a,o=this.safeString(e,"code");if(void 0!==o&&"0"!==o){let t=this.safeString(e,"category"),i="contract";return"spot"===t&&(i="spot"),this.safeOrder({info:e,status:"rejected",id:this.safeString(e,"orderId"),clientOrderId:this.safeString(e,"orderLinkId"),symbol:this.safeSymbol(this.safeString(e,"symbol"),void 0,void 0,i)})}let n=this.safeString(e,"symbol"),d="tpslMode"in e;i=void 0!==t?this.safeString(t,"type"):d?"contract":"spot";let h=this.safeMarket(n,t,void 0,i),c=h.symbol,l=this.safeInteger2(e,"createdTime","createdAt"),u=this.safeString(e,"marketUnit"),f=this.safeString(e,"orderId"),p=this.safeStringLower(e,"orderType"),m=this.safeString(e,"price"),g=this.safeStringLower(e,"side");!0==(!0===h.spot&&"market"===p&&("quoteCoin"===u||void 0===u&&"buy"===g))||(s=this.safeString(e,"qty")),r=this.safeString(e,"cumExecValue");let v=this.safeString(e,"cumExecQty"),y=this.safeString(e,"leavesQty"),b=this.safeInteger2(e,"updatedTime","updatedAt"),w=this.safeString(e,"orderStatus"),k=this.parseOrderStatus(w),S=this.safeDict(e,"cumFeeDetail",{}),O=Object.keys(S),T=this.safeString(O,0);void 0!==T&&(a={cost:this.safeNumber(S,T),currency:T});let P=this.safeString(e,"orderLinkId");void 0!==P&&P.length<1&&(P=void 0);let I=this.omitZero(this.safeString(e,"avgPrice")),A=this.safeString(e,"timeInForce"),x=this.parseTimeInForce(A),M=this.omitZero(this.safeString(e,"triggerPrice")),_=this.safeBool(e,"reduceOnly"),C=this.omitZero(this.safeString(e,"takeProfit")),B=this.omitZero(this.safeString(e,"stopLoss")),E="1"===this.safeString(e,"triggerDirection"),R=void 0!==M&&_;return void 0===B&&!0===R&&(E&&"buy"===g&&(B=M),E||"sell"!==g||(B=M)),void 0===C&&!0===R&&(E&&"sell"===g&&(C=M),E||"buy"!==g||(C=M)),this.safeOrder({info:e,id:f,clientOrderId:P,timestamp:l,datetime:this.iso8601(l),lastTradeTimestamp:b,lastUpdateTimestamp:b,symbol:c,type:p,timeInForce:x,postOnly:void 0,reduceOnly:this.safeBool(e,"reduceOnly"),side:g,price:m,triggerPrice:M,takeProfitPrice:C,stopLossPrice:B,amount:s,cost:r,average:I,filled:v,remaining:y,status:k,fee:a,trades:void 0},h)}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new a.NotSupported(this.id+" createMarketBuyOrderWithCost() supports spot orders only");return await this.createOrder(e,"market","buy",-1,void 0,this.extend({cost:t},i))}async createMarketSellOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==(await this.isUnifiedEnabled())[1])throw new a.NotSupported(this.id+" createMarketSellOrderWithCost() supports UTA accounts only");if(!0!==this.market(e).spot)throw new a.NotSupported(this.id+" createMarketSellOrderWithCost() supports spot orders only");return await this.createOrder(e,"market","sell",-1,void 0,this.extend({cost:t},i))}async createOrder(e,t,i,s,r,a={}){let o,n;void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h=(await this.isUnifiedEnabled())[1],c=void 0!==this.safeString2(a,"trailingAmount","trailingStop"),l=void 0!==this.safeString(a,"stopLossPrice"),u=void 0!==this.safeString(a,"takeProfitPrice"),f=this.createOrderRequest(e,t,i,s,r,a,h),p=l&&u||this.safeBool(a,"tradingStopEndpoint",!1);n=(c||!0===p)&&!0!==d.spot?"privatePostV5PositionTradingStop":"privatePostV5OrderCreate",o="privatePostV5PositionTradingStop"===this.handleOptionStringAndParams(a,"createOrder","method",n)[0]?await this.privatePostV5PositionTradingStop(f):await this.privatePostV5OrderCreate(f);let m=this.safeDict(o,"result",{});return this.parseOrder(m,d)}createOrderRequest(e,t,i,s,r,n={},d=!0){let h,c,l,u;if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let f=this.market(e),p=f.symbol,m=t.toLowerCase(),g={symbol:f.id},v=this.safeBool(n,"hedged",!1),y=this.safeBool(n,"reduceOnly"),b=this.safeValue2(n,"triggerPrice","stopPrice"),w=this.safeValue(n,"stopLossPrice"),k=this.safeValue(n,"takeProfitPrice"),S=this.safeValue(n,"stopLoss"),O=this.safeValue(n,"takeProfit"),T=this.safeString2(n,"trailingTriggerPrice","activePrice",this.numberToString(r)),P=this.safeString2(n,"trailingAmount","trailingStop"),I=void 0!==P,A=void 0!==b,x=void 0!==w,M=void 0!==k,_=void 0!==S,C=void 0!==O,B="market"===m,E="limit"===m,R="buy"===i,L=x&&M||this.safeBool(n,"tradingStopEndpoint",!1);[h,c]=this.handleOptionStringAndParams(n,"createOrder","method",I||!0===L?"privatePostV5PositionTradingStop":"privatePostV5OrderCreate");let N="privatePostV5PositionTradingStop"===h;if(void 0===r&&"limit"===m&&!N)throw new a.ArgumentsRequired(this.id+" createOrder requires a price argument for limit orders");o.Y.stringGt(this.numberToString(s),"0")&&(l=s);let D=void 0!==l?this.getAmount(p,l):void 0,q=void 0!==r?this.getPrice(p,this.numberToString(r)):void 0;if(N){if(_||C||A||!0===f.spot)throw new a.InvalidOrder(this.id+" the API endpoint used only supports contract trailingAmount, stopLossPrice and takeProfitPrice orders");if(x||M){let e,t;if(x){g.stopLoss=this.getPrice(p,w);let t=this.safeString2(c,"stopLossLimitPrice","slLimitPrice");void 0!==t?(e="Partial",g.slOrderType="Limit",g.slLimitPrice=t,g.slSize=D):(g.slOrderType="Market",void 0!==D?(g.slSize=D,e="Partial"):e="Full")}if(M){g.takeProfit=this.getPrice(p,k);let e=this.safeString2(c,"takeProfitLimitPrice","tpLimitPrice");void 0!==e?(t="Partial",g.tpOrderType="Limit",g.tpLimitPrice=e,g.tpSize=D):(g.tpOrderType="Market",void 0!==D?(g.tpSize=D,t="Partial"):t="Full")}if(M&&x&&e!==t)throw new a.InvalidOrder(this.id+" createOrder() requires both stopLoss and takeProfit to be full or partial when using as OCO combination");void 0!==e?g.tpslMode=e:g.tpslMode=t,c=this.omit(c,["stopLossLimitPrice","takeProfitLimitPrice","tradingStopEndpoint"])}}else{let e;g.side=this.capitalize(i),g.orderType=this.capitalize(m);let t=this.safeStringLower(c,"timeInForce");[e,c]=this.handlePostOnly(B,"postonly"===t,c),!0===e?g.timeInForce="PostOnly":"gtc"===t?g.timeInForce="GTC":"fok"===t?g.timeInForce="FOK":"ioc"===t&&(g.timeInForce="IOC"),!0===f.spot&&(void 0!==b?g.orderFilter="StopOrder":(x||M)&&(g.orderFilter="tpslOrder"));let s=this.safeString(c,"clientOrderId");void 0!==s?g.orderLinkId=s:!0===f.option&&(g.orderLinkId=this.uuid16()),E&&(g.price=q)}[u,c]=this.getBybitType("createOrderRequest",f,c),g.category=u;let F=this.safeString(c,"cost");c=this.omit(c,"cost");let V="market"===m&&"buy"===i&&(void 0!==r||void 0!==F),G="market"===m;if(!0===f.spot&&G&&d&&!V)if(void 0!==F||void 0!==r){let e;g.marketUnit="quoteCoin",e=void 0!==F?F:o.Y.stringMul(D,q),g.qty=this.getCost(p,e)}else g.marketUnit="baseCoin",g.qty=D;else if(!0===f.spot&&G&&"buy"===i){let e=!0;if([e,c]=this.handleOptionBoolAndParams(c,"createOrder","createMarketBuyOrderRequiresPrice",!1),e)if(void 0===r&&void 0===F)throw new a.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument");else{let e=o.Y.stringMul(this.numberToString(l),q);void 0!==F&&(e=F),g.qty=this.getCost(p,e)}else void 0!==F?g.qty=this.getCost(p,this.numberToString(F)):void 0!==r?g.qty=this.getCost(p,o.Y.stringMul(D,q)):g.qty=D}else I||N||(g.qty=D);if(I)void 0!==T&&(g.activePrice=this.getPrice(p,T)),g.trailingStop=P;else if(A&&!N){let e=this.safeString(c,"triggerDirection");if(c=this.omit(c,["triggerPrice","stopPrice","triggerDirection"]),!0===f.spot){if(void 0!==e)throw new a.NotSupported(this.id+" createOrder() : trigger order does not support triggerDirection for spot markets yet")}else{if(void 0===e)throw new a.ArgumentsRequired(this.id+' stop/trigger orders require a triggerDirection parameter, either "ascending" or "descending" to determine the direction of the trigger.');g.triggerDirection="ascending"===e||"above"===e||"1"===e?1:2}g.triggerPrice=this.getPrice(p,b)}else(x||M)&&!N&&(R?g.triggerDirection=x?1:2:g.triggerDirection=x?2:1,b=x?w:k,g.triggerPrice=this.getPrice(p,b),g.reduceOnly=!0);if((_||C)&&!N){if(_){let e=this.safeValue2(S,"triggerPrice","stopPrice",S);g.stopLoss=this.getPrice(p,e);let t=this.safeValue(S,"price");if(void 0!==t?(g.tpslMode="Partial",g.slOrderType="Limit",g.slLimitPrice=this.getPrice(p,t)):!0===f.spot&&(g.slOrderType="Market"),!0===f.spot&&G)throw new a.InvalidOrder(this.id+" createOrder(): attached stopLoss is not supported for spot market orders")}if(C){let e=this.safeValue2(O,"triggerPrice","stopPrice",O);g.takeProfit=this.getPrice(p,e);let t=this.safeValue(O,"price");if(void 0!==t?(g.tpslMode="Partial",g.tpOrderType="Limit",g.tpLimitPrice=this.getPrice(p,t)):!0===f.spot&&(g.tpOrderType="Market"),!0===f.spot&&G)throw new a.InvalidOrder(this.id+" createOrder(): attached takeProfit is not supported for spot market orders")}}if(!0!==f.spot&&!0===v){!0===y&&(c=this.omit(c,"reduceOnly"));g.positionIdx=(!0===y?"sell"===i:"buy"===i)?1:2}return c=this.omit(c,["stopPrice","timeInForce","stopLossPrice","takeProfitPrice","postOnly","clientOrderId","triggerPrice","stopLoss","takeProfit","trailingAmount","trailingTriggerPrice","hedged"]),this.extend(g,c)}async createOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=(await this.isUnifiedEnabled())[1],s=[],r=[];for(let t=0;t<e.length;t++){let a=this.safeDict(e,t),o=this.safeString(a,"symbol");r.push(o);let n=this.safeString(a,"type"),d=this.safeString(a,"side"),h=this.safeValue(a,"amount"),c=this.safeValue(a,"price"),l=this.safeDict(a,"params",{}),u=this.createOrderRequest(o,n,d,h,c,l,i);delete u.category,s.push(u)}let o=this.marketSymbols(r,void 0,!1,!0,!0),n=this.market(o[0]),d=this.safeInteger(this.options,"unifiedMarginStatus",6),[h,c]=this.getBybitType("createOrders",n,t);if("inverse"===h&&d<5)throw new a.NotSupported(this.id+" createOrders does not allow inverse orders for non UTA2.0 account");let l=await this.privatePostV5OrderCreateBatch(this.extend({category:h,request:s},c)),u=this.safeDict(l,"result",{}),f=this.safeList(u,"list",[]),p=this.safeDict(l,"retExtInfo",{}),m=this.safeList(p,"list",[]);for(let e=0;e<m.length;e++){let t=m[e];0!==this.safeInteger(t,"code")&&(f[e]=this.extend(f[e],t))}return this.parseOrders(f)}editOrderRequest(e,t,i,s,r,o,n={}){if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===s)throw new a.ArgumentsRequired(this.id+" requires a side argument");let d=this.market(t),h={symbol:d.id},c=this.safeString2(n,"orderLinkId","clientOrderId");void 0===c?h.orderId=e:h.orderLinkId=c;let[l,u]=this.getBybitType("editOrderRequest",d,n);h.category=l,void 0!==r&&(h.qty=this.getAmount(t,r)),void 0!==o&&(h.price=this.getPrice(t,this.numberToString(o)));let f=this.safeString2(u,"triggerPrice","stopPrice"),p=this.safeString(u,"stopLossPrice"),m=this.safeString(u,"takeProfitPrice"),g=this.safeValue(u,"stopLoss"),v=this.safeValue(u,"takeProfit"),y=void 0!==p,b=void 0!==g,w=void 0!==v;if((y||void 0!==m)&&(f=y?p:m),void 0!==f&&(h.triggerPrice="0"===f?f:this.getPrice(t,f),h.triggerBy=this.safeString(u,"triggerBy","LastPrice")),b||w){if(b){let e=this.safeString2(g,"triggerPrice","stopPrice",g);h.stopLoss="0"===e?e:this.getPrice(t,e),h.slTriggerBy=this.safeString(u,"slTriggerBy","LastPrice")}if(w){let e=this.safeString2(v,"triggerPrice","stopPrice",v);h.takeProfit="0"===e?e:this.getPrice(t,e),h.tpTriggerBy=this.safeString(u,"tpTriggerBy","LastPrice")}}return h}async editOrder(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets(),this.checkRequiredArgument("editOrder",t,"symbol");let n=this.market(t),d=this.editOrderRequest(e,t,i,s,r,a,o),h=await this.privatePostV5OrderAmend(this.extend(d,o)),c=this.safeDict(h,"result",{});return this.safeOrder({info:h,id:this.safeString(c,"orderId"),clientOrderId:this.safeString(c,"orderLinkId")},n)}async editOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=[],s=[];for(let t=0;t<e.length;t++){let r=this.safeDict(e,t),a=this.safeString(r,"symbol");s.push(a);let o=this.safeString(r,"id"),n=this.safeString(r,"type"),d=this.safeString(r,"side"),h=this.safeValue(r,"amount"),c=this.safeValue(r,"price"),l=this.safeDict(r,"params",{}),u=this.editOrderRequest(o,a,n,d,h,c,l);delete u.category,i.push(u)}s=this.marketSymbols(s,void 0,!1,!0,!0);let r=this.market(s[0]),o=this.safeInteger(this.options,"unifiedMarginStatus",6),[n,d]=this.getBybitType("editOrders",r,t);if("inverse"===n&&o<5)throw new a.NotSupported(this.id+" editOrders does not allow inverse orders for non UTA2.0 account");let h=await this.privatePostV5OrderAmendBatch(this.extend({category:n,request:i},d)),c=this.safeDict(h,"result",{}),l=this.safeList(c,"list",[]),u=this.safeDict(h,"retExtInfo",{}),f=this.safeList(u,"list",[]);for(let e=0;e<f.length;e++){let t=f[e];0!==this.safeInteger(t,"code")&&(l[e]=this.extend(l[e],t))}return this.parseOrders(l)}cancelOrderRequest(e,t,i={}){let s=this.market(t),r={symbol:s.id};!0===s.spot&&(r.orderFilter=!0===this.safeBool2(i,"stop","trigger",!1)?"StopOrder":"Order"),void 0!==e&&(r.orderId=e);let a=!0===s.spot?this.omit(i,["stop","trigger"]):i,[o,n]=this.getBybitType("cancelOrderRequest",s,a);return r.category=o,this.extend(r,n)}async cancelOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r=this.cancelOrderRequest(e,t,i),o=await this.privatePostV5OrderCancel(r),n=this.safeDict(o,"result",{});return this.parseOrder(n,s)}async cancelOrders(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t);if(!0!==(await this.isUnifiedEnabled())[1])throw new a.NotSupported(this.id+" cancelOrders() supports UTA accounts only");let[r,o]=this.getBybitType("cancelOrders",s,i);if("inverse"===r)throw new a.NotSupported(this.id+" cancelOrders does not allow inverse orders");let n=[],d=this.safeList2(o,"clientOrderIds","clientOids",[]),h=this.omit(o,["clientOrderIds","clientOids"]);for(let e=0;e<d.length;e++)n.push({symbol:s.id,orderLinkId:this.safeString(d,e)});for(let t=0;t<e.length;t++)n.push({symbol:s.id,orderId:this.safeString(e,t)});let c=await this.privatePostV5OrderCancelBatch(this.extend({category:r,request:n},h)),l=this.safeDict(c,"result",{}),u=this.safeList(l,"list",[]);return this.parseOrders(u,s)}async cancelAllOrdersAfter(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ExchangeError(this.id+" cancelAllOrdersAfter() missing timeout");let i={timeWindow:this.parseToInt(e/1e3)},[s,r]=this.handleMarketTypeAndParams("cancelAllOrdersAfter",void 0,t,"swap");return i.product=this.safeString({spot:"SPOT",swap:"DERIVATIVES",option:"OPTIONS"},s,s),await this.privatePostV5OrderDisconnectedCancelAll(this.extend(i,r))}async cancelOrdersForSymbols(e,t={}){let i;if(void 0===this.markets&&await this.loadMarkets(),!0!==(await this.isUnifiedEnabled())[1])throw new a.NotSupported(this.id+" cancelOrdersForSymbols() supports UTA accounts only");let s=[],r=t;for(let t=0;t<e.length;t++){let o,n=this.safeDict(e,t),d=this.safeString(n,"symbol"),h=this.market(d);if([o,r]=this.getBybitType("cancelOrders",h,r),"inverse"===o)throw new a.NotSupported(this.id+" cancelOrdersForSymbols does not allow inverse orders");if(void 0!==i&&i!==o)throw new a.ExchangeError(this.id+" cancelOrdersForSymbols requires all orders to be of the same category (linear, spot or option))");i=o;let c=this.safeString(n,"id"),l=this.safeString(n,"clientOrderId"),u="orderId";void 0!==l&&(u="orderLinkId");let f={symbol:h.id};f[u]="orderId"===u?c:l,s.push(f)}let o={category:i,request:s},n=await this.privatePostV5OrderCancelBatch(this.extend(o,r)),d=this.safeDict(n,"result",{}),h=this.safeList(d,"list",[]);return this.parseOrders(h)}async cancelAllOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let[s,r]=await this.isUnifiedEnabled(),o={};void 0!==e&&(o.symbol=(i=this.market(e)).id);let[n,d]=this.getBybitType("cancelAllOrders",i,t);if(o.category=n,"option"===n&&!0!==s&&!0!==r)throw new a.NotSupported(this.id+" cancelAllOrders() Normal Account not support "+n+" market");if("linear"===n||"inverse"===n){let t=this.safeString(d,"baseCoin");if(void 0===e&&void 0===t){let e=this.safeString(this.options,"defaultSettle","USDT");o.settleCoin=this.safeString(d,"settleCoin",e)}}let h=this.safeBool2(d,"stop","trigger",!1),c=this.omit(d,["stop","trigger"]);!0===h&&(o.orderFilter="StopOrder");let l=await this.privatePostV5OrderCancelAll(this.extend(o,c)),u=this.safeDict(l,"result",{}),f=this.safeList(u,"list");return Array.isArray(f)?this.parseOrders(f,i):[this.safeOrder({info:l})]}async fetchOrderClassic(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");if(void 0===this.markets&&await this.loadMarkets(),!0===this.market(t).spot)throw new a.NotSupported(this.id+" fetchOrder() is not supported for spot markets");let s=await this.fetchOrdersClassic(t,void 0,void 0,this.extend({orderId:e},i)),r=s.length;if(0===r){let t=this.safeBool2(i,"trigger","stop",!1);throw new a.OrderNotFound("Order "+e.toString()+" was not found."+(!0===t?"":' If you are trying to fetch SL/TP conditional order, you might try setting params["trigger"] = true'))}if(r>1)throw new a.InvalidOrder(this.id+" returned more than one order");return this.safeValue(s,0)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let[s,r]=await this.isUnifiedEnabled();if(!0!==s&&!0!==r)return await this.fetchOrderClassic(e,t,i);let[o,n]=this.handleOptionBoolAndParams(i,"fetchOrder","acknowledged",!1);if(!o)throw new a.ArgumentsRequired(this.id+' fetchOrder() can only access an order if it is in last 500 orders (of any status) for your account. Set params["acknowledged"] = true to hide this warning. Alternatively, we suggest to use fetchOpenOrder or fetchClosedOrder');let d=this.market(t),[h,c]=this.getBybitType("fetchOrder",d,n),l={symbol:d.id,orderId:e,category:h},[u,f]=this.handleParamBool2(c,"trigger","stop",!1);!0===u&&(l.orderFilter="StopOrder");let p=await this.privateGetV5OrderRealtime(this.extend(l,f)),m=this.safeDict(p,"result",{}),g=this.safeList(m,"list",[]);if(0===g.length){let t=' If you are trying to fetch SL/TP conditional order, you might try setting params["trigger"] = true';throw!0===u&&(t=""),new a.OrderNotFound("Order "+e.toString()+" was not found."+t)}let v=this.safeDict(g,0,{});return this.parseOrder(v,d)}async fetchOrdersClassic(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(s,"fetchOrdersClassic","paginate",!1);if(o)return await this.fetchPaginatedCallCursor("fetchOrdersClassic",e,t,i,n,"nextPageCursor","cursor",void 0,50);let d={};void 0!==e&&(d.symbol=(r=this.market(e)).id);let[h,c]=this.getBybitType("fetchOrdersClassic",r,n);if("spot"===h)throw new a.NotSupported(this.id+" fetchOrdersClassic() is not supported for spot markets");d.category=h;let l=this.safeBool2(c,"trigger","stop",!1),u=this.omit(c,["trigger","stop"]);!0===l&&(d.orderFilter="StopOrder"),void 0!==i&&(d.limit=i),void 0!==t&&(d.startTime=t);let f=this.safeInteger(u,"until"),p=this.safeInteger(u,"endTime",f),m=this.omit(u,["endTime","until"]);void 0!==p&&(d.endTime=p);let g=await this.privateGetV5OrderHistory(this.extend(d,m)),v=this.addPaginationCursorToResult(g);return this.parseOrders(v,r,t,i)}async fetchClosedOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.fetchClosedOrders(t,void 0,void 0,this.extend({orderId:e},i)),r=s.length;if(0===r){let t=this.safeBool2(i,"trigger","stop",!1);throw new a.OrderNotFound("Order "+e.toString()+" was not found."+(!0===t?"":' If you are trying to fetch SL/TP conditional order, you might try setting params["trigger"] = true'))}if(r>1)throw new a.InvalidOrder(this.id+" returned more than one order");return this.safeValue(s,0)}async fetchOpenOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.fetchOpenOrders(t,void 0,void 0,this.extend({orderId:e},i)),r=s.length;if(0===r){let t=this.safeBool2(i,"trigger","stop",!1);throw new a.OrderNotFound("Order "+e.toString()+" was not found."+(!0===t?"":' If you are trying to fetch SL/TP conditional order, you might try setting params["trigger"] = true'))}if(r>1)throw new a.InvalidOrder(this.id+" returned more than one order");return this.safeValue(s,0)}async fetchCanceledAndClosedOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchCanceledAndClosedOrders","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchCanceledAndClosedOrders",e,t,i,o,"nextPageCursor","cursor",void 0,50);let n={};void 0!==e&&(n.symbol=(r=this.market(e)).id);let[d,h]=this.getBybitType("fetchCanceledAndClosedOrders",r,o);n.category=d;let c=this.safeBool2(h,"trigger","stop",!1),l=this.omit(h,["trigger","stop"]);!0===c&&(n.orderFilter="StopOrder"),void 0!==i&&(n.limit=i),void 0!==t&&(n.startTime=t);let u=this.safeInteger(l,"until"),f=this.safeInteger(l,"endTime",u),p=this.omit(l,["endTime","until"]);void 0!==f&&(n.endTime=f);let m=await this.privateGetV5OrderHistory(this.extend(n,p)),g=this.addPaginationCursorToResult(m);return this.parseOrders(g,r,t,i)}async fetchClosedOrders(e,t,i,s={}){return void 0===this.markets&&await this.loadMarkets(),await this.fetchCanceledAndClosedOrders(e,t,i,this.extend({orderStatus:"Filled"},s))}async fetchCanceledOrders(e,t,i,s={}){return void 0===this.markets&&await this.loadMarkets(),await this.fetchCanceledAndClosedOrders(e,t,i,this.extend({orderStatus:"Cancelled"},s))}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchOpenOrders","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchOpenOrders",e,t,i,o,"nextPageCursor","cursor",void 0,50);let n={};void 0!==e&&(n.symbol=(r=this.market(e)).id);let[d,h]=this.getBybitType("fetchOpenOrders",r,o);if("linear"===d||"inverse"===d){let t=this.safeString(h,"baseCoin");if(void 0===e&&void 0===t){let e=this.safeString(this.options,"defaultSettle","USDT");n.settleCoin=this.safeString(h,"settleCoin",e)}}n.category=d;let c=this.safeBool2(h,"stop","trigger",!1),l=this.omit(h,["stop","trigger"]);!0===c&&(n.orderFilter="StopOrder"),void 0!==i&&(n.limit=i);let u=await this.privateGetV5OrderRealtime(this.extend(n,l)),f=this.addPaginationCursorToResult(u);return this.parseOrders(f,r,t,i)}async fetchOrderTrades(e,t,i,s,r={}){let a={},o=this.safeString2(r,"clientOrderId","orderLinkId");void 0!==o?a.orderLinkId=o:a.orderId=e;let n=this.omit(r,["clientOrderId","orderLinkId"]);return await this.fetchMyTrades(t,i,s,this.extend(a,n))}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchMyTrades",e,t,i,o,"nextPageCursor","cursor",void 0,100);let n={execType:"Trade"};void 0!==e&&(n.symbol=(r=this.market(e)).id);let[d,h]=this.getBybitType("fetchMyTrades",r,o);n.category=d,void 0!==i&&(n.limit=i),void 0!==t&&(n.startTime=t);let[c,l]=this.handleUntilOption("endTime",n,h),u=await this.privateGetV5ExecutionList(this.extend(c,l)),f=this.addPaginationCursorToResult(u);return this.parseTrades(f,r,t,i)}parseDepositAddress(e,t){let i=this.safeString(e,"addressDeposit"),s=this.safeString(e,"tagDeposit"),r=this.safeString(t,"code");return this.checkAddress(i),{info:e,currency:r,network:this.networkIdToCode(this.safeString(e,"chain"),r),address:i,tag:s}}async fetchDepositAddressesByNetwork(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={coin:this.currency(e).id},[s,r]=this.handleNetworkCodeAndParams(t);void 0!==s&&(i.chainType=this.networkCodeToId(s,e));let a=await this.privateGetV5AssetDepositQueryAddress(this.extend(i,r)),o=this.safeDict(a,"result",{}),n=this.safeList(o,"chains",[]),d=this.safeString(o,"coin"),h=this.currency(d),c=this.parseDepositAddresses(n,[h.code],!1,{currency:h.code});return this.indexBy(c,"network")}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),[s,r]=this.handleNetworkCodeAndParams(t),a=await this.fetchDepositAddressesByNetwork(e,r),o=this.selectNetworkCodeFromUnifiedNetworks(i.code,s,a);return this.safeValue(a,o)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchDeposits","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchDeposits",e,t,i,o,"nextPageCursor","cursor",void 0,50);let n={};void 0!==e&&(n.coin=(r=this.currency(e)).id),void 0!==t&&(n.startTime=t),void 0!==i&&(n.limit=i);let[d,h]=this.handleUntilOption("endTime",n,o),c=await this.privateGetV5AssetDepositQueryRecord(this.extend(d,h)),l=this.addPaginationCursorToResult(c);return this.parseTransactions(l,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchWithdrawals","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchWithdrawals",e,t,i,o,"nextPageCursor","cursor",void 0,50);let n={};void 0!==e&&(n.coin=(r=this.currency(e)).id),void 0!==t&&(n.startTime=t),void 0!==i&&(n.limit=i);let[d,h]=this.handleUntilOption("endTime",n,o),c=await this.privateGetV5AssetWithdrawQueryRecord(this.extend(d,h)),l=this.addPaginationCursorToResult(c);return this.parseTransactions(l,r,t,i)}parseTransactionStatus(e){return this.safeString({0:"unknown",1:"pending",2:"processing",3:"ok",4:"fail",SecurityCheck:"pending",Pending:"pending",success:"ok",CancelByUser:"canceled",Reject:"rejected",Fail:"failed",BlockchainConfirmed:"ok"},e,e)}parseTransaction(e,t){let i,s=this.safeString(e,"coin"),r=this.safeCurrencyCode(s,t),a=this.safeInteger2(e,"createTime","successAt"),o=this.safeInteger(e,"updateTime"),n=this.parseTransactionStatus(this.safeString(e,"status")),d=this.safeNumber2(e,"depositFee","withdrawFee"),h="withdrawal";"depositFee"in e&&(h="deposit"),void 0!==d&&(i={cost:d,currency:r});let c=this.safeString(e,"toAddress");return{info:e,id:this.safeString2(e,"id","withdrawId"),txid:this.safeString(e,"txID"),timestamp:a,datetime:this.iso8601(a),network:this.networkIdToCode(this.safeString(e,"chain"),r),address:void 0,addressTo:c,addressFrom:void 0,tag:this.safeString(e,"tag"),tagTo:void 0,tagFrom:void 0,type:h,amount:this.safeNumber(e,"amount"),currency:r,status:n,updated:o,fee:i,internal:void 0,comment:void 0}}async fetchLedger(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(s,"fetchLedger","paginate",!1);if(o)return await this.fetchPaginatedCallCursor("fetchLedger",e,t,i,n,"nextPageCursor","cursor",void 0,50);let d={},h=await this.isUnifiedEnabled(),c="coin";!0===h[1]?(c="currency",void 0!==t&&(d.startTime=t)):void 0!==t&&(d.start_date=this.yyyymmdd(t)),void 0!==e&&(a=this.currency(e),d[c]=a.id),void 0!==i&&(d.limit=i);let[l,u]=this.handleSubTypeAndParams("fetchLedger",void 0,n);if(!0===h[1]){let e=this.safeInteger(this.options,"unifiedMarginStatus",5);r="inverse"===l&&e<5?await this.privateGetV5AccountContractTransactionLog(this.extend(d,u)):await this.privateGetV5AccountTransactionLog(this.extend(d,u))}else r=await this.privateGetV5AccountContractTransactionLog(this.extend(d,u));let f=this.addPaginationCursorToResult(r);return this.parseLedger(f,a,t,i)}parseLedgerEntry(e,t){let i,s,r,a=this.safeString2(e,"coin","currency"),n=this.safeCurrencyCode(a,t),d=this.safeCurrency(a,t),h=this.safeString2(e,"amount","change"),c=this.safeString2(e,"wallet_balance","cashBalance"),l="in";if(o.Y.stringLt(h,"0")&&(l="out"),void 0!==c&&void 0!==h){let e;e="out"===l?h:o.Y.stringNeg(h),i=this.parseToNumeric(o.Y.stringAdd(c,e)),s=this.parseToNumeric(c),r=this.parseToNumeric(o.Y.stringAbs(h))}let u=this.parse8601(this.safeString(e,"exec_time"));return void 0===u&&(u=this.safeInteger(e,"transactionTime")),this.safeLedgerEntry({info:e,id:this.safeString(e,"id"),direction:l,account:this.safeString(e,"wallet_id"),referenceId:this.safeString(e,"tx_id"),referenceAccount:void 0,type:this.parseLedgerEntryType(this.safeString(e,"type")),currency:n,amount:r,timestamp:u,datetime:this.iso8601(u),before:i,after:s,status:"ok",fee:{currency:n,cost:this.safeNumber(e,"fee")}},d)}parseLedgerEntryType(e){return this.safeString({Deposit:"transaction",Withdraw:"transaction",RealisedPNL:"trade",Commission:"fee",Refund:"cashback",Prize:"prize",ExchangeOrderWithdraw:"transaction",ExchangeOrderDeposit:"transaction",TRANSFER_IN:"transaction",TRANSFER_OUT:"transaction",TRADE:"trade",SETTLEMENT:"trade",DELIVERY:"trade",LIQUIDATION:"trade",BONUS:"Prize",FEE_REFUND:"cashback",INTEREST:"transaction",CURRENCY_BUY:"trade",CURRENCY_SELL:"trade"},e,e)}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r),n=(await this.isUnifiedEnabled())[1],[d,h]=this.handleOptionStringAndParams(o,"withdraw","accountType");void 0===this.markets&&await this.loadMarkets(),this.checkAddress(i);let c=this.currency(e),l={coin:c.id,amount:this.numberToString(t),address:i,timestamp:this.milliseconds(),accountType:void 0===d?!0===n?"UTA":"SPOT":d};void 0!==a&&(l.tag=a);let[u,f]=this.handleNetworkCodeAndParams(h),p=this.networkCodeToId(u,e);void 0!==p&&(l.chain=p.toUpperCase());let m=await this.privatePostV5AssetWithdrawCreate(this.extend(l,f)),g=this.safeDict(m,"result",{});return this.parseTransaction(g,c)}async fetchPosition(e,t={}){let i;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchPosition() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id},[o,n]=this.getBybitType("fetchPosition",s,t);r.category=o,i=await this.privateGetV5PositionList(this.extend(r,n));let d=this.safeDict(i,"result",{}),h=this.safeList2(d,"list","dataList",[]),c=this.safeInteger(i,"time"),l=this.safeDict(h,0,{}),u=this.parsePosition(l,s);return u.timestamp=c,u.datetime=this.iso8601(c),u}async fetchPositions(e,t={}){let i,s,r;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(t,"fetchPositions","paginate",!1);if(o)return await this.fetchPaginatedCallCursor("fetchPositions",e,void 0,void 0,n,"nextPageCursor","cursor",void 0,200);if(void 0!==e&&Array.isArray(e)){let t=e.length;if(t>1)throw new a.ArgumentsRequired(this.id+" fetchPositions() does not accept an array with more than one symbol");1===t&&(i=e[0]),s=this.marketSymbols(e)}else void 0!==e&&(i=e,s=[this.symbol(i)]);let d={};void 0!==i&&(i=(r=this.market(i)).symbol,d.symbol=r.id);let[h,c]=this.getBybitType("fetchPositions",r,n);if("linear"===h||"inverse"===h){let e=this.safeString(c,"baseCoin");if("linear"===h){if(void 0===i&&void 0===e){let e=this.safeString(this.options,"defaultSettle","USDT");d.settleCoin=this.safeString(c,"settleCoin",e)}}else void 0===i&&void 0===e&&(d.category="inverse")}void 0===this.safeInteger(c,"limit")&&(d.limit=200);let l=this.omit(c,["type"]);d.category=h;let u=await this.privateGetV5PositionList(this.extend(d,l)),f=this.addPaginationCursorToResult(u),p=[];for(let e=0;e<f.length;e++){let t=f[e];"data"in t&&"is_valid"in t&&(t=this.safeDict(t,"data")),p.push(this.parsePosition(t))}return this.filterByArrayPositions(p,"symbol",s)}parsePosition(e,t){let i,s,r=void 0!==this.safeString(e,"closedSize"),a=this.safeString(e,"symbol"),n=this.safeMarket(a,t,void 0,"contract"),d=o.Y.stringAbs(this.safeString2(e,"size","qty")),h=this.safeString(e,"side"),c=this.safeString(e,"positionIdx");void 0!==c&&(i="0"!==c),void 0!==i&&i?h="1"===c?"long":"short":void 0!==h&&(h="Buy"===h?r?"short":"long":"Sell"===h?r?"long":"short":void 0);let l=this.safeString(n,"contractSize"),u=this.safeString(e,"markPrice");s=!0===n.inverse?o.Y.stringDiv(o.Y.stringMul(d,l),u):this.safeString2(e,"positionValue","cumExitValue");let f=this.omitZero(this.safeString(e,"unrealisedPnl")),p=this.safeString2(e,"positionIM","cumEntryValue"),m=this.safeString(e,"positionMM"),g=this.safeInteger2(e,"createdTime","createdAt"),v=this.parse8601(this.safeString(e,"updated_at"));void 0===v&&(v=this.safeInteger2(e,"updatedTime","updatedAt"));let y=this.safeString(e,"positionBalance"),b=this.omitZero(this.safeStringN(e,["entryPrice","avgPrice","avgEntryPrice"])),w=this.omitZero(this.safeString(e,"liqPrice")),k=this.safeString(e,"leverage");if(void 0!==w)if("USDC"===n.settle){let e=this.safeBool(this.options,"useMarkPriceForPositionCollateral",!1),t=b;e&&(t=u);let i=o.Y.stringAbs(o.Y.stringSub(t,w));y=o.Y.stringAdd(o.Y.stringAdd(o.Y.stringMul(i,d),m),f)}else{let t=this.safeString(e,"bustPrice");if(!0===n.linear){let e=o.Y.stringAbs(o.Y.stringSub(w,t));m=o.Y.stringMul(e,d),void 0!==b&&void 0===p&&(p=o.Y.stringDiv(o.Y.stringMul(d,b),k))}else{let e=o.Y.stringAbs(o.Y.stringSub(t,w)),i=o.Y.stringMul(t,w);m=o.Y.stringDiv(o.Y.stringMul(d,e),i),void 0!==b&&void 0===p&&(p=o.Y.stringDiv(d,o.Y.stringMul(b,k)))}}let S=o.Y.stringDiv(m,s),O=o.Y.stringDiv(m,y,4);return this.safePosition({info:e,id:void 0,symbol:n.symbol,timestamp:g,datetime:this.iso8601(g),lastUpdateTimestamp:v,initialMargin:this.parseNumber(p),initialMarginPercentage:this.parseNumber(o.Y.stringDiv(p,s)),maintenanceMargin:this.parseNumber(m),maintenanceMarginPercentage:this.parseNumber(S),entryPrice:this.parseNumber(b),notional:this.parseNumber(s),leverage:this.parseNumber(k),unrealizedPnl:this.parseNumber(f),realizedPnl:this.safeNumber2(e,"curRealisedPnl","closedPnl"),contracts:this.parseNumber(d),contractSize:this.safeNumber(n,"contractSize"),marginRatio:this.parseNumber(O),liquidationPrice:this.parseNumber(w),markPrice:this.parseNumber(u),lastPrice:this.safeNumber(e,"avgExitPrice"),collateral:this.parseNumber(y),marginMode:void 0,side:h,percentage:void 0,stopLossPrice:this.safeNumber2(e,"stop_loss","stopLoss"),takeProfitPrice:this.safeNumber2(e,"take_profit","takeProfit"),hedged:i})}async fetchLeverage(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=await this.fetchPosition(e,t);return this.parseLeverage(s,i)}parseLeverage(e,t){let i=this.safeString(e,"symbol"),s=this.safeInteger(e,"leverage");return{info:e,symbol:this.safeSymbol(i,t),marginMode:this.safeStringLower(e,"marginMode"),longLeverage:s,shortLeverage:s}}async setMarginMode(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets();let[o,n]=await this.isUnifiedEnabled(),d={isolated:"ISOLATED_MARGIN",cross:"REGULAR_MARGIN",portfolio:"PORTFOLIO_MARGIN"};if(!0===o||!0===n){let t=this.safeString(d,e);if(void 0===t)throw new a.NotSupported(this.id+" setMarginMode() marginMode must be either [isolated, cross, portfolio]");s=await this.privatePostV5AccountSetMarginMode(this.extend({setMarginMode:t},i))}else{if(void 0===t)throw new a.ArgumentsRequired(this.id+" setMarginMode() requires a symbol parameter for non unified account");if("USDC"===(r=this.market(t)).settle){if("cross"!==e&&"portfolio"!==e)throw new a.NotSupported(this.id+" setMarginMode() for usdc market marginMode must be either [cross, portfolio]");let t={setMarginMode:this.safeString(d,e)};s=await this.privatePostV5AccountSetMarginMode(this.extend(t,i))}else{let t,o,n,d,[h,c]=this.getBybitType("setPositionMode",r,i);if("cross"===e)t=0;else if("isolated"===e)t=1;else throw new a.NotSupported(this.id+" setMarginMode() with symbol marginMode must be either [isolated, cross]");let l=this.safeString(c,"leverage");if(void 0===l){if(o=this.safeString2(c,"sell_leverage","sellLeverage"),n=this.safeString2(c,"buy_leverage","buyLeverage"),void 0===o&&void 0===n)throw new a.ArgumentsRequired(this.id+" setMarginMode() requires a leverage parameter or sell_leverage and buy_leverage parameters");void 0===n&&(n=o),void 0===o&&(o=n),d=this.omit(c,["buy_leverage","sell_leverage","sellLeverage","buyLeverage"])}else o=l,n=l,d=this.omit(c,"leverage");let u={category:h,symbol:r.id,tradeMode:t,buyLeverage:n,sellLeverage:o};s=await this.privatePostV5PositionSwitchIsolated(this.extend(u,d))}}return s}async setLeverage(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r=this.numberToString(e),o={symbol:s.id,buyLeverage:r,sellLeverage:r};if(o.buyLeverage=r,o.sellLeverage=r,!0===s.linear)o.category="linear";else if(!0===s.inverse)o.category="inverse";else throw new a.NotSupported(this.id+" setLeverage() only support linear and inverse market");return await this.privatePostV5PositionSetLeverage(this.extend(o,i))}async setPositionMode(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let r={mode:3*!!e};void 0===t?r.coin="USDT":r.symbol=this.safeString(s,"id");let a=i;if(void 0!==t)r.category=this.safeBool(s,"linear",!1)?"linear":"inverse";else{let e;[e,a]=this.getBybitType("setPositionMode",s,i),r.category=e}let o=this.omit(a,"type");return await this.privatePostV5PositionSwitchMode(this.extend(r,o))}async fetchDerivativesOpenInterestHistory(e,t="1h",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n="inverse";!0===o.linear&&(n="linear");let d=this.safeString(r,"category",n),h=this.safeDict(this.options,"intervals"),c=this.safeString(h,t);if(void 0===c)throw new a.BadRequest(this.id+" fetchOpenInterestHistory() cannot use the "+t+" timeframe");let l={symbol:o.id,intervalTime:c,category:d};void 0!==i&&(l.startTime=i);let u=this.safeInteger(r,"until"),f=this.omit(r,["until"]);if(void 0!==u)l.endTime=u;else if(void 0!==i){let e=this.parseTimeframe(t),r=void 0===s?50:s;l.endTime=this.sum(i,e*r*1e3)}void 0!==s&&(l.limit=s);let p=await this.publicGetV5MarketOpenInterest(this.extend(l,f)),m=this.safeDict(p,"result",{}),g=this.addPaginationCursorToResult(p),v=this.safeString(m,"symbol"),y=this.safeMarket(v,o,void 0,"contract");return this.parseOpenInterestsHistory(g,y,i,s)}async fetchOpenInterest(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.contract)throw new a.BadRequest(this.id+" fetchOpenInterest() supports contract markets only");let s=this.safeString(t,"interval","1h"),r=this.safeDict(this.options,"intervals"),o=this.safeString(r,s);if(void 0===o)throw new a.BadRequest(this.id+" fetchOpenInterest() cannot use the "+s+" timeframe");let n="inverse";!0===i.linear&&(n="linear");let d=this.safeString(t,"category",n),h={symbol:i.id,intervalTime:o,category:d},c=await this.publicGetV5MarketOpenInterest(this.extend(h,t)),l=this.safeDict(c,"result",{}),u=this.safeString(l,"symbol"),f=this.safeMarket(u,i,void 0,"contract"),p=this.addPaginationCursorToResult(c);return this.parseOpenInterest(p[0],f)}async fetchOpenInterestHistory(e,t="1h",i,s,r={}){if("1m"===t)throw new a.BadRequest(this.id+" fetchOpenInterestHistory cannot use the 1m timeframe");if(void 0===this.markets&&await this.loadMarkets(),!0===this.safeBool(r,"paginate")){let a=this.omit(r,"paginate");return a.timeframe=t,await this.fetchPaginatedCallCursor("fetchOpenInterestHistory",e,i,s,a,"nextPageCursor","cursor",void 0,200)}let o=this.market(e);if(!0===o.spot||!0===o.option)throw new a.BadRequest(this.id+" fetchOpenInterestHistory() symbol does not support market "+e);let n={symbol:o.id};return void 0!==s&&(n.limit=s),await this.fetchDerivativesOpenInterestHistory(e,t,i,s,r)}parseOpenInterest(e,t){let i=this.safeInteger(e,"timestamp"),s=this.safeNumber2(e,"open_interest","openInterest"),r=this.safeBool(t,"linear",!1),a=this.safeBool(t,"inverse",!1),o=r?s:void 0,n=a?s:void 0;return this.safeOpenInterest({symbol:this.safeString(t,"symbol"),openInterestAmount:o,openInterestValue:n,timestamp:i,datetime:this.iso8601(i),info:e},t)}async fetchCrossBorrowRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={currency:i.id,vipLevel:"No VIP"},r=await this.publicGetV5SpotMarginTradeData(this.extend(s,t)),a=this.safeInteger(r,"time"),o=this.safeDict(r,"result",{}),n=this.safeList(o,"vipCoinList",[]),d=this.safeDict(n,0,{}),h=this.safeList(d,"list",[]),c=this.safeDict(h,0,{});return c.timestamp=a,this.parseBorrowRate(c,i)}parseBorrowRate(e,t){let i=this.safeInteger(e,"timestamp"),s=this.safeString2(e,"coin","currency"),r=this.safeNumber(e,"hourlyBorrowRate"),a=void 0!==r?36e5:864e5;return{currency:this.safeCurrencyCode(s,t),rate:this.safeNumber(e,"interestRate",r),period:a,timestamp:i,datetime:this.iso8601(i),info:e}}async fetchBorrowInterest(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=await this.privateGetV5SpotCrossMarginTradeAccount(this.extend({},r)),o=this.safeDict(a,"result",{}),n=this.safeList(o,"loanAccountList",[]),d=this.parseBorrowInterests(n);return this.filterByCurrencySinceLimit(d,e,i,s)}async fetchBorrowRateHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={currency:this.currency(e).id},a=void 0===t?this.milliseconds()-2592e6:t;r.startTime=a;let o=this.safeInteger2(s,"until","endTime"),n=this.omit(s,["until"]);void 0===o&&(o=a+2592e6),r.endTime=o;let d=await this.privateGetV5SpotMarginTradeInterestRateHistory(this.extend(r,n)),h=this.safeDict(d,"result"),c=this.safeList(h,"list",[]);return this.parseBorrowRateHistory(c,e,a,i)}parseBorrowInterest(e,t){return{info:e,symbol:void 0,currency:this.safeCurrencyCode(this.safeString(e,"tokenId")),interest:this.safeNumber(e,"interest"),interestRate:void 0,amountBorrowed:this.safeNumber(e,"loan"),marginMode:"cross",timestamp:void 0,datetime:void 0}}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.safeString(r,"transferId",this.uuid()),o=this.safeDict(this.options,"accountsByType",{}),n=this.safeString(o,i,i),d=this.safeString(o,s,s),h=this.currency(e),c=this.currencyToPrecision(e,t),l={transferId:a,fromAccountType:n,toAccountType:d,coin:h.id,amount:c},u=await this.privatePostV5AssetTransferInterTransfer(this.extend(l,r)),f=this.safeInteger(u,"time"),p=this.safeDict(u,"result",{}),m=this.safeString2(u,"retCode","retMsg"),g=this.parseTransferStatus(m);return this.extend(this.parseTransfer(p,h),{timestamp:f,datetime:this.iso8601(f),amount:this.parseNumber(c),fromAccount:i,toAccount:s,status:g})}async fetchTransfers(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchTransfers","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchTransfers",e,t,i,o,"nextPageCursor","cursor",void 0,50);let n={};void 0!==e&&(n.coin=(r=this.safeCurrency(e)).id),void 0!==t&&(n.startTime=t),void 0!==i&&(n.limit=i);let[d,h]=this.handleUntilOption("endTime",n,o),c=await this.privateGetV5AssetTransferQueryInterTransferList(this.extend(d,h)),l=this.addPaginationCursorToResult(c);return this.parseTransfers(l,r,t,i)}async borrowCrossMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.currency(e),r={coin:s.id,amount:this.currencyToPrecision(e,t)},a=await this.privatePostV5AccountBorrow(this.extend(r,i)),o=this.safeDict(a,"result",{});return this.parseMarginLoan(o,s)}async repayCrossMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.currency(e),r={coin:s.id,amount:this.numberToString(t)},a=await this.privatePostV5AccountNoConvertRepay(this.extend(r,i)),o=this.safeDict(a,"result",{}),n=this.parseMarginLoan(o,s);return this.extend(n,{amount:t})}parseMarginLoan(e,t){let i=this.safeString(e,"coin");return{id:void 0,currency:this.safeCurrencyCode(i,t),amount:this.safeNumber(e,"amount"),symbol:void 0,timestamp:void 0,datetime:void 0,info:e}}parseTransferStatus(e){return this.safeString({0:"ok",OK:"ok",SUCCESS:"ok"},e,e)}parseTransfer(e,t){let i=this.safeString(e,"coin"),s=this.safeInteger(e,"timestamp"),r=this.safeString(e,"fromAccountType"),a=this.safeString(e,"toAccountType"),o=this.safeDict(this.options,"accountsById",{}),n=this.safeString(o,r,r),d=this.safeString(o,a,a);return{info:e,id:this.safeString(e,"transferId"),timestamp:s,datetime:this.iso8601(s),currency:this.safeCurrencyCode(i,t),amount:this.safeNumber(e,"amount"),fromAccount:n,toAccount:d,status:this.parseTransferStatus(this.safeString(e,"status"))}}async fetchDerivativesMarketLeverageTiers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id};!0===i.linear?s.category="linear":!0===i.inverse&&(s.category="inverse");let r=await this.publicGetV5MarketRiskLimit(this.extend(s,t)),a=this.safeDict(r,"result"),o=this.safeList(a,"list");return this.parseMarketLeverageTiers(o,i)}async fetchMarketLeverageTiers(e,t={}){let i;if(void 0===this.markets&&await this.loadMarkets(),!0===(i=this.market(e)).spot||!0===i.option)throw new a.BadRequest(this.id+" fetchMarketLeverageTiers() symbol does not support market "+e);return i.id,await this.fetchDerivativesMarketLeverageTiers(e,t)}parseTradingFee(e,t){let i=this.safeString(e,"symbol"),s="contract";return void 0!==t&&(s=this.safeString(t,"type")),{info:e,symbol:this.safeSymbol(i,t,void 0,s),maker:this.safeNumber(e,"makerFeeRate"),taker:this.safeNumber(e,"takerFeeRate"),percentage:void 0,tierBased:void 0}}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},[r,a]=this.getBybitType("fetchTradingFee",i,t);s.category=r;let o=await this.privateGetV5AccountFeeRate(this.extend(s,a)),n=this.safeDict(o,"result",{}),d=this.safeList(n,"list",[]),h=this.safeDict(d,0,{});return this.parseTradingFee(h,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleOptionStringAndParams(e,"fetchTradingFees","type","future");if("spot"===t)throw new a.NotSupported(this.id+" fetchTradingFees() is not supported for spot market");let s=await this.privateGetV5AccountFeeRate(i),r=this.safeDict(s,"result",{});r=this.safeList(r,"list",[]);let o={};for(let e=0;e<r.length;e++){let t=this.parseTradingFee(r[e]),i=t.symbol;void 0!==i&&(o[i]=t)}return o}parseDepositWithdrawFee(e,t){let i=this.safeList(e,"chains",[]),s=i.length,r={info:e,withdraw:{fee:void 0,percentage:void 0},deposit:{fee:void 0,percentage:void 0},networks:{}};if(0!==s)for(let e=0;e<s;e++){let a=this.safeDict(i,e),o=this.safeString(a,"chain"),n=this.safeString(t,"code"),d=this.networkIdToCode(o,n);void 0!==d&&(r.networks[d]={deposit:{fee:void 0,percentage:void 0},withdraw:{fee:this.safeNumber(a,"withdrawFee"),percentage:!1}}),1===s&&(r.withdraw.fee=this.safeNumber(a,"withdrawFee"),r.withdraw.percentage=!1)}return r}async fetchDepositWithdrawFees(e,t={}){this.checkRequiredCredentials(),void 0===this.markets&&await this.loadMarkets();let i=await this.privateGetV5AssetCoinQueryInfo(t),s=this.safeDict(i,"result",{}),r=this.safeList(s,"rows",[]);return this.parseDepositWithdrawFees(r,e,"coin")}async fetchSettlementHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o={};void 0!==e&&(o.symbol=(r=this.market(e)).id);let[n,d]=this.getBybitType("fetchSettlementHistory",r,s);if("spot"===n)throw new a.NotSupported(this.id+" fetchSettlementHistory() is not supported for spot market");o.category=n,void 0!==i&&(o.limit=i);let h=await this.publicGetV5MarketDeliveryPrice(this.extend(o,d)),c=this.safeDict(h,"result",{}),l=this.safeList(c,"list",[]),u=this.parseSettlements(l,r),f=this.sortBy(u,"timestamp");return this.filterBySymbolSinceLimit(f,this.safeString(r,"symbol"),t,i)}async fetchMySettlementHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o={};void 0!==e&&(o.symbol=(r=this.market(e)).id);let[n,d]=this.getBybitType("fetchMySettlementHistory",r,s);if("spot"===n)throw new a.NotSupported(this.id+" fetchMySettlementHistory() is not supported for spot market");o.category=n,void 0!==i&&(o.limit=i);let h=await this.privateGetV5AssetDeliveryRecord(this.extend(o,d)),c=this.safeDict(h,"result",{}),l=this.safeList(c,"list",[]),u=this.parseSettlements(l,r),f=this.sortBy(u,"timestamp");return this.filterBySymbolSinceLimit(f,this.safeString(r,"symbol"),t,i)}parseSettlement(e,t){let i=this.safeInteger(e,"deliveryTime"),s=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(s,t),price:this.safeNumber(e,"deliveryPrice"),timestamp:i,datetime:this.iso8601(i)}}parseSettlements(e,t){let i=[];for(let s=0;s<e.length;s++)i.push(this.parseSettlement(e[s],t));return i}async fetchVolatilityHistory(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={category:"option",baseCoin:this.currency(e).id},s=await this.publicGetV5MarketHistoricalVolatility(this.extend(i,t)),r=this.safeList(s,"result",[]);return this.parseVolatilityHistory(r)}parseVolatilityHistory(e){let t=[];for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeInteger(s,"time");t.push({info:e,timestamp:r,datetime:this.iso8601(r),volatility:this.safeNumber(s,"value")})}return t}async fetchGreeks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id,category:"option"},r=await this.publicGetV5MarketTickers(this.extend(s,t)),a=this.safeInteger(r,"time"),o=this.safeDict(r,"result",{}),n=this.safeList(o,"list",[]),d=this.parseGreeks(n[0],i);return this.extend(d,{timestamp:a,datetime:this.iso8601(a)})}async fetchAllGreeks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s={category:"option",baseCoin:this.safeString(t,"baseCoin","BTC")};void 0!==i&&1===i.length&&(s.symbol=this.market(i[0]).id);let r=await this.publicGetV5MarketTickers(this.extend(s,t)),a=this.safeDict(r,"result",{}),o=this.safeList(a,"list",[]);return this.parseAllGreeks(o,i)}parseGreeks(e,t){let i=this.safeString(e,"symbol");return{symbol:this.safeSymbol(i,t),timestamp:void 0,datetime:void 0,delta:this.safeNumber(e,"delta"),gamma:this.safeNumber(e,"gamma"),theta:this.safeNumber(e,"theta"),vega:this.safeNumber(e,"vega"),rho:void 0,bidSize:this.safeNumber(e,"bid1Size"),askSize:this.safeNumber(e,"ask1Size"),bidImpliedVolatility:this.safeNumber(e,"bid1Iv"),askImpliedVolatility:this.safeNumber(e,"ask1Iv"),markImpliedVolatility:this.safeNumber(e,"markIv"),bidPrice:this.safeNumber(e,"bid1Price"),askPrice:this.safeNumber(e,"ask1Price"),markPrice:this.safeNumber(e,"markPrice"),lastPrice:this.safeNumber(e,"lastPrice"),underlyingPrice:this.safeNumber(e,"underlyingPrice"),info:e}}async fetchMyLiquidations(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyLiquidations","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchMyLiquidations",e,t,i,o,"nextPageCursor","cursor",void 0,100);let n={execType:"BustTrade"};void 0!==e&&(n.symbol=(r=this.market(e)).id);let[d,h]=this.getBybitType("fetchMyLiquidations",r,o);n.category=d,void 0!==i&&(n.limit=i),void 0!==t&&(n.startTime=t);let[c,l]=this.handleUntilOption("endTime",n,h),u=await this.privateGetV5ExecutionList(this.extend(c,l)),f=this.addPaginationCursorToResult(u);return this.parseLiquidations(f,r,t,i)}parseLiquidation(e,t){let i=this.safeString(e,"symbol"),s=this.safeInteger(e,"execTime"),r=this.safeString(e,"execQty"),a=this.safeString(t,"contractSize"),n=this.safeString(e,"execPrice"),d=o.Y.stringMul(r,a),h=o.Y.stringMul(d,n);return this.safeLiquidation({info:e,symbol:this.safeSymbol(i,t,void 0,"contract"),contracts:this.parseNumber(r),contractSize:this.parseNumber(a),price:this.parseNumber(n),baseValue:this.parseNumber(d),quoteValue:this.parseNumber(h),timestamp:s,datetime:this.iso8601(s)})}async getLeverageTiersPaginated(e,t={}){let i;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(i=this.market(e));let[s,r]=this.handleOptionBoolAndParams(t,"getLeverageTiersPaginated","paginate",!1);if(s)return await this.fetchPaginatedCallCursor("getLeverageTiersPaginated",e,void 0,void 0,r,"nextPageCursor","cursor",void 0,100);let[a,o]=this.handleSubTypeAndParams("getLeverageTiersPaginated",i,r,"linear"),n=await this.publicGetV5MarketRiskLimit(this.extend({category:a},o)),d=this.addPaginationCursorToResult(n),h=this.safeDict(d,0),c=d.length-1,l=this.safeDict(d,c,{});return l.info={nextPageCursor:this.safeString(h,"nextPageCursor")},d[c]=l,d}async fetchLeverageTiers(e,t={}){let i,s;if(void 0===this.markets&&await this.loadMarkets(),void 0!==e){if(!0===(i=this.market(e[0])).spot)throw new a.NotSupported(this.id+" fetchLeverageTiers() is not supported for spot market");s=this.safeString(i,"symbol")}let r=await this.getLeverageTiersPaginated(s,this.extend({paginate:!0,paginationCalls:200},t)),o=this.marketSymbols(e);return this.parseLeverageTiers(r,o,"symbol")}parseLeverageTiers(e,t,i){let s={},r=this.marketIds(t),a=void 0===i?"symbol":i,o=this.filterByArray(e,a,r,!1),n=this.groupBy(o,a),d=Object.keys(n);for(let e=0;e<d.length;e++){let t=d[e],i=n[t];for(let e=0;e<i.length;e++){let t=this.safeInteger(i[e],"id");i[e].id=t}let r=this.safeMarket(t,void 0,void 0,"contract");s[r.symbol]=this.parseMarketLeverageTiers(this.sortBy(i,"id"),r)}return s}parseMarketLeverageTiers(e,t){let i=[];for(let t=0;t<e.length;t++){let s=this.safeDict(e,t),r=this.safeString(e,"symbol"),a=this.safeMarket(r),o=this.parseNumber("0");0!==t&&(o=this.safeNumber(e[t-1],"riskLimitValue")),i.push({tier:this.safeInteger(s,"id"),symbol:this.safeSymbol(r,a),currency:a.settle,minNotional:o,maxNotional:this.safeNumber(s,"riskLimitValue"),maintenanceMarginRate:this.safeNumber(s,"maintenanceMargin"),maxLeverage:this.safeNumber(s,"maxLeverage"),info:s})}return i}async fetchFundingHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchFundingHistory","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchFundingHistory",e,t,i,o,"nextPageCursor","cursor",void 0,100);let n={execType:"Funding"};void 0!==e&&(n.symbol=(r=this.market(e)).id);let[d,h]=this.getBybitType("fetchFundingHistory",r,o);n.category=d,void 0!==e&&(n.symbol=this.safeString(r,"id")),void 0!==t&&(n.startTime=t),void 0!==i?n.size=i:n.size=100;let[c,l]=this.handleUntilOption("endTime",n,h),u=await this.privateGetV5ExecutionList(this.extend(c,l)),f=this.addPaginationCursorToResult(u);return this.parseIncomes(f,r,t,i)}parseIncome(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t,void 0,"contract"),r="USDT";!0===s.inverse&&(r=s.quote);let a=this.safeInteger(e,"execTime");return{info:e,symbol:this.safeSymbol(i,s,"-","swap"),code:r,timestamp:a,datetime:this.iso8601(a),id:this.safeString(e,"execId"),amount:this.safeNumber(e,"execFee"),rate:this.safeNumber(e,"feeRate")}}async fetchOption(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={category:"option",symbol:i.id},r=await this.publicGetV5MarketTickers(this.extend(s,t)),a=this.safeDict(r,"result",{}),o=this.safeList(a,"list",[]),n=this.safeDict(o,0,{});return this.parseOption(n,void 0,i)}async fetchOptionChain(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={category:"option",baseCoin:this.currency(e).id},s=await this.publicGetV5MarketTickers(this.extend(i,t)),r=this.safeDict(s,"result",{}),a=this.safeList(r,"list",[]);return this.parseOptionChain(a,void 0,"symbol")}parseOption(e,t,i){let s=this.safeString(e,"symbol");return{info:e,currency:void 0,symbol:this.safeMarket(s,i).symbol,timestamp:void 0,datetime:void 0,impliedVolatility:this.safeNumber(e,"markIv"),openInterest:this.safeNumber(e,"openInterest"),bidPrice:this.safeNumber(e,"bid1Price"),askPrice:this.safeNumber(e,"ask1Price"),midPrice:void 0,markPrice:this.safeNumber(e,"markPrice"),lastPrice:this.safeNumber(e,"lastPrice"),underlyingPrice:this.safeNumber(e,"underlyingPrice"),change:this.safeNumber(e,"change24h"),percentage:void 0,baseVolume:this.safeNumber(e,"totalVolume"),quoteVolume:void 0}}async fetchPositionsHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=0;void 0!==e&&(a=e.length)>0&&(r=this.market(e[0]));let o=this.safeInteger(s,"until"),[n,d]=this.handleSubTypeAndParams("fetchPositionsHistory",r,s,"linear"),h=this.omit(d,"until"),c={category:n};void 0!==e&&1===a&&(c.symbol=this.safeString(r,"id")),void 0!==t&&(c.startTime=t),void 0!==i&&(c.limit=i),void 0!==o&&(c.endTime=o);let l=await this.privateGetV5PositionClosedPnl(this.extend(c,h)),u=this.safeDict(l,"result"),f=this.safeList(u,"list"),p=[];void 0!==f&&(p=f);let m=this.parsePositions(p,e,h);return this.filterBySinceLimit(m,t,i)}async fetchConvertCurrencies(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=await this.isUnifiedEnabled(),s="eb_convert_spot";(!0===t||!0===i)&&(s="eb_convert_uta");let[r,a]=this.handleOptionStringAndParams(e,"fetchConvertCurrencies","accountType",s),o=await this.privateGetV5AssetExchangeQueryCoinList(this.extend({accountType:r},a)),n={},d=this.safeDict(o,"result",{}),h=this.safeList(d,"coins",[]);for(let e=0;e<h.length;e++){let t=h[e],i=this.safeString(t,"coin"),s=this.safeBool(t,"disableFrom"),r=this.safeBool(t,"disableTo"),a=!0===s||!0===r,o=this.safeCurrencyCode(i);void 0!==o&&(n[o]={info:t,id:i,code:o,networks:void 0,type:this.safeString(t,"coinType"),name:this.safeString(t,"fullName"),active:!a,deposit:void 0,withdraw:this.safeNumber(t,"balance"),fee:void 0,precision:void 0,limits:{amount:{min:this.safeNumber(t,"singleFromMinLimit"),max:this.safeNumber(t,"singleFromMaxLimit")},withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},created:void 0})}return n}async fetchConvertQuote(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=await this.isUnifiedEnabled(),o="eb_convert_spot";(!0===r||!0===a)&&(o="eb_convert_uta");let[n,d]=this.handleOptionStringAndParams(s,"fetchConvertQuote","accountType",o),h={fromCoin:e,toCoin:t,requestAmount:this.numberToString(i),requestCoin:e,accountType:n},c=await this.privatePostV5AssetExchangeQuoteApply(this.extend(h,d)),l=this.safeDict(c,"result",{}),u=this.safeString(l,"fromCoin",e),f=this.currency(u),p=this.safeString(l,"toCoin",t),m=this.currency(p);return this.parseConversion(l,f,m)}async createConvertTrade(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=await this.privatePostV5AssetExchangeConvertExecute(this.extend({quoteTxId:e},r)),o=this.safeDict(a,"result",{});return this.parseConversion(o)}async fetchConvertTrade(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets();let[a,o]=await this.isUnifiedEnabled(),n="eb_convert_spot";(!0===a||!0===o)&&(n="eb_convert_uta");let[d,h]=this.handleOptionStringAndParams(i,"fetchConvertTrade","accountType",n),c=await this.privateGetV5AssetExchangeConvertResultQuery(this.extend({quoteTxId:e,accountType:d},h)),l=this.safeDict(c,"result",{}),u=this.safeDict(l,"result",{}),f=this.safeString(u,"fromCoin"),p=this.safeString(u,"toCoin");return void 0!==f&&(s=this.currency(f)),void 0!==p&&(r=this.currency(p)),this.parseConversion(u,s,r)}async fetchConvertTradeHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={};void 0!==i&&(r.limit=i);let a=await this.privateGetV5AssetExchangeQueryConvertHistory(this.extend(r,s)),o=this.safeDict(a,"result",{}),n=this.safeList(o,"list",[]);return this.parseConversions(n,e,"fromCoin","toCoin",t,i)}parseConversion(e,t,i){let s=this.safeInteger2(e,"expiredTime","createdAt"),r=this.safeString(e,"fromCoin"),a=this.safeCurrencyCode(r,t),o=this.safeString(e,"toCoin"),n=this.safeCurrencyCode(o,i);return{info:e,timestamp:s,datetime:this.iso8601(s),id:this.safeString2(e,"quoteTxId","exchangeTxId"),fromCurrency:a,fromAmount:this.safeNumber(e,"fromAmount"),toCurrency:n,toAmount:this.safeNumber(e,"toAmount"),price:void 0,fee:void 0}}async fetchLongShortRatioHistory(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),[n,d]=this.getBybitType("fetchLongShortRatioHistory",o,r);if("spot"===n||"option"===n)throw new a.NotSupported(this.id+" fetchLongShortRatioHistory() only support linear and inverse markets");let h={symbol:o.id,period:void 0===t?"1d":t,category:n};void 0!==s&&(h.limit=s);let c=await this.publicGetV5MarketAccountRatio(this.extend(h,d)),l=this.safeDict(c,"result",{}),u=this.safeList(l,"list",[]);return this.parseLongShortRatioHistory(u,o)}parseLongShortRatio(e,t){let i=this.safeString(e,"symbol"),s=this.safeIntegerOmitZero(e,"timestamp"),r=this.safeString(e,"buyRatio"),a=this.safeString(e,"sellRatio");return{info:e,symbol:this.safeSymbol(i,t,void 0,"contract"),timestamp:s,datetime:this.iso8601(s),timeframe:void 0,longShortRatio:this.parseToNumeric(o.Y.stringDiv(r,a))}}async fetchPositionsADLRank(e,t={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchPositionsADLRank() requires a symbols argument");void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s=this.getMarketFromSymbols(i),r={};void 0!==s&&(r.symbol=s.id);let[o,n]=this.getBybitType("fetchPositionsADLRank",s,t);r.category=o;let d=await this.privateGetV5PositionList(this.extend(r,n)),h=this.safeDict(d,"result",{}),c=this.safeList(h,"list",[]);return this.parseADLRanks(c,i)}parseADLRank(e,t){let i=this.safeString(e,"symbol"),s=this.safeInteger(e,"updatedTime");return{info:e,symbol:this.safeSymbol(i,t,void 0,"contract"),rank:this.safeInteger(e,"adlRankIndicator"),rating:void 0,percentage:void 0,timestamp:s,datetime:this.iso8601(s)}}async fetchMarginMode(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=await this.privateGetV5AccountInfo(t),r=this.safeDict(s,"result",{});return this.parseMarginMode(r,i)}parseMarginMode(e,t){let i=this.safeString(e,"marginMode");return{info:e,symbol:this.safeSymbol(void 0,t),marginMode:this.parseMarginModeType(i)}}parseMarginModeType(e){return this.safeString({ISOLATED_MARGIN:"isolated",REGULAR_MARGIN:"cross",PORTFOLIO_MARGIN:"portfolio"},e,e)}sign(e,t="public",i="GET",r={},o,d){let h,c,l=this.safeString(this.urls.api,t);if(void 0===l)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let u=this.implodeHostname(l)+"/"+e;if("public"===t)Object.keys(r).length>0&&(u+="?"+this.rawencode(r));else if("private"===t){this.checkRequiredCredentials();let e=u.indexOf("openapi")>=0,t=u.indexOf("unified/v3")>=0,a=u.indexOf("contract/v3")>=0,o=u.indexOf("v5")>=0,d=this.nonce().toString();if(e){h=Object.keys(r).length>0?this.json(r):"{}";let e=d+this.apiKey+h,t=this.hmac(this.encode(e),this.encode(this.secret),s.sc,"hex");c={"Content-Type":"application/json","X-BAPI-API-KEY":this.apiKey,"X-BAPI-TIMESTAMP":d,"X-BAPI-SIGN":t}}else if(t||a||o){let e,o;c={"Content-Type":"application/json","X-BAPI-API-KEY":this.apiKey,"X-BAPI-TIMESTAMP":d,"X-BAPI-RECV-WINDOW":this.options.recvWindow.toString()},(t||a)&&(c["X-BAPI-SIGN-TYPE"]="2");let l=this.extend({},r),f=this.rawencode(l),p=d.toString()+this.apiKey+this.options.recvWindow.toString();"POST"===i?e=p+(h=this.json(l)):(e=p+f,u+="?"+f),o=this.secret.indexOf("PRIVATE KEY")>-1?(0,n.n)(e,this.secret,s.sc):this.hmac(this.encode(e),this.encode(this.secret),s.sc),c["X-BAPI-SIGN"]=o}else{let e,t=this.extend(r,{api_key:this.apiKey,recv_window:this.options.recvWindow,timestamp:d}),a=this.keysort(t),o=this.rawencode(a,!0);if(e=this.secret.indexOf("PRIVATE KEY")>-1?(0,n.n)(o,this.secret,s.sc):this.hmac(this.encode(o),this.encode(this.secret),s.sc),"POST"===i){let i=u.indexOf("spot")>=0,s=this.extend(t,{sign:e});i?(h=this.urlencode(s),c={"Content-Type":"application/x-www-form-urlencoded"}):(h=this.json(s),c={"Content-Type":"application/json"})}else u+="?"+this.rawencode(a,!0)+"&sign="+e}}if("POST"===i){let e=this.safeString(this.options,"brokerId","CCXT"),t=void 0===c?o:c;(c=void 0===t?{}:t).Referer=e}return{url:u,method:i,body:void 0===h?d:h,headers:void 0===c?o:c}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString2(n,"ret_code","retCode");if("0"!==c){let e;if("30084"===c)return;throw e="10005"===c&&0>i.indexOf("order")?this.id+' private api uses /user/v3/private/query-api to check if you have a unified account. The API key of user id must own one of permissions: "Account Transfer", "Subaccount Transfer", "Withdrawal" '+o:this.id+" "+o,o.indexOf("Withdraw address chain or destination tag are not equal")>-1&&(e+="; You might also need to ensure the address is whitelisted"),this.throwBroadlyMatchedException(this.exceptions.broad,o,e),this.throwExactlyMatchedException(this.exceptions.exact,c,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>d})},3574(e,t,i){"use strict";var s=i(1484);class r extends s.A{describe(){return this.deepExtend(super.describe(),{id:"bybiteu",name:"Bybit EU",countries:["EU"],version:"v5",rateLimit:20,hostname:"bybit.eu",pro:!0,certified:!1,urls:{test:{spot:"https://api-testnet.{hostname}",futures:"https://api-testnet.{hostname}",v2:"https://api-testnet.{hostname}",public:"https://api-testnet.{hostname}",private:"https://api-testnet.{hostname}"},logo:"https://github.com/user-attachments/assets/97a5d0b3-de10-423d-90e1-6620960025ed",api:{spot:"https://api.{hostname}",futures:"https://api.{hostname}",v2:"https://api.{hostname}",public:"https://api.{hostname}",private:"https://api.{hostname}"},demotrading:{spot:"https://api-demo.{hostname}",futures:"https://api-demo.{hostname}",v2:"https://api-demo.{hostname}",public:"https://api-demo.{hostname}",private:"https://api-demo.{hostname}"},www:"https://www.bybit.com",doc:["https://bybit-exchange.github.io/docs/inverse/","https://bybit-exchange.github.io/docs/linear/","https://github.com/bybit-exchange"],fees:"https://help.bybit.com/hc/en-us/articles/360039261154",referral:"https://www.bybit.com/invite?ref=XDK12WP"},has:{CORS:!0,spot:!0,margin:!0,swap:!1,future:!1,option:void 0},options:{mica:!0,defaultType:"spot",fetchMarkets:{types:["spot"]}}})}}i.d(t,{A:()=>r})},3825(e,t,i){"use strict";var s=i(1484),r=i(1453);class a extends s.A{describe(){return this.deepExtend(super.describe(),{id:"bybitid",name:"Bybit Indonesia",countries:["ID"],hostname:"bybit.id",certified:!1,urls:{logo:"https://github.com/user-attachments/assets/97a5d0b3-de10-423d-90e1-6620960025ed",www:"https://www.bybit.id",doc:["https://bybit-exchange.github.io/docs/v5/intro","https://github.com/bybit-exchange"],fees:"https://help.bybit.com/hc/en-us/articles/360039261154",referral:void 0},httpExceptions:{403:r.PermissionDenied}})}}i.d(t,{A:()=>a})},6094(e,t,i){"use strict";var s=i(4721),r=i(6141),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"bydfi",name:"BYDFi",countries:["SG"],rateLimit:50,version:"v1",certified:!1,pro:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!1,cancelOrders:!1,cancelOrdersWithClientOrderId:!1,cancelOrderWithClientOrderId:!1,closeAllPositions:!1,closePosition:!1,createDepositAddress:!1,createLimitBuyOrder:!1,createLimitOrder:!0,createLimitSellOrder:!1,createMarketBuyOrder:!1,createMarketBuyOrderWithCost:!1,createMarketOrder:!0,createMarketOrderWithCost:!1,createMarketSellOrder:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!1,createPostOnlyOrder:!0,createReduceOnlyOrder:!0,createStopLimitOrder:!0,createStopLossOrder:!0,createStopMarketOrder:!1,createStopOrder:!1,createTakeProfitOrder:!0,createTrailingAmountOrder:!1,createTrailingPercentOrder:!0,createTriggerOrder:!1,deposit:!1,editOrder:!0,editOrders:!0,editOrderWithClientOrderId:!0,fetchAccounts:!1,fetchBalance:!0,fetchBidsAsks:!1,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCanceledAndClosedOrders:!0,fetchCanceledOrders:!1,fetchClosedOrder:!1,fetchClosedOrders:!1,fetchConvertCurrencies:!1,fetchConvertQuote:!1,fetchConvertTrade:!1,fetchConvertTradeHistory:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDeposit:!1,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!1,fetchDepositWithdrawFee:!1,fetchDepositWithdrawFees:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchL2OrderBook:!0,fetchL3OrderBook:!1,fetchLastPrices:!1,fetchLedger:!1,fetchLedgerEntry:!1,fetchLeverage:!0,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!0,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrder:!0,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!1,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrders:!1,fetchOrdersByStatus:!1,fetchOrderTrades:!1,fetchOrderWithClientOrderId:!1,fetchPosition:!1,fetchPositionHistory:!0,fetchPositionMode:!0,fetchPositions:!0,fetchPositionsForSymbol:!0,fetchPositionsHistory:!0,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchStatus:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!1,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTradingLimits:!1,fetchTransactionFee:!1,fetchTransactionFees:!1,fetchTransactions:!1,fetchTransfer:!1,fetchTransfers:!0,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,fetchWithdrawAddresses:!1,fetchWithdrawal:!1,fetchWithdrawals:!0,fetchWithdrawalWhitelist:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!0,setMargin:!1,setMarginMode:!0,setPositionMode:!0,signIn:!1,transfer:!0,watchMyLiquidationsForSymbols:!1,withdraw:!1,ws:!0},urls:{logo:"https://github.com/user-attachments/assets/0e9319dc-b5f5-458b-bcfd-b21b50e162ea",api:{public:"https://api.bydfi.com/api",private:"https://api.bydfi.com/api"},www:"https://bydfi.com/",doc:"https://developers.bydfi.com/en/",referral:"https://partner.bydfi.com/j/DilWutCI"},fees:{},api:{public:{get:{"v1/public/api_limits":{cost:1},"v1/fapi/market/exchange_info":{cost:1},"v1/fapi/market/depth":{cost:1},"v1/fapi/market/trades":{cost:1},"v1/fapi/market/klines":{cost:1},"v1/fapi/market/ticker/24hr":{cost:1},"v1/fapi/market/ticker/price":{cost:1},"v1/fapi/market/mark_price":{cost:1},"v1/fapi/market/funding_rate":{cost:1},"v1/fapi/market/funding_rate_history":{cost:1},"v1/fapi/market/risk_limit":{cost:1}}},private:{get:{"v1/account/assets":{cost:1},"v1/account/transfer_records":{cost:1},"v1/spot/deposit_records":{cost:1},"v1/spot/withdraw_records":{cost:1},"v1/fapi/trade/open_order":{cost:1},"v1/fapi/trade/plan_order":{cost:1},"v1/fapi/trade/leverage":{cost:1},"v1/fapi/trade/history_order":{cost:1},"v1/fapi/trade/history_trade":{cost:1},"v1/fapi/trade/position_history":{cost:1},"v1/fapi/trade/positions":{cost:1},"v2/fapi/trade/open_order":{cost:1},"v2/fapi/trade/plan_order":{cost:1},"v2/fapi/trade/history_order":{cost:1},"v2/fapi/trade/history_trade":{cost:1},"v2/fapi/trade/position_history":{cost:1},"v2/fapi/trade/positions":{cost:1},"v1/fapi/account/balance":{cost:1},"v1/fapi/user_data/assets_margin":{cost:1},"v1/fapi/user_data/position_side/dual":{cost:1},"v1/agent/teams":{cost:1},"v1/agent/agent_links":{cost:1},"v1/agent/regular_overview":{cost:1},"v1/agent/agent_sub_overview":{cost:1},"v1/agent/partener_user_deposit":{cost:1},"v1/agent/partener_users_data":{cost:1},"v1/agent/affiliate_uids":{cost:1},"v1/agent/affiliate_commission":{cost:1},"v1/agent/internal_withdrawal_status":{cost:1}},post:{"v1/account/transfer":{cost:1},"v1/fapi/trade/place_order":{cost:1},"v1/fapi/trade/batch_place_order":{cost:1},"v1/fapi/trade/edit_order":{cost:1},"v1/fapi/trade/batch_edit_order":{cost:1},"v1/fapi/trade/cancel_all_order":{cost:1},"v1/fapi/trade/leverage":{cost:1},"v1/fapi/trade/batch_leverage_margin":{cost:1},"v2/fapi/trade/place_order":{cost:1},"v2/fapi/trade/batch_place_order":{cost:1},"v2/fapi/trade/edit_order":{cost:1},"v2/fapi/trade/batch_edit_order":{cost:1},"v2/fapi/trade/cancel_order":{cost:1},"v2/fapi/trade/batch_cancel_order":{cost:1},"v2/fapi/trade/cancel_all_order":{cost:1},"v1/fapi/user_data/margin_type":{cost:1},"v1/fapi/user_data/position_side/dual":{cost:1},"v1/agent/internal_withdrawal":{cost:1}}}},features:{spot:void 0,swap:{linear:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:{mark:!0,last:!0,index:!1},stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!0,selfTradePrevention:!1,trailing:!0,iceberg:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1},createOrders:{max:5},fetchMyTrades:{marginMode:!1,daysBack:182,limit:500,untilDays:7,symbolRequired:!1},fetchOrder:void 0,fetchOpenOrder:{marginMode:!1,trigger:!0,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:500,trigger:!0,trailing:!1,symbolRequired:!0},fetchOrders:void 0,fetchCanceledAndClosedOrders:{marginMode:!1,limit:500,daysBack:182,untilDays:7,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:void 0,fetchOHLCV:{limit:500}},inverse:void 0},future:{linear:void 0,inverse:void 0}},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","12h":"12h","1d":"1d"},precisionMode:4,exceptions:{exact:{101001:a.AuthenticationError,101103:a.AuthenticationError,102001:a.BadRequest,102002:a.PermissionDenied,401:a.AuthenticationError,500:a.ExchangeError,501:a.ExchangeError,506:a.ExchangeError,510:a.RateLimitExceeded,511:a.AuthenticationError,513:a.BadRequest,514:a.BadRequest,600:a.BadRequest,"Position does not exist":a.BadRequest,"Requires transaction permissions":a.PermissionDenied,"Service error":a.ExchangeError,"transfer failed":a.InsufficientFunds},broad:{"is missing":a.ArgumentsRequired}},commonCurrencies:{},options:{networks:{ERC20:"ETH"},timeInForce:{GTC:"GTC",FOK:"FOK",IOC:"IOC",PO:"POST_ONLY"},accountsByType:{spot:"SPOT",swap:"UMFUTURE",funding:"FUNDING",inverse:"CMFUTURE"},accountsById:{SPOT:"spot",UMFUTURE:"swap",FUNDING:"funding",CMFUTURE:"inverse"}}})}async fetchMarkets(e={}){let t=await this.publicGetV1FapiMarketExchangeInfo(e),i=this.safeList(t,"data",[]);return this.parseMarkets(i)}parseMarket(e){let t=this.safeString(e,"symbol"),i=this.safeString(e,"baseAsset"),s=this.safeString(e,"quoteAsset"),r=this.safeString(e,"marginAsset"),a=this.safeCurrencyCode(i),n=this.safeCurrencyCode(s);if(void 0===a||void 0===n)return;let d=this.safeCurrencyCode(r),h=this.safeBool(e,"reverse"),c=this.safeString(e,"limitMaxQty"),l=this.safeString(e,"marketMaxQty"),u=o.Y.stringMax(c,l),f=this.safeString(e,"marketMinQty"),p=this.safeString(e,"limitMinQty"),m=o.Y.stringMin(f,p),g=this.safeString(e,"contractFactor"),v=this.parsePrecision(this.safeString(e,"priceOrderPrecision")),y=this.parsePrecision(this.safeString(e,"volumePrecision")),b=o.Y.stringDiv(y,g),w=this.parsePrecision(this.safeString(e,"basePrecision")),k=this.safeNumber(e,"feeRateTaker"),S=this.safeNumber(e,"feeRateMaker"),O=this.safeNumber(e,"maxLeverageLevel"),T=this.safeString(e,"status");return this.safeMarketStructure({id:t,symbol:a+"/"+n+":"+d,base:a,quote:n,settle:d,baseId:i,quoteId:s,settleId:r,type:"swap",spot:!1,margin:void 0,swap:!0,future:!1,option:!1,active:"NORMAL"===T,contract:!0,linear:!0!==h,inverse:h,taker:k,maker:S,contractSize:this.parseNumber(g),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(b),price:this.parseNumber(v),base:this.parseNumber(w)},limits:{leverage:{min:void 0,max:O},amount:{min:this.parseNumber(m),max:this.parseNumber(u)},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:this.parse8601(this.safeString(e,"createdAt")),info:e})}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};void 0!==t&&(r.limit=this.getClosestLimit(t));let a=await this.publicGetV1FapiMarketDepth(this.extend(r,i)),o=this.safeDict(a,"data",{}),n=this.parseOrderBook(o,s.symbol,void 0,"bids","asks","price","amount");return n.nonce=this.safeInteger(o,"lastUpdateId"),n}getClosestLimit(e){let t=[5,10,20,50,100,500,1e3],i=1e3;for(let s=0;s<t.length;s++){if(void 0===e)throw new a.ArgumentsRequired(this.id+" getClosestLimit() requires a limit argument");if(e<=t[s]){i=t[s];break}}return i}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id};void 0!==i&&(a.limit=Math.min(i,1e3));let o=await this.publicGetV1FapiMarketTrades(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTrades(n,r,t,i)}async fetchMyTrades(e,t,i,s={}){let r;if(void 0===this.markets&&await this.loadMarkets(),!0===this.safeBool(s,"paginate",!1)){let r=this.extend(this.omit(s,"paginate"),{paginationDirection:"backward"}),a=await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,r,500,!0);return this.sortBy(a,"timestamp")}let[a,o]=this.handleOptionStringAndParams(s,"fetchMyTrades","contractType","FUTURE"),n={contractType:a};void 0!==e&&(n.symbol=(r=this.market(e)).id);let d=this.handleSinceAndUntil("fetchMyTrades",t,o);void 0!==i&&(n.limit=i);let h=await this.privateGetV1FapiTradeHistoryTrade(this.extend(n,d)),c=this.safeList(h,"data",[]);return this.parseTrades(c,r,t,i)}parseTrade(e,t){let i,s,r=this.safeString(e,"symbol"),a=this.safeMarket(r,t),o=this.safeInteger(e,"time"),n=this.safeString(e,"type"),d=this.safeString(e,"fee");void 0!==d&&(i={cost:d,currency:a.settle});let h=this.safeString(e,"orderId");return void 0===h&&(s=this.safeStringLower(e,"side")),this.safeTrade({info:e,timestamp:o,datetime:this.iso8601(o),symbol:a.symbol,id:this.safeString(e,"id"),order:h,type:this.parseTradeType(n),side:s,takerOrMaker:void 0,price:this.safeString2(e,"price","dealPrice"),amount:this.safeString2(e,"quantity","dealVolume"),cost:void 0,fee:i},a)}parseTradeType(e){return this.safeString({1:"limit",2:"market",3:"liquidation"},e,e)}async fetchOHLCV(e,t="1m",i,s,r={}){let o,n;void 0===this.markets&&await this.loadMarkets();let[d,h]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(d)return this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,h,500);let c=this.market(e),l=this.safeString(this.timeframes,t,t),u={symbol:c.id,interval:l},f=i,p=500;null!=s&&0!==s&&(p=s),[o,n]=this.handleOptionIntegerAndParams(h,"fetchOHLCV","until");let m=this.milliseconds(),g=1e3*this.parseTimeframe(t)*p;if(void 0===f&&void 0===o)f=m-g,o=m;else if(void 0===o){if(void 0===f)throw new a.ArgumentsRequired(this.id+" fetchOHLCV() requires a since or until argument");(o=f+g)>m&&(o=m)}else void 0===f&&(f=o-g);u.startTime=f,u.endTime=o,void 0!==s&&(u.limit=s);let v=await this.publicGetV1FapiMarketKlines(this.extend(u,n)),y=this.safeList(v,"data",[]);return this.parseOHLCVs(y,c,t,i,s)}parseOHLCV(e,t){return[this.safeInteger(e,"t"),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetV1FapiMarketTicker24hr(t),s=this.safeList(i,"data",[]);return this.parseTickers(s,e)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetV1FapiMarketTicker24hr(this.extend(s,t)),a=this.safeList(r,"data",[]),o=this.safeDict(a,0,{});return this.parseTicker(o,i)}parseTicker(e,t){let i=this.safeString2(e,"symbol","s"),s=this.safeMarket(i,t),r=this.safeInteger2(e,"time","E"),a=this.safeString2(e,"last","c");return this.safeTicker({symbol:this.safeSymbol(i,s),timestamp:r,datetime:this.iso8601(r),high:this.safeString2(e,"high","h"),low:this.safeString2(e,"low","l"),bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:this.safeString2(e,"open","o"),close:a,last:a,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString2(e,"vol","v"),quoteVolume:void 0,markPrice:void 0,indexPrice:void 0,info:e},s)}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetV1FapiMarketFundingRate(this.extend(s,t)),a=this.safeDict(r,"data");return this.parseFundingRate(a,i)}parseFundingRate(e,t){let i=this.safeString(e,"symbol"),s=this.safeSymbol(i,t),r=this.safeInteger(e,"time"),a=this.safeInteger(e,"nextFundingTime");return{info:e,symbol:s,markPrice:void 0,indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:r,datetime:this.iso8601(r),fundingRate:this.safeNumber(e,"lastFundingRate"),fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:void 0,nextFundingTimestamp:a,nextFundingDatetime:this.iso8601(a),previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:void 0}}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={symbol:r.id};void 0!==t&&(o.startTime=t),void 0!==i&&(o.limit=i);let[n,d]=this.handleOptionIntegerAndParams(s,"fetchFundingRateHistory","until");void 0!==n&&(o.endTime=n);let h=await this.publicGetV1FapiMarketFundingRateHistory(this.extend(o,d)),c=this.safeList(h,"data",[]);return this.parseFundingRateHistories(c,r,t,i)}parseFundingRateHistory(e,t){let i=this.safeString(e,"symbol"),s=this.safeInteger(e,"fundingTime");return{info:e,symbol:this.safeSymbol(i,t),fundingRate:this.safeNumber(e,"fundingRate"),timestamp:s,datetime:this.iso8601(s)}}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=this.createOrderRequest(e,t,i,s,r,a),d=this.handleOptionStringAndParams(a,"createOrder","wallet","W001")[0];n=this.extend(n,{wallet:d});let h=await this.privatePostV1FapiTradePlaceOrder(n),c=this.safeDict(h,"data",{});return this.parseOrder(c,o)}createOrderRequest(e,t,i,s,r,o={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let n=this.market(e);if(void 0===i)throw new a.ArgumentsRequired(this.id+" createOrderRequest() requires a side argument");let d={symbol:n.id,side:i.toUpperCase()},h=this.safeString(o,"stopLossPrice"),c=void 0!==h,l=this.safeString(o,"takeProfitPrice"),u=void 0!==l,f=this.safeString(o,"trailingPercent"),p=void 0!==f,m=c||u,g=o;if(m&&(g=this.omit(o,["stopLossPrice","takeProfitPrice"])),m)d.stopPrice=this.priceToPrecision(e,c?h:l);else if(p){g=this.omit(g,["trailingPercent"]),d.callbackRate=f;let t=this.numberToString(r);[t,g]=this.handleParamString(g,"trailingTriggerPrice",t),void 0!==t&&(d.activationPrice=this.priceToPrecision(e,t),g=this.omit(g,["trailingTriggerPrice"]))}let v=t.toUpperCase(),y="MARKET"===v||"STOP_MARKET"===v||"TAKE_PROFIT_MARKET"===v||"TRAILING_STOP_MARKET"===v;if(y)"MARKET"===v&&(c?v="STOP_MARKET":u?v="TAKE_PROFIT_MARKET":p&&(v="TRAILING_STOP_MARKET"));else{if(void 0===r)throw new a.ArgumentsRequired(this.id+" createOrder() requires a price argument for a "+v+" order");d.price=this.priceToPrecision(e,r),c?v="STOP":u&&(v="TAKE_PROFIT")}d.type=v;let b=!1;[b,g]=this.handleOptionBoolAndParams(g,"createOrder","hedged",b);let w=this.safeBool(g,"reduceOnly",!1);if(b&&(g=this.omit(g,"reduceOnly"),"buy"===i?d.positionSide=!0===w?"SHORT":"LONG":"sell"===i&&(d.positionSide=!0===w?"LONG":"SHORT")),!0!==this.safeBool(g,"closePosition",!1))g=this.omit(g,"closePosition"),d.quantity=this.amountToPrecision(e,s);else if("STOP_MARKET"!==v&&"TAKE_PROFIT_MARKET"!==v)throw new a.NotSupported(this.id+" createOrder() closePosition is only supported for stopLoss and takeProfit market orders");let k=this.handleTimeInForce(g),S=!1;if([S,g]=this.handlePostOnly(y,"POST_ONLY"===k,g),S&&(k="POST_ONLY"),void 0!==k&&(d.timeInForce=k,g=this.omit(g,"timeInForce")),c||u||p){let e="CONTRACT_PRICE";[e,g]=this.handleOptionStringAndParams(g,"createOrder","triggerPriceType",e),d.workingType=this.encodeWorkingType(e)}return this.extend(d,g)}encodeWorkingType(e){return this.safeString({markPrice:"MARK_PRICE",mark:"MARK_PRICE",contractPrice:"CONTRACT_PRICE",contract:"CONTRACT_PRICE",last:"CONTRACT_PRICE"},e,e)}async createOrders(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),e.length>5)throw new a.BadRequest(this.id+" createOrders() accepts a maximum of 5 orders");let i=[];for(let t=0;t<e.length;t++){let s=this.safeDict(e,t),r=this.safeString(s,"symbol"),a=this.safeString(s,"type"),o=this.safeString(s,"side"),n=this.safeNumber(s,"amount"),d=this.safeNumber(s,"price"),h=this.safeDict(s,"params",{}),c=this.createOrderRequest(r,a,o,n,d,h);i.push(c)}let[s,r]=this.handleOptionStringAndParams(t,"createOrder","wallet","W001"),o=await this.privatePostV1FapiTradeBatchPlaceOrder(this.extend({wallet:s,orders:i},r)),n=this.safeList(o,"data",[]);return this.parseOrders(n)}async editOrder(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.createEditOrderRequest(e,t,"limit",s,r,a,o);n.wallet=this.handleOptionStringAndParams(o,"editOrder","wallet","W001")[0];let d=await this.privatePostV1FapiTradeEditOrder(n),h=this.safeDict(d,"data",{});return this.parseOrder(h)}async editOrders(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),e.length>5)throw new a.BadRequest(this.id+" editOrders() accepts a maximum of 5 orders");let i=[];for(let t=0;t<e.length;t++){let s=this.safeDict(e,t),r=this.safeString(s,"id"),a=this.safeString(s,"symbol"),o=this.safeString(s,"side"),n=this.safeNumber(s,"amount"),d=this.safeNumber(s,"price"),h=this.safeDict(s,"params",{}),c=this.createEditOrderRequest(r,a,"limit",o,n,d,h);i.push(c)}let[s,r]=this.handleOptionStringAndParams(t,"editOrder","wallet","W001"),o=await this.privatePostV1FapiTradeBatchEditOrder(this.extend({wallet:s,editOrders:i},r)),n=this.safeList(o,"data",[]);return this.parseOrders(n)}createEditOrderRequest(e,t,i,s,r,o,n={}){let d=this.safeString(n,"clientOrderId"),h={};if(void 0===e&&void 0===d)throw new a.ArgumentsRequired(this.id+" editOrder() requires an id argument or a clientOrderId parameter");return void 0!==e&&(h.orderId=e),h.symbol=this.market(t).id,void 0!==s&&(h.side=s.toUpperCase()),void 0!==r&&(h.quantity=this.amountToPrecision(t,r)),void 0!==o&&(h.price=this.priceToPrecision(t,o)),this.extend(h,n)}async cancelAllOrders(e,t={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let i=this.market(e),[s,r]=this.handleOptionStringAndParams(t,"cancelAllOrders","wallet","W001"),o={symbol:i.id,wallet:s},n=await this.privatePostV1FapiTradeCancelAllOrder(this.extend(o,r)),d=this.safeList(n,"data",[]);return this.parseOrders(d,i)}async fetchOpenOrders(e,t,i,s={}){let r;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOpenOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let o=this.market(e),[n,d]=this.handleOptionStringAndParams(s,"fetchOpenOrders","wallet","W001"),h={symbol:o.id,wallet:n},[c,l]=this.handleOptionBoolAndParams(d,"fetchOpenOrders","trigger",!1);r=c?await this.privateGetV1FapiTradePlanOrder(this.extend(h,l)):await this.privateGetV1FapiTradeOpenOrder(this.extend(h,l));let u=this.safeList(r,"data",[]);return this.parseOrders(u,o,t,i)}async fetchOpenOrder(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOpenOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),o={symbol:r.id},n=this.safeString(i,"clientOrderId");if(void 0===e&&void 0===n)throw new a.ArgumentsRequired(this.id+" fetchOpenOrder() requires an id argument or a clientOrderId parameter");void 0!==e&&(o.orderId=e);let[d,h]=this.handleOptionStringAndParams(i,"fetchOpenOrder","wallet","W001");o.wallet=d;let[c,l]=this.handleOptionBoolAndParams(h,"fetchOpenOrder","trigger",!1);s=c?await this.privateGetV1FapiTradePlanOrder(this.extend(o,l)):await this.privateGetV1FapiTradeOpenOrder(this.extend(o,l));let u=this.safeList(s,"data",[]),f=this.safeDict(u,0,{});return this.parseOrder(f,r)}async fetchCanceledAndClosedOrders(e,t,i,s={}){let r;if(void 0===this.markets&&await this.loadMarkets(),!0===this.safeBool(s,"paginate",!1)){let r=this.extend(this.omit(s,"paginate"),{paginationDirection:"backward"}),a=await this.fetchPaginatedCallDynamic("fetchCanceledAndClosedOrders",e,t,i,r,500,!0);return this.sortBy(a,"timestamp")}let[a,o]=this.handleOptionStringAndParams(s,"fetchCanceledAndClosedOrders","contractType","FUTURE"),n={contractType:a};void 0!==e&&(n.symbol=(r=this.market(e)).id);let d=this.handleSinceAndUntil("fetchCanceledAndClosedOrders",t,o);void 0!==i&&(n.limit=i);let h=await this.privateGetV1FapiTradeHistoryOrder(this.extend(n,d)),c=this.safeList(h,"data",[]);return this.parseOrders(c,r,t,i)}handleSinceAndUntil(e,t,i={}){let s,r;[s,r]=this.handleOptionIntegerAndParams2(i,e,"until","endTime");let a=this.milliseconds(),o=t;void 0===o?void 0===s?(o=a-6048e5,s=a):o=s-6048e5:void 0===s&&(s=a-o>6048e5?o+6048e5:a);let n={startTime:o,endTime:s};return this.extend(n,r)}parseOrder(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeInteger2(e,"createTime","ctime"),a=this.safeString(e,"orderType"),o=this.safeStringN(e,["stopPrice","activatePrice","triggerPrice"]),n="STOP"===a||"STOP_MARKET"===a||"TRAILING_STOP_MARKET"===a,d="TAKE_PROFIT"===a||"TAKE_PROFIT_MARKET"===a,h=this.safeString(e,"timeInForce"),c=this.parseOrderTimeInForce(h),l=!1;"PO"===c&&(l=!0);let u=this.safeString(e,"status"),f={},p=this.safeNumber(e,"quoteFee");return void 0!==p&&(f.cost=p,f.currency=s.quote),this.safeOrder({info:e,id:this.safeString(e,"orderId"),clientOrderId:this.safeString(e,"clientOrderId"),timestamp:r,datetime:this.iso8601(r),lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeInteger2(e,"updateTime","mtime"),status:this.parseOrderStatus(u),symbol:s.symbol,type:this.parseOrderType(a),timeInForce:c,postOnly:l,reduceOnly:this.safeBool(e,"reduceOnly"),side:this.safeStringLower(e,"side"),price:this.safeString(e,"price"),triggerPrice:o,stopLossPrice:n?o:void 0,takeProfitPrice:d?o:void 0,amount:this.safeString(e,"origQty"),filled:this.safeString(e,"executedQty"),remaining:void 0,cost:void 0,trades:void 0,fee:f,average:this.omitZero(this.safeString(e,"avgPrice"))},s)}parseOrderType(e){return this.safeString({LIMIT:"limit",MARKET:"market",STOP:"limit",STOP_MARKET:"market",TAKE_PROFIT:"limit",TAKE_PROFIT_MARKET:"market",TRAILING_STOP_MARKET:"market"},e,e)}parseOrderTimeInForce(e){return this.safeString({GTC:"GTC",FOK:"FOK",IOC:"IOC",POST_ONLY:"PO",TRAILING_STOP:"IOC"},e,e)}parseOrderStatus(e){return this.safeString({NEW:"open",PARTIALLY_FILLED:"open",FILLED:"closed",EXPIRED:"canceled",PART_FILLED_CANCELLED:"canceled",CANCELED:"canceled",2:"closed",4:"canceled"},e,e)}async setLeverage(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),[r,o]=this.handleOptionStringAndParams(i,"setLeverage","wallet","W001"),n={symbol:s.id,leverage:e,wallet:r},d=await this.privatePostV1FapiTradeLeverage(this.extend(n,o));return this.safeDict(d,"data",{})}async fetchLeverage(e,t={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchLeverage() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let i=this.market(e),[s,r]=this.handleOptionStringAndParams(t,"fetchLeverage","wallet","W001"),o={symbol:i.id,wallet:s},n=await this.privateGetV1FapiTradeLeverage(this.extend(o,r)),d=this.safeDict(n,"data",{});return this.parseLeverage(d,i)}parseLeverage(e,t){let i=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(i,t),marginMode:void 0,longLeverage:this.safeInteger(e,"leverage"),shortLeverage:this.safeInteger(e,"leverage")}}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionStringAndParams(t,"fetchPositions","contractType","FUTURE"),r=await this.privateGetV1FapiTradePositions(this.extend({contractType:i},s)),a=this.safeList(r,"data",[]);return this.parsePositions(a,e)}async fetchPositionsForSymbol(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),[s,r]=this.handleOptionStringAndParams(t,"fetchPositions","contractType","FUTURE"),a={contractType:s,symbol:i.id},o=await this.privateGetV1FapiTradePositions(this.extend(a,r)),n=this.safeList(o,"data",[]);return this.parsePositions(n,[i.symbol])}parsePosition(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeString(e,"side"),a=this.safeStringLower(e,"positionSide"),n=this.parsePositionSide(r),d=!1,h=!1;void 0!==a&&(h=!0,"both"!==a?(n=a,d=!0):d=!1);let c=this.safeString(s,"contractSize"),l=this.safeString2(e,"volume","openPositionVolume");h||(l=o.Y.stringDiv(l,c));let u=this.safeInteger(e,"createTime");return this.safePosition({info:e,id:this.safeString(e,"id"),symbol:s.symbol,entryPrice:this.parseNumber(this.safeString2(e,"avgOpenPositionPrice","avgPrice")),markPrice:this.parseNumber(this.safeString(e,"markPrice")),lastPrice:this.parseNumber(this.safeString(e,"avgClosePositionPrice")),notional:this.parseNumber(this.safeString(e,"closePositionCost")),collateral:void 0,unrealizedPnl:this.parseNumber(this.safeString(e,"unPnl")),realizedPnl:this.parseNumber(this.safeString(e,"positionProfits")),side:n,contracts:this.parseNumber(l),contractSize:this.parseNumber(c),timestamp:u,datetime:this.iso8601(u),lastUpdateTimestamp:this.safeInteger(e,"updateTime"),hedged:d,maintenanceMargin:this.parseNumber(this.safeString(e,"mm")),maintenanceMarginPercentage:void 0,initialMargin:this.parseNumber(this.safeString(e,"im")),initialMarginPercentage:void 0,leverage:this.parseNumber(this.safeString(e,"leverage")),liquidationPrice:this.parseNumber(this.safeString(e,"liqPrice")),marginRatio:void 0,marginMode:void 0,percentage:void 0})}parsePositionSide(e){return this.safeString({BUY:"long",SELL:"short"},e,e)}async fetchPositionHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),[a,o]=this.handleOptionStringAndParams(s,"fetchPositionHistory","contractType","FUTURE"),n={symbol:r.id,contractType:a},d=this.handleSinceAndUntil("fetchPositionsHistory",t,o);void 0!==i&&(n.limit=i);let h=await this.privateGetV1FapiTradePositionHistory(this.extend(n,d)),c=this.safeList(h,"data",[]),l=this.parsePositions(c);return this.filterBySinceLimit(l,t,i)}async fetchPositionsHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionStringAndParams(s,"fetchPositionsHistory","contractType","FUTURE"),o={contractType:r},n=this.handleSinceAndUntil("fetchPositionsHistory",t,a);void 0!==i&&(o.limit=i);let d=await this.privateGetV1FapiTradePositionHistory(this.extend(o,n)),h=this.safeList(d,"data",[]),c=this.parsePositions(h,e);return this.filterBySinceLimit(c,t,i)}async fetchMarginMode(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),[s,r]=this.handleOptionStringAndParams(t,"fetchMarginMode","contractType","FUTURE"),[a,o]=this.handleOptionStringAndParams(r,"fetchMarginMode","wallet","W001"),n={contractType:s,symbol:i.id,wallet:a},d=await this.privateGetV1FapiUserDataAssetsMargin(this.extend(n,o)),h=this.safeDict(d,"data",{});return this.parseMarginMode(h,i)}parseMarginMode(e,t){let i=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(i,t),marginMode:this.safeStringLower(e,"marginType")}}async setMarginMode(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");let s=e.toLowerCase();if("isolated"!==s&&"cross"!==s)throw new a.BadRequest(this.id+" setMarginMode() marginMode argument should be isolated or cross");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),[o,n]=this.handleOptionStringAndParams(i,"setMarginMode","contractType","FUTURE"),[d,h]=this.handleOptionStringAndParams(n,"setMarginMode","wallet","W001"),c={contractType:o,symbol:r.id,marginType:s.toUpperCase(),wallet:d};return await this.privatePostV1FapiUserDataMarginType(this.extend(c,h))}async setPositionMode(e,t,i={}){if(void 0!==t)throw new a.NotSupported(this.id+" setPositionMode() does not support a symbol argument. The position mode is set identically for all markets with same settle currency");void 0===this.markets&&await this.loadMarkets();let s="ONEWAY";e&&(s="HEDGE");let[r,o]=this.handleOptionStringAndParams(i,"setPositionMode","wallet","W001"),[n,d]=this.handleOptionStringAndParams(o,"setPositionMode","contractType","FUTURE"),[h,c]=this.handleOptionStringAndParams(d,"setPositionMode","settleCoin","USDT"),l={contractType:n,wallet:r,positionType:s,settleCoin:h};return await this.privatePostV1FapiUserDataPositionSideDual(this.extend(l,c))}async fetchPositionMode(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionStringAndParams(t,"fetchPositionMode","wallet","W001"),[r,a]=this.handleOptionStringAndParams(s,"fetchPositionMode","contractType","FUTURE"),o="USDT",n=a;void 0===e?[o,n]=this.handleOptionStringAndParams(a,"fetchPositionMode","settleCoin",o):o=this.market(e).settleId;let d={contractType:r,settleCoin:o,wallet:i},h=await this.privateGetV1FapiUserDataPositionSideDual(this.extend(d,n)),c=this.safeDict(h,"data",{});return{info:h,hedged:"HEDGE"===this.safeString(c,"positionType")}}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleMarketTypeAndParams("fetchBalance",void 0,e),[r,a]=this.handleOptionStringAndParams(s,"fetchBalance","wallet"),o={};if(void 0===r){let e=this.safeDict(this.options,"accountsByType",{});o.walletType=this.safeStringUpper(e,i,i),t=await this.privateGetV1AccountAssets(this.extend(o,a))}else o.wallet=r,t=await this.privateGetV1FapiAccountBalance(this.extend(o,a));let n=this.safeList(t,"data",[]);return this.parseBalance(n)}parseBalance(e){let t={info:e,timestamp:void 0,datetime:void 0};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"asset"),a=this.safeCurrencyCode(r),o=this.account();o.total=this.safeString2(s,"total","balance"),o.free=this.safeString2(s,"available","availableBalance"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(e),o=this.safeDict(this.options,"accountsByType",{}),n=this.safeString(o,i,i),d=this.safeString(o,s,s),h={asset:a.id,amount:this.currencyToPrecision(e,t),fromType:n,toType:d},c=await this.privatePostV1AccountTransfer(this.extend(h,r)),l=this.parseTransfer(c,a),u=this.safeDict(this.options,"transfer",{});return!0===this.safeBool(u,"fillResponseFromRequest",!0)&&(l.currency=e,l.fromAccount=i,l.toAccount=s,l.amount=t),l}async fetchTransfers(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchTransfers() requires a code argument");void 0===this.markets&&await this.loadMarkets();let r=this.currency(e);if(!0===this.safeBool(s,"paginate",!1)){let e=this.extend(this.omit(s,"paginate"),{paginationDirection:"backward"}),a=await this.fetchPaginatedCallDynamic("fetchTransfers",this.safeString(r,"code"),t,i,e,50,!0);return this.sortBy(a,"timestamp")}let o={asset:r.id},[n,d]=this.handleOptionIntegerAndParams2(s,"fetchTransfers","until","endTime"),h=void 0===t?1:t;o.startTime=h,o.endTime=void 0===n?this.milliseconds():n,void 0!==i&&(o.rows=i);let c=await this.privateGetV1AccountTransferRecords(this.extend(o,d)),l=this.safeList(c,"data",[]);return this.parseTransfers(l,r,h,i)}parseTransfer(e,t){let i=this.safeStringUpper2(e,"message","status"),s=this.safeDict(this.options,"accountsById",{}),r=this.safeStringUpper(e,"sourceWallet"),a=this.safeStringUpper(e,"targetWallet"),o=this.safeString(s,r,r),n=this.safeString(s,a,a),d=this.safeInteger(e,"timestamp"),h=this.safeString(e,"asset");return{info:e,id:this.safeString(e,"txId"),timestamp:d,datetime:this.iso8601(d),currency:this.safeCurrencyCode(h,t),amount:this.safeNumber(e,"amount"),fromAccount:o,toAccount:n,status:this.paraseTransferStatus(i)}}paraseTransferStatus(e){return this.safeString({SUCCESS:"ok",WAIT:"pending",FAILED:"failed"},e,e)}async fetchDeposits(e,t,i,s={}){return await this.fetchTransactionsHelper("deposit",e,t,i,s)}async fetchWithdrawals(e,t,i,s={}){return await this.fetchTransactionsHelper("withdrawal",e,t,i,s)}async fetchTransactionsHelper(e,t,i,s,r){let o,n,d,h="fetchWithdrawals";if("deposit"===e&&(h="fetchDeposits"),void 0===t)throw new a.ArgumentsRequired(this.id+" "+h+"() requires a code argument");void 0===this.markets&&await this.loadMarkets();let c=this.currency(t);if(!0===this.safeBool(r,"paginate",!1)){let e=this.extend(this.omit(r,"paginate"),{paginationDirection:"backward"}),t=await this.fetchPaginatedCallDynamic(h,this.safeString(c,"code"),i,s,e,50,!0);return this.sortBy(t,"timestamp")}let l={asset:c.id};[o,n]=this.handleOptionIntegerAndParams2(r,"fetchTransfers","until","endTime");let u=this.milliseconds(),f=i;void 0===f?void 0===o?(f=u-6048e5,o=u):f=o-6048e5:void 0===o&&(o=u-f>6048e5?f+6048e5:u),l.startTime=f,l.endTime=o,void 0!==s&&(l.limit=s),d="deposit"===e?await this.privateGetV1SpotDepositRecords(this.extend(l,n)):await this.privateGetV1SpotWithdrawRecords(this.extend(l,n));let p=this.safeList(d,"data",[]),m=this.extend(n,{type:e});return this.parseTransactions(p,c,i,s,m)}parseTransaction(e,t){let i,s=this.safeString(e,"asset"),r=this.safeCurrencyCode(s,t),a=this.safeStringLower(e,"status"),o=this.safeInteger(e,"createTime"),n=this.safeNumber(e,"fee");return void 0!==n&&(i={cost:n,currency:void 0}),{info:e,id:this.safeString(e,"orderId"),txid:this.safeString(e,"txId"),type:void 0,currency:r,network:this.networkIdToCode(this.safeString(e,"network"),r),amount:this.safeNumber(e,"amount"),status:this.parseTransactionStatus(a),timestamp:o,datetime:this.iso8601(o),address:this.safeString(e,"address"),addressFrom:void 0,addressTo:void 0,tag:this.safeString(e,"addressTag"),tagFrom:void 0,tagTo:void 0,updated:this.safeInteger(e,"finishTime"),comment:void 0,fee:i,internal:!1}}parseTransactionStatus(e){return this.safeString({success:"ok",wait:"pending",failed:"failed"},e,e)}sign(e,t="public",i="GET",r={},o,n){let d,h,c=this.safeString(this.urls.api,t);if(void 0===c)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let l=c,u="/"+e,f="",p=this.keysort(r);if("GET"===i&&0!==(f=this.urlencode(p)).length&&(u+="?"+f),"private"===t){this.checkRequiredCredentials();let e=this.milliseconds().toString();if("GET"===i){let t=this.apiKey+e+f,i=this.hmac(this.encode(t),this.encode(this.secret),s.sc,"hex");h={"X-API-KEY":this.apiKey,"X-API-TIMESTAMP":e,"X-API-SIGNATURE":i}}else{d=this.json(p);let t=this.apiKey+e+d,i=this.hmac(this.encode(t),this.encode(this.secret),s.sc,"hex");h={"Content-Type":"application/json","X-API-KEY":this.apiKey,"X-API-TIMESTAMP":e,"X-API-SIGNATURE":i}}}let m=void 0===d?n:d,g=void 0===h?o:h;return{url:l+=u,method:i,body:m,headers:g}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"code"),l=this.safeString(n,"message");if("200"!==c){let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,l,e),this.throwBroadlyMatchedException(this.exceptions.broad,l,e),this.throwExactlyMatchedException(this.exceptions.exact,c,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>n})},5704(e,t,i){"use strict";var s=i(4721),r=i(6131),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"cex",name:"CEX.IO",countries:["GB","EU","CY","RU"],rateLimit:300,pro:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,createStopOrder:!0,createTriggerOrder:!0,fetchAccounts:!0,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrder:!0,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositsWithdrawals:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLedger:!0,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrder:!0,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrderBook:!0,fetchOrdersByStatus:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFees:!0,fetchVolatilityHistory:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!0},urls:{logo:"https://github.com/user-attachments/assets/6105a195-3bae-4a08-a1bd-b2a86e3e8f99",api:{public:"https://trade.cex.io/api/spot/rest-public",private:"https://trade.cex.io/api/spot/rest"},www:"https://cex.io",doc:"https://trade.cex.io/docs/",fees:["https://cex.io/fee-schedule","https://cex.io/limits-commissions"],referral:"https://cex.io/r/0/up105393824/0/"},api:{public:{get:{},post:{get_server_time:{cost:1},get_pairs_info:{cost:1},get_currencies_info:{cost:1},get_processing_info:{cost:10},get_ticker:{cost:1},get_trade_history:{cost:1},get_order_book:{cost:1},get_candles:{cost:1}}},private:{get:{},post:{get_my_current_fee:{cost:5},get_fee_strategy:{cost:1},get_my_volume:{cost:5},do_create_account:{cost:1},get_my_account_status_v3:{cost:5},get_my_wallet_balance:{cost:5},get_my_orders:{cost:5},do_my_new_order:{cost:1},do_cancel_my_order:{cost:1},do_cancel_all_orders:{cost:5},get_order_book:{cost:1},get_ticker:{cost:1},get_candles:{cost:1},get_trade_history:{cost:1},get_my_transaction_history:{cost:1},get_my_funding_history:{cost:5},do_my_internal_transfer:{cost:1},get_processing_info:{cost:10},get_deposit_address:{cost:5},do_deposit_funds_from_wallet:{cost:1},do_withdrawal_funds_to_wallet:{cost:1}}}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!1,GTD:!0},hedged:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!0,selfTradePrevention:!1,trailing:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:void 0,fetchOrder:void 0,fetchOpenOrders:{marginMode:!1,limit:1e3,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:1e3,daysBack:1e5,daysBackCanceled:1,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:1e3}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},precisionMode:4,exceptions:{exact:{},broad:{"You have negative balance on following accounts":a.InsufficientFunds,"Mandatory parameter side should be one of BUY,SELL":a.BadRequest,"API orders from Main account are not allowed":a.BadRequest,"check failed":a.BadRequest,"Insufficient funds":a.InsufficientFunds,"Get deposit address for main account is not allowed":a.PermissionDenied,"Market Trigger orders are not allowed":a.BadRequest,"key not passed or incorrect":a.AuthenticationError,"API rate limit reached":a.RateLimitExceeded}},timeframes:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","1d":"1d"},options:{networks:{BTC:"bitcoin",ERC20:"ERC20",BSC20:"binancesmartchain",DOGE:"dogecoin",ALGO:"algorand",XLM:"stellar",ATOM:"cosmos",LTC:"litecoin",XRP:"ripple",FTM:"fantom",MINA:"mina",THETA:"theta",XTZ:"tezos",TIA:"celestia",CRONOS:"cronos",MATIC:"polygon",TON:"ton",TRC20:"tron",SOLANA:"solana",SGB:"songbird",DYDX:"dydx",DASH:"dash",ZIL:"zilliqa",EOS:"eos",AVALANCHEC:"avalanche",ETHPOW:"ethereumpow",NEAR:"near",ARBITRUM:"arbitrum",DOT:"polkadot",OPT:"optimism",INJ:"injective",ADA:"cardano",ONT:"ontology",ICP:"icp",KAVA:"kava",KSM:"kusama",SEI:"sei",NEO:"neo",NEO3:"neo3",XDC:"xdc"}}})}async fetchCurrencies(e={}){let t=[];t.push(this.publicPostGetCurrenciesInfo(e)),t.push(this.publicPostGetProcessingInfo(e));let i=await Promise.all(t),s=this.safeList(i[0],"data",[]),r=this.safeDict(i[1],"data",{}),a=this.indexBy(s,"currency"),o=this.deepExtend(a,r);return this.parseCurrencies(this.toArray(o))}parseCurrency(e){let t=this.safeString(e,"currency"),i=this.safeCurrencyCode(t),s=this.safeBool(e,"fiat",!1),r="crypto";s&&(r="fiat");let a=this.parseNumber(this.parsePrecision(this.safeString(e,"precision"))),o={},n=this.safeDict(e,"blockchains",{}),d=Object.keys(n);for(let e=0;e<d.length;e++){let t=d[e],s=this.safeDict(n,t),r=this.networkIdToCode(t,i),h="enabled"===this.safeString(s,"deposit"),c="enabled"===this.safeString(s,"withdrawal");void 0!==r&&(o[r]={id:t,network:r,margin:void 0,deposit:h,withdraw:c,active:void 0,fee:this.safeNumber(s,"withdrawalFee"),precision:a,limits:{deposit:{min:this.safeNumber(s,"minDeposit"),max:void 0},withdraw:{min:this.safeNumber(s,"minWithdrawal"),max:void 0}},info:s})}return this.safeCurrencyStructure({id:t,code:i,name:void 0,type:r,active:void 0,deposit:this.safeBool(e,"walletDeposit"),withdraw:this.safeBool(e,"walletWithdrawal"),fee:void 0,precision:a,limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}},networks:o,info:e})}async fetchMarkets(e={}){let t=await this.publicPostGetPairsInfo(e),i=this.safeList(t,"data",[]);return this.parseMarkets(i)}parseMarket(e){let t=this.safeString(e,"base"),i=this.safeCurrencyCode(t),s=this.safeString(e,"quote"),r=this.safeCurrencyCode(s);if(void 0!==i&&void 0!==r)return this.safeMarketStructure({id:i+"-"+r,symbol:i+"/"+r,base:i,baseId:t,quote:r,quoteId:s,settle:void 0,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,limits:{amount:{min:this.safeNumber(e,"baseMin"),max:this.safeNumber(e,"baseMax")},price:{min:this.safeNumber(e,"minPrice"),max:this.safeNumber(e,"maxPrice")},cost:{min:this.safeNumber(e,"quoteMin"),max:this.safeNumber(e,"quoteMax")},leverage:{min:void 0,max:void 0}},precision:{amount:this.safeString(e,"baseLotSize"),price:this.parseNumber(this.parsePrecision(this.safeString(e,"pricePrecision"))),base:this.parseNumber(this.parsePrecision(this.safeString(e,"basePrecision"))),quote:this.parseNumber(this.parsePrecision(this.safeString(e,"quotePrecision")))},active:void 0,created:void 0,info:e})}async fetchTime(e={}){let t=await this.publicPostGetServerTime(e),i=this.safeDict(t,"data");return this.safeInteger(i,"timestamp")}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.fetchTickers([e],t);return this.safeDict(i,e,{})}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={};void 0!==e&&(i.pairs=this.marketIds(e));let s=await this.publicPostGetTicker(this.extend(i,t)),r=this.safeDict(s,"data",{});return this.parseTickers(r,e)}parseTicker(e,t){let i=this.safeString(e,"id"),s=this.safeSymbol(i,t);return this.safeTicker({symbol:s,timestamp:void 0,datetime:void 0,high:this.safeNumber(e,"high"),low:this.safeNumber(e,"low"),bid:this.safeNumber(e,"bestBid"),bidVolume:void 0,ask:this.safeNumber(e,"bestAsk"),askVolume:void 0,vwap:void 0,open:void 0,close:this.safeString(e,"last"),previousClose:void 0,change:this.safeNumber(e,"priceChange"),percentage:this.safeNumber(e,"priceChangePercentage"),average:void 0,baseVolume:this.safeString(e,"volume"),quoteVolume:this.safeString(e,"quoteVolume"),info:e},t)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={pair:r.id};void 0!==t&&(a.fromDateISO=this.iso8601(t));let[o,n]=this.handleParamInteger2(s,"until","till");void 0!==o&&(a.toDateISO=this.iso8601(o)),void 0!==i&&(a.pageSize=Math.min(i,1e4));let d=await this.publicPostGetTradeHistory(this.extend(a,n)),h=this.safeDict(d,"data",{}),c=this.safeList(h,"trades",[]);return this.parseTrades(c,r,t,i)}parseTrade(e,t){let i=this.safeString(e,"dateISO"),s=this.parse8601(i),r=this.safeMarket(void 0,t);return this.safeTrade({info:e,timestamp:s,datetime:this.iso8601(s),symbol:r.symbol,id:this.safeString(e,"tradeId"),order:void 0,type:void 0,takerOrMaker:void 0,side:this.safeStringLower(e,"side"),price:this.safeString(e,"price"),amount:this.safeString(e,"amount"),cost:void 0,fee:void 0},r)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={pair:s.id},a=await this.publicPostGetOrderBook(this.extend(r,i)),o=this.safeDict(a,"data",{}),n=this.safeInteger(o,"timestamp");return this.parseOrderBook(o,s.symbol,n)}async fetchOHLCV(e,t="1m",i,s,r={}){let[o,n]=this.handleOptionStringAndParams(r,"fetchOHLCV","dataType");if(void 0===o)throw new a.ArgumentsRequired(this.id+' fetchOHLCV requires a parameter "dataType" to be either "bestBid" or "bestAsk"');void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h={pair:d.id,resolution:this.timeframes[t],dataType:o};void 0!==i&&(h.fromISO=this.iso8601(i));let[c,l]=this.handleParamInteger2(n,"until","till");if(void 0!==c?h.toISO=this.iso8601(c):void 0===i&&(h.toISO=this.iso8601(this.milliseconds())),void 0!==i&&void 0!==c&&void 0!==s)throw new a.ArgumentsRequired(this.id+" fetchOHLCV does not support fetching candles with both a limit and since/until");if((void 0!==i||void 0!==c)&&void 0===s)throw new a.ArgumentsRequired(this.id+" fetchOHLCV requires a limit parameter when fetching candles with since or until");void 0!==s&&(h.limit=s);let u=await this.publicPostGetCandles(this.extend(h,l)),f=this.safeList(u,"data",[]);return this.parseOHLCVs(f,d,t,i,s)}parseOHLCV(e,t){return[this.safeInteger(e,"timestamp"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostGetMyCurrentFee(e),i=this.safeDict(t,"data",{}),s=this.safeDict(i,"tradingFee",{});return this.parseTradingFees(s,!0)}parseTradingFees(e,t=!1){let i={},s=Object.keys(e);for(let r=0;r<s.length;r++){let a,o=s[r];t&&(a=this.safeMarket(o));let n=this.parseTradingFee(e[o],a),d=this.safeString(n,"symbol");void 0!==d&&(i[d]=n)}let r=this.symbols;for(let t=0;t<r.length;t++){let s=r[t];if(!(s in i)){let t=this.market(s);i[s]=this.parseTradingFee(e,t)}}return i}parseTradingFee(e,t){return{info:e,symbol:this.safeString(t,"symbol"),maker:this.safeNumber(e,"percent"),taker:this.safeNumber(e,"percent"),percentage:void 0,tierBased:void 0}}async fetchAccounts(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostGetMyAccountStatusV3(e),i=this.safeDict(t,"data",{}),s=this.safeDict(i,"balancesPerAccounts",{}),r=this.toArray(s);return this.parseAccounts(r,e)}parseAccount(e){return{id:void 0,type:void 0,code:void 0,info:e}}async fetchBalance(e={}){let t,[i,s]=this.handleParamString(e,"account",""),[r,a]=this.handleParamString(s,"method","privatePostGetMyWalletBalance");if("privatePostGetMyAccountStatusV3"===r){let e=await this.privatePostGetMyAccountStatusV3(a),s=this.safeDict(e,"data",{}),r=this.safeDict(s,"balancesPerAccounts",{});t=this.safeDict(r,i,{})}else{let e=await this.privatePostGetMyWalletBalance(a);t=this.safeDict(e,"data",{})}return this.parseBalance(t)}parseBalance(e){let t={info:e},i=Object.keys(e);for(let s=0;s<i.length;s++){let r=i[s],a=this.safeDict(e,r,{}),o=this.safeCurrencyCode(r),n={used:this.safeString(a,"balanceOnHold"),total:this.safeString(a,"balance")};void 0!==o&&(t[o]=n)}return this.safeBalance(t)}async fetchOrdersByStatus(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o={},n="closed"===e;n&&(o.archived=!0),void 0!==t&&(o.pair=(a=this.market(t)).id),void 0!==s&&(o.pageSize=s),void 0!==i?o.serverCreateTimestampFrom=i:n&&(o.serverCreateTimestampFrom=this.milliseconds()-314496e5);let[d,h]=this.handleParamInteger2(r,"until","till");void 0!==d&&(o.serverCreateTimestampTo=d);let c=await this.privatePostGetMyOrders(this.extend(o,h)),l=this.safeList(c,"data",[]);return this.parseOrders(l,a,i,s)}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrdersByStatus("closed",e,t,i,s)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrdersByStatus("open",e,t,i,s)}async fetchOpenOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={orderId:parseInt(e)};return(await this.fetchOpenOrders(t,void 0,void 0,this.extend(s,i)))[0]}async fetchClosedOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={orderId:parseInt(e)};return(await this.fetchClosedOrders(t,void 0,void 0,this.extend(s,i)))[0]}parseOrderStatus(e){return this.safeString({PENDING_NEW:"open",NEW:"open",PARTIALLY_FILLED:"open",FILLED:"closed",EXPIRED:"expired",REJECTED:"rejected",PENDING_CANCEL:"canceling",CANCELLED:"canceled"},e,e)}parseOrder(e,t){let i,s=this.safeString(e,"currency1"),r=this.safeString(e,"currency2");void 0!==s&&void 0!==r&&(i=s+"-"+r);let a=this.safeMarket(i,t),o=a.symbol,n=this.parseOrderStatus(this.safeString(e,"status")),d={},h=this.safeNumber(e,"feeAmount");if(void 0!==h){let t=this.safeString(e,"feeCurrency");d.currency=this.safeCurrencyCode(t),d.cost=h}let c=this.safeInteger(e,"serverCreateTimestamp"),l=this.safeNumber(e,"requestedAmountCcy1"),u=this.safeNumber(e,"executedAmountCcy1"),f=this.safeNumber(e,"executedAmountCcy2");return this.safeOrder({id:this.safeString(e,"orderId"),clientOrderId:this.safeString(e,"clientOrderId"),timestamp:c,datetime:this.iso8601(c),lastUpdateTimestamp:this.safeInteger(e,"lastUpdateTimestamp"),lastTradeTimestamp:void 0,symbol:o,type:this.safeStringLower(e,"orderType"),timeInForce:this.safeString(e,"timeInForce"),postOnly:void 0,side:this.safeStringLower(e,"side"),price:this.safeNumber(e,"price"),triggerPrice:this.safeNumber(e,"stopPrice"),amount:l,cost:f,average:this.safeNumber(e,"averagePrice"),filled:u,remaining:void 0,status:n,fee:d,trades:void 0,info:e},a)}async createOrder(e,t,i,s,r,o={}){let[n,d]=this.handleOptionStringAndParams(o,"createOrder","accountId");if(void 0===n)throw new a.ArgumentsRequired(this.id+' createOrder() : API trading is now allowed from main account, set params["accountId"] or .options["createOrder"]["accountId"] to the name of your sub-account');void 0===this.markets&&await this.loadMarkets();let h=this.market(e);this.checkRequiredArgument("createOrder",i,"side");let c={clientOrderId:this.uuid(),currency1:h.baseId,currency2:h.quoteId,accountId:n,orderType:this.capitalize(t.toLowerCase()),side:i.toUpperCase(),timestamp:this.milliseconds(),amountCcy1:this.amountToPrecision(e,s)},[l,u]=this.handleOptionStringAndParams(d,"createOrder","timeInForce","GTC");"limit"===t&&(c.price=this.priceToPrecision(e,r),c.timeInForce=l);let[f,p]=this.handleParamString(u,"triggerPrice");void 0!==f&&(c.type="Stop Limit",c.stopPrice=f);let m=await this.privatePostDoMyNewOrder(this.extend(c,p)),g=this.safeDict(m,"data",{});return this.parseOrder(g,h)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={orderId:parseInt(e),cancelRequestId:"c_"+this.milliseconds().toString(),timestamp:this.milliseconds()},r=await this.privatePostDoCancelMyOrder(this.extend(s,i)),a=this.safeDict(r,"data",{});return this.parseOrder(a)}async cancelAllOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privatePostDoCancelAllOrders(t),s=this.safeDict(i,"data",{}),r=this.safeList(s,"clientOrderIds",[]),a=[];for(let e=0;e<r.length;e++){let t=r[e];a.push({clientOrderId:t})}return this.parseOrders(a)}async fetchLedger(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.currency=(r=this.currency(e)).id),void 0!==t&&(a.dateFrom=t),void 0!==i&&(a.pageSize=i);let[o,n]=this.handleParamInteger2(s,"until","till");void 0!==o&&(a.dateTo=o);let d=await this.privatePostGetMyTransactionHistory(this.extend(a,n)),h=this.safeList(d,"data",[]);return this.parseLedger(h,r,t,i)}parseLedgerEntry(e,t){let i,s=this.safeString(e,"amount");o.Y.stringLe(s,"0")?(i="out",s=o.Y.stringMul("-1",s)):i="in";let r=this.safeString(e,"currency"),a=this.safeCurrency(r,t),n=this.safeCurrencyCode(r,a),d=this.safeString(e,"timestamp"),h=this.parse8601(d),c=this.safeString(e,"type");return this.safeLedgerEntry({info:e,id:this.safeString(e,"transactionId"),direction:i,account:this.safeString(e,"accountId",""),referenceAccount:void 0,referenceId:void 0,type:this.parseLedgerEntryType(c),currency:n,amount:this.parseNumber(s),timestamp:h,datetime:this.iso8601(h),before:void 0,after:void 0,status:void 0,fee:void 0},a)}parseLedgerEntryType(e){return this.safeString({deposit:"deposit",withdraw:"withdrawal",commission:"fee"},e,e)}async fetchDepositsWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(r=this.currency(e)),void 0!==t&&(a.dateFrom=t),void 0!==i&&(a.pageSize=i);let[o,n]=this.handleParamInteger2(s,"until","till");void 0!==o&&(a.dateTo=o);let d=await this.privatePostGetMyFundingHistory(this.extend(a,n)),h=this.safeList(d,"data",[]);return this.parseTransactions(h,r,t,i)}parseTransaction(e,t){let i=this.safeString(e,"currency"),s=this.safeString(e,"direction"),r="deposit";"withdraw"===s&&(r="withdrawal");let a=this.safeCurrencyCode(i,t),o=this.safeString(e,"updatedAt"),n=this.parse8601(o);return{info:e,id:this.safeString(e,"txId"),txid:void 0,type:r,currency:a,network:void 0,amount:this.safeNumber(e,"amount"),status:this.parseTransactionStatus(this.safeString(e,"status")),timestamp:n,datetime:this.iso8601(n),address:void 0,addressFrom:void 0,addressTo:void 0,tag:void 0,tagFrom:void 0,tagTo:void 0,updated:void 0,comment:void 0,fee:{currency:a,cost:this.safeNumber(e,"commissionAmount")},internal:void 0}}parseTransactionStatus(e){return this.safeString({rejected:"rejected",pending:"pending",approved:"ok"},e,e)}async transfer(e,t,i,s,r={}){let a;a=""!==s&&""!==i?await this.transferBetweenSubAccounts(e,t,i,s,r):await this.transferBetweenMainAndSubAccount(e,t,i,s,r);let o=this.handleOption("transfer","fillResponseFromRequest",!0),n={};return!0===o&&(n.fromAccount=i,n.toAccount=s),this.extend(a,n)}async transferBetweenMainAndSubAccount(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.currency(e),n=""===i,d=i;n&&(d=s);let h=this.safeString(r,"guid",this.uuid()),c={currency:o.id,amount:this.currencyToPrecision(e,t),accountId:d,clientTxId:h};a=n?await this.privatePostDoDepositFundsFromWallet(this.extend(c,r)):await this.privatePostDoWithdrawalFundsToWallet(this.extend(c,r));let l=this.safeDict(a,"data",{});return this.parseTransfer(l,o)}async transferBetweenSubAccounts(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(e),o={currency:a.id,amount:this.currencyToPrecision(e,t),fromAccountId:i,toAccountId:s},n=await this.privatePostDoMyInternalTransfer(this.extend(o,r)),d=this.safeDict(n,"data",{});return this.parseTransfer(d,a)}parseTransfer(e,t){let i=this.safeString(e,"currency"),s=this.safeCurrencyCode(i,t);return{info:e,id:this.safeString2(e,"transactionId","clientTxId"),timestamp:void 0,datetime:void 0,currency:s,amount:void 0,fromAccount:void 0,toAccount:void 0,status:this.parseTransactionStatus(this.safeString(e,"status"))}}async fetchDepositAddress(e,t={}){let[i,s]=this.handleOptionStringAndParams(t,"createOrder","accountId");if(void 0===i)throw new a.ArgumentsRequired(this.id+' fetchDepositAddress() : main account is not allowed to fetch deposit address from api, set params["accountId"] or .options["createOrder"]["accountId"] to the name of your sub-account');void 0===this.markets&&await this.loadMarkets();let[r,o]=this.handleNetworkCodeAndParams(s),n=this.currency(e),d={accountId:i,currency:n.id,blockchain:this.networkCodeToId(r,this.safeString(n,"code"))},h=await this.privatePostGetDepositAddress(this.extend(d,o)),c=this.safeDict(h,"data",{});return this.parseDepositAddress(c,n)}parseDepositAddress(e,t){let i=this.safeString(e,"address"),s=this.safeString(e,"currency"),r=this.safeCurrency(s,t);return this.checkAddress(i),{info:e,currency:r.code,network:this.networkIdToCode(this.safeString(e,"blockchain"),this.safeString(r,"code")),address:i,tag:void 0}}sign(e,t="public",i="GET",r={},o,n){let d=this.safeString(this.urls.api,t);if(void 0===d)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let h=d+"/"+this.implodeParams(e,r),c=this.omit(r,this.extractParams(e));if("public"===t)if("GET"!==i)return{url:h,method:i,body:this.json(c),headers:{"Content-Type":"application/json"}};else Object.keys(c).length>0&&(h+="?"+this.urlencode(c));else{this.checkRequiredCredentials();let t=this.seconds().toString(),r=this.json(c),a=e+t+r,o=this.hmac(this.encode(a),this.encode(this.secret),s.sc,"base64");return{url:h,method:i,body:r,headers:{"Content-Type":"application/json","X-AGGR-KEY":this.apiKey,"X-AGGR-TIMESTAMP":t,"X-AGGR-SIGNATURE":o}}}return{url:h,method:i,body:n,headers:o}}handleErrors(e,t,i,s,r,o,n,d,h){let c;if(void 0===n)if(void 0===o)throw new a.NullResponse(this.id+" returned empty response");else if("{"===o[0]){let e=this.fixStringifiedJsonMembers(o);c=this.parseJson(e)}else throw new a.NullResponse(this.id+" returned unparsed response: "+o);let l=void 0===n?c:n,u=this.safeString(l,"error");if(void 0!==u){let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,u,e),this.throwBroadlyMatchedException(this.exceptions.broad,u,e),new a.ExchangeError(e)}if(i.indexOf("do_my_new_order")>=0){let e=this.safeDict(l,"data",{}),t=this.safeString(e,"rejectReason");if(void 0!==t)throw this.throwBroadlyMatchedException(this.exceptions.broad,t,t),new a.ExchangeError(this.id+" createOrder() "+t)}}}i.d(t,{A:()=>n})},4038(e,t,i){"use strict";var s=i(4721),r=i(1251),a=i(1453),o=i(7749),n=i(8748);class d extends r.A{describe(){return this.deepExtend(super.describe(),{id:"coinbase",name:"Coinbase Advanced",countries:["US"],pro:!0,certified:!1,rateLimit:34,version:"v2",userAgent:this.userAgents.chrome,headers:{"CB-VERSION":"2018-05-30"},has:{CORS:!0,spot:!0,margin:!1,swap:!0,future:!0,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!1,closePosition:!0,createConvertTrade:!0,createDepositAddress:!0,createLimitBuyOrder:!0,createLimitSellOrder:!0,createMarketBuyOrder:!0,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!1,createMarketSellOrder:!0,createMarketSellOrderWithCost:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createPostOnlyOrder:!0,createReduceOnlyOrder:!1,createStopLimitOrder:!0,createStopMarketOrder:!1,createStopOrder:!0,deposit:!0,editOrder:!0,fetchAccounts:!0,fetchBalance:!0,fetchBidsAsks:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCanceledOrders:!0,fetchClosedOrders:!0,fetchConvertQuote:!0,fetchConvertTrade:!0,fetchConvertTradeHistory:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:!0,fetchDepositAddress:"emulated",fetchDepositAddresses:!0,fetchDepositAddressesByNetwork:!0,fetchDepositMethodId:!0,fetchDepositMethodIds:!0,fetchDeposits:!0,fetchDepositsWithdrawals:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchL2OrderBook:!1,fetchLedger:!0,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyBuys:!0,fetchMyLiquidations:!1,fetchMySells:!0,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchOrdersByStatus:!0,fetchPosition:!0,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:"emulated",fetchTradingFees:!0,fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!0,withdraw:!0},urls:{logo:"https://user-images.githubusercontent.com/1294454/40811661-b6eceae2-653a-11e8-829e-10bfadb078cf.jpg",api:{rest:"https://api.coinbase.com"},www:"https://www.coinbase.com",doc:["https://docs.cdp.coinbase.com/coinbase-app/introduction/welcome","https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/api-reference"],fees:["https://support.coinbase.com/customer/portal/articles/2109597-buy-sell-bank-transfer-fees","https://www.coinbase.com/advanced-fees"],referral:"https://www.coinbase.com/join/58cbe25a355148797479dbd2"},requiredCredentials:{apiKey:!0,secret:!0},api:{v2:{public:{get:{currencies:{cost:10.6},"currencies/crypto":{cost:10.6},time:{cost:10.6},"exchange-rates":{cost:10.6},"users/{user_id}":{cost:10.6},"prices/{symbol}/buy":{cost:10.6},"prices/{symbol}/sell":{cost:10.6},"prices/{symbol}/spot":{cost:10.6}}},private:{get:{accounts:{cost:10.6},"accounts/{account_id}":{cost:10.6},"accounts/{account_id}/addresses":{cost:10.6},"accounts/{account_id}/addresses/{address_id}":{cost:10.6},"accounts/{account_id}/addresses/{address_id}/transactions":{cost:10.6},"accounts/{account_id}/transactions":{cost:10.6},"accounts/{account_id}/transactions/{transaction_id}":{cost:10.6},"accounts/{account_id}/buys":{cost:10.6},"accounts/{account_id}/buys/{buy_id}":{cost:10.6},"accounts/{account_id}/sells":{cost:10.6},"accounts/{account_id}/sells/{sell_id}":{cost:10.6},"accounts/{account_id}/deposits":{cost:10.6},"accounts/{account_id}/deposits/{deposit_id}":{cost:10.6},"accounts/{account_id}/withdrawals":{cost:10.6},"accounts/{account_id}/withdrawals/{withdrawal_id}":{cost:10.6},"payment-methods":{cost:10.6},"payment-methods/{payment_method_id}":{cost:10.6},user:{cost:10.6},"user/auth":{cost:10.6},"subscriptions/coinbase-one":{cost:10.6}},post:{accounts:{cost:10.6},"accounts/{account_id}/primary":{cost:10.6},"accounts/{account_id}/addresses":{cost:10.6},"accounts/{account_id}/transactions":{cost:10.6},"accounts/{account_id}/transactions/{transaction_id}/complete":{cost:10.6},"accounts/{account_id}/transactions/{transaction_id}/resend":{cost:10.6},"accounts/{account_id}/buys":{cost:10.6},"accounts/{account_id}/buys/{buy_id}/commit":{cost:10.6},"accounts/{account_id}/sells":{cost:10.6},"accounts/{account_id}/sells/{sell_id}/commit":{cost:10.6},"accounts/{account_id}/deposits":{cost:10.6},"accounts/{account_id}/deposits/{deposit_id}/commit":{cost:10.6},"accounts/{account_id}/withdrawals":{cost:10.6},"accounts/{account_id}/withdrawals/{withdrawal_id}/commit":{cost:10.6}},put:{"accounts/{account_id}":{cost:10.6},user:{cost:10.6}},delete:{"accounts/{id}":{cost:10.6},"accounts/{account_id}/transactions/{transaction_id}":{cost:10.6}}}},v3:{public:{get:{"brokerage/time":{cost:3},"brokerage/market/product_book":{cost:3},"brokerage/market/products":{cost:3},"brokerage/market/products/{product_id}":{cost:3},"brokerage/market/products/{product_id}/candles":{cost:3},"brokerage/market/products/{product_id}/ticker":{cost:3}}},private:{get:{"brokerage/accounts":{cost:1},"brokerage/accounts/{account_uuid}":{cost:1},"brokerage/orders/historical/batch":{cost:1},"brokerage/orders/historical/fills":{cost:1},"brokerage/orders/historical/{order_id}":{cost:1},"brokerage/products":{cost:3},"brokerage/products/{product_id}":{cost:3},"brokerage/products/{product_id}/candles":{cost:3},"brokerage/products/{product_id}/ticker":{cost:3},"brokerage/best_bid_ask":{cost:3},"brokerage/product_book":{cost:3},"brokerage/transaction_summary":{cost:3},"brokerage/portfolios":{cost:1},"brokerage/portfolios/{portfolio_uuid}":{cost:1},"brokerage/convert/trade/{trade_id}":{cost:1},"brokerage/cfm/balance_summary":{cost:1},"brokerage/cfm/positions":{cost:1},"brokerage/cfm/positions/{product_id}":{cost:1},"brokerage/cfm/sweeps":{cost:1},"brokerage/cfm/intraday/current_margin_window":{cost:1},"brokerage/cfm/intraday/margin_setting":{cost:1},"brokerage/intx/balances/{portfolio_uuid}":{cost:1},"brokerage/intx/portfolio/{portfolio_uuid}":{cost:1},"brokerage/intx/positions/{portfolio_uuid}":{cost:1},"brokerage/intx/positions/{portfolio_uuid}/{symbol}":{cost:1},"brokerage/payment_methods":{cost:1},"brokerage/payment_methods/{payment_method_id}":{cost:1},"brokerage/key_permissions":{cost:1}},post:{"brokerage/orders":{cost:1},"brokerage/orders/batch_cancel":{cost:1},"brokerage/orders/edit":{cost:1},"brokerage/orders/edit_preview":{cost:1},"brokerage/orders/preview":{cost:1},"brokerage/portfolios":{cost:1},"brokerage/portfolios/move_funds":{cost:1},"brokerage/convert/quote":{cost:1},"brokerage/convert/trade/{trade_id}":{cost:1},"brokerage/cfm/sweeps/schedule":{cost:1},"brokerage/cfm/intraday/margin_setting":{cost:1},"brokerage/intx/allocate":{cost:1},"brokerage/intx/multi_asset_collateral":{cost:1},"brokerage/orders/close_position":{cost:1}},put:{"brokerage/portfolios/{portfolio_uuid}":{cost:1}},delete:{"brokerage/portfolios/{portfolio_uuid}":{cost:1},"brokerage/cfm/sweeps":{cost:1}}}}},fees:{trading:{taker:this.parseNumber("0.012"),maker:this.parseNumber("0.006"),tierBased:!0,percentage:!0,tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.006")],[this.parseNumber("10000"),this.parseNumber("0.004")],[this.parseNumber("50000"),this.parseNumber("0.0025")],[this.parseNumber("100000"),this.parseNumber("0.002")],[this.parseNumber("1000000"),this.parseNumber("0.0018")],[this.parseNumber("15000000"),this.parseNumber("0.0016")],[this.parseNumber("75000000"),this.parseNumber("0.0012")],[this.parseNumber("250000000"),this.parseNumber("0.0008")],[this.parseNumber("400000000"),this.parseNumber("0.0005")]],maker:[[this.parseNumber("0"),this.parseNumber("0.004")],[this.parseNumber("10000"),this.parseNumber("0.0025")],[this.parseNumber("50000"),this.parseNumber("0.0015")],[this.parseNumber("100000"),this.parseNumber("0.001")],[this.parseNumber("1000000"),this.parseNumber("0.0008")],[this.parseNumber("15000000"),this.parseNumber("0.0006")],[this.parseNumber("75000000"),this.parseNumber("0.0003")],[this.parseNumber("250000000"),this.parseNumber("0.0")],[this.parseNumber("400000000"),this.parseNumber("0.0")]]}}},precisionMode:4,exceptions:{exact:{two_factor_required:a.AuthenticationError,param_required:a.ExchangeError,validation_error:a.ExchangeError,invalid_request:a.ExchangeError,personal_details_required:a.AuthenticationError,identity_verification_required:a.AuthenticationError,jumio_verification_required:a.AuthenticationError,jumio_face_match_verification_required:a.AuthenticationError,unverified_email:a.AuthenticationError,authentication_error:a.AuthenticationError,unauthorized:a.AuthenticationError,invalid_authentication_method:a.AuthenticationError,invalid_token:a.AuthenticationError,revoked_token:a.AuthenticationError,expired_token:a.AuthenticationError,invalid_scope:a.AuthenticationError,not_found:a.ExchangeError,rate_limit_exceeded:a.RateLimitExceeded,resource_exhausted:a.RateLimitExceeded,internal_server_error:a.ExchangeError,UNSUPPORTED_ORDER_CONFIGURATION:a.BadRequest,INSUFFICIENT_FUND:a.InsufficientFunds,PERMISSION_DENIED:a.PermissionDenied,INVALID_ARGUMENT:a.BadRequest,PREVIEW_STOP_PRICE_ABOVE_LAST_TRADE_PRICE:a.InvalidOrder,PREVIEW_INSUFFICIENT_FUND:a.InsufficientFunds},broad:{"Insufficient balance in source account":a.InsufficientFunds,"request timestamp expired":a.InvalidNonce,"order with this orderID was not found":a.OrderNotFound}},timeframes:{"1m":"ONE_MINUTE","5m":"FIVE_MINUTE","15m":"FIFTEEN_MINUTE","30m":"THIRTY_MINUTE","1h":"ONE_HOUR","2h":"TWO_HOUR","6h":"SIX_HOUR","1d":"ONE_DAY"},commonCurrencies:{CGLD:"CELO"},options:{mica:!0,usePrivate:!1,brokerId:"ccxt",stablePairs:["BUSD-USD","CBETH-ETH","DAI-USD","GUSD-USD","GYEN-USD","PAX-USD","PAX-USDT","USDC-EUR","USDC-GBP","USDT-EUR","USDT-GBP","USDT-USD","USDT-USDC","WBTC-BTC"],fetchCurrencies:{expires:5e3},accounts:["wallet","fiat"],v3Accounts:["ACCOUNT_TYPE_CRYPTO","ACCOUNT_TYPE_FIAT"],networks:{ERC20:"ethereum",XLM:"stellar"},createMarketBuyOrderRequiresPrice:!0,advanced:!0,fetchMarkets:"fetchMarketsV3",timeDifference:0,adjustForTimeDifference:!1,fetchTicker:"fetchTickerV3",fetchTickers:"fetchTickersV3",fetchAccounts:"fetchAccountsV3",fetchBalance:"v2PrivateGetAccounts",fetchTime:"v2PublicGetTime",user_native_currency:"USD"},features:{default:{sandbox:!1,createOrder:{marginMode:!0,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!0,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!0},hedged:!1,trailing:!1,leverage:!0,marketBuyByCost:!0,marketBuyRequiresPrice:!0,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:3e3,daysBack:void 0,untilDays:1e4,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:void 0,daysBack:void 0,untilDays:1e4,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:void 0,daysBack:void 0,daysBackCanceled:void 0,untilDays:1e4,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:300}},spot:{extends:"default"},swap:{linear:{extends:"default"},inverse:void 0},future:{linear:{extends:"default"},inverse:void 0}}})}async fetchTime(e={}){let t,i=this.safeString(this.options,"fetchTime","v2PublicGetTime"),s=this.safeString(e,"method",i),r=this.omit(e,"method");return"v2PublicGetTime"===s?(t=await this.v2PublicGetTime(r),t=this.safeDict(t,"data",{})):t=await this.v3PublicGetBrokerageTime(r),this.safeTimestamp2(t,"epoch","epochSeconds")}async fetchAccounts(e={}){return"fetchAccountsV3"===this.safeString(this.options,"fetchAccounts","fetchAccountsV3")?await this.fetchAccountsV3(e):await this.fetchAccountsV2(e)}async fetchAccountsV2(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleOptionBoolAndParams(e,"fetchAccounts","paginate",!1);if(t)return await this.fetchPaginatedCallCursor("fetchAccounts",void 0,void 0,void 0,i,"next_starting_after","starting_after",void 0,100);let s=await this.v2PrivateGetAccounts(this.extend({limit:100},i)),r=this.safeList(s,"data",[]),a=this.safeDict(s,"pagination",{}),o=this.safeString(a,"next_starting_after"),n=this.safeList(s,"data",[]),d=n.length-1,h=this.safeDict(n,d,{});return void 0!==o&&""!==o&&(h.next_starting_after=o,n[d]=h),this.parseAccounts(r,i)}async fetchAccountsV3(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleOptionBoolAndParams(e,"fetchAccounts","paginate",!1);if(t)return await this.fetchPaginatedCallCursor("fetchAccounts",void 0,void 0,void 0,i,"cursor","cursor",void 0,250);let s=await this.v3PrivateGetBrokerageAccounts(this.extend({limit:250},i)),r=this.safeList(s,"accounts",[]),a=r.length,o=this.safeString(s,"cursor");if(a>0&&void 0!==o&&""!==o){let e=a-1,t=this.safeDict(r,e,{});t.cursor=o,r[e]=t}return this.parseAccounts(r,i)}async fetchPortfolios(e={}){let t=await this.v3PrivateGetBrokeragePortfolios(e),i=this.safeList(t,"portfolios",[]),s=[];for(let e=0;e<i.length;e++){let t=i[e];s.push({id:this.safeString(t,"uuid"),type:this.safeString(t,"type"),code:void 0,info:t})}return s}parseAccount(e){let t=this.safeBool(e,"active"),i=this.safeString(e,"currency"),s=this.safeDict(e,"currency",{}),r=this.safeString(s,"code",i),a=this.safeString(e,"name"),o=this.safeString(e,"type"),n=a.split(" ");return{id:this.safeString2(e,"id","uuid"),type:void 0!==t?this.safeStringLower(n,1):o,code:this.safeCurrencyCode(r),info:e}}async createDepositAddress(e,t={}){let i=this.safeString(t,"account_id"),s=this.omit(t,"account_id");if(void 0===i){await this.loadAccounts();for(let t=0;t<this.accounts.length;t++){let s=this.accounts[t];if(s.code===e&&"wallet"===s.type){i=this.safeString(s,"id");break}}}if(void 0===i)throw new a.ExchangeError(this.id+" createDepositAddress() could not find the account with matching currency code "+e+", specify an `account_id` extra param to target specific wallet");let r={account_id:i},o=await this.v2PrivatePostAccountsAccountIdAddresses(this.extend(r,s)),n=this.safeDict(o,"data",{});return{currency:e,tag:this.safeString(n,"destination_tag"),address:this.safeString(n,"address"),network:void 0,info:o}}async fetchMySells(e,t,i,s={}){let r=this.prepareAccountRequest(i,s);void 0===this.markets&&await this.loadMarkets();let a=this.omit(s,["account_id","accountId"]),o=await this.v2PrivateGetAccountsAccountIdSells(this.extend(r,a)),n=this.safeList(o,"data",[]);return this.parseTrades(n,void 0,t,i)}async fetchMyBuys(e,t,i,s={}){let r=this.prepareAccountRequest(i,s);void 0===this.markets&&await this.loadMarkets();let a=this.omit(s,["account_id","accountId"]),o=await this.v2PrivateGetAccountsAccountIdBuys(this.extend(r,a)),n=this.safeList(o,"data",[]);return this.parseTrades(n,void 0,t,i)}async fetchTransactionsWithMethod(e,t,i,s,r={}){let a,[o,n]=await this.prepareAccountRequestWithCurrencyCode(t,s,r);return void 0===this.markets&&await this.loadMarkets(),a="v2PrivateGetAccountsAccountIdTransactions"===e?await this.v2PrivateGetAccountsAccountIdTransactions(this.extend(o,n)):"v2PrivateGetAccountsAccountIdWithdrawals"===e?await this.v2PrivateGetAccountsAccountIdWithdrawals(this.extend(o,n)):await this.v2PrivateGetAccountsAccountIdDeposits(this.extend(o,n)),this.parseTransactions(a.data,void 0,i,s)}async fetchWithdrawals(e,t,i,s={}){let[r,a]=this.handleOptionStringAndParams(s,"fetchWithdrawals","currencyType");if("crypto"===r){let s=await this.fetchTransactionsWithMethod("v2PrivateGetAccountsAccountIdTransactions",e,t,i,a);return this.filterByArray(s,"type","withdrawal",!1)}return await this.fetchTransactionsWithMethod("v2PrivateGetAccountsAccountIdWithdrawals",e,t,i,a)}async fetchDeposits(e,t,i,s={}){let[r,a]=this.handleOptionStringAndParams(s,"fetchDeposits","currencyType");if("crypto"===r){let s=await this.fetchTransactionsWithMethod("v2PrivateGetAccountsAccountIdTransactions",e,t,i,a);return this.filterByArray(s,"type","deposit",!1)}return await this.fetchTransactionsWithMethod("v2PrivateGetAccountsAccountIdDeposits",e,t,i,a)}async fetchDepositsWithdrawals(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.fetchTransactionsWithMethod("v2PrivateGetAccountsAccountIdTransactions",e,t,i,s);return this.filterByArray(r,"type",["deposit","withdrawal"],!1)}parseTransactionStatus(e){return this.safeString({created:"pending",completed:"ok",canceled:"canceled"},e,e)}parseTransaction(e,t){let i,s,r=this.safeString(e,"type"),a=this.safeDict(e,"network",{});"send"===r?(i=this.safeDict(a,"transaction_amount"),s=this.safeDict(a,"transaction_fee",{})):(i=this.safeDict(e,"subtotal"),s=this.safeDict(e,"fee",{})),void 0===i&&(i=this.safeDict(e,"amount"));let n=this.safeString(i,"amount"),d=o.Y.stringAbs(n),h=this.parseTransactionStatus(this.safeString(e,"status"));void 0===h&&(h=!0===this.safeBool(e,"committed")?"ok":"pending");let c=this.safeString(e,"id"),l=this.safeString(i,"currency"),u=this.safeString(s,"currency"),f=this.safeString(e,"created_at"),p=this.safeString(e,"resource");!this.inArray(p,["deposit","withdrawal"])&&(o.Y.stringGt(n,"0")?p="deposit":o.Y.stringLt(n,"0")&&(p="withdrawal"));let m=this.safeDict(e,"to"),g=this.safeString(m,"address"),v=this.safeString(a,"network_name"),y=this.safeCurrencyCode(l,t);return{info:e,id:c,txid:this.safeString(a,"hash",c),timestamp:this.parse8601(f),datetime:f,network:this.networkIdToCode(v,y),address:g,addressTo:g,addressFrom:void 0,tag:void 0,tagTo:void 0,tagFrom:void 0,type:p,amount:this.parseNumber(d),currency:y,status:h,updated:this.parse8601(this.safeString(e,"updated_at")),fee:{cost:this.safeNumber(s,"amount"),currency:this.safeCurrencyCode(u)}}}parseTrade(e,t){let i,s,r,a,n=this.safeDict(e,"total",{}),d=this.safeDict(e,"amount",{}),h=this.safeDict(e,"subtotal",{}),c=this.safeDict(e,"fee",{}),l=this.safeString(e,"product_id"),u=this.safeMarket(l,t,"-");if(void 0!==u)i=u.symbol;else{let e=this.safeString(d,"currency"),t=this.safeString(n,"currency");void 0!==e&&void 0!==t&&(i=this.safeCurrencyCode(e)+"/"+this.safeCurrencyCode(t))}let f=this.safeBool(e,"size_in_quote"),p=this.safeString(e,"price"),m=this.safeString(e,"size");!0===f&&(s=m,m=o.Y.stringDiv(m,p));let g=this.safeString(e,"commission"),v=this.safeString(d,"amount",m),y=this.safeString(h,"amount",s);a=void 0!==(r=void 0!==y&&void 0!==v?o.Y.stringDiv(y,v):p)&&void 0!==v?o.Y.stringMul(r,v):y;let b=this.safeString(c,"currency"),w=this.safeNumber(c,"amount",this.parseNumber(g));void 0===b&&void 0!==u&&void 0!==w&&(b=this.safeString(u,"quote"));let k=this.safeStringN(e,["created_at","trade_time","time"]),S=this.safeStringLower2(e,"resource","side"),O=this.safeStringLower(e,"liquidity_indicator");return this.safeTrade({info:e,id:this.safeString2(e,"id","trade_id"),order:this.safeString(e,"order_id"),timestamp:this.parse8601(k),datetime:k,symbol:i,type:void 0,side:"unknown_order_side"===S?void 0:S,takerOrMaker:"unknown_liquidity_indicator"===O?void 0:O,price:r,amount:v,cost:a,fee:{cost:w,currency:this.safeCurrencyCode(b)}})}async fetchMarkets(e={}){return(this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference(),"fetchMarketsV3"===this.safeString(this.options,"fetchMarkets","fetchMarketsV3"))?await this.fetchMarketsV3(e):await this.fetchMarketsV2(e)}async fetchMarketsV2(e={}){let t=await this.fetchCurrenciesFromCache(e),i=this.safeDict(t,"currencies",{}),s=this.safeDict(t,"exchangeRates",{}),r=this.safeList(i,"data",[]),a=this.indexBy(r,"id"),o=Object.keys(this.safeDict(this.safeDict(s,"data",{}),"rates",{})),n=[];for(let e=0;e<o.length;e++){let t=o[e],i=this.safeCurrencyCode(t);if(void 0===i)continue;let s="crypto";if(t in a&&(s="fiat"),"crypto"===s)for(let e=0;e<r.length;e++){let s=r[e],a=this.safeString(s,"id"),o=this.safeCurrencyCode(a);void 0!==o&&n.push(this.safeMarketStructure({id:t+"-"+a,symbol:i+"/"+o,base:i,quote:o,settle:void 0,baseId:t,quoteId:a,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!0,future:!0,option:!1,active:void 0,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:void 0,price:void 0},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(s,"min_size"),max:void 0}},info:s}))}}return n}async fetchMarketsV3(e={}){let t,[i,s]=this.handleOptionBoolAndParams(e,"fetchMarkets","usePrivate",!1),r=[];i?r.push(this.v3PrivateGetBrokerageProducts(s)):r.push(this.v3PublicGetBrokerageMarketProducts(s)),this.checkRequiredCredentials(!1)&&r.push(this.v3PrivateGetBrokerageTransactionSummary(s));let a=await Promise.all(r),o=[];try{o=[this.v3PublicGetBrokerageMarketProducts(this.extend(s,{product_type:"FUTURE"})),this.v3PublicGetBrokerageMarketProducts(this.extend(s,{product_type:"FUTURE",contract_expiry_type:"PERPETUAL"}))]}catch(e){o=[]}try{t=await Promise.all(o)}catch(e){t=[]}let n=this.safeDict(a,0,{}),d=this.safeDict(a,1,{}),h=this.safeDict(t,0,{}),c=this.safeDict(t,1,{}),l=this.safeDict(t,0,{}),u=this.safeDict(t,1,{}),f=this.safeDict(d,"fee_tier",{}),p=this.safeDict(l,"fee_tier",{}),m=this.safeDict(u,"fee_tier",{}),g=this.safeList(n,"products",[]),v=[];for(let e=0;e<g.length;e++){let t=this.parseSpotMarket(g[e],f);void 0!==t&&v.push(t)}let y=this.safeList(h,"products",[]);for(let e=0;e<y.length;e++){let t=this.parseContractMarket(y[e],p);void 0!==t&&v.push(t)}let b=this.safeList(c,"products",[]);for(let e=0;e<b.length;e++){let t=this.parseContractMarket(b[e],m);void 0!==t&&v.push(t)}let w=[];for(let e=0;e<v.length;e++){let t=v[e],i=this.safeDict(t,"info",{}),s=this.safeList(i,"alias_to",[]);s.length>0?t.alias=s[0]:t.alias=void 0,w.push(t)}return w}parseSpotMarket(e,t){let i=this.safeString(e,"product_id"),s=this.safeString(e,"base_currency_id"),r=this.safeString(e,"quote_currency_id"),a=this.safeCurrencyCode(s),o=this.safeCurrencyCode(r);if(void 0===a||void 0===o)return;let n=this.safeStringLower(e,"product_type"),d=this.safeBool(e,"trading_disabled"),h=this.safeList(this.options,"stablePairs",[]),c=this.safeNumber(this.fees.trading,"taker"),l=this.safeNumber(this.fees.trading,"maker"),u=this.inArray(i,h)?1e-5:this.safeNumber(t,"taker_fee_rate",c),f=this.inArray(i,h)?0:this.safeNumber(t,"maker_fee_rate",l);return this.safeMarketStructure({id:i,symbol:a+"/"+o,base:a,quote:o,settle:void 0,baseId:s,quoteId:r,settleId:void 0,type:n,spot:"spot"===n,margin:void 0,swap:!1,future:!1,option:!1,active:!0!==d,contract:!1,linear:void 0,inverse:void 0,taker:u,maker:f,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(e,"base_increment"),price:this.safeNumber2(e,"price_increment","quote_increment")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(e,"base_min_size"),max:this.safeNumber(e,"base_max_size")},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(e,"quote_min_size"),max:this.safeNumber(e,"quote_max_size")}},created:void 0,info:e})}parseContractMarket(e,t){let i,s=this.safeString(e,"product_id"),r=this.safeDict(e,"future_product_details",{}),a=this.safeString(r,"contract_expiry_type"),o=this.safeNumber(r,"contract_size"),n=this.safeString(r,"contract_expiry"),d=this.parse8601(n),h=this.iso8601(d),c="PERPETUAL"===a,l=this.safeString(r,"contract_root_unit"),u=this.safeString(e,"quote_currency_id"),f=this.safeCurrencyCode(l),p=this.safeCurrencyCode(u);if(void 0===f||void 0===p)return;let m=this.safeBool(e,"is_disabled"),g=f+"/"+p;c?(i="swap",g=g+":"+p):(i="future",g=g+":"+p+"-"+this.yymmdd(d));let v=this.safeNumber(t,"taker_fee_rate"),y=this.safeNumber(t,"maker_fee_rate"),b=null!=v&&0!==v?v:this.parseNumber("0.06"),w=null!=y&&0!==y?y:this.parseNumber("0.04");return this.safeMarketStructure({id:s,symbol:g,base:f,quote:p,settle:p,baseId:l,quoteId:u,settleId:u,type:i,spot:!1,margin:!1,swap:c,future:!c,option:!1,active:!0!==m,contract:!0,linear:!0,inverse:!1,taker:b,maker:w,contractSize:o,expiry:d,expiryDatetime:h,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(e,"base_increment"),price:this.safeNumber2(e,"price_increment","quote_increment")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(e,"base_min_size"),max:this.safeNumber(e,"base_max_size")},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(e,"quote_min_size"),max:this.safeNumber(e,"quote_max_size")}},created:void 0,info:e})}async fetchCurrenciesFromCache(e={}){let t=this.safeDict(this.options,"fetchCurrencies",{}),i=this.safeInteger(t,"timestamp"),s=this.safeInteger(t,"expires",1e3),r=this.milliseconds();if(void 0===i||r-i>s){let i=[this.v2PublicGetCurrencies(e),this.v2PublicGetCurrenciesCrypto(e)],s=await Promise.all(i),a=this.safeDict(s,0,{}),o=this.safeDict(s,1,{}),n=this.safeList(a,"data",[]),d=this.safeList(o,"data",[]),h=await this.v2PublicGetExchangeRates(e);this.options.fetchCurrencies=this.extend(t,{currencies:this.arrayConcat(n,d),exchangeRates:h,timestamp:r})}return this.safeDict(this.options,"fetchCurrencies",{})}async fetchCurrencies(e={}){let t=[this.v2PublicGetCurrencies(e),this.v2PublicGetCurrenciesCrypto(e),this.v2PublicGetExchangeRates(e)],i=await Promise.all(t),s=this.safeDict(i,0,{}),r=this.safeDict(i,1,{}),a=this.safeDict(i,2,{}),o=this.safeList(s,"data",[]),n=this.safeList(r,"data",[]),d=this.safeDict(a,"data",{}),h=Object.keys(this.safeDict(d,"rates",{})),c=this.arrayConcat(o,n),l={},u={},f={};for(let e=0;e<c.length;e++){let t=c[e],i=this.safeString(t,"asset_id"),s=this.safeString2(t,"id","code"),r=this.safeCurrencyCode(s),a=this.safeString(t,"name");void 0!==r&&(this.options.networks[r]=a.toLowerCase()),void 0!==r&&(this.options.networksById[r]=a.toLowerCase());let o="fiat";if(void 0!==i&&(o="crypto"),void 0!==r&&(l[r]=this.safeCurrencyStructure({info:t,id:s,code:r,type:o,name:a,active:!0,deposit:void 0,withdraw:void 0,fee:void 0,precision:void 0,networks:{},limits:{amount:{min:this.safeNumber(t,"min_size"),max:void 0},withdraw:{min:void 0,max:void 0}}})),void 0!==i){let e=a.toLowerCase();void 0!==r&&(u[r]=e),f[e]=r}}for(let e=0;e<h.length;e++){let t=h[e],i=this.safeCurrencyCode(t);void 0!==i&&i in l||void 0===i||(l[i]=this.safeCurrencyStructure({info:{},id:t,code:i,type:"crypto",networks:{}}))}return this.options.networks=this.extend(u,this.options.networks),this.options.networksById=this.extend(f,this.options.networksById),l}async fetchTickers(e,t={}){return"fetchTickersV3"===this.safeString(this.options,"fetchTickers","fetchTickersV3")?await this.fetchTickersV3(e,t):await this.fetchTickersV2(e,t)}async fetchTickersV2(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.v2PublicGetExchangeRates(this.extend({},t)),r=this.safeDict(s,"data",{}),a=this.safeDict(r,"rates",{}),o=this.safeString(r,"currency"),n={},d=Object.keys(a);for(let e=0;e<d.length;e++){let t=d[e],i=t+"-"+o,s=this.safeMarket(i,void 0,"-");n[s.symbol]=this.parseTicker(a[t],s)}return this.filterByArrayTickers(n,"symbol",i)}async fetchTickersV3(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e),r={};void 0!==s&&(r.product_ids=this.marketIds(s));let[a,o]=this.handleMarketTypeAndParams("fetchTickers",this.getMarketFromSymbols(s),t,"default");void 0!==a&&"default"!==a&&(r.product_type="swap"===a?"FUTURE":"SPOT");let[n,d]=this.handleOptionBoolAndParams(o,"fetchTickers","usePrivate",!1);i=n?await this.v3PrivateGetBrokerageProducts(this.extend(r,d)):await this.v3PublicGetBrokerageMarketProducts(this.extend(r,d));let h=this.safeList(i,"products",[]),c={};for(let e=0;e<h.length;e++){let t=h[e],i=this.safeString(t,"product_id"),s=this.safeMarket(i,void 0,"-");c[s.symbol]=this.parseTicker(t,s)}return this.filterByArrayTickers(c,"symbol",s)}async fetchTicker(e,t={}){return"fetchTickerV3"===this.safeString(this.options,"fetchTicker","fetchTickerV3")?await this.fetchTickerV3(e,t):await this.fetchTickerV2(e,t)}async fetchTickerV2(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.extend({symbol:i.id},t),r=await this.v2PublicGetPricesSymbolSpot(s),a=await this.v2PublicGetPricesSymbolBuy(s),o=await this.v2PublicGetPricesSymbolSell(s),n=this.safeDict(r,"data",{}),d=this.safeDict(a,"data",{}),h=this.safeDict(o,"data",{}),c={bid:this.safeNumber(h,"amount"),ask:this.safeNumber(d,"amount"),price:this.safeNumber(n,"amount")};return this.parseTicker(c,i)}async fetchTickerV3(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={product_id:s.id,limit:1},[a,o]=this.handleOptionBoolAndParams(t,"fetchTicker","usePrivate",!1);i=a?await this.v3PrivateGetBrokerageProductsProductIdTicker(this.extend(r,o)):await this.v3PublicGetBrokerageMarketProductsProductIdTicker(this.extend(r,o));let n=this.safeList(i,"trades",[]),d=this.safeDict(n,0,{}),h=this.parseTicker(d,s);return h.bid=this.safeNumber(i,"best_bid"),h.ask=this.safeNumber(i,"best_ask"),h}parseTicker(e,t){let i,s,r=this.safeNumber(e,"bid"),a=this.safeNumber(e,"ask");if("bids"in e){let t=this.safeList(e,"bids",[]),o=this.safeList(e,"asks",[]),n=this.safeDict(t,0,{}),d=this.safeDict(o,0,{});r=this.safeNumber(n,"price"),i=this.safeNumber(n,"size"),a=this.safeNumber(d,"price"),s=this.safeNumber(d,"size")}let o=this.safeString(e,"product_id"),n=this.safeMarket(o,t),d=this.safeNumber(e,"price"),h=this.safeString(e,"time");return this.safeTicker({symbol:n.symbol,timestamp:this.parse8601(h),datetime:h,bid:r,ask:a,last:d,high:void 0,low:void 0,bidVolume:i,askVolume:s,vwap:void 0,open:void 0,close:d,previousClose:void 0,change:void 0,percentage:this.safeNumber(e,"price_percentage_change_24h"),average:void 0,baseVolume:this.safeNumber(e,"volume_24h"),quoteVolume:this.safeNumber(e,"approximate_quote_24h_volume"),info:e},n)}parseCustomBalance(e,t={}){let i=this.safeList2(e,"data","accounts",[]),s=this.safeList(t,"type",this.options.accounts),r=this.safeList(t,"type",this.options.v3Accounts),a={info:e};for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),n=this.safeString(t,"type");if(this.inArray(n,s)){let e=this.safeDict(t,"balance");if(void 0!==e){let t=this.safeString(e,"currency"),i=this.safeCurrencyCode(t),s=this.safeString(e,"amount"),r=this.safeDict(a,i);void 0===r?((r=this.account()).free=s,r.total=s):(r.free=o.Y.stringAdd(r.free,s),r.total=o.Y.stringAdd(r.total,s)),void 0!==i&&(a[i]=r)}}else if(this.inArray(n,r)){let e=this.safeDict(t,"available_balance"),i=this.safeDict(t,"hold");if(void 0!==e&&void 0!==i){let t=this.safeString(e,"currency"),s=this.safeCurrencyCode(t),r=this.safeString(i,"value"),n=this.safeString(e,"value"),d=o.Y.stringAdd(r,n),h=this.safeDict(a,s);void 0===h?((h=this.account()).free=n,h.used=r,h.total=d):(h.free=o.Y.stringAdd(h.free,n),h.used=o.Y.stringAdd(h.used,r),h.total=o.Y.stringAdd(h.total,d)),void 0!==s&&(a[s]=h)}}}return this.safeBalance(a)}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let i={},s=this.safeBool(e,"v3",!1),r=this.omit(e,["v3"]),[a,o]=this.handleMarketTypeAndParams("fetchBalance",void 0,r),n=this.safeString(this.options,"fetchBalance","v3PrivateGetBrokerageAccounts");return"future"===a?t=await this.v3PrivateGetBrokerageCfmBalanceSummary(this.extend(i,o)):!0===s||"v3PrivateGetBrokerageAccounts"===n?(i.limit=250,t=await this.v3PrivateGetBrokerageAccounts(this.extend(i,o))):(i.limit=250,t=await this.v2PrivateGetAccounts(this.extend(i,o))),o.type=a,this.parseCustomBalance(t,o)}async fetchLedger(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchLedger","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchLedger",e,t,i,o,"next_starting_after","starting_after",void 0,100);void 0!==e&&(r=this.currency(e));let[n,d]=await this.prepareAccountRequestWithCurrencyCode(e,i,o),h=await this.v2PrivateGetAccountsAccountIdTransactions(this.extend(n,d)),c=this.safeList(h,"data",[]),l=this.parseLedger(c,r,t,i),u=l.length;if(0===u)return l;let f=u-1,p=this.safeDict(l,f),m=this.safeDict(h,"pagination",{}),g=this.safeString(m,"next_starting_after");return void 0!==g&&""!==g&&(p.info.next_starting_after=g,l[f]=p),l}parseLedgerEntryStatus(e){return this.safeString({completed:"ok"},e,e)}parseLedgerEntryType(e){return this.safeString({buy:"trade",sell:"trade",fiat_deposit:"transaction",fiat_withdrawal:"transaction",exchange_deposit:"transaction",exchange_withdrawal:"transaction",send:"transaction",pro_deposit:"transaction",pro_withdrawal:"transaction"},e,e)}parseLedgerEntry(e,t){let i,s,r,a=this.safeDict(e,"amount",{}),n=this.safeString(a,"amount");o.Y.stringLt(n,"0")?(i="out",n=o.Y.stringNeg(n)):i="in";let d=this.safeString(a,"currency"),h=this.safeCurrencyCode(d,t),c=this.safeCurrency(d,t),l=this.safeDict(e,"network",{}),u=this.safeDict(l,"transaction_fee");if(void 0!==u){let e=this.safeString(u,"currency"),t=this.safeCurrencyCode(e,c);s={cost:this.safeNumber(u,"amount"),currency:t}}let f=this.parse8601(this.safeString(e,"created_at")),p=this.safeString(e,"id"),m=this.parseLedgerEntryType(this.safeString(e,"type")),g=this.parseLedgerEntryStatus(this.safeString(e,"status")),v=this.safeString(e,"resource_path");if(void 0!==v){let e=v.split("/");e.length>3&&(r=e[3])}return this.safeLedgerEntry({info:e,id:p,timestamp:f,datetime:this.iso8601(f),direction:i,account:r,referenceId:void 0,referenceAccount:void 0,type:m,currency:h,amount:this.parseNumber(n),before:void 0,after:void 0,status:g,fee:s},c)}async findAccountId(e,t={}){void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts(!1,t);for(let t=0;t<this.accounts.length;t++){let i=this.accounts[t];if(i.code===e)return i.id}}prepareAccountRequest(e,t={}){let i=this.safeString2(t,"account_id","accountId");if(void 0===i)throw new a.ArgumentsRequired(this.id+" prepareAccountRequest() method requires an account_id (or accountId) parameter");let s={account_id:i};return void 0!==e&&(s.limit=e),s}async prepareAccountRequestWithCurrencyCode(e,t,i={}){let s=this.safeString2(i,"account_id","accountId"),r=this.omit(i,["account_id","accountId"]);if(void 0===s){if(void 0===e)throw new a.ArgumentsRequired(this.id+" prepareAccountRequestWithCurrencyCode() method requires an account_id (or accountId) parameter OR a currency code argument");if(void 0===(s=await this.findAccountId(e,r)))throw new a.ExchangeError(this.id+" prepareAccountRequestWithCurrencyCode() could not find account id for "+e+". You might try to generate the deposit address in the website for that coin first.")}let o={account_id:s};return void 0!==t&&(o.limit=t),[o,r]}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new a.NotSupported(this.id+" createMarketBuyOrderWithCost() supports spot orders only");return i.createMarketBuyOrderRequiresPrice=!1,await this.createOrder(e,"market","buy",t,void 0,i)}async createOrder(e,t,i,s,r,n={}){let d,h,c;void 0===this.markets&&await this.loadMarkets();let l=this.market(e),u={client_order_id:this.safeString(this.options,"brokerId","ccxt")+"-"+this.uuid(),product_id:l.id,side:i.toUpperCase()};if(!0===this.safeBool(n,"reduceOnly")){let t=this.omit(n,"reduceOnly");return t.amount=s,await this.closePosition(e,i,t)}let f=this.safeNumberN(n,["stopPrice","stop_price","triggerPrice"]),p=this.safeNumber(n,"stopLossPrice"),m=this.safeNumber(n,"takeProfitPrice"),g=void 0!==f,v=void 0!==p,y=void 0!==m,b=this.safeString(n,"timeInForce");h="PO"===b||this.safeBool2(n,"postOnly","post_only",!1);let w=this.safeString(n,"end_time"),k=this.safeString(n,"stop_direction");if("limit"===t)if(g)if(void 0===k&&(k="buy"===i?"STOP_DIRECTION_STOP_DOWN":"STOP_DIRECTION_STOP_UP"),"GTD"===b||void 0!==w){if(void 0===w)throw new a.ExchangeError(this.id+" createOrder() requires an end_time parameter for a GTD order");u.order_configuration={stop_limit_stop_limit_gtd:{base_size:this.amountToPrecision(e,s),limit_price:this.priceToPrecision(e,r),stop_price:this.priceToPrecision(e,f),stop_direction:k,end_time:w}}}else u.order_configuration={stop_limit_stop_limit_gtc:{base_size:this.amountToPrecision(e,s),limit_price:this.priceToPrecision(e,r),stop_price:this.priceToPrecision(e,f),stop_direction:k}};else if(v||y){let t;v?(void 0===k&&(k="buy"===i?"STOP_DIRECTION_STOP_UP":"STOP_DIRECTION_STOP_DOWN"),t=this.priceToPrecision(e,p)):(void 0===k&&(k="buy"===i?"STOP_DIRECTION_STOP_DOWN":"STOP_DIRECTION_STOP_UP"),t=this.priceToPrecision(e,m)),u.order_configuration={stop_limit_stop_limit_gtc:{base_size:this.amountToPrecision(e,s),limit_price:this.priceToPrecision(e,r),stop_price:t,stop_direction:k}}}else if("GTD"===b||void 0!==w){if(void 0===w)throw new a.ExchangeError(this.id+" createOrder() requires an end_time parameter for a GTD order");u.order_configuration={limit_limit_gtd:{base_size:this.amountToPrecision(e,s),limit_price:this.priceToPrecision(e,r),end_time:w,post_only:h}}}else"IOC"===b?u.order_configuration={sor_limit_ioc:{base_size:this.amountToPrecision(e,s),limit_price:this.priceToPrecision(e,r)}}:"FOK"===b?u.order_configuration={limit_limit_fok:{base_size:this.amountToPrecision(e,s),limit_price:this.priceToPrecision(e,r)}}:u.order_configuration={limit_limit_gtc:{base_size:this.amountToPrecision(e,s),limit_price:this.priceToPrecision(e,r),post_only:h}};else{if(g||v||y)throw new a.NotSupported(this.id+" createOrder() only stop limit orders are supported");if(!0===l.spot&&"buy"===i){let t,[i,h]=this.handleOptionBoolAndParams(n,"createOrder","createMarketBuyOrderRequiresPrice",!0),c=this.safeNumber(h,"cost");if(d=this.omit(h,"cost"),void 0!==c)t=this.costToPrecision(e,c);else if(i)if(void 0===r)throw new a.InvalidOrder(this.id+" createOrder() requires a price argument for market buy orders on spot markets to calculate the total amount to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument");else{let i=this.numberToString(s),a=this.numberToString(r),n=o.Y.stringMul(i,a);t=this.costToPrecision(e,n)}else t=this.costToPrecision(e,s);u.order_configuration={market_market_ioc:{quote_size:t}}}else u.order_configuration={market_market_ioc:{base_size:this.amountToPrecision(e,s)}}}let S=void 0===d?n:d,O=this.safeString(S,"marginMode");void 0!==O&&("isolated"===O?u.margin_type="ISOLATED":"cross"===O&&(u.margin_type="CROSS"));let T=this.omit(S,["timeInForce","triggerPrice","stopLossPrice","takeProfitPrice","stopPrice","stop_price","stopDirection","stop_direction","clientOrderId","postOnly","post_only","end_time","marginMode"]);if(!0===this.safeBool2(T,"preview","test",!1)?(u=this.omit(u,"client_order_id"),c=await this.v3PrivatePostBrokerageOrdersPreview(this.extend(u,this.omit(T,["preview","test"])))):c=await this.v3PrivatePostBrokerageOrders(this.extend(u,T)),!0!==this.safeBool(c,"success")){let e=this.safeDict(c,"error_response"),t=this.safeString(e,"error"),i=this.safeString(e,"message");if(void 0!==e)throw this.throwExactlyMatchedException(this.exceptions.exact,t,i),this.throwBroadlyMatchedException(this.exceptions.broad,t,i),new a.ExchangeError(i)}let P=this.safeDict(c,"success_response",{});return this.parseOrder(P,l)}parseOrder(e,t){let i,s,r,a,o,n=this.safeString(e,"product_id"),d=this.safeSymbol(n,t,"-"),h=void 0!==d?this.safeMarket(d,t):t,c=this.safeDict(e,"order_configuration",{}),l=this.safeDict(c,"limit_limit_gtc"),u=this.safeDict(c,"limit_limit_gtd"),f=this.safeDict(c,"sor_limit_ioc"),p=this.safeDict(c,"stop_limit_stop_limit_gtc"),m=this.safeDict(c,"stop_limit_stop_limit_gtd"),g=this.safeDict(c,"market_market_ioc"),v=void 0!==p||void 0!==m;if(void 0!==l||void 0!==u||void 0!==f){let e;e=void 0!==l?l:void 0!==u?u:f,i=this.safeString(e,"limit_price"),s=this.safeString(e,"base_size"),r=this.safeBool(e,"post_only")}else if(v){let e=void 0!==p?p:m;i=this.safeString(e,"limit_price"),s=this.safeString(e,"base_size"),r=this.safeBool(e,"post_only"),a=this.safeString(e,"stop_price")}else s=this.safeString(g,"base_size");let y=this.safeString(e,"created_time");return void 0!==this.safeString(e,"total_fees")&&void 0!==h&&(o=this.safeString(h,"quote")),this.safeOrder({info:e,id:this.safeString(e,"order_id"),clientOrderId:this.safeString(e,"client_order_id"),timestamp:this.parse8601(y),datetime:y,lastTradeTimestamp:void 0,symbol:d,type:this.parseOrderType(this.safeString(e,"order_type")),timeInForce:this.parseTimeInForce(this.safeString(e,"time_in_force")),postOnly:r,side:this.safeStringLower(e,"side"),price:i,triggerPrice:a,amount:s,filled:this.safeString(e,"filled_size"),remaining:void 0,cost:void 0,average:this.safeString(e,"average_filled_price"),status:this.parseOrderStatus(this.safeString(e,"status")),fee:{cost:this.safeString(e,"total_fees"),currency:o},trades:void 0},h)}parseOrderStatus(e){return this.safeString({OPEN:"open",FILLED:"closed",CANCELLED:"canceled",EXPIRED:"canceled",FAILED:"canceled",UNKNOWN_ORDER_STATUS:void 0},e,e)}parseOrderType(e){if("UNKNOWN_ORDER_TYPE"!==e)return this.safeString({MARKET:"market",LIMIT:"limit",STOP:"limit",STOP_LIMIT:"limit"},e,e)}parseTimeInForce(e){return this.safeString({GOOD_UNTIL_CANCELLED:"GTC",GOOD_UNTIL_DATE_TIME:"GTD",IMMEDIATE_OR_CANCEL:"IOC",FILL_OR_KILL:"FOK",UNKNOWN_TIME_IN_FORCE:void 0},e,e)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.cancelOrders([e],t,i);return this.safeDict(s,0,{})}async cancelOrders(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let r=await this.v3PrivatePostBrokerageOrdersBatchCancel(this.extend({order_ids:e},i)),o=this.safeList(r,"results",[]);for(let e=0;e<o.length;e++)if(!0!==this.safeBool(o[e],"success"))throw new a.BadRequest(this.id+" cancelOrders() has failed, check your arguments and parameters");return this.parseOrders(o,s)}async editOrder(e,t,i,s,r,a,o={}){let n;void 0===this.markets&&await this.loadMarkets();let d=this.market(t),h={order_id:e};return void 0!==r&&(h.size=this.amountToPrecision(t,r)),void 0!==a&&(h.price=this.priceToPrecision(t,a)),n=!0===this.safeBool2(o,"preview","test",!1)?await this.v3PrivatePostBrokerageOrdersEditPreview(this.extend(h,this.omit(o,["preview","test"]))):await this.v3PrivatePostBrokerageOrdersEdit(this.extend(h,o)),this.parseOrder(n,d)}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let r=await this.v3PrivateGetBrokerageOrdersHistoricalOrderId(this.extend({order_id:e},i)),a=this.safeDict(r,"order",{});return this.parseOrder(a,s)}async fetchOrders(e,t,i=100,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchOrders","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchOrders",e,t,i,o,"cursor","cursor",void 0,1e3);void 0!==e&&(r=this.market(e));let n={};void 0!==r&&(n.product_id=r.id),void 0!==i&&(n.limit=i),void 0!==t&&(n.start_date=this.iso8601(t));let d=this.safeInteger(o,"until");void 0!==d&&(n.end_date=this.iso8601(d));let h=void 0!==d?this.omit(o,["until"]):o,c=await this.v3PrivateGetBrokerageOrdersHistoricalBatch(this.extend(n,h)),l=this.safeList(c,"orders",[]),u=this.safeDict(l,0,{}),f=this.safeString(c,"cursor");return void 0!==f&&""!==f&&(u.cursor=f,l[0]=u),this.parseOrders(l,r,t,i)}async fetchOrdersByStatus(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(a=this.market(t));let o={order_status:e};void 0!==a&&(o.product_id=a.id);let n=void 0===s?100:s;o.limit=n,void 0!==i&&(o.start_date=this.iso8601(i));let d=this.safeInteger(r,"until");void 0!==d&&(o.end_date=this.iso8601(d));let h=void 0!==d?this.omit(r,["until"]):r,c=await this.v3PrivateGetBrokerageOrdersHistoricalBatch(this.extend(o,h)),l=this.safeList(c,"orders",[]),u=this.safeDict(l,0,{}),f=this.safeString(c,"cursor");return void 0!==f&&""!==f&&(u.cursor=f,l[0]=u),this.parseOrders(l,a,i,n)}async fetchOpenOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchOpenOrders","paginate",!1);return r?await this.fetchPaginatedCallCursor("fetchOpenOrders",e,t,i,a,"cursor","cursor",void 0,100):await this.fetchOrdersByStatus("OPEN",e,t,i,a)}async fetchClosedOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchClosedOrders","paginate",!1);return r?await this.fetchPaginatedCallCursor("fetchClosedOrders",e,t,i,a,"cursor","cursor",void 0,1e3):await this.fetchOrdersByStatus("FILLED",e,t,i,a)}async fetchCanceledOrders(e,t,i,s={}){return await this.fetchOrdersByStatus("CANCELLED",e,t,i,s)}async fetchOHLCV(e,t="1m",i,s,r={}){let a,n;void 0===this.markets&&await this.loadMarkets();let d=void 0===s?300:Math.min(s,300),[h,c]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(h)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,d,t,c,299);let l=this.market(e),u={product_id:l.id,granularity:this.safeString(this.timeframes,t,t)},f=this.safeInteger2(c,"until","end"),p=this.omit(c,["until"]),m=d*this.parseTimeframe(t);if(void 0!==i)a=this.numberToString(this.parseToInt(i/1e3));else{let e=this.seconds().toString();a=o.Y.stringSub(e,m.toString())}u.start=a,void 0!==f?u.end=this.numberToString(this.parseToInt(f/1e3)):u.end=o.Y.stringAdd(a,m.toString());let[g,v]=this.handleOptionBoolAndParams(p,"fetchOHLCV","usePrivate",!1);n=g?await this.v3PrivateGetBrokerageProductsProductIdCandles(this.extend(u,v)):await this.v3PublicGetBrokerageMarketProductsProductIdCandles(this.extend(u,v));let y=this.safeList(n,"candles",[]);return this.parseOHLCVs(y,l,t,i,d)}parseOHLCV(e,t){return[this.safeTimestamp(e,"start"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={product_id:o.id};void 0!==t&&(n.start=this.numberToString(this.parseToInt(t/1e3))),void 0!==i&&(n.limit=Math.min(i,1e3));let[d,h]=this.handleOptionIntegerAndParams(s,"fetchTrades","until");if(void 0!==d)n.end=this.numberToString(this.parseToInt(d/1e3));else if(void 0!==t)throw new a.ArgumentsRequired(this.id+" fetchTrades() requires a `until` parameter when you use `since` argument");let[c,l]=this.handleOptionBoolAndParams(h,"fetchTrades","usePrivate",!1);r=c?await this.v3PrivateGetBrokerageProductsProductIdTicker(this.extend(n,l)):await this.v3PublicGetBrokerageMarketProductsProductIdTicker(this.extend(n,l));let u=this.safeList(r,"trades",[]);return this.parseTrades(u,o,t,i)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchMyTrades",e,t,i,o,"cursor","cursor",void 0,250);void 0!==e&&(r=this.market(e));let n={};void 0!==r&&(n.product_id=r.id),void 0!==i&&(n.limit=i),void 0!==t&&(n.start_sequence_timestamp=this.iso8601(t));let d=this.safeInteger(o,"until");void 0!==d&&(n.end_sequence_timestamp=this.iso8601(d));let h=void 0!==d?this.omit(o,["until"]):o,c=await this.v3PrivateGetBrokerageOrdersHistoricalFills(this.extend(n,h)),l=this.safeList(c,"fills",[]),u=this.safeDict(l,0,{}),f=this.safeString(c,"cursor");return void 0!==f&&""!==f&&(u.cursor=f,l[0]=u),this.parseTrades(l,r,t,i)}async fetchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r={product_id:this.market(e).id};void 0!==t&&(r.limit=t);let[a,o]=this.handleOptionBoolAndParams(i,"fetchOrderBook","usePrivate",!1);s=a?await this.v3PrivateGetBrokerageProductBook(this.extend(r,o)):await this.v3PublicGetBrokerageMarketProductBook(this.extend(r,o));let n=this.safeDict(s,"pricebook",{}),d=this.safeString(n,"time"),h=this.parse8601(d);return this.parseOrderBook(n,e,h,"bids","asks","price","size")}async fetchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s={};void 0!==i&&(s.product_ids=this.marketIds(i));let r=await this.v3PrivateGetBrokerageBestBidAsk(this.extend(s,t)),a=this.safeList(r,"pricebooks",[]);return this.parseTickers(a,i)}async withdraw(e,t,i,s,r={}){let[o,n]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let d=this.currency(e),h={type:"send",to:i,amount:this.numberToString(t),currency:d.id},c=this.safeString2(n,"account_id","accountId"),l=this.omit(n,["account_id","accountId"]);if(void 0===c){if(void 0===e)throw new a.ArgumentsRequired(this.id+" withdraw() requires an account_id (or accountId) parameter OR a currency code argument");if(void 0===(c=await this.findAccountId(e,l)))throw new a.ExchangeError(this.id+" withdraw() could not find account id for "+e);h.account_id=c}else h.account_id=c;void 0!==o&&(h.destination_tag=o);let u=await this.v2PrivatePostAccountsAccountIdTransactions(this.extend(h,l)),f=this.safeDict(u,"data",{});return this.parseTransaction(f,d)}async fetchDepositAddressesByNetwork(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),[s,r]=await this.prepareAccountRequestWithCurrencyCode(this.safeString(i,"code"),void 0,t),a=await this.v2PrivateGetAccountsAccountIdAddresses(this.extend(s,r)),o=this.safeList(a,"data",[]),n=this.parseDepositAddresses(o,void 0,!1);return this.indexBy(n,"network")}parseDepositAddress(e,t){let i,s=this.safeString(e,"address");this.checkAddress(s);let r=this.safeString(e,"network"),a=this.safeCurrencyCode(void 0,t),o=this.safeString(e,"address_label");if(void 0!==o){let e=o.split(" ");i=this.safeString(e,0)}else i=this.safeString(e,"currency");let n=this.safeDict(e,"address_info");return{info:e,currency:this.safeCurrencyCode(i,t),network:this.networkIdToCode(r,a),address:s,tag:this.safeString(n,"destination_tag")}}async deposit(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.safeString2(s,"account_id","accountId"),o=this.omit(s,["account_id","accountId"]);if(void 0===r){if(void 0===e)throw new a.ArgumentsRequired(this.id+" deposit() requires an account_id (or accountId) parameter OR a currency code argument");if(void 0===(r=await this.findAccountId(e,o)))throw new a.ExchangeError(this.id+" deposit() could not find account id for "+e)}let n={account_id:r,amount:this.numberToString(t),currency:e.toUpperCase(),payment_method:i,commit:!0},d=await this.v2PrivatePostAccountsAccountIdDeposits(this.extend(n,o)),h=this.safeDict2(d,"data","transfer",{});return this.parseTransaction(h)}async fetchDeposit(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.safeString2(i,"account_id","accountId"),r=this.omit(i,["account_id","accountId"]);if(void 0===s){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchDeposit() requires an account_id (or accountId) parameter OR a currency code argument");if(void 0===(s=await this.findAccountId(t,r)))throw new a.ExchangeError(this.id+" fetchDeposit() could not find account id for "+t)}let o={account_id:s,deposit_id:e},n=await this.v2PrivateGetAccountsAccountIdDepositsDepositId(this.extend(o,r)),d=this.safeDict2(n,"data","transfer",{});return this.parseTransaction(d)}async fetchDepositMethodIds(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v3PrivateGetBrokeragePaymentMethods(e),i=this.safeList(t,"payment_methods",[]);return this.parseDepositMethodIds(i)}async fetchDepositMethodId(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.v3PrivateGetBrokeragePaymentMethodsPaymentMethodId(this.extend({payment_method_id:e},t)),s=this.safeDict(i,"payment_method",{});return this.parseDepositMethodId(s)}parseDepositMethodIds(e,t={}){let i=[];for(let s=0;s<e.length;s++){let r=this.extend(this.parseDepositMethodId(e[s]),t);i.push(r)}return i}parseDepositMethodId(e){return{info:e,id:this.safeString(e,"id"),currency:this.safeString(e,"currency"),verified:this.safeBool(e,"verified"),tag:this.safeString(e,"name")}}async fetchConvertQuote(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={from_account:e,to_account:t,amount:this.numberToString(i)},a=await this.v3PrivatePostBrokerageConvertQuote(this.extend(r,s)),o=this.safeDict(a,"trade",{});return this.parseConversion(o)}async createConvertTrade(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=await this.v3PrivatePostBrokerageConvertTradeTradeId(this.extend({trade_id:e,from_account:t,to_account:i},r)),o=this.safeDict(a,"trade",{});return this.parseConversion(o)}async fetchConvertTrade(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===t)throw new a.ArgumentsRequired(this.id+" fetchConvertTrade() requires a code argument");let s=this.safeString(i,"toCode");if(void 0===s)throw new a.ArgumentsRequired(this.id+" fetchConvertTrade() requires a toCode parameter");let r=this.omit(i,"toCode"),o=await this.v3PrivateGetBrokerageConvertTradeTradeId(this.extend({trade_id:e,from_account:t,to_account:s},r)),n=this.safeDict(o,"trade",{});return this.parseConversion(n)}parseConversion(e,t,i){let s=this.safeString(e,"source_currency"),r=this.safeCurrencyCode(s,t),a=this.safeString(e,"target_currency"),o=this.safeCurrencyCode(a,i),n=this.safeDict(e,"user_entered_amount"),d=this.safeDict(e,"total_fee"),h=this.safeDict(d,"amount");return{info:e,timestamp:void 0,datetime:void 0,id:this.safeString(e,"id"),fromCurrency:r,fromAmount:this.safeNumber(n,"value"),toCurrency:o,toAmount:void 0,price:void 0,fee:this.safeNumber(h,"value")}}async transfer(e,t,i,s,r={}){await this.loadMarkets();let a=this.currency(e),o={funds:{value:this.currencyToPrecision(e,t),currency:a.id},source_portfolio_uuid:i,target_portfolio_uuid:s},n=await this.v3PrivatePostBrokeragePortfoliosMoveFunds(this.extend(o,r)),d=this.parseTransfer(n,a);return d.amount=t,d.status="ok",d}parseTransfer(e,t){return{info:e,id:void 0,timestamp:void 0,datetime:void 0,currency:this.safeCurrencyCode(void 0,t),amount:void 0,fromAccount:this.safeString(e,"source_portfolio_uuid"),toAccount:this.safeString(e,"target_portfolio_uuid"),status:void 0}}async closePosition(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=this.safeString2(i,"client_order_id","clientOrderId"),o=this.omit(i,"clientOrderId"),n={product_id:s.id};if(void 0===r)throw new a.ArgumentsRequired(this.id+" closePosition() requires a clientOrderId parameter");n.client_order_id=r;let d=await this.v3PrivatePostBrokerageOrdersClosePosition(this.extend(n,o)),h=this.safeDict(d,"success_response",{});return this.parseOrder(h)}async fetchPositions(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e);void 0!==r&&(i=this.market(r[0]));let[o,n]=this.handleMarketTypeAndParams("fetchPositions",i,t);if("future"===o)s=await this.v3PrivateGetBrokerageCfmPositions(n);else{let[e,t]=this.handleOptionStringAndParams(n,"fetchPositions","portfolio");if(void 0===e)throw new a.ArgumentsRequired(this.id+' fetchPositions() requires a "portfolio" value in params (eg: dbcb91e7-2bc9-515), or set as exchange.options["portfolio"]. You can get a list of portfolios with fetchPortfolios()');s=await this.v3PrivateGetBrokerageIntxPositionsPortfolioUuid(this.extend({portfolio_uuid:e},t))}let d=this.safeList(s,"positions",[]);return this.parsePositions(d,r)}async fetchPosition(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e);if(!0===s.future){let e=this.safeString(s,"product_id");if(void 0===e)throw new a.ArgumentsRequired(this.id+' fetchPosition() requires a "product_id" in params');i=await this.v3PrivateGetBrokerageCfmPositionsProductId(this.extend({product_id:e},t))}else{let[e,r]=this.handleOptionStringAndParams(t,"fetchPositions","portfolio");if(void 0===e)throw new a.ArgumentsRequired(this.id+' fetchPosition() requires a "portfolio" value in params (eg: dbcb91e7-2bc9-515), or set as exchange.options["portfolio"]. You can get a list of portfolios with fetchPortfolios()');let o={symbol:s.id,portfolio_uuid:e};i=await this.v3PrivateGetBrokerageIntxPositionsPortfolioUuidSymbol(this.extend(o,r))}let r=this.safeDict(i,"position",{});return this.parsePosition(r,s)}parsePosition(e,t){let i,s=this.safeString(e,"symbol",""),r=this.safeMarket(s,t),a=this.safeString(e,"margin_type");void 0!==a&&(i="MARGIN_TYPE_CROSS"===a?"cross":"isolated");let o=this.safeDict(e,"position_notional",{}),n=this.safeString(e,"position_side"),d="short";"POSITION_SIDE_LONG"===n&&(d="long");let h=this.safeDict(e,"unrealized_pnl",{}),c=this.safeDict(e,"liquidation_price",{}),l=this.safeNumber(c,"value"),u=this.safeDict(e,"vwap",{}),f=this.safeDict(e,"portfolio_summary",{});return this.safePosition({info:e,id:this.safeString(e,"product_id"),symbol:this.safeSymbol(s,r),notional:this.safeNumber(o,"value"),marginMode:i,liquidationPrice:l,entryPrice:this.safeNumber(u,"value"),unrealizedPnl:this.safeNumber(h,"value"),realizedPnl:void 0,percentage:void 0,contracts:this.safeNumber(e,"net_size"),contractSize:r.contractSize,markPrice:void 0,lastPrice:void 0,side:d,hedged:void 0,timestamp:void 0,datetime:void 0,lastUpdateTimestamp:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,collateral:this.safeNumber(f,"collateral"),initialMargin:void 0,initialMarginPercentage:void 0,leverage:this.safeNumber(e,"leverage"),marginRatio:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleMarketTypeAndParams("fetchTradingFees",void 0,e),s="spot"===t,r="FUTURE";s&&(r="SPOT");let a={product_type:r},o=await this.v3PrivateGetBrokerageTransactionSummary(this.extend(a,i)),n=this.safeDict(o,"fee_tier",{}),d=this.safeNumber(n,"taker_fee_rate"),h=this.safeNumber(n,"maker_fee_rate"),c={};for(let e=0;e<this.symbols.length;e++){let t=this.symbols[e],i=this.market(t);(s&&!0===i.spot||!s&&!0!==i.spot)&&(c[t]={info:o,symbol:t,maker:h,taker:d,percentage:!0})}return c}async fetchPortfolioDetails(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.v3PrivateGetBrokeragePortfoliosPortfolioUuid(this.extend({portfolio_uuid:e},t));return this.parsePortfolioDetails(i)}parsePortfolioDetails(e){let t=this.safeDict(e,"breakdown"),i=this.safeDict(t,"portfolio",{}),s=this.safeString(i,"name","Unknown"),r=this.safeString(i,"uuid",""),a=this.safeList(t,"spot_positions",[]),o=[];for(let e=0;e<a.length;e++){let t=a[e],i=this.safeString(t,"asset","Unknown"),n=this.safeString(t,"available_to_trade_fiat","0"),d=this.parseNumber(n),h=this.safeString(t,"total_balance_fiat","0"),c=this.parseNumber(h),l=c-d,u=this.safeDict(t,"cost_basis",{}),f=this.safeString(u,"value","0"),p=this.safeDict(t,"average_entry_price",{}),m=this.safeString(p,"value","0"),g={currency:i,available_balance:d,hold_amount:l>0?l:0,wallet_name:s,account_id:r,account_uuid:this.safeString(t,"account_uuid",""),total_balance_fiat:c,total_balance_crypto:this.parseNumber(this.safeString(t,"total_balance_crypto","0")),available_to_trade_fiat:this.parseNumber(this.safeString(t,"available_to_trade_fiat","0")),available_to_trade_crypto:this.parseNumber(this.safeString(t,"available_to_trade_crypto","0")),available_to_transfer_fiat:this.parseNumber(this.safeString(t,"available_to_transfer_fiat","0")),available_to_transfer_crypto:this.parseNumber(this.safeString(t,"available_to_trade_crypto","0")),allocation:this.parseNumber(this.safeString(t,"allocation","0")),cost_basis:this.parseNumber(f),cost_basis_currency:this.safeString(u,"currency","USD"),is_cash:this.safeBool(t,"is_cash",!1),average_entry_price:this.parseNumber(m),average_entry_price_currency:this.safeString(p,"currency","USD"),asset_uuid:this.safeString(t,"asset_uuid",""),unrealized_pnl:this.parseNumber(this.safeString(t,"unrealized_pnl","0")),asset_color:this.safeString(t,"asset_color",""),account_type:this.safeString(t,"account_type","")};o.push(g)}return o}createAuthToken(e,t,i,r=!1){let a;if(void 0!==i){let e=(a=t+" "+i.replace("https://","")).indexOf("?");e>0&&(a=a.slice(0,e))}let o=this.randomBytes(16),d="retail_rest_api_proxy";r&&(d="cdp_service");let h="coinbase-cloud";r&&(h="cdp");let c={aud:[d],iss:h,nbf:e,exp:e+120,sub:this.apiKey,iat:e};if(void 0!==a&&(r?c.uris=[a]:c.uri=a),!r)return(0,n.a)(c,this.encode(this.secret),s.sc,!1,{kid:this.apiKey,nonce:o,alg:"ES256"});{let e=this.base64ToBinary(this.secret),t=this.arraySlice(e,0,32);return(0,n.a)(c,t,s.sc,!1,{kid:this.apiKey,nonce:o,alg:"EdDSA"})}}nonce(){let e=this.safeInteger(this.options,"timeDifference");if(void 0===e)throw new a.ExchangeError(this.id+' nonce() requires a numeric options["timeDifference"]');return this.milliseconds()-e}sign(e,t=[],i="GET",r={},o,n){let d,h,c=this.safeString(t,0),l="private"===this.safeString(t,1),u="v3"===c,f="v2";u&&(f="api/v3");let p="/"+f+"/"+this.implodeParams(e,r),m=this.omit(r,this.extractParams(e)),g=p;"GET"===i&&Object.keys(m).length>0&&(p+="?"+this.urlencodeWithArrayRepeat(m));let v=this.safeString(this.urls.api,"rest");if(void 0===v)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let y=v+p;if(l){let e,t=this.safeString(this.headers,"Authorization");if(void 0!==t)e=t;else if(""===this.token||this.checkRequiredCredentials(!1)){this.checkRequiredCredentials();let t=this.seconds(),r="";"GET"!==i?Object.keys(m).length>0&&(r=d=this.json(m)):!u&&Object.keys(m).length>0&&(r+="?"+this.urlencode(m));let o=this.apiKey.indexOf("organizations/")>=0||this.secret.startsWith("-----BEGIN"),n=88===this.secret.length||this.safeBool(this.options,"v2CloudAPiKey",!1)||this.secret.endsWith("=");if(o||n){if(o&&this.apiKey.startsWith("-----BEGIN"))throw new a.ArgumentsRequired(this.id+" apiKey should contain the name (eg: organizations/3b910e93....) and not the public key");e="Bearer "+this.createAuthToken(t,i,y,n)}else{let e=this.nonce(),t=this.parseToInt(e/1e3).toString(),a=t+i+g+r,o=this.hmac(this.encode(a),this.encode(this.secret),s.sc);h={"CB-ACCESS-KEY":this.apiKey,"CB-ACCESS-SIGN":o,"CB-ACCESS-TIMESTAMP":t,"Content-Type":"application/json"}}}else e="Bearer "+this.token;void 0!==e&&(h={Authorization:e,"Content-Type":"application/json"},"GET"!==i&&Object.keys(m).length>0&&(d=this.json(m)))}return{url:y,method:i,body:void 0===d?n:d,headers:void 0===h?o:h}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.id+" "+o,l=this.safeString(n,"error");if(void 0!==l){let e=this.safeString2(n,"error_description","error");throw this.throwExactlyMatchedException(this.exceptions.exact,l,c),this.throwBroadlyMatchedException(this.exceptions.broad,e,c),new a.ExchangeError(c)}let u=this.safeDict(n,"error_response");if(void 0!==u){let e=this.safeString2(u,"preview_failure_reason","preview_failure_reason");throw this.throwExactlyMatchedException(this.exceptions.exact,e,c),this.throwBroadlyMatchedException(this.exceptions.broad,e,c),new a.ExchangeError(c)}let f=this.safeList(n,"errors");if(void 0!==f&&Array.isArray(f)&&f.length>0){l=this.safeString(f[0],"id");let e=this.safeString(f[0],"message");if(void 0!==l)throw this.throwExactlyMatchedException(this.exceptions.exact,l,c),this.throwBroadlyMatchedException(this.exceptions.broad,e,c),new a.ExchangeError(c)}let p=this.safeBool(this.options,"advanced");if(!("data"in n)&&!0!==p)throw new a.ExchangeError(this.id+" failed due to a malformed response "+this.json(n))}async fetchDepositAddresses(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.prepareAccountRequest(void 0,t),s=await this.v2PrivateGetAccountsAccountIdAddresses(this.extend(i,t)),r=this.safeList(s,"data",[]);return this.parseDepositAddresses(r,e,!1,{})}}i.d(t,{A:()=>d})},7455(e,t,i){"use strict";var s=i(4721),r=i(5266),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"coinbaseexchange",name:"Coinbase Exchange",countries:["US"],rateLimit:100,userAgent:this.userAgents.chrome,pro:!0,has:{CORS:!0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createDepositAddress:!0,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,fetchAccounts:!0,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLedger:!0,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchOrderTrades:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchTransactions:"emulated",fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,withdraw:!0},timeframes:{"1m":60,"5m":300,"15m":900,"1h":3600,"6h":21600,"1d":86400},hostname:"exchange.coinbase.com",urls:{test:{public:"https://api-public.sandbox.exchange.coinbase.com",private:"https://api-public.sandbox.exchange.coinbase.com"},logo:"https://github.com/user-attachments/assets/a99ef849-a4b2-4dd4-87fe-458ef17db7fd",api:{public:"https://api.{hostname}",private:"https://api.{hostname}"},www:"https://coinbase.com/",doc:"https://docs.cloud.coinbase.com/exchange/docs/",fees:["https://docs.pro.coinbase.com/#fees","https://support.pro.coinbase.com/customer/en/portal/articles/2945310-fees"]},requiredCredentials:{apiKey:!0,secret:!0,password:!0},api:{public:{get:{currencies:{cost:1},products:{cost:1},"products/{id}":{cost:1},"products/{id}/book":{cost:1},"products/{id}/candles":{cost:1},"products/{id}/stats":{cost:1},"products/{id}/ticker":{cost:1},"products/{id}/trades":{cost:1},time:{cost:1},"products/spark-lines":{cost:1},"products/volume-summary":{cost:1},"wrapped-assets":{cost:1},"wrapped-assets/{wrapped_asset_id}":{cost:1},"wrapped-assets/{wrapped_asset_id}/conversion-rate":{cost:1}}},private:{get:{"address-book":{cost:1},"address-book/counterparty":{cost:1},accounts:{cost:1},"accounts/{id}":{cost:1},"accounts/{id}/holds":{cost:1},"accounts/{id}/ledger":{cost:1},"accounts/{id}/transfers":{cost:1},"coinbase-accounts":{cost:1},fills:{cost:1},funding:{cost:1},fees:{cost:1},"margin/profile_information":{cost:1},"margin/buying_power":{cost:1},"margin/withdrawal_power":{cost:1},"margin/withdrawal_power_all":{cost:1},"margin/exit_plan":{cost:1},"margin/liquidation_history":{cost:1},"margin/position_refresh_amounts":{cost:1},"margin/status":{cost:1},oracle:{cost:1},orders:{cost:1},"orders/{id}":{cost:1},"orders/client:{client_oid}":{cost:1},"otc/orders":{cost:1},"payment-methods":{cost:1},position:{cost:1},profiles:{cost:1},"profiles/{id}":{cost:1},"reports/{report_id}":{cost:1},transfers:{cost:1},"transfers/{transfer_id}":{cost:1},"travel-rules":{cost:1},"users/self/exchange-limits":{cost:1},"users/self/hold-balances":{cost:1},"users/self/trailing-volume":{cost:1},"users/{user_id}/trading-volumes":{cost:1},"withdrawals/fee-estimate":{cost:1},"conversions/{conversion_id}":{cost:1},conversions:{cost:1},"conversions/fees":{cost:1},"loans/lending-overview":{cost:1},"loans/lending-overview-xm":{cost:1},"loans/loan-preview":{cost:1},"loans/loan-preview-xm":{cost:1},"loans/repayment-preview":{cost:1},"loans/repayment-preview-xm":{cost:1},"loans/interest/{loan_id}":{cost:1},"loans/interest/history/{loan_id}":{cost:1},"loans/interest":{cost:1},"loans/assets":{cost:1},loans:{cost:1},"loans/options":{cost:1},"wrapped-assets/redeem":{cost:1},"wrapped-assets/redeem/{redeem_id}":{cost:1},"wrapped-assets/stake-wrap":{cost:1},"wrapped-assets/stake-wrap/{stake_wrap_id}":{cost:1}},post:{conversions:{cost:1},"deposits/coinbase-account":{cost:1},"deposits/payment-method":{cost:1},"coinbase-accounts/{id}/addresses":{cost:1},"address-book":{cost:1},"funding/repay":{cost:1},orders:{cost:1},"position/close":{cost:1},profiles:{cost:1},"profiles/margin-transfer":{cost:1},"profiles/transfer":{cost:1},reports:{cost:1},"withdrawals/coinbase":{cost:1},"withdrawals/coinbase-account":{cost:1},"withdrawals/counterparty":{cost:1},"withdrawals/crypto":{cost:1},"withdrawals/payment-method":{cost:1},"transfers/{transfer_id}/travel-rules":{cost:1},"travel-rules":{cost:1},"users/{user_id}/settlement-preferences":{cost:1},"wrapped-assets/redeem":{cost:1},"wrapped-assets/stake-wrap":{cost:1},"loans/open":{cost:1},"loans/repay-interest":{cost:1},"loans/repay-principal":{cost:1}},delete:{orders:{cost:1},"orders/client:{client_oid}":{cost:1},"orders/{id}":{cost:1},"address-book/{id}":{cost:1},"travel-rules/{id}":{cost:1}},put:{"profiles/{id}/deactivate":{cost:1},"profiles/{id}":{cost:1},"address-book/{id}":{cost:1}}}},commonCurrencies:{CGLD:"CELO"},precisionMode:4,fees:{trading:{tierBased:!0,percentage:!0,maker:this.parseNumber("0.004"),taker:this.parseNumber("0.006")},funding:{tierBased:!1,percentage:!1,withdraw:{BCH:0,BTC:0,LTC:0,ETH:0,EUR:.15,USD:25},deposit:{BCH:0,BTC:0,LTC:0,ETH:0,EUR:.15,USD:10}}},features:{default:{sandbox:!0,createOrder:{marginMode:!0,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!0},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!0},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:100,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:100,daysBack:1e5,daysBackCanceled:1,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:300}},spot:{extends:"default"},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},options:{networks:{BTC:"bitcoin",ETH:"ethereum",SOL:"solana",ARBITRUM:"arbitrum",AVAXC:"avacchain",MATIC:"polygon",BASE:"base",SUI:"sui",OP:"optimism",NEAR:"near",APT:"aptos",KAVA:"kava",BLAST:"blast",XLM:"stellar",SEI:"sei",ADA:"cardano",CORE:"coredao",ALGO:"algorand",OSMO:"osmosis",CELO:"celo",HBAR:"hedera",ZKSYNC:"zksync",STX:"stacks",XTZ:"tezos",EGLD:"elrond",LTC:"litecoin",ATOM:"cosmos",FIL:"filecoin",DOT:"polkadot",DOGE:"dogecoin",XRP:"ripple",DASH:"dash"}},exceptions:{exact:{"Insufficient funds":a.InsufficientFunds,NotFound:a.OrderNotFound,"Invalid API Key":a.AuthenticationError,"invalid signature":a.AuthenticationError,"Invalid Passphrase":a.AuthenticationError,"Invalid order id":a.InvalidOrder,"Private rate limit exceeded":a.RateLimitExceeded,"Trading pair not available":a.PermissionDenied,"Product not found":a.InvalidOrder},broad:{"Order already done":a.OrderNotFound,"order not found":a.OrderNotFound,"price too small":a.InvalidOrder,"price too precise":a.InvalidOrder,"under maintenance":a.OnMaintenance,"size is too small":a.InvalidOrder,"Cancel only mode":a.OnMaintenance}}})}async fetchCurrencies(e={}){let t=await this.publicGetCurrencies(e);return this.parseCurrencies(t)}parseCurrency(e){let t=this.safeString(e,"id"),i=this.safeString(e,"name"),s=this.safeCurrencyCode(t),r=this.safeDict(e,"details",{}),a={},o=this.safeList(e,"supported_networks",[]);for(let e=0;e<o.length;e++){let t=o[e],i=this.safeString(t,"id"),r=this.networkIdToCode(i,s);void 0!==r&&(a[r]={id:i,name:this.safeString(t,"name"),network:r,active:"online"===this.safeString(t,"status"),withdraw:void 0,deposit:void 0,fee:void 0,precision:void 0,limits:{withdraw:{min:this.safeNumber(t,"min_withdrawal_amount"),max:this.safeNumber(t,"max_withdrawal_amount")}},contract:this.safeString(t,"contract_address"),info:t})}return this.safeCurrencyStructure({id:t,code:s,info:e,type:this.safeString(r,"type"),name:i,active:"online"===this.safeString(e,"status"),deposit:void 0,withdraw:void 0,fee:void 0,precision:this.safeNumber(e,"max_precision"),limits:{amount:{min:this.safeNumber(r,"min_size"),max:void 0},withdraw:{min:this.safeNumber(r,"min_withdrawal_amount"),max:this.safeNumber(r,"max_withdrawal_amount")}},networks:a})}async fetchMarkets(e={}){let t=await this.publicGetProducts(e),i=[],s=this.toArray(t);for(let e=0;e<s.length;e++){let t=s[e],r=this.safeString(t,"id"),[a,o]=r.split("-"),n=this.safeCurrencyCode(a),d=this.safeCurrencyCode(o);if(void 0===n||void 0===d)continue;let h=this.safeString(t,"status");i.push(this.extend(this.fees.trading,{id:r,symbol:n+"/"+d,base:n,quote:d,settle:void 0,baseId:a,quoteId:o,settleId:void 0,type:"spot",spot:!0,margin:this.safeBool(t,"margin_enabled"),swap:!1,future:!1,option:!1,active:"online"===h,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(t,"base_increment"),price:this.safeNumber(t,"quote_increment")},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(t,"min_market_funds"),max:void 0}},created:void 0,info:t}))}return i}async fetchAccounts(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetAccounts(e),i=this.toArray(t);return this.parseAccounts(i,e)}parseAccount(e){let t=this.safeString(e,"currency");return{id:this.safeString(e,"id"),type:void 0,code:this.safeCurrencyCode(t),info:e}}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"currency"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(s,"available"),o.used=this.safeString(s,"hold"),o.total=this.safeString(s,"balance"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetAccounts(e);return this.parseBalance(t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={id:this.marketId(e),level:2},r=await this.publicGetProductsIdBook(this.extend(s,i)),a=this.parseOrderBook(r,e);return a.nonce=this.safeInteger(r,"sequence"),a}parseTicker(e,t){let i,s,r,a,o,n,d,h,c=void 0===t?void 0:t.symbol;return Array.isArray(e)?a=this.safeString(e,4):(i=this.parse8601(this.safeString(e,"time")),s=this.safeString(e,"bid"),r=this.safeString(e,"ask"),o=this.safeString(e,"high"),n=this.safeString(e,"low"),d=this.safeString(e,"open"),a=this.safeString2(e,"price","last"),h=this.safeString(e,"volume")),this.safeTicker({symbol:c,timestamp:i,datetime:this.iso8601(i),high:o,low:n,bid:s,bidVolume:void 0,ask:r,askVolume:void 0,vwap:void 0,open:d,close:a,last:a,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:h,quoteVolume:void 0,info:e},t)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetProductsSparkLines(this.extend({},t)),r={},a=Object.keys(s);for(let e=0;e<a.length;e++){let t=a[e],i=this.safeList(s,t,[]),o=this.safeList(i,0,[]),n=this.safeMarket(t,void 0,"-");r[n.symbol]=this.parseTicker(o,n)}return this.filterByArrayTickers(r,"symbol",i)}async fetchTicker(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={id:s.id};return i="publicGetProductsIdStats"===this.safeString(this.options,"fetchTickerMethod","publicGetProductsIdTicker")?await this.publicGetProductsIdStats(this.extend(r,t)):await this.publicGetProductsIdTicker(this.extend(r,t)),this.parseTicker(i,s)}parseTrade(e,t){let i,s,r,a=this.parse8601(this.safeString2(e,"time","created_at")),o=this.safeString(e,"product_id"),n=this.safeMarket(o,t,"-"),d=this.safeStringLower(n,"quoteId");if(void 0!==d){r=this.safeString(e,d+"_value");let t=this.safeString(e,"liquidity");void 0!==t&&(s="T"===t?"taker":"maker",i=this.safeString(n,s))}let h={cost:this.safeString2(e,"fill_fees","fee"),currency:n.quote,rate:i},c=this.safeString(e,"trade_id"),l=this.safeString(e,"side"),u="buy";"buy"===l&&(u="sell");let f=this.safeString(e,"order_id"),p=this.safeString(e,"maker_order_id"),m=this.safeString(e,"taker_order_id");(void 0!==f||void 0!==p&&void 0!==m)&&(u="buy"===l?"buy":"sell");let g=this.safeString(e,"price"),v=this.safeString(e,"size"),y=n.symbol;return this.safeTrade({id:c,order:f,info:e,timestamp:a,datetime:this.iso8601(a),symbol:y,type:void 0,takerOrMaker:s,side:u,price:g,amount:v,fee:h,cost:r},n)}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");let[r,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(r)return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,o,100);void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d={product_id:n.id};void 0!==i&&(d.limit=i),void 0!==t&&(d.start_date=this.iso8601(t));let h=this.safeValue2(o,"until","end_date");void 0!==h&&(d.end_date=this.iso8601(h));let c=void 0!==h?this.omit(o,["until"]):o,l=await this.privateGetFills(this.extend(d,c));return this.parseTrades(l,n,t,i)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={id:r.id};void 0!==i&&(a.limit=i);let o=await this.publicGetProductsIdTrades(this.extend(a,s));return this.parseTrades(o,r,t,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetFees(e),i=this.safeNumber(t,"maker_fee_rate"),s=this.safeNumber(t,"taker_fee_rate"),r={};for(let e=0;e<this.symbols.length;e++){let a=this.symbols[e];r[a]={info:t,symbol:a,maker:i,taker:s,percentage:!0,tierBased:!0}}return r}parseOHLCV(e,t){return[this.safeTimestamp(e,0),this.safeNumber(e,3),this.safeNumber(e,2),this.safeNumber(e,1),this.safeNumber(e,4),this.safeNumber(e,5)]}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,o,300);let n=this.market(e),d=this.safeInteger(this.timeframes,t),h={id:n.id};void 0!==d?h.granularity=d:h.granularity=t;let c=this.safeValue2(o,"until","end"),l=this.omit(o,["until"]),u=void 0===s?300:Math.min(300,s),f=void 0!==i?u:s;if(void 0!==i)if(h.start=this.iso8601(i),void 0===c){let e=1e3*d;this.isRoundNumber(i%e)?h.end=this.iso8601(this.sum((u-1)*e,i)):h.end=this.iso8601(this.sum(u*e,i))}else h.end=this.iso8601(c);let p=await this.publicGetProductsIdCandles(this.extend(h,l));return this.parseOHLCVs(this.toArray(p),n,t,i,f)}async fetchTime(e={}){let t=await this.publicGetTime(e);return this.safeTimestamp(t,"epoch")}parseOrderStatus(e){return this.safeString({pending:"open",active:"open",open:"open",done:"closed",canceled:"canceled",canceling:"open"},e,e)}parseOrder(e,t){let i,s=this.parse8601(this.safeString(e,"created_at")),r=this.safeString(e,"product_id"),a=this.safeMarket(r,t,"-"),o=this.parseOrderStatus(this.safeString(e,"status")),n=this.safeString(e,"done_reason");"closed"===o&&"canceled"===n&&(o="canceled");let d=this.safeString(e,"price"),h=this.safeString(e,"filled_size"),c=this.safeString(e,"size",h),l=this.safeString(e,"executed_value"),u=this.safeNumber(e,"fill_fees");void 0!==u&&(i={cost:u,currency:a.quote,rate:void 0});let f=this.safeString(e,"id"),p=this.safeString(e,"type"),m=this.safeString(e,"side"),g=this.safeString(e,"time_in_force"),v=this.safeBool(e,"post_only"),y=this.safeNumber(e,"stop_price"),b=this.safeString(e,"client_oid");return this.safeOrder({id:f,clientOrderId:b,info:e,timestamp:s,datetime:this.iso8601(s),lastTradeTimestamp:void 0,status:o,symbol:a.symbol,type:p,timeInForce:g,postOnly:v,side:m,price:d,triggerPrice:y,cost:l,amount:c,filled:h,remaining:void 0,fee:i,average:void 0,trades:void 0},a)}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r={},a=this.safeString2(i,"clientOrderId","client_oid");if(void 0===a)r.id=e,s=await this.privateGetOrdersId(this.extend(r,i));else{r.client_oid=a;let e=this.omit(i,["clientOrderId","client_oid"]);s=await this.privateGetOrdersClientClientOid(this.extend(r,e))}return this.parseOrder(s)}async fetchOrderTrades(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(a=this.market(t));let o=await this.privateGetFills(this.extend({order_id:e},r));return this.parseTrades(o,a,i,s)}async fetchOrders(e,t,i,s={}){return await this.fetchOpenOrders(e,t,i,this.extend({status:"all"},s))}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchOpenOrders","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchOpenOrders",e,t,i,o,100);let n={};void 0!==e&&(n.product_id=(r=this.market(e)).id),void 0!==i&&(n.limit=i),void 0!==t&&(n.start_date=this.iso8601(t));let d=this.safeValue2(o,"until","end_date");void 0!==d&&(n.end_date=this.iso8601(d));let h=void 0!==d?this.omit(o,["until"]):o,c=await this.privateGetOrders(this.extend(n,h));return this.parseOrders(c,r,t,i)}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOpenOrders(e,t,i,this.extend({status:"done"},s))}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={type:t,side:i,product_id:o.id},d=this.safeString2(a,"clientOrderId","client_oid");void 0!==d&&(n.client_oid=d);let h=this.safeNumberN(a,["stopPrice","stop_price","triggerPrice"]);void 0!==h&&(n.stop_price=this.priceToPrecision(e,h));let c=this.safeString2(a,"timeInForce","time_in_force");void 0!==c&&(n.time_in_force=c),!0===this.safeBool2(a,"postOnly","post_only",!1)&&(n.post_only=!0);let l=this.omit(a,["timeInForce","time_in_force","stopPrice","stop_price","clientOrderId","client_oid","postOnly","post_only","triggerPrice"]),u=this.safeNumber2(l,"cost","funds"),f=l;if("market"===t&&void 0!==u&&(f=this.omit(l,["cost","funds"])),"limit"===t)n.price=this.priceToPrecision(e,r),n.size=this.amountToPrecision(e,s);else if("market"===t){let t=u;void 0===t&&void 0!==r&&(t=s*r),void 0!==t?n.funds=this.costToPrecision(e,t):n.size=this.amountToPrecision(e,s)}let p=await this.privatePostOrders(this.extend(n,f));return this.parseOrder(p,o)}async cancelOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r={},a=this.safeString2(i,"clientOrderId","client_oid");void 0===a?r.id=e:r.client_oid=a;let o=void 0!==a?this.omit(i,["clientOrderId","client_oid"]):i;return void 0!==t&&(r.product_id=this.market(t).symbol),s=void 0===a?await this.privateDeleteOrdersId(this.extend(r,o)):await this.privateDeleteOrdersClientClientOid(this.extend(r,o)),this.safeOrder({info:s})}async cancelAllOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={};void 0!==e&&(i.product_id=this.market(e).symbol);let s=await this.privateDeleteOrders(this.extend(i,t));return[this.safeOrder({info:s})]}async fetchPaymentMethods(e={}){return await this.privateGetPaymentMethods(e)}async withdraw(e,t,i,s,r={}){let o,[n,d]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let h=this.currency(e),c={currency:h.id,amount:t};if("payment_method_id"in d?o=await this.privatePostWithdrawalsPaymentMethod(this.extend(c,d)):"coinbase_account_id"in d?o=await this.privatePostWithdrawalsCoinbaseAccount(this.extend(c,d)):(c.crypto_address=i,void 0!==n&&(c.destination_tag=n),o=await this.privatePostWithdrawalsCrypto(this.extend(c,d))),void 0===o)throw new a.ExchangeError(this.id+" withdraw() error: "+this.json(o));return this.parseTransaction(o,h)}parseLedgerEntryType(e){return this.safeString({transfer:"transfer",match:"trade",fee:"fee",rebate:"rebate",conversion:"trade"},e,e)}parseLedgerEntry(e,t){let i,s,r,a,n=this.safeString(e,"id"),d=this.safeString(e,"amount"),h=this.safeString(e,"balance"),c=o.Y.stringSub(h,d);o.Y.stringLt(d,"0")?(i="out",d=o.Y.stringAbs(d)):i="in";let l=this.parseNumber(d),u=this.parseNumber(h),f=this.parseNumber(c),p=this.parse8601(this.safeString(e,"created_at")),m=this.parseLedgerEntryType(this.safeString(e,"type")),g=this.safeCurrencyCode(void 0,t),v=this.safeDict(e,"details",{});return"transfer"===m?(s=this.safeString(v,"from"),r=this.safeString(v,"to"),a=this.safeString(v,"profile_transfer_id")):a=this.safeString(v,"order_id"),this.safeLedgerEntry({info:e,id:n,timestamp:p,datetime:this.iso8601(p),direction:i,account:s,referenceAccount:r,referenceId:a,type:m,currency:g,amount:l,before:f,after:u,status:"ok",fee:void 0},t)}async fetchLedger(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchLedger() requires a code param");void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let r=this.currency(e),o=this.indexBy(this.accounts,"code"),n=this.safeDict(o,e);if(void 0===n)throw new a.ExchangeError(this.id+" fetchLedger() could not find account id for "+e);let d={id:n.id};void 0!==t&&(d.start_date=this.iso8601(t)),void 0!==i&&(d.limit=i);let h=this.safeValue2(s,"until","end_date");void 0!==h&&(d.end_date=this.iso8601(h));let c=void 0!==h?this.omit(s,["until"]):s,l=await this.privateGetAccountsIdLedger(this.extend(d,c)),u=this.toArray(l);for(let t=0;t<u.length;t++)u[t].currency=e;return this.parseLedger(u,r,t,i)}async fetchDepositsWithdrawals(e,t,i,s={}){let r,o;void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let n=this.safeString(s,"id");if(void 0===n&&void 0!==e){o=this.currency(e);let t=this.indexBy(this.accounts,"code"),i=this.safeDict(t,e);if(void 0===i)throw new a.ExchangeError(this.id+" fetchDepositsWithdrawals() could not find account id for "+e);n=this.safeString(i,"id")}let d={};if(void 0!==n&&(d.id=n),void 0!==i&&(d.limit=i),void 0===n){let e=await this.privateGetTransfers(this.extend(d,s));r=this.toArray(e);for(let e=0;e<r.length;e++){let t=this.safeString(r[e],"account_id"),i=this.safeDict(this.accountsById,t),s=this.safeString(i,"code");r[e].currency=s}}else{let t=await this.privateGetAccountsIdTransfers(this.extend(d,s));r=this.toArray(t);for(let t=0;t<r.length;t++)r[t].currency=e}return this.parseTransactions(r,o,t,i)}async fetchDeposits(e,t,i,s={}){return await this.fetchDepositsWithdrawals(e,t,i,this.extend({type:"deposit"},s))}async fetchWithdrawals(e,t,i,s={}){return await this.fetchDepositsWithdrawals(e,t,i,this.extend({type:"withdraw"},s))}parseTransactionStatus(e){if(null!=this.safeString(e,"canceled_at"))return"canceled";let t=this.safeString(e,"processed_at");return null!=this.safeString(e,"completed_at")?"ok":null!=t?"failed":"pending"}parseTransaction(e,t){let i=this.safeDict(e,"details",{}),s=this.parse8601(this.safeString(e,"created_at")),r=this.safeString(e,"currency"),a=this.safeCurrencyCode(r,t),o=this.safeNumber(e,"amount"),n=this.safeString(e,"type"),d=this.safeString(i,"crypto_address");d=this.safeString(e,"crypto_address",d);let h={currency:void 0,cost:void 0,rate:void 0};if("withdraw"===n){n="withdrawal",d=this.safeString(i,"sent_to_address",d);let e=this.safeNumber(i,"fee");void 0!==e&&(void 0!==o&&(o-=e),h.cost=e,h.currency=a)}let c=this.safeString(i,"network");return{info:e,id:this.safeString(e,"id"),txid:this.safeString(i,"crypto_transaction_hash"),type:n,currency:a,network:this.networkIdToCode(c,a),amount:o,status:this.parseTransactionStatus(e),timestamp:s,datetime:this.iso8601(s),address:d,addressFrom:void 0,addressTo:this.safeString(i,"crypto_address"),tag:this.safeString(i,"destination_tag"),tagFrom:void 0,tagTo:void 0,updated:this.parse8601(this.safeString(e,"processed_at")),comment:void 0,internal:!1,fee:h}}async createDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s=this.safeValue(this.options,"coinbaseAccounts");void 0===s&&(s=await this.privateGetCoinbaseAccounts(),this.options.coinbaseAccounts=s,this.options.coinbaseAccountsByCurrencyId=this.indexBy(s,"currency"));let r=i.id,o=this.safeDict(this.options.coinbaseAccountsByCurrencyId,r);if(void 0===o)throw new a.InvalidAddress(this.id+" createDepositAddress() could not find currency code "+e+" with id = "+r+" in this.options['coinbaseAccountsByCurrencyId']");let n={id:o.id},d=await this.privatePostCoinbaseAccountsIdAddresses(this.extend(n,t)),h=this.safeString(d,"address"),c=this.safeString(d,"destination_tag");return{currency:e,address:this.checkAddress(h),network:void 0,tag:c,info:d}}sign(e,t="public",i="GET",r={},o,n){let d=o,h=n,c="/"+this.implodeParams(e,r),l=this.omit(r,this.extractParams(e));"GET"===i&&Object.keys(l).length>0&&(c+="?"+this.urlencode(l));let u=this.safeString(this.urls.api,t);if(void 0===u)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let f=this.implodeHostname(u)+c;if("private"===t){let e;this.checkRequiredCredentials();let t=this.nonce().toString(),r="";"GET"!==i&&Object.keys(l).length>0&&(r=h=this.json(l));let o=t+i+c+r;try{e=this.base64ToBinary(this.secret)}catch(e){throw new a.AuthenticationError(this.id+" sign() invalid base64 secret")}let n=this.hmac(this.encode(o),e,s.sc,"base64");d={"CB-ACCESS-KEY":this.apiKey,"CB-ACCESS-SIGN":n,"CB-ACCESS-TIMESTAMP":t,"CB-ACCESS-PASSPHRASE":this.password,"Content-Type":"application/json"}}return{url:f,method:i,body:h,headers:d}}handleErrors(e,t,i,s,r,o,n,d,h){if(400===e||404===e){if("{"===o[0]){let e=this.safeString(n,"message"),t=this.id+" "+e;throw this.throwExactlyMatchedException(this.exceptions.exact,e,t),this.throwBroadlyMatchedException(this.exceptions.broad,e,t),new a.ExchangeError(t)}throw new a.ExchangeError(this.id+" "+o)}}async request(e,t="public",i="GET",s={},r,o,n={}){let d=await this.fetch2(e,t,i,s,r,o,n);if("string"!=typeof d&&"message"in d)throw new a.ExchangeError(this.id+" "+this.json(d));return d}}i.d(t,{A:()=>n})},5700(e,t,i){"use strict";var s=i(4721),r=i(9487),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"coinbaseinternational",name:"Coinbase International",countries:["US"],certified:!1,pro:!0,rateLimit:100,version:"v1",userAgent:this.userAgents.chrome,headers:{"CB-VERSION":"2018-05-30"},has:{CORS:!0,spot:!0,margin:!0,swap:!0,future:!1,option:!1,addMargin:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!1,closeAllPositions:!1,closePosition:!1,createDepositAddress:!0,createLimitBuyOrder:!0,createLimitSellOrder:!0,createMarketBuyOrder:!0,createMarketBuyOrderWithCost:!1,createMarketOrderWithCost:!1,createMarketSellOrder:!0,createMarketSellOrderWithCost:!1,createOrder:!0,createPostOnlyOrder:!0,createReduceOnlyOrder:!1,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,editOrder:!0,fetchAccounts:!0,fetchBalance:!0,fetchBidsAsks:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchCanceledOrders:!1,fetchClosedOrders:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposits:!0,fetchDepositsWithdrawals:!0,fetchFundingHistory:!0,fetchFundingRate:!1,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchL2OrderBook:!1,fetchLedger:!1,fetchLeverage:!1,fetchLeverageTiers:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyBuys:!1,fetchMySells:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterestHistory:!1,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!1,fetchOrders:!1,fetchPosition:!0,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!1,fetchTrades:!1,fetchTradingFee:!1,fetchTradingFees:!1,fetchTransfers:!0,fetchWithdrawals:!0,reduceMargin:!1,sandbox:!0,setLeverage:!1,setMargin:!0,setMarginMode:!1,setPositionMode:!1,transfer:!0,withdraw:!0},urls:{logo:"https://github.com/ccxt/ccxt/assets/43336371/866ae638-6ab5-4ebf-ab2c-cdcce9545625",api:{rest:"https://api.international.coinbase.com/api"},test:{rest:"https://api-n5e1.coinbase.com/api"},www:"https://international.coinbase.com",doc:["https://docs.cloud.coinbase.com/intx/docs"],fees:["https://help.coinbase.com/en/international-exchange/trading-deposits-withdrawals/international-exchange-fees"],referral:""},requiredCredentials:{apiKey:!0,secret:!0,password:!0},api:{v1:{public:{get:{assets:{cost:1},"assets/{assets}":{cost:1},"assets/{asset}/networks":{cost:1},instruments:{cost:1},"instruments/{instrument}":{cost:1},"instruments/{instrument}/quote":{cost:1},"instruments/{instrument}/funding":{cost:1},"instruments/{instrument}/candles":{cost:1},"instruments/volumes/daily":{cost:1},"position-offsets":{cost:1},"fee-rate-tiers":{cost:1}}},private:{get:{"address-book":{cost:1},orders:{cost:1},"orders/{id}":{cost:1},"index/{index}/composition":{cost:1},"index/{index}/composition-history":{cost:1},"index/{index}/price":{cost:1},"index/{index}/candles":{cost:1},portfolios:{cost:1},"portfolios/{portfolio}":{cost:1},"portfolios/{portfolio}/detail":{cost:1},"portfolios/{portfolio}/summary":{cost:1},"portfolios/{portfolio}/balances":{cost:1},"portfolios/{portfolio}/balances/{asset}":{cost:1},"portfolios/{portfolio}/positions":{cost:1},"portfolios/{portfolio}/positions/{instrument}":{cost:1},"portfolios/{portfolio}/position-limits":{cost:1},"portfolios/{portfolio}/position-limits/positions":{cost:1},"portfolios/{portfolio}/position-limits/positions/{instrument}":{cost:1},"portfolios/fills":{cost:1},"portfolios/{portfolio}/fills":{cost:1},"portfolios/fee-rates":{cost:1},"portfolios/{portfolio}/loans":{cost:1},"portfolios/{portfolio}/loans/{asset}":{cost:1},"portfolios/{portfolio}/loans/{asset}/availability":{cost:1},"portfolios/{portfolio}/margin-call-status":{cost:1},transfers:{cost:1},"transfers/{transfer_uuid}":{cost:1},"transfers/withdraw/{portfolio}/{asset}/counterparty-withdrawal-limit":{cost:1}},post:{orders:{cost:1},portfolios:{cost:1},"portfolios/margin":{cost:1},"portfolios/{portfolio}/cross-collateral-enabled":{cost:1},"portfolios/{portfolio}/auto-margin-enabled":{cost:1},"portfolios/{portfolio}/loans/{asset}":{cost:1},"portfolios/{portfolio}/loans/{asset}/preview":{cost:1},"portfolios/transfer":{cost:1},"portfolios/transfer-position":{cost:1},"transfers/withdraw":{cost:1},"transfers/address":{cost:1},"transfers/create-counterparty-id":{cost:1},"transfers/validate-counterparty-id":{cost:1},"transfers/withdraw/counterparty":{cost:1}},put:{"orders/{id}":{cost:1},"portfolios/{portfolio}":{cost:1}},delete:{orders:{cost:1},"orders/{id}":{cost:1}},patch:{"portfolios/{portfolio}":{cost:1}}}}},fees:{trading:{taker:this.parseNumber("0.004"),maker:this.parseNumber("0.002"),tierBased:!0,percentage:!0,tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.004")],[this.parseNumber("1000000"),this.parseNumber("0.004")],[this.parseNumber("5000000"),this.parseNumber("0.0035")],[this.parseNumber("10000000"),this.parseNumber("0.0035")],[this.parseNumber("50000000"),this.parseNumber("0.003")],[this.parseNumber("250000000"),this.parseNumber("0.0025")]],maker:[[this.parseNumber("0"),this.parseNumber("0.002")],[this.parseNumber("1000000"),this.parseNumber("0.0016")],[this.parseNumber("5000000"),this.parseNumber("0.001")],[this.parseNumber("10000000"),this.parseNumber("0.0008")],[this.parseNumber("50000000"),this.parseNumber("0.0005")],[this.parseNumber("250000000"),this.parseNumber("0")]]}}},precisionMode:4,exceptions:{exact:{},broad:{DUPLICATE_CLIENT_ORDER_ID:a.DuplicateOrderId,"Order rejected":a.InvalidOrder,"market orders must be IoC":a.InvalidOrder,"tif is required":a.InvalidOrder,"Invalid replace order request":a.InvalidOrder,Unauthorized:a.PermissionDenied,"invalid result_limit":a.BadRequest,"is a required field":a.BadRequest,"Not Found":a.BadRequest,"ip not allowed":a.AuthenticationError,"cbe spot routing instrument not supported":a.NotSupported}},timeframes:{"1m":"ONE_MINUTE","5m":"FIVE_MINUTE","15m":"FIFTEEN_MINUTE","30m":"THIRTY_MINUTE","1h":"ONE_HOUR","2h":"TWO_HOUR","6h":"SIX_HOUR","1d":"ONE_DAY"},options:{brokerId:"nfqkvdjp",portfolio:"",withdraw:{method:"v1PrivatePostTransfersWithdraw"},networksById:{ethereum:"ETH",arbitrum:"ARBITRUM",avacchain:"AVAX",optimism:"OPTIMISM",polygon:"MATIC",solana:"SOL",bitcoin:"BTC"}},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!0,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!0,GTC:!0},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!0,selfTradePrevention:!0,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:void 0,untilDays:1e4,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:100,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:{limit:300}},spot:{extends:"default"},swap:{linear:{extends:"default"},inverse:{extends:"default"}},future:{linear:void 0,inverse:void 0}}})}async handlePortfolioAndParams(e,t={}){let[i,s]=this.handleOptionStringAndParams(t,e,"portfolio");if(void 0!==i&&""!==i)return[i,s];let r=this.safeString(this.options,"portfolio");if(void 0!==r&&""!==r)return[r,s];let o=await this.fetchAccounts();for(let e=0;e<o.length;e++){let t=this.safeDict(o,e),i=this.safeDict(t,"info",{});if(this.safeBool(i,"is_default",!1)){let e=this.safeString(i,"portfolio_id");return this.options.portfolio=e,[e,s]}}throw new a.ArgumentsRequired(this.id+" "+e+'() requires a portfolio parameter or set the default portfolio with this.options["portfolio"]')}async handleNetworkIdAndParams(e,t,i={}){let[s,r]=this.handleOptionStringAndParams(i,t,"network_arn_id"),o=s;if(void 0===o){await this.loadCurrencyNetworks(e);let t=this.currencies[e].networks,i=this.safeString2(r,"networkCode","network");if(void 0===i){if(this.isEmpty(t))throw new a.BadRequest(this.id+" createDepositAddress network not found for currency "+e+" please specify networkId in params");o=this.findDefaultNetwork(t).id}else o=this.networkCodeToId(i,e)}return[o,r]}async fetchAccounts(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v1PrivateGetPortfolios(e);return this.parseAccounts(t,e)}parseAccount(e){return{id:this.safeString2(e,"portfolio_id","portfolio_uuid"),type:void 0,code:void 0,info:e}}async fetchOHLCV(e,t="1m",i,s=100,r={}){void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,o,1e4);let n=this.market(e),d={instrument:n.id,granularity:this.safeString(this.timeframes,t,t)},h=this.parseTimeframe(t);if(void 0!==i)d.start=this.iso8601(i);else{let e=s;void 0===e&&(e=300);let t=this.sum(this.milliseconds(),-e*h*1e3);d.start=this.iso8601(t)}let c=this.safeInteger(o,"until");void 0!==c&&(d.end=this.iso8601(c));let l=void 0!==c?this.omit(o,"until"):o,u=await this.v1PublicGetInstrumentsInstrumentCandles(this.extend(d,l)),f=this.safeList(u,"aggregations",[]);return this.parseOHLCVs(f,n,t,i,s)}parseOHLCV(e,t){return[this.parse8601(this.safeString2(e,"start","time")),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let[r,o]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1),[n,d]=this.handleOptionIntegerAndParams(o,"fetchFundingRateHistory","maxEntriesPerRequest",100),h="ccxtPageKey";if(r)return await this.fetchPaginatedCallIncremental("fetchFundingRateHistory",e,t,i,d,h,n);let c=this.market(e),l=this.safeInteger(d,h,1)-1,u=this.safeInteger2(d,"offset","result_offset",l*n),f={instrument:c.id,result_offset:u};void 0!==i&&(f.result_limit=i);let p=await this.v1PublicGetInstrumentsInstrumentFunding(this.extend(f,d)),m=this.safeList(p,"results",[]);return this.parseFundingRateHistories(m,c,t,i)}parseFundingRateHistory(e,t){let i=this.parseFundingRate(e,t);return{info:e,symbol:i.symbol,fundingRate:i.fundingRate,timestamp:i.timestamp,datetime:i.datetime}}parseFundingRate(e,t){let i=this.safeString2(e,"event_time","time");return{info:e,symbol:this.safeSymbol(void 0,t),markPrice:this.safeNumber(e,"mark_price"),indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:this.parse8601(i),datetime:i,fundingRate:this.safeNumber(e,"funding_rate"),fundingTimestamp:this.parse8601(i),fundingDatetime:i,nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0}}async fetchFundingHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={type:"FUNDING"};void 0!==e&&(r=this.market(e));let[o,n]=this.handleOptionStringAndParams(s,"fetchFundingHistory","portfolios");void 0!==o&&(a.portfolios=o),void 0!==t&&(a.time_from=this.iso8601(t)),void 0!==i?a.result_limit=i:a.result_limit=100;let d=await this.v1PrivateGetTransfers(this.extend(a,n)),h=this.safeList(d,"results",[]);return this.parseIncomes(h,r,t,i)}parseIncome(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t,void 0,"contract"),r=this.safeInteger(e,"created_at"),a=this.parse8601(r),o=this.safeString(e,"asset"),n=this.safeCurrencyCode(o);return{info:e,symbol:s.symbol,code:n,timestamp:a,datetime:this.iso8601(a),id:this.safeString(e,"transfer_uuid"),amount:this.safeNumber(e,"amount"),rate:void 0}}async fetchTransfers(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={type:"INTERNAL"};void 0!==e&&(r=this.currency(e));let[o,n]=this.handleOptionStringAndParams(s,"fetchTransfers","portfolios");void 0!==o&&(a.portfolios=o),void 0!==t&&(a.time_from=this.iso8601(t)),void 0!==i?a.result_limit=i:a.result_limit=100;let d=await this.v1PrivateGetTransfers(this.extend(a,n)),h=this.safeList(d,"results",[]);return this.parseTransfers(h,r,t,i)}parseTransfer(e,t){let i=this.safeInteger(e,"created_at"),s=this.parse8601(i),r=this.safeString(e,"asset"),a=this.safeCurrencyCode(r),o=this.safeDict(e,"from_portfolio",{}),n=this.safeString(o,"id"),d=this.safeDict(e,"to_portfolio",{}),h=this.safeString(d,"id");return{info:e,id:this.safeString(e,"transfer_uuid"),timestamp:s,datetime:this.iso8601(s),currency:a,amount:this.safeNumber(e,"amount"),fromAccount:n,toAccount:h,status:this.parseTransferStatus(this.safeString(e,"status"))}}parseTransferStatus(e){return this.safeString({FAILED:"failed",PROCESSED:"ok",NEW:"pending",STARTED:"pending"},e,e)}async createDepositAddress(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleOptionStringAndParams(t,"createDepositAddress","method","v1PrivatePostTransfersAddress"),[a,o]=await this.handlePortfolioAndParams("createDepositAddress",r),n=o,d={portfolio:a};if("v1PrivatePostTransfersAddress"===s){d.asset=this.currency(e).id;let[t,i]=await this.handleNetworkIdAndParams(e,"createDepositAddress",o);d.network_arn_id=t,n=i}return i="v1PrivatePostTransfersCreateCounterpartyId"===s?await this.v1PrivatePostTransfersCreateCounterpartyId(this.extend(d,n)):await this.v1PrivatePostTransfersAddress(this.extend(d,n)),{currency:e,tag:this.safeString(i,"destination_tag"),address:this.safeString2(i,"address","counterparty_id"),network:void 0,info:i}}findDefaultNetwork(e){let t=this.toArray(e);for(let e=0;e<t.length;e++){let i=this.safeDict(t[e],"info");if(!0===this.safeBool(i,"is_default",!1))return t[e]}return t[0]}async loadCurrencyNetworks(e,t={}){let i=this.currency(e);if(void 0!==this.safeDict(i,"networks"))return!1;let s={asset:i.id},r=await this.v1PublicGetAssetsAssetNetworks(s);return i.networks=this.parseNetworks(r),!0}parseNetworks(e,t={}){let i={};for(let s=0;s<e.length;s++){let r=this.extend(this.parseNetwork(e[s]),t);i[r.network]=r}return i}parseNetwork(e,t={}){let i=this.safeString(e,"asset_name"),s=this.safeCurrencyCode(i),r=this.safeString(e,"network_arn_id"),a=this.safeStringN(e,["network_name","display_name","network_arn_id"],"");return this.safeNetwork({info:e,id:r,name:this.safeString(e,"display_name"),network:this.networkIdToCode(a,s),active:void 0,deposit:void 0,withdraw:void 0,precision:void 0,fee:void 0,limits:{withdraw:{min:this.safeNumber(e,"min_withdrawal_amt"),max:this.safeNumber(e,"max_withdrawal_amt")},deposit:{min:void 0,max:void 0}}})}async setMargin(e,t,i={}){let[s,r]=await this.handlePortfolioAndParams("setMargin",i);if(void 0!==e)throw new a.BadRequest(this.id+" setMargin() only allows setting margin to full portfolio");return await this.v1PrivatePostPortfoliosMargin(this.extend({portfolio:s,margin_override:t},r))}async fetchDepositsWithdrawals(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchDepositsWithdrawals","paginate"),[o,n]=this.handleOptionIntegerAndParams(a,"fetchDepositsWithdrawals","maxEntriesPerRequest",100),d="ccxtPageKey";if(!0===r)return await this.fetchPaginatedCallIncremental("fetchDepositsWithdrawals",e,t,i,n,d,o);let h=this.safeInteger(n,d,1)-1,c={result_offset:this.safeInteger2(n,"offset","result_offset",h*o)};void 0!==t&&(c.time_from=this.iso8601(t)),void 0!==i&&(c.result_limit=Math.min(i,100));let[l,u]=this.handleOptionStringAndParams(n,"fetchDepositsWithdrawals","portfolios");void 0!==l&&(c.portfolios=l);let[f,p]=this.handleOptionIntegerAndParams(u,"fetchDepositsWithdrawals","until");void 0!==f&&(c.time_to=this.iso8601(f));let m=await this.v1PrivateGetTransfers(this.extend(c,p)),g=this.safeList(m,"results",[]);return this.parseTransactions(g)}async fetchPosition(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.symbol(e),[s,r]=await this.handlePortfolioAndParams("fetchPosition",t),a={portfolio:s,instrument:this.marketId(i)},o=await this.v1PrivateGetPortfoliosPortfolioPositionsInstrument(this.extend(a,r));return this.parsePosition(o)}parsePosition(e,t){let i=this.safeString(e,"symbol"),s=this.safeString(e,"net_size"),r=this.safeMarket(i,t,"-"),a="long";return o.Y.stringLe(s,"0")&&(a="short",s=o.Y.stringMul("-1",s)),this.safePosition({info:e,id:this.safeString(e,"id"),symbol:r.symbol,entryPrice:void 0,markPrice:this.safeNumber(e,"mark_price"),notional:void 0,collateral:void 0,unrealizedPnl:this.safeNumber(e,"unrealized_pnl"),side:a,contracts:this.parseNumber(s),contractSize:this.safeNumber(r,"contractSize"),timestamp:void 0,datetime:void 0,hedged:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,initialMargin:this.safeNumber(e,"im_contribution"),initialMarginPercentage:void 0,leverage:void 0,liquidationPrice:void 0,marginRatio:void 0,marginMode:void 0,percentage:void 0})}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=await this.handlePortfolioAndParams("fetchPositions",t),r=await this.v1PrivateGetPortfoliosPortfolioPositions(this.extend({portfolio:i},s)),a=this.parsePositions(r);if(this.isEmpty(e))return a;let o=this.marketSymbols(e);return this.filterByArrayPositions(a,"symbol",o)}async fetchWithdrawals(e,t,i,s={}){return void 0===this.markets&&await this.loadMarkets(),s.type="WITHDRAW",await this.fetchDepositsWithdrawals(e,t,i,s)}async fetchDeposits(e,t,i,s={}){return void 0===this.markets&&await this.loadMarkets(),s.type="DEPOSIT",await this.fetchDepositsWithdrawals(e,t,i,s)}parseTransactionStatus(e){return this.safeString({PROCESSED:"ok",NEW:"pending",STARTED:"pending",FAILED:"canceled"},e,e)}parseTransaction(e,t){let i=this.safeString(e,"updated_at"),s=this.safeDict(e,"from_portfolio",{}),r=this.safeStringN(e,["from_address","from_cb_account",this.safeStringN(s,["id","uuid","name"]),"from_counterparty_id"]),a=this.safeDict(e,"from_portfolio",{}),o=this.safeStringN(e,["to_address","to_cb_account",this.safeStringN(a,["id","uuid","name"]),"to_counterparty_id"]),n=this.safeString(t,"code");return{info:e,id:this.safeString(e,"transfer_uuid"),txid:this.safeString(e,"transaction_uuid"),timestamp:this.parse8601(i),datetime:i,network:this.networkIdToCode(this.safeString(e,"network_name"),n),address:void 0,addressTo:o,addressFrom:r,tag:void 0,tagTo:void 0,tagFrom:void 0,type:this.safeString(e,"resource"),amount:this.safeNumber(e,"amount"),currency:this.safeCurrencyCode(this.safeString(e,"asset"),t),status:this.parseTransactionStatus(this.safeString(e,"status")),updated:this.parse8601(i),fee:{cost:void 0,currency:void 0}}}parseTrade(e,t){let i=this.safeString(e,"symbol"),s=this.safeString(e,"event_time");return this.safeTrade({info:e,id:this.safeString2(e,"fill_id","exec_id"),order:this.safeString(e,"order_id"),timestamp:this.parse8601(s),datetime:s,symbol:this.safeSymbol(i,t),type:void 0,side:this.safeStringLower(e,"side"),takerOrMaker:void 0,price:this.safeNumber(e,"fill_price"),amount:this.safeNumber(e,"fill_qty"),cost:void 0,fee:{cost:this.safeNumber(e,"fee"),currency:this.safeCurrencyCode(this.safeString(e,"fee_asset"))}})}async fetchMarkets(e={}){let t=await this.v1PublicGetInstruments(e);return this.parseMarkets(t)}parseMarket(e){let t,i=this.safeString(e,"symbol"),s=this.safeString(e,"base_asset_name"),r=this.safeString(e,"quote_asset_name"),o="SPOT"===this.safeString(e,"type"),n=this.fees;if(void 0===s||void 0===r)return;let d=s+"/"+r;o||(t=r,d+=":"+r);let h=o?void 0:t===r,c=o?void 0:t!==r;if(void 0===i)throw new a.ExchangeError(this.id+" parseMarket() missing marketId");return this.safeMarketStructure({id:i,lowercaseId:i.toLowerCase(),symbol:d,base:s,quote:r,settle:t,baseId:s,quoteId:r,settleId:t,type:o?"spot":"swap",spot:o,margin:!1,swap:!o,future:!1,option:!1,active:"TRADING"===this.safeString(e,"trading_state"),contract:!o,linear:h,inverse:c,taker:n.trading.taker,maker:n.trading.maker,contractSize:o?void 0:1,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(e,"base_increment"),price:this.safeNumber(e,"quote_increment"),cost:this.safeNumber(e,"quote_increment")},limits:{leverage:{min:void 0,max:this.safeNumber(e,"base_imf")},amount:{min:void 0,max:o?void 0:this.safeNumber(e,"position_limit_qty")},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(e,"min_notional_value"),max:void 0}},info:e,created:void 0})}async fetchCurrencies(e={}){let t=await this.v1PublicGetAssets(e);return this.parseCurrencies(t)}parseCurrency(e){let t=this.safeString(e,"asset_name"),i=this.safeCurrencyCode(t),s=this.safeString(e,"status");return this.safeCurrencyStructure({id:t,name:i,code:i,precision:void 0,info:e,active:"ACTIVE"===s,deposit:void 0,withdraw:void 0,networks:void 0,fee:void 0,fees:void 0,limits:this.limits})}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.v1PublicGetInstruments(t),r={},a=[];Array.isArray(s)&&(a=s);for(let e=0;e<a.length;e++){let t=this.safeDict(a,e),i=this.safeString(t,"symbol"),s=this.safeSymbol(i),o=this.safeDict(t,"quote",{});r[s]=this.parseTicker(o,this.safeMarket(i))}return this.filterByArray(r,"symbol",i,!0)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instrument:this.marketId(e)},r=await this.v1PublicGetInstrumentsInstrumentQuote(this.extend(s,t));return this.parseTicker(r,i)}parseTicker(e,t){let i=this.safeString(e,"timestamp");return this.safeTicker({info:e,symbol:this.safeSymbol(void 0,t),timestamp:this.parse8601(i),datetime:i,bid:this.safeNumber(e,"best_bid_price"),bidVolume:this.safeNumber(e,"best_bid_size"),ask:this.safeNumber(e,"best_ask_price"),askVolume:this.safeNumber(e,"best_ask_size"),high:void 0,low:void 0,open:void 0,close:void 0,last:void 0,change:void 0,percentage:void 0,average:void 0,vwap:void 0,baseVolume:void 0,quoteVolume:void 0,previousClose:void 0,markPrice:this.safeNumber(e,"mark_price"),indexPrice:this.safeNumber(e,"index_price")})}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=await this.handlePortfolioAndParams("fetchBalance",e),s=await this.v1PrivateGetPortfoliosPortfolioBalances(this.extend({portfolio:t},i));return this.parseBalance(s)}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"asset_name"),a=this.safeCurrencyCode(r),o=this.account();o.total=this.safeString(s,"quantity"),o.used=this.safeString(s,"hold"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a={asset:this.currency(e).id,amount:t,from:i,to:s},o=await this.v1PrivatePostPortfoliosTransfer(this.extend(a,r)),n=this.safeBool(o,"success");return{info:o,id:void 0,timestamp:void 0,datetime:void 0,currency:e,amount:t,fromAccount:i,toAccount:s,status:!0===n?"ok":"failed"}}async createOrder(e,t,i,s,r,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=t.toUpperCase(),h=this.safeNumberN(o,["triggerPrice","stopPrice","stop_price"]),c=this.safeString(this.options,"brokerId","nfqkvdjp")+"-"+this.uuid();c=c.slice(0,17),this.checkRequiredArgument("createOrder",i,"side");let l={client_order_id:c,side:i.toUpperCase(),instrument:n.id,size:this.amountToPrecision(n.symbol,s)};if(void 0!==h&&(d="limit"===t?"STOP_LIMIT":"STOP",l.stop_price=h),l.type=d,"limit"===t){if(void 0===r)throw new a.InvalidOrder(this.id+" createOrder() requires a price parameter for a limit order types");l.price=r}let[u,f]=await this.handlePortfolioAndParams("createOrder",o);void 0!==u&&(l.portfolio=u);let p=this.safeBool2(f,"postOnly","post_only"),m=this.safeString2(f,"tif","timeInForce");if("MARKET"===d){if(void 0!==m&&"IOC"!==m)throw new a.InvalidOrder(this.id+' createOrder() market orders must have tif set to "IOC"');m="IOC"}else void 0===m&&(m="GTC");void 0!==p&&(l.post_only=p),l.tif=m;let g=this.omit(f,["client_order_id","user","postOnly","timeInForce"]),v=await this.v1PrivatePostOrders(this.extend(l,g));return this.parseOrder(v,n)}parseOrder(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeNumber(e,"fee");void 0!==r&&(i={cost:r});let a=this.safeString2(e,"submit_time","event_time");return this.safeOrder({info:e,id:this.safeString(e,"order_id"),clientOrderId:this.safeString(e,"client_order_id"),timestamp:this.parse8601(a),datetime:a,lastTradeTimestamp:void 0,symbol:this.safeSymbol(s,t),type:this.parseOrderType(this.safeString(e,"type")),timeInForce:this.safeString(e,"tif"),postOnly:void 0,side:this.safeStringLower(e,"side"),price:this.safeString(e,"price"),triggerPrice:this.safeString(e,"stop_price"),amount:this.safeString(e,"size"),filled:this.safeString(e,"exec_qty"),remaining:this.safeString(e,"leaves_qty"),cost:void 0,average:this.safeString(e,"avg_price"),status:this.parseOrderStatus(this.safeString(e,"order_status")),fee:i,trades:void 0},t)}parseOrderStatus(e){return this.safeString({WORKING:"open",NEW:"open",PARTIAL_FILLED:"open",FILLED:"closed",CANCELED:"canceled",REPLACED:"canceled",PENDING_CANCEL:"open",REJECTED:"rejected",PENDING_NEW:"open",EXPIRED:"expired",PENDING_REPLACE:"open"},e,e)}parseOrderType(e){if("UNKNOWN_ORDER_TYPE"!==e)return this.safeString({MARKET:"market",LIMIT:"limit",STOP:"limit",STOP_LIMIT:"limit"},e,e)}async cancelOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let[r,a]=await this.handlePortfolioAndParams("cancelOrder",i);void 0!==t&&(s=this.market(t));let o=await this.v1PrivateDeleteOrdersId(this.extend({portfolio:r,id:e},a));return this.parseOrder(o,s)}async cancelAllOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let[s,r]=await this.handlePortfolioAndParams("cancelAllOrders",t),a={portfolio:s};void 0!==e&&""!==e&&(a.instrument=(i=this.market(e)).id);let o=await this.v1PrivateDeleteOrders(this.extend(a,r));return this.parseOrders(o,i)}async editOrder(e,t,i,s,r,o,n={}){void 0===this.markets&&await this.loadMarkets();let d=this.market(t),h={id:e},[c,l]=await this.handlePortfolioAndParams("editOrder",n);void 0!==c&&(h.portfolio=c),void 0!==r&&(h.size=this.amountToPrecision(t,r)),void 0!==o&&(h.price=this.priceToPrecision(t,o));let u=this.safeNumberN(l,["stopPrice","stop_price","triggerPrice"]);void 0!==u&&(h.stop_price=u);let f=this.safeString2(l,"client_order_id","clientOrderId");if(void 0===f)throw new a.BadRequest(this.id+" editOrder() requires a clientOrderId parameter");h.client_order_id=f;let p=await this.v1PrivatePutOrdersId(this.extend(h,l));return this.parseOrder(p,d)}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let[r,a]=await this.handlePortfolioAndParams("fetchOrder",i),o=await this.v1PrivateGetOrdersId(this.extend({id:e,portfolio:r},a));return this.parseOrder(o,s)}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[o,n]=await this.handlePortfolioAndParams("fetchOpenOrders",s),[d,h]=this.handleOptionBoolAndParams(n,"fetchOpenOrders","paginate",!1),[c,l]=this.handleOptionIntegerAndParams(h,"fetchOpenOrders","maxEntriesPerRequest",100),u="ccxtPageKey";if(d)return await this.fetchPaginatedCallIncremental("fetchOpenOrders",e,t,i,l,u,c);let f=this.safeInteger(l,u,1)-1,p={portfolio:o,result_offset:this.safeInteger2(l,"offset","result_offset",f*c)};if(void 0!==e&&""!==e&&(r=this.market(e),p.instrument=e),void 0!==i){if(i>100)throw new a.BadRequest(this.id+" fetchOpenOrders() maximum limit is 100");p.result_limit=i}void 0!==t&&(p.ref_datetime=this.iso8601(t));let m=await this.v1PrivateGetOrders(this.extend(p,l)),g=this.safeList(m,"results",[]);return this.parseOrders(g,r,t,i)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1),d="ccxtPageKey",[h,c]=this.handleOptionIntegerAndParams(n,"fetchMyTrades","maxEntriesPerRequest",100);if(o)return await this.fetchPaginatedCallIncremental("fetchMyTrades",e,t,i,c,d,h);void 0!==e&&(r=this.market(e));let l=this.safeInteger(c,d,1)-1,u={result_offset:this.safeInteger2(c,"offset","result_offset",l*h)};if(void 0!==i){if(i>100)throw new a.BadRequest(this.id+" fetchMyTrades() maximum limit is 100. Consider setting paginate to true to fetch more trades.");u.result_limit=i}void 0!==t&&(u.time_from=this.iso8601(t));let f=this.safeString(c,"until");void 0!==f&&(u.ref_datetime=this.iso8601(f));let p=void 0!==f?this.omit(c,["until"]):c,m=await this.v1PrivateGetPortfoliosFills(this.extend(u,p)),g=this.safeList(m,"results",[]);return this.parseTrades(g,r,t,i)}async withdraw(e,t,i,s,r={}){let a,o=this.handleWithdrawTagAndParams(s,r)[1];this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),[d,h]=await this.handlePortfolioAndParams("withdraw",o),[c,l]=this.handleOptionStringAndParams(h,"withdraw","method","v1PrivatePostTransfersWithdraw"),[u,f]=await this.handleNetworkIdAndParams(e,"withdraw",l),p={portfolio:d,type:"send",asset:n.id,address:i,amount:t,currency:n.id,network_arn_id:u,nonce:this.nonce()};return a="v1PrivatePostTransfersWithdrawCounterparty"===c?await this.v1PrivatePostTransfersWithdrawCounterparty(this.extend(p,f)):await this.v1PrivatePostTransfersWithdraw(this.extend(p,f)),this.parseTransaction(a,n)}sign(e,t=[],i="GET",r={},o,n){let d,h=this.safeString(t,0),c="private"===this.safeString(t,1),l="/"+h+"/"+this.implodeParams(e,r),u=this.omit(r,this.extractParams(e)),f="/api"+l;("GET"===i||"DELETE"===i)&&Object.keys(u).length>0&&(l+="?"+this.urlencodeWithArrayRepeat(u));let p=this.safeString(this.urls.api,"rest");if(void 0===p)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let m=p+l,g=c&&"GET"!==i&&Object.keys(u).length>0,v="";g&&(v=this.json(u));let y=n;if(g&&(y=v),c){this.checkRequiredCredentials();let e=this.nonce().toString(),t=v,r=this.hmac(this.encode(e+i+f+t),this.base64ToBinary(this.secret),s.sc,"base64");d={"CB-ACCESS-TIMESTAMP":e,"CB-ACCESS-SIGN":r,"CB-ACCESS-PASSPHRASE":this.password,"CB-ACCESS-KEY":this.apiKey}}let b=o;return c&&(b=d),{url:m,method:i,body:y,headers:b}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.id+" "+o,l=this.safeString(n,"title");if(void 0!==l)throw this.throwExactlyMatchedException(this.exceptions.exact,l,c),this.throwBroadlyMatchedException(this.exceptions.broad,l,c),new a.ExchangeError(c)}}i.d(t,{A:()=>n})},2603(e,t,i){"use strict";var s=i(4721),r=i(5936),a=i(1453);class o extends r.A{describe(){return this.deepExtend(super.describe(),{id:"coincheck",name:"Coincheck",countries:["JP","ID"],rateLimit:1500,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchDeposits:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrderBook:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchStatus:!0,fetchTicker:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,ws:!0},urls:{logo:"https://user-images.githubusercontent.com/51840849/87182088-1d6d6380-c2ec-11ea-9c64-8ab9f9b289f5.jpg",api:{rest:"https://coincheck.com/api"},www:"https://coincheck.com",doc:"https://coincheck.com/documents/exchange/api",fees:["https://coincheck.com/exchange/fee","https://coincheck.com/info/fee"]},api:{public:{get:{"exchange/orders/rate":{cost:1},exchange_status:{cost:1},order_books:{cost:1},"rate/{pair}":{cost:1},ticker:{cost:1},trades:{cost:1}}},private:{get:{accounts:{cost:1},"accounts/balance":{cost:1},"accounts/leverage_balance":{cost:1},bank_accounts:{cost:1},deposit_money:{cost:1},"exchange/orders/{id}":{cost:1},"exchange/orders/opens":{cost:1},"exchange/orders/cancel_status":{cost:1},"exchange/orders/transactions":{cost:1},"exchange/orders/transactions_pagination":{cost:1},"exchange/leverage/positions":{cost:1},"lending/borrows/matches":{cost:1},send_money:{cost:1},withdraws:{cost:1}},post:{bank_accounts:{cost:1},"deposit_money/{id}/fast":{cost:1},"exchange/orders":{cost:1},"exchange/transfers/to_leverage":{cost:1},"exchange/transfers/from_leverage":{cost:1},"lending/borrows":{cost:1},"lending/borrows/{id}/repay":{cost:1},send_money:{cost:1},withdraws:{cost:1}},delete:{"bank_accounts/{id}":{cost:1},"exchange/orders/{id}":{cost:1},"withdraws/{id}":{cost:1}}}},markets:{"BTC/JPY":this.safeMarketStructure({id:"btc_jpy",symbol:"BTC/JPY",base:"BTC",quote:"JPY",baseId:"btc",quoteId:"jpy",type:"spot",spot:!0}),"ETC/JPY":this.safeMarketStructure({id:"etc_jpy",symbol:"ETC/JPY",base:"ETC",quote:"JPY",baseId:"etc",quoteId:"jpy",type:"spot",spot:!0}),"FCT/JPY":this.safeMarketStructure({id:"fct_jpy",symbol:"FCT/JPY",base:"FCT",quote:"JPY",baseId:"fct",quoteId:"jpy",type:"spot",spot:!0}),"MONA/JPY":this.safeMarketStructure({id:"mona_jpy",symbol:"MONA/JPY",base:"MONA",quote:"JPY",baseId:"mona",quoteId:"jpy",type:"spot",spot:!0}),"ETC/BTC":this.safeMarketStructure({id:"etc_btc",symbol:"ETC/BTC",base:"ETC",quote:"BTC",baseId:"etc",quoteId:"btc",type:"spot",spot:!0})},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:void 0,daysBack:void 0,untilDays:void 0,symbolRequired:!0},fetchOrder:void 0,fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:void 0},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},fees:{trading:{tierBased:!1,percentage:!0,maker:this.parseNumber("0"),taker:this.parseNumber("0")}},precisionMode:4,exceptions:{exact:{"disabled API Key":a.AuthenticationError,"invalid authentication":a.AuthenticationError},broad:{}}})}parseBalance(e){let t={info:e},i=Object.keys(this.currencies);for(let s=0;s<i.length;s++){let r=i[s],a=this.currency(r).id;if(a in e){let i=this.account(),s=a+"_reserved";i.free=this.safeString(e,a),i.used=this.safeString(e,s),t[r]=i}}return this.safeBalance(t)}async fetchStatus(e={}){let t,i=await this.publicGetExchangeStatus(e),s=this.safeList(i,"exchange_status",[]),r="ok";for(let e=0;e<s.length;e++){let i=this.safeDict(s,e),a=this.safeString(i,"status");void 0===t&&(t=this.safeTimestamp(i,"timestamp")),"available"!==a&&(r="maintenance")}return{status:r,updated:t,eta:void 0,url:void 0,info:i}}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetAccountsBalance(e);return this.parseBalance(t)}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a=await this.privateGetExchangeOrdersOpens(s),o=this.safeList(a,"orders",[]),n=this.parseOrders(o,r,t,i),d=[];for(let e=0;e<n.length;e++)d.push(this.extend(n[e],{status:"open"}));return d}parseOrder(e,t){let i=this.safeString(e,"id"),s=this.safeString(e,"order_type"),r=this.parse8601(this.safeString(e,"created_at")),a=this.safeString(e,"pending_amount"),o=this.safeString(e,"pending_amount"),n=this.safeString(e,"rate"),d=this.safeString(e,"pair"),h=this.safeSymbol(d,t,"_");return this.safeOrder({id:i,clientOrderId:void 0,timestamp:r,datetime:this.iso8601(r),lastTradeTimestamp:void 0,amount:a,remaining:o,filled:void 0,side:s,type:void 0,timeInForce:void 0,postOnly:void 0,status:void 0,symbol:h,price:n,triggerPrice:void 0,cost:void 0,fee:void 0,info:e,average:void 0,trades:void 0},t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={pair:s.id},a=await this.publicGetOrderBooks(this.extend(r,i));return this.parseOrderBook(a,s.symbol)}parseTicker(e,t){let i=this.safeSymbol(void 0,t),s=this.safeTimestamp(e,"timestamp"),r=this.safeString(e,"last");return this.safeTicker({symbol:i,timestamp:s,datetime:this.iso8601(s),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"bid"),bidVolume:void 0,ask:this.safeString(e,"ask"),askVolume:void 0,vwap:void 0,open:void 0,close:r,last:r,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"volume"),quoteVolume:void 0,info:e},t)}async fetchTicker(e,t={}){if("BTC/JPY"!==e)throw new a.BadSymbol(this.id+" fetchTicker() supports BTC/JPY only");void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={pair:i.id},r=await this.publicGetTicker(this.extend(s,t));return this.parseTicker(r,i)}parseTrade(e,t){let i,s,r,a,o,n,d=this.parse8601(this.safeString(e,"created_at")),h=this.safeString(e,"id"),c=this.safeString(e,"rate"),l=this.safeString(e,"pair"),u=this.safeMarket(l,t,"_"),f=u.baseId,p=u.quoteId,m=u.symbol;if("liquidity"in e){"T"===this.safeString(e,"liquidity")?i="taker":"M"===this.safeString(e,"liquidity")&&(i="maker");let t=this.safeDict(e,"funds",{});s=this.safeString(t,f),r=this.safeString(t,p),o={currency:this.safeString(e,"fee_currency"),cost:this.safeString(e,"fee")},a=this.safeString(e,"side"),n=this.safeString(e,"order_id")}else s=this.safeString(e,"amount"),a=this.safeString(e,"order_type");return this.safeTrade({id:h,info:e,datetime:this.iso8601(d),timestamp:d,symbol:m,type:void 0,side:a,order:n,takerOrMaker:i,price:c,amount:s,cost:r,fee:o},u)}async fetchMyTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={};void 0!==i&&(a.limit=i);let o=await this.privateGetExchangeOrdersTransactionsPagination(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTrades(n,r,t,i)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={pair:r.id};void 0!==i&&(a.limit=i);let o=await this.publicGetTrades(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTrades(n,r,t,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetAccounts(e),i=this.safeDict(t,"exchange_fees",{}),s={},r=this.symbols;if(void 0===r)return s;for(let e=0;e<r.length;e++){let t=r[e],a=this.market(t),o=this.safeDict(i,a.id,{});s[t]={info:o,symbol:t,maker:this.safeNumber(o,"maker_fee"),taker:this.safeNumber(o,"taker_fee"),percentage:!0,tierBased:!1}}return s}async createOrder(e,t,i,s,r,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d={pair:n.id};if("market"===t)if(d.order_type=t+"_"+i,"sell"===i)d.amount=s;else{let e=this.safeNumber(o,"cost");if(void 0!==e)throw new a.ArgumentsRequired(this.id+' createOrder() : you should use "cost" parameter instead of "amount" argument to create market buy orders');d.market_buy_amount=e}else d.order_type=i,d.rate=r,d.amount=s;let h=await this.privatePostExchangeOrders(this.extend(d,this.omit(o,"cost"))),c=this.safeString(h,"id");return this.safeOrder({id:c,info:h},n)}async cancelOrder(e,t,i={}){let s=await this.privateDeleteExchangeOrdersId(this.extend({id:e},i));return this.parseOrder(s)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.currency=(r=this.currency(e)).id),void 0!==i&&(a.limit=i);let o=await this.privateGetDepositMoney(this.extend(a,s)),n=this.safeList(o,"deposits",[]);return this.parseTransactions(n,r,t,i,{type:"deposit"})}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.currency(e));let a={};void 0!==i&&(a.limit=i);let o=await this.privateGetWithdraws(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTransactions(n,r,t,i,{type:"withdrawal"})}parseTransactionStatus(e){return this.safeString({pending:"pending",processing:"pending",finished:"ok",canceled:"canceled",confirmed:"pending",received:"ok"},e,e)}parseTransaction(e,t){let i,s=this.safeString(e,"id"),r=this.parse8601(this.safeString(e,"created_at")),a=this.safeString(e,"address"),o=this.safeNumber(e,"amount"),n=this.safeString(e,"currency"),d=this.safeCurrencyCode(n,t),h=this.parseTransactionStatus(this.safeString(e,"status")),c=this.parse8601(this.safeString(e,"confirmed_at")),l=this.safeNumber(e,"fee");return void 0!==l&&(i={cost:l,currency:d}),{info:e,id:s,txid:void 0,timestamp:r,datetime:this.iso8601(r),network:void 0,address:a,addressTo:a,addressFrom:void 0,tag:void 0,tagTo:void 0,tagFrom:void 0,type:void 0,amount:o,currency:d,status:h,updated:c,comment:void 0,internal:void 0,fee:i}}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},o,n){let d,h,c=this.safeString(this.urls.api,"rest");if(void 0===c)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let l=c+"/"+this.implodeParams(e,r),u=this.omit(r,this.extractParams(e));if("public"===t)Object.keys(u).length>0&&(l+="?"+this.urlencode(u));else{this.checkRequiredCredentials();let e=this.nonce().toString(),t="";"GET"===i?Object.keys(u).length>0&&(l+="?"+this.urlencode(this.keysort(u))):Object.keys(u).length>0&&(t=d=this.urlencode(this.keysort(u)));let r=e+l+t;h={"Content-Type":"application/x-www-form-urlencoded","ACCESS-KEY":this.apiKey,"ACCESS-NONCE":e,"ACCESS-SIGNATURE":this.hmac(this.encode(r),this.encode(this.secret),s.sc)}}return{url:l,method:i,body:void 0===d?n:d,headers:void 0===h?o:h}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0!==n&&!0!==this.safeBool(n,"success",!0)){let e=this.safeString(n,"error"),t=this.id+" "+this.json(n);throw this.throwExactlyMatchedException(this.exceptions.exact,e,t),this.throwBroadlyMatchedException(this.exceptions.broad,o,t),new a.ExchangeError(this.id+" "+this.json(n))}}}i.d(t,{A:()=>o})},6494(e,t,i){"use strict";var s=i(4721),r=i(8858),a=i(8451),o=i(1453),n=i(7749);class d extends a.A{describe(){return this.deepExtend(super.describe(),{id:"coinex",name:"CoinEx",version:"v2",countries:["CN"],rateLimit:2.5,pro:!0,certified:!0,has:{CORS:void 0,spot:!0,margin:!0,swap:!0,future:!1,option:!1,addMargin:!0,borrowCrossMargin:!1,borrowIsolatedMargin:!0,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!1,closePosition:!0,createDepositAddress:!0,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createReduceOnlyOrder:!0,createStopLossOrder:!0,createStopOrder:!0,createTakeProfitOrder:!0,createTriggerOrder:!0,editOrder:!0,editOrders:!0,fetchBalance:!0,fetchBorrowInterest:!0,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositWithdrawFee:!0,fetchDepositWithdrawFees:!0,fetchFundingHistory:!0,fetchFundingInterval:!0,fetchFundingIntervals:!1,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!0,fetchIsolatedBorrowRates:!1,fetchLeverage:!0,fetchLeverages:!1,fetchLeverageTiers:!0,fetchMarginAdjustmentHistory:!0,fetchMarketLeverageTiers:"emulated",fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrdersByStatus:!0,fetchPosition:!0,fetchPositionHistory:!0,fetchPositions:!0,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTransfer:!1,fetchTransfers:!0,fetchWithdrawal:!1,fetchWithdrawals:!0,reduceMargin:!0,repayCrossMargin:!1,repayIsolatedMargin:!0,setLeverage:!0,setMarginMode:!0,setPositionMode:!1,transfer:!0,withdraw:!0},timeframes:{"1m":"1min","3m":"3min","5m":"5min","15m":"15min","30m":"30min","1h":"1hour","2h":"2hour","4h":"4hour","6h":"6hour","12h":"12hour","1d":"1day","3d":"3day","1w":"1week"},urls:{logo:"https://user-images.githubusercontent.com/51840849/87182089-1e05fa00-c2ec-11ea-8da9-cc73b45abbbc.jpg",api:{public:"https://api.coinex.com",private:"https://api.coinex.com",perpetualPublic:"https://api.coinex.com/perpetual",perpetualPrivate:"https://api.coinex.com/perpetual"},www:"https://www.coinex.com",doc:"https://docs.coinex.com/api/v2",fees:"https://www.coinex.com/fees",referral:"https://www.coinex.com/register?refer_code=yw5fz"},api:{v1:{public:{get:{"amm/market":{cost:1},"common/currency/rate":{cost:1},"common/asset/config":{cost:1},"common/maintain/info":{cost:1},"common/temp-maintain/info":{cost:1},"margin/market":{cost:1},"market/info":{cost:1},"market/list":{cost:1},"market/ticker":{cost:1},"market/ticker/all":{cost:1},"market/depth":{cost:1},"market/deals":{cost:1},"market/kline":{cost:1},"market/detail":{cost:1}}},private:{get:{"account/amm/balance":{cost:40},"account/investment/balance":{cost:40},"account/balance/history":{cost:40},"account/market/fee":{cost:40},"balance/coin/deposit":{cost:40},"balance/coin/withdraw":{cost:40},"balance/info":{cost:40},"balance/deposit/address/{coin_type}":{cost:40},"contract/transfer/history":{cost:40},"credit/info":{cost:40},"credit/balance":{cost:40},"investment/transfer/history":{cost:40},"margin/account":{cost:1},"margin/config":{cost:1},"margin/loan/history":{cost:40},"margin/transfer/history":{cost:40},"order/deals":{cost:40},"order/finished":{cost:40},"order/pending":{cost:8},"order/status":{cost:8},"order/status/batch":{cost:8},"order/user/deals":{cost:40},"order/stop/finished":{cost:40},"order/stop/pending":{cost:8},"order/user/trade/fee":{cost:1},"order/market/trade/info":{cost:1},"sub_account/balance":{cost:1},"sub_account/transfer/history":{cost:40},"sub_account/auth/api":{cost:40},"sub_account/auth/api/{user_auth_id}":{cost:40}},post:{"balance/coin/withdraw":{cost:40},"contract/balance/transfer":{cost:40},"margin/flat":{cost:40},"margin/loan":{cost:40},"margin/transfer":{cost:40},"order/limit/batch":{cost:40},"order/ioc":{cost:13.334},"order/limit":{cost:13.334},"order/market":{cost:13.334},"order/modify":{cost:13.334},"order/stop/limit":{cost:13.334},"order/stop/market":{cost:13.334},"order/stop/modify":{cost:13.334},"sub_account/transfer":{cost:40},"sub_account/register":{cost:1},"sub_account/unfrozen":{cost:40},"sub_account/frozen":{cost:40},"sub_account/auth/api":{cost:40}},put:{"balance/deposit/address/{coin_type}":{cost:40},"sub_account/unfrozen":{cost:40},"sub_account/frozen":{cost:40},"sub_account/auth/api/{user_auth_id}":{cost:40},"v1/account/settings":{cost:40}},delete:{"balance/coin/withdraw":{cost:40},"order/pending/batch":{cost:40},"order/pending":{cost:13.334},"order/stop/pending":{cost:40},"order/stop/pending/{id}":{cost:13.334},"order/pending/by_client_id":{cost:40},"order/stop/pending/by_client_id":{cost:40},"sub_account/auth/api/{user_auth_id}":{cost:40},"sub_account/authorize/{id}":{cost:40}}},perpetualPublic:{get:{ping:{cost:1},time:{cost:1},"market/list":{cost:1},"market/limit_config":{cost:1},"market/ticker":{cost:1},"market/ticker/all":{cost:1},"market/depth":{cost:1},"market/deals":{cost:1},"market/funding_history":{cost:1},"market/kline":{cost:1}}},perpetualPrivate:{get:{"market/user_deals":{cost:1},"asset/query":{cost:40},"order/pending":{cost:8},"order/finished":{cost:40},"order/stop_finished":{cost:40},"order/stop_pending":{cost:8},"order/status":{cost:8},"order/stop_status":{cost:8},"position/finished":{cost:40},"position/pending":{cost:40},"position/funding":{cost:40},"position/adl_history":{cost:40},"market/preference":{cost:40},"position/margin_history":{cost:40},"position/settle_history":{cost:40}},post:{"market/adjust_leverage":{cost:1},"market/position_expect":{cost:1},"order/put_limit":{cost:20},"order/put_market":{cost:20},"order/put_stop_limit":{cost:20},"order/put_stop_market":{cost:20},"order/modify":{cost:20},"order/modify_stop":{cost:20},"order/cancel":{cost:20},"order/cancel_all":{cost:40},"order/cancel_batch":{cost:40},"order/cancel_stop":{cost:20},"order/cancel_stop_all":{cost:40},"order/close_limit":{cost:20},"order/close_market":{cost:20},"position/adjust_margin":{cost:20},"position/stop_loss":{cost:20},"position/take_profit":{cost:20},"position/market_close":{cost:20},"order/cancel/by_client_id":{cost:20},"order/cancel_stop/by_client_id":{cost:20},"market/preference":{cost:20}}}},v2:{public:{get:{"maintain/info":{cost:1},ping:{cost:1},time:{cost:1},"spot/market":{cost:1},"spot/ticker":{cost:1},"spot/depth":{cost:1},"spot/deals":{cost:1},"spot/kline":{cost:1},"spot/index":{cost:1},"futures/market":{cost:1},"futures/ticker":{cost:1},"futures/depth":{cost:1},"futures/deals":{cost:1},"futures/kline":{cost:1},"futures/index":{cost:1},"futures/funding-rate":{cost:1},"futures/funding-rate-history":{cost:1},"futures/premium-index-history":{cost:1},"futures/position-level":{cost:1},"futures/liquidation-history":{cost:1},"futures/basis-history":{cost:1},"assets/deposit-withdraw-config":{cost:1},"assets/all-deposit-withdraw-config":{cost:1},"assets/info":{cost:1}}},private:{get:{"account/subs":{cost:1},"account/subs/api-detail":{cost:40},"account/subs/info":{cost:1},"account/subs/api":{cost:40},"account/subs/transfer-history":{cost:40},"account/subs/balance":{cost:1},"account/subs/spot-balance":{cost:1},"account/trade-fee-rate":{cost:40},"account/futures-market-settings":{cost:1},"account/info":{cost:1},"assets/spot/balance":{cost:40},"assets/futures/balance":{cost:40},"assets/margin/balance":{cost:1},"assets/financial/balance":{cost:40},"assets/amm/liquidity":{cost:40},"assets/credit/info":{cost:40},"assets/spot/transcation-history":{cost:1},"assets/margin/borrow-history":{cost:40},"assets/margin/interest-limit":{cost:1},"assets/deposit-address":{cost:40},"assets/deposit-history":{cost:40},"assets/withdraw":{cost:40},"assets/transfer-history":{cost:40},"assets/amm/liquidity-pool":{cost:40},"assets/amm/income-history":{cost:40},"spot/order-status":{cost:8},"spot/batch-order-status":{cost:8},"spot/pending-order":{cost:8},"spot/finished-order":{cost:40},"spot/pending-stop-order":{cost:8},"spot/finished-stop-order":{cost:40},"spot/user-deals":{cost:40},"spot/order-deals":{cost:40},"futures/order-status":{cost:8},"futures/batch-order-status":{cost:1},"futures/pending-order":{cost:8},"futures/finished-order":{cost:40},"futures/pending-stop-order":{cost:8},"futures/finished-stop-order":{cost:40},"futures/user-deals":{cost:1},"futures/order-deals":{cost:1},"futures/pending-position":{cost:40},"futures/finished-position":{cost:1},"futures/position-margin-history":{cost:1},"futures/position-funding-history":{cost:40},"futures/position-adl-history":{cost:1},"futures/position-settle-history":{cost:1},"refer/referee":{cost:1},"refer/referee-rebate/record":{cost:1},"refer/referee-rebate/detail":{cost:1},"refer/agent-referee":{cost:1},"refer/agent-rebate/record":{cost:1},"refer/agent-rebate/detail":{cost:1}},post:{"account/subs":{cost:40},"account/subs/frozen":{cost:40},"account/subs/unfrozen":{cost:40},"account/subs/api":{cost:40},"account/subs/edit-api":{cost:40},"account/subs/delete-api":{cost:40},"account/subs/transfer":{cost:40},"account/settings":{cost:40},"account/futures-market-settings":{cost:40},"assets/margin/borrow":{cost:40},"assets/margin/repay":{cost:40},"assets/renewal-deposit-address":{cost:40},"assets/withdraw":{cost:40},"assets/cancel-withdraw":{cost:40},"assets/transfer":{cost:40},"assets/amm/add-liquidity":{cost:1},"assets/amm/remove-liquidity":{cost:1},"spot/order":{cost:13.334},"spot/stop-order":{cost:13.334},"spot/batch-order":{cost:40},"spot/batch-stop-order":{cost:1},"spot/modify-order":{cost:13.334},"spot/modify-stop-order":{cost:13.334},"spot/batch-modify-order":{cost:13.334},"spot/cancel-all-order":{cost:1},"spot/cancel-order":{cost:6.667},"spot/cancel-stop-order":{cost:6.667},"spot/cancel-batch-order":{cost:10},"spot/cancel-batch-stop-order":{cost:10},"spot/cancel-order-by-client-id":{cost:1},"spot/cancel-stop-order-by-client-id":{cost:1},"futures/order":{cost:20},"futures/stop-order":{cost:20},"futures/batch-order":{cost:1},"futures/batch-stop-order":{cost:1},"futures/cancel-position-stop-loss":{cost:20},"futures/cancel-position-take-profit":{cost:20},"futures/modify-order":{cost:20},"futures/modify-stop-order":{cost:20},"futures/batch-modify-order":{cost:20},"futures/cancel-all-order":{cost:1},"futures/cancel-order":{cost:10},"futures/cancel-stop-order":{cost:10},"futures/cancel-batch-order":{cost:20},"futures/cancel-batch-stop-order":{cost:20},"futures/cancel-order-by-client-id":{cost:1},"futures/cancel-stop-order-by-client-id":{cost:1},"futures/close-position":{cost:20},"futures/adjust-position-margin":{cost:20},"futures/adjust-position-leverage":{cost:20},"futures/set-position-stop-loss":{cost:20},"futures/set-position-take-profit":{cost:20},"futures/modify-position-stop-loss":{cost:20},"futures/modify-position-take-profit":{cost:20}}}}},fees:{trading:{maker:.001,taker:.001},funding:{withdraw:{BCH:0,BTC:.001,LTC:.001,ETH:.001,ZEC:1e-4,DASH:1e-4}}},limits:{amount:{min:.001,max:void 0}},options:{brokerId:"x-167673045",createMarketBuyOrderRequiresPrice:!0,defaultType:"spot",defaultSubType:"linear",fetchDepositAddress:{fillResponseFromRequest:!0},accountsByType:{spot:"SPOT",margin:"MARGIN",swap:"FUTURES"},accountsById:{SPOT:"spot",MARGIN:"margin",FUTURES:"swap"},networks:{BTC:"BTC",BEP20:"BSC",TRC20:"TRC20",ERC20:"ERC20",BRC20:"BRC20",SOL:"SOL",TON:"TON",BSV:"BSV",AVAXC:"AVA_C",AVAXX:"AVA",SUI:"SUI",ACA:"ACA",CHZ:"CHILIZ",ADA:"ADA",ARBITRUM:"ARBITRUM",ARBITRUM_NOVA:"ARBITRUM_NOVA",OP:"OPTIMISM",APT:"APTOS",ATOM:"ATOM",FTM:"FTM",BCH:"BCH",ASTR:"ASTR",LTC:"LTC",MATIC:"MATIC",CRONOS:"CRONOS",DASH:"DASH",DOT:"DOT",ETC:"ETC",ETHW:"ETHPOW",FIL:"FIL",ZIL:"ZIL",DOGE:"DOGE",TIA:"CELESTIA",SEI:"SEI",XRP:"XRP",XMR:"XMR"}},features:{spot:{sandbox:!1,createOrder:{marginMode:!0,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!0,selfTradePrevention:!0,iceberg:!0},createOrders:{max:5},fetchMyTrades:{marginMode:!0,limit:1e3,daysBack:void 0,untilDays:1e5,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!0,limit:1e3,trigger:!0,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!0,limit:1e3,daysBack:void 0,daysBackCanceled:void 0,untilDays:void 0,trigger:!0,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:1e3}},forDerivatives:{extends:"spot",createOrder:{marginMode:!0,stopLossPrice:!0,takeProfitPrice:!0},fetchOpenOrders:{marginMode:!1},fetchClosedOrders:{marginMode:!1}},swap:{linear:{extends:"forDerivatives"},inverse:{extends:"forDerivatives"}},future:{linear:void 0,inverse:void 0}},commonCurrencies:{ACM:"Actinium"},precisionMode:4,exceptions:{exact:{23:o.PermissionDenied,24:o.AuthenticationError,25:o.AuthenticationError,34:o.AuthenticationError,35:o.ExchangeNotAvailable,36:o.RequestTimeout,213:o.RateLimitExceeded,107:o.InsufficientFunds,158:o.PermissionDenied,600:o.OrderNotFound,601:o.InvalidOrder,602:o.InvalidOrder,606:o.InvalidOrder,3008:o.RequestTimeout,3109:o.InsufficientFunds,3127:o.InvalidOrder,3157:o.BadSymbol,3600:o.OrderNotFound,3606:o.InvalidOrder,3610:o.ExchangeError,3612:o.InvalidOrder,3613:o.InvalidOrder,3614:o.InvalidOrder,3615:o.InvalidOrder,3616:o.InvalidOrder,3617:o.InvalidOrder,3618:o.InvalidOrder,3619:o.InvalidOrder,3620:o.InvalidOrder,3621:o.InvalidOrder,3622:o.InvalidOrder,3627:o.InvalidOrder,3628:o.InvalidOrder,3629:o.InvalidOrder,3632:o.InvalidOrder,3633:o.InvalidOrder,3634:o.InvalidOrder,3635:o.InvalidOrder,4001:o.ExchangeNotAvailable,4002:o.RequestTimeout,4003:o.ExchangeError,4004:o.BadRequest,4005:o.AuthenticationError,4006:o.AuthenticationError,4007:o.PermissionDenied,4008:o.AuthenticationError,4009:o.ExchangeError,4010:o.ExchangeError,4011:o.PermissionDenied,4017:o.ExchangeError,4115:o.AccountSuspended,4117:o.BadSymbol,4123:o.RateLimitExceeded,4130:o.ExchangeError,4158:o.ExchangeError,4213:o.RateLimitExceeded,4512:o.PermissionDenied},broad:{"ip not allow visit":o.PermissionDenied,"service too busy":o.ExchangeNotAvailable,"Service is not available during funding fee settlement":o.OperationFailed}},rollingWindowSize:1e3})}async fetchCurrencies(e={}){let t=await this.v2PublicGetAssetsAllDepositWithdrawConfig(e),i=this.safeList(t,"data",[]);return this.parseCurrencies(i)}parseCurrency(e){let t=this.safeDict(e,"asset",{}),i=this.safeString(t,"ccy"),s=this.safeList(e,"chains",[]),r=this.safeCurrencyCode(i),a={};for(let e=0;e<s.length;e++){let t=s[e],i=this.safeString(t,"chain"),o=this.networkIdToCode(i,r);if(void 0===i)continue;let n={id:i,network:o,name:void 0,active:void 0,deposit:this.safeBool(t,"deposit_enabled"),withdraw:this.safeBool(t,"withdraw_enabled"),fee:this.safeNumber(t,"withdrawal_fee"),precision:this.parseNumber(this.parsePrecision(this.safeString(t,"withdrawal_precision"))),limits:{amount:{min:void 0,max:void 0},deposit:{min:this.safeNumber(t,"min_deposit_amount"),max:void 0},withdraw:{min:this.safeNumber(t,"min_withdraw_amount"),max:void 0}},info:t};void 0!==o&&(a[o]=n)}return this.safeCurrencyStructure({id:i,code:r,name:void 0,active:void 0,deposit:this.safeBool(t,"deposit_enabled"),withdraw:this.safeBool(t,"withdraw_enabled"),fee:void 0,precision:void 0,limits:{amount:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}},networks:a,type:"crypto",info:e})}async fetchMarkets(e={}){let t=[this.fetchSpotMarkets(e),this.fetchContractMarkets(e)],i=await Promise.all(t),s=i[0],r=i[1];return this.arrayConcat(s,r)}async fetchSpotMarkets(e){let t=await this.v2PublicGetSpotMarket(e),i=this.safeList(t,"data",[]),s=[];for(let e=0;e<i.length;e++){let t=i[e],r=this.safeString(t,"market"),a=this.safeString(t,"base_ccy"),o=this.safeString(t,"quote_ccy"),n=this.safeCurrencyCode(a),d=this.safeCurrencyCode(o);if(void 0===n||void 0===d)continue;let h=n+"/"+d;s.push({id:r,symbol:h,base:n,quote:d,settle:void 0,baseId:a,quoteId:o,settleId:void 0,type:"spot",spot:!0,margin:this.safeBool(t,"is_margin_available"),swap:!1,future:!1,option:!1,active:this.safeBool(t,"is_api_trading_available"),contract:!1,linear:void 0,inverse:void 0,taker:this.safeNumber(t,"taker_fee_rate"),maker:this.safeNumber(t,"maker_fee_rate"),contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(t,"base_ccy_precision"))),price:this.parseNumber(this.parsePrecision(this.safeString(t,"quote_ccy_precision")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(t,"min_amount"),max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:t})}return s}async fetchContractMarkets(e){let t=await this.v2PublicGetFuturesMarket(e),i=this.safeList(t,"data",[]),s=[];for(let e=0;e<i.length;e++){let t=i[e],r=this.fees,a=this.safeList(t,"leverage",[]),o=this.safeString(t,"contract_type"),n="linear"===o,d="inverse"===o,h=this.safeString(t,"market"),c=this.safeString(t,"base_ccy"),l=this.safeString(t,"quote_ccy"),u=this.safeCurrencyCode(c),f=this.safeCurrencyCode(l);if(void 0===u||void 0===f)continue;let p=c;"linear"===o&&(p="USDT");let m=this.safeCurrencyCode(p),g=u+"/"+f+":"+m,v=a.length;s.push({id:h,symbol:g,base:u,quote:f,settle:m,baseId:c,quoteId:l,settleId:p,type:"swap",spot:!1,margin:!1,swap:!0,future:!1,option:!1,active:void 0,contract:!0,linear:n,inverse:d,taker:r.trading.taker,maker:r.trading.maker,contractSize:this.parseNumber("1"),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(t,"base_ccy_precision"))),price:this.parseNumber(this.parsePrecision(this.safeString(t,"quote_ccy_precision")))},limits:{leverage:{min:this.safeNumber(a,0),max:this.safeNumber(a,v-1)},amount:{min:this.safeNumber(t,"min_amount"),max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:t})}return s}parseTicker(e,t){let i="mark_price"in e?"swap":"spot",s=this.safeString(e,"market"),r=this.safeMarket(s,t,void 0,i),a=r.symbol,o=!0===r.inverse?void 0:this.safeString(e,"value");return this.safeTicker({symbol:a,timestamp:void 0,datetime:void 0,high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:void 0,bidVolume:this.safeString(e,"volume_buy"),ask:void 0,askVolume:this.safeString(e,"volume_sell"),vwap:void 0,open:this.safeString(e,"open"),close:this.safeString(e,"close"),last:this.safeString(e,"last"),previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"volume"),quoteVolume:o,markPrice:this.safeString(e,"mark_price"),indexPrice:this.safeString(e,"index_price"),info:e},r)}async fetchTicker(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={market:s.id};i=!0===s.swap?await this.v2PublicGetFuturesTicker(this.extend(r,t)):await this.v2PublicGetSpotTicker(this.extend(r,t));let a=this.safeList(i,"data",[]),o=this.safeDict(a,0,{});return this.parseTicker(o,s)}async fetchTickers(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e);if(void 0!==r){let e=this.safeString(r,0);i=this.market(e)}let[a,o]=this.handleMarketTypeAndParams("fetchTickers",i,t);s="swap"===a?await this.v2PublicGetFuturesTicker(o):await this.v2PublicGetSpotTicker(o);let n=this.safeList(s,"data",[]);return this.parseTickers(n,r)}async fetchTime(e={}){let t=await this.v2PublicGetTime(e),i=this.safeDict(t,"data",{});return this.safeInteger(i,"timestamp")}async fetchOrderBook(e,t=20,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=t;void 0===a&&(a=20);let o={market:r.id,limit:a,interval:"0"};s=!0===r.swap?await this.v2PublicGetFuturesDepth(this.extend(o,i)):await this.v2PublicGetSpotDepth(this.extend(o,i));let n=this.safeDict(s,"data",{}),d=this.safeDict(n,"depth",{}),h=this.safeInteger(d,"updated_at");return this.parseOrderBook(d,e,h)}parseTrade(e,t){let i,s=this.safeInteger(e,"created_at"),r=this.safeString(this.options,"defaultType");void 0!==t&&(r=this.safeString(t,"type"));let a=this.safeString(e,"market"),o=this.safeMarket(a,t,void 0,r),n=this.safeString(e,"fee");if(void 0!==n){let t=this.safeString(e,"fee_ccy");i={cost:n,currency:this.safeCurrencyCode(t)}}return this.safeTrade({info:e,timestamp:s,datetime:this.iso8601(s),symbol:o.symbol,id:this.safeString(e,"deal_id"),order:this.safeString(e,"order_id"),type:void 0,side:this.safeString(e,"side"),takerOrMaker:this.safeString(e,"role"),price:this.safeString(e,"price"),amount:this.safeString(e,"amount"),cost:this.safeString(e,"deal_money"),fee:i},o)}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={market:a.id};return void 0!==i&&(o.limit=Math.min(i,1e3)),r=!0===a.swap?await this.v2PublicGetFuturesDeals(this.extend(o,s)):await this.v2PublicGetSpotDeals(this.extend(o,s)),this.parseTrades(r.data,a,t,i)}async fetchTradingFee(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={market:s.id};i=!0===s.spot?await this.v2PublicGetSpotMarket(this.extend(r,t)):await this.v2PublicGetFuturesMarket(this.extend(r,t));let a=this.safeList(i,"data",[]),o=this.safeDict(a,0,{});return this.parseTradingFee(o,s)}async fetchTradingFees(e={}){let t;void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleMarketTypeAndParams("fetchTradingFees",void 0,e);t="swap"===i?await this.v2PublicGetFuturesMarket(s):await this.v2PublicGetSpotMarket(s);let r=this.safeList(t,"data",[]),a={};for(let e=0;e<r.length;e++){let t=r[e],s=this.safeString(t,"market"),o=this.safeMarket(s,void 0,void 0,i);a[o.symbol]=this.parseTradingFee(t,o)}return a}parseTradingFee(e,t){let i=this.safeString(e,"market");return{info:e,symbol:this.safeSymbol(i,t),maker:this.safeNumber(e,"maker_fee_rate"),taker:this.safeNumber(e,"taker_fee_rate"),percentage:!0,tierBased:!0}}parseOHLCV(e,t){return[this.safeInteger(e,"created_at"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"value")]}async fetchOHLCV(e,t="1m",i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={market:o.id,period:this.safeString(this.timeframes,t,t)};void 0!==s&&(n.limit=s),a=!0===o.swap?await this.v2PublicGetFuturesKline(this.extend(n,r)):await this.v2PublicGetSpotKline(this.extend(n,r));let d=this.safeList(a,"data",[]);return this.parseOHLCVs(d,o,t,i,s)}async fetchMarginBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v2PrivateGetAssetsMarginBalance(e),i={info:t},s=this.safeList(t,"data",[]);for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),r=this.safeDict(t,"available",{}),a=this.safeDict(t,"frozen",{}),o=this.safeDict(t,"repaid",{}),d=this.safeDict(t,"interest",{}),h=this.account(),c=this.safeString(t,"base_ccy"),l=this.safeCurrencyCode(c);h.free=this.safeString(r,"base_ccy"),h.used=this.safeString(a,"base_ccy");let u=this.safeString(o,"base_ccy"),f=this.safeString(d,"base_ccy");h.debt=n.Y.stringAdd(u,f),void 0!==l&&(i[l]=h)}return this.safeBalance(i)}async fetchSpotBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v2PrivateGetAssetsSpotBalance(e),i={info:t},s=this.safeList(t,"data",[]);for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),r=this.safeString(t,"ccy"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(t,"available"),o.used=this.safeString(t,"frozen"),void 0!==a&&(i[a]=o)}return this.safeBalance(i)}async fetchSwapBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v2PrivateGetAssetsFuturesBalance(e),i={info:t},s=this.safeList(t,"data",[]);for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),r=this.safeString(t,"ccy"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(t,"available"),o.used=this.safeString(t,"frozen"),void 0!==a&&(i[a]=o)}return this.safeBalance(i)}async fetchFinancialBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v2PrivateGetAssetsFinancialBalance(e),i={info:t},s=this.safeList(t,"data",[]);for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),r=this.safeString(t,"ccy"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(t,"available"),o.used=this.safeString(t,"frozen"),void 0!==a&&(i[a]=o)}return this.safeBalance(i)}async fetchBalance(e={}){let[t,i]=this.handleMarketTypeAndParams("fetchBalance",void 0,e),[s,r]=this.handleMarginModeAndParams("fetchBalance",i);return"swap"===t?await this.fetchSwapBalance(r):"financial"===t?await this.fetchFinancialBalance(r):void 0!==s||"margin"===t?await this.fetchMarginBalance(r):await this.fetchSpotBalance(r)}parseOrderStatus(e){return this.safeString({rejected:"rejected",open:"open",not_deal:"open",part_deal:"open",done:"closed",cancel:"canceled"},e,e)}parseOrder(e,t){let i=this.safeString(e,"status"),s=this.safeInteger(e,"created_at"),r=this.safeInteger(e,"updated_at");0===r&&(r=s);let a=this.safeString(e,"market"),o=this.safeString(this.options,"defaultType"),n=this.safeStringLower(e,"market_type",o);"futures"===n&&(n="swap");let d="spot";"swap"===n&&(d="swap");let h=this.safeMarket(a,t,void 0,d),c=this.safeString(e,"fee_ccy"),l=this.safeCurrencyCode(c);void 0===l&&(l=this.safeString(h,"quote"));let u=this.safeString(e,"side");"long"===u?u="buy":"short"===u&&(u="sell");let f=this.safeString(e,"client_id");return""===f&&(f=void 0),this.safeOrder({id:this.safeStringN(e,["position_id","order_id","stop_id"]),clientOrderId:f,datetime:this.iso8601(s),timestamp:s,lastTradeTimestamp:r,status:this.parseOrderStatus(i),symbol:h.symbol,type:this.safeString(e,"type"),timeInForce:void 0,postOnly:void 0,reduceOnly:void 0,side:u,price:this.safeString(e,"price"),triggerPrice:this.safeString(e,"trigger_price"),takeProfitPrice:this.safeNumber(e,"take_profit_price"),stopLossPrice:this.safeNumber(e,"stop_loss_price"),cost:this.safeString(e,"filled_value"),average:this.safeString(e,"avg_entry_price"),amount:this.safeString(e,"amount"),filled:this.safeString(e,"filled_amount"),remaining:this.safeString(e,"unfilled_amount"),trades:void 0,fee:{currency:l,cost:this.safeString2(e,"quote_fee","fee")},info:e},h)}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new o.NotSupported(this.id+" createMarketBuyOrderWithCost() supports spot orders only");return i.createMarketBuyOrderRequiresPrice=!1,await this.createOrder(e,"market","buy",t,void 0,i)}createOrderRequest(e,t,i,s,r,a={}){let d;if(void 0===t)throw new o.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new o.ArgumentsRequired(this.id+" requires a side argument");let h=this.market(e),c=h.swap,l=this.safeString2(a,"client_id","clientOrderId"),u=this.safeString2(a,"stopPrice","triggerPrice"),f=this.safeString(a,"stopLossPrice"),p=this.safeString(a,"takeProfitPrice"),m=this.safeString(a,"option"),g="market"===t,v=this.isPostOnly(g,"maker_only"===m,a),y=this.safeStringUpper(a,"timeInForce"),b=this.safeBool(a,"reduceOnly");if(!0===b&&!0!==h.swap)throw new o.InvalidOrder(this.id+" createOrder() does not support reduceOnly for "+h.type+" orders, reduceOnly orders are supported for swap markets only");let w={market:h.id};if(void 0===l?w.client_id=this.safeString(this.options,"brokerId","x-167673045")+"-"+this.uuid16():w.client_id=l,void 0===f&&void 0===p){!0!==b&&(w.side=i);let s=t;v?s="maker_only":void 0!==y&&("IOC"===y?s="ioc":"FOK"===y&&(s="fok")),g||(w.price=this.priceToPrecision(e,r)),w.type=s}let k=["reduceOnly","timeInForce","postOnly","stopPrice","triggerPrice","stopLossPrice","takeProfitPrice"];if(!0===c)d=this.omit(a,k),w.market_type="FUTURES",void 0!==f&&""!==f||void 0!==p&&""!==p?void 0!==f&&""!==f?(w.stop_loss_price=this.priceToPrecision(e,f),w.stop_loss_type=this.safeString(a,"stop_type","latest_price")):void 0!==p&&""!==p&&(w.take_profit_price=this.priceToPrecision(e,p),w.take_profit_type=this.safeString(a,"stop_type","latest_price")):(w.amount=this.amountToPrecision(e,s),void 0!==u&&(w.trigger_price=this.priceToPrecision(e,u),w.trigger_price_type=this.safeString(a,"stop_type","latest_price")));else{let[h,c]=this.handleMarginModeAndParams("createOrder",a);void 0!==h?w.market_type="MARGIN":w.market_type="SPOT";let l="market"===t&&"buy"===i,f=this.handleOptionBoolAndParams(c,"createOrder","createMarketBuyOrderRequiresPrice",!0),p=this.safeNumber(f[1],"cost"),m=c;if(l&&(m=this.omit(f[1],"cost")),d=this.omit(m,k),l)if(f[0])if(void 0===r&&void 0===p)throw new o.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument");else{let t=this.numberToString(s),i=this.numberToString(r),a=this.parseToNumeric(n.Y.stringMul(t,i));w.amount=this.costToPrecision(e,void 0!==p?p:a)}else w.amount=this.costToPrecision(e,s);else w.amount=this.amountToPrecision(e,s);void 0!==u&&(w.trigger_price=this.priceToPrecision(e,u))}return this.extend(w,d)}async createOrder(e,t,i,s,r,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=this.safeBool(a,"reduceOnly"),h=this.safeString2(a,"stopPrice","triggerPrice"),c=this.safeString(a,"stopLossPrice"),l=this.safeString(a,"takeProfitPrice"),u=void 0!==h,f=void 0!==c,p=void 0!==l,m=this.createOrderRequest(e,t,i,s,r,a);!0===n.spot?o=u?await this.v2PrivatePostSpotStopOrder(m):await this.v2PrivatePostSpotOrder(m):u?o=await this.v2PrivatePostFuturesStopOrder(m):f||p?f?o=await this.v2PrivatePostFuturesSetPositionStopLoss(m):p&&(o=await this.v2PrivatePostFuturesSetPositionTakeProfit(m)):o=!0===d?await this.v2PrivatePostFuturesClosePosition(m):await this.v2PrivatePostFuturesOrder(m);let g=this.safeDict(o,"data",{});return this.parseOrder(g,n)}async createOrders(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=[],a=!1,n=!1,d=!1;for(let t=0;t<e.length;t++){let s=this.safeDict(e,t),h=this.safeString(s,"symbol");if(void 0===i)i=h;else if(i!==h)throw new o.BadRequest(this.id+" createOrders() requires all orders to have the same symbol");let c=this.safeString(s,"type"),l=this.safeString(s,"side"),u=this.safeNumber(s,"amount"),f=this.safeNumber(s,"price"),p=this.safeDict(s,"params",{});if("limit"!==c)throw new o.NotSupported(this.id+" createOrders() does not support "+c+" orders, only limit orders are accepted");a=this.safeValue(p,"reduceOnly");let m=this.safeNumber2(p,"stopPrice","triggerPrice"),g=this.safeNumber(p,"stopLossPrice"),v=this.safeNumber(p,"takeProfitPrice");n=void 0!==m;let y=void 0!==v;d=void 0!==g||y;let b=this.createOrderRequest(h,c,l,u,f,p);r.push(b)}let h=this.market(i),c={market:h.id,orders:r};if(!0===h.spot)s=n?await this.v2PrivatePostSpotBatchStopOrder(c):await this.v2PrivatePostSpotBatchOrder(c);else if(n)s=await this.v2PrivatePostFuturesBatchStopOrder(c);else if(d)throw new o.NotSupported(this.id+" createOrders() does not support stopLossPrice or takeProfitPrice orders");else if(a)throw new o.NotSupported(this.id+" createOrders() does not support reduceOnly orders");else s=await this.v2PrivatePostFuturesBatchOrder(c);let l=this.safeList(s,"data",[]),u=[];for(let e=0;e<l.length;e++){let t,i,s=l[e],r=this.safeInteger(s,"code");void 0!==r&&(i=0!==r?"rejected":"open");let a=this.safeDict(s,"data",{});!0!==h.spot||n?(a.status=i,t=this.parseOrder(a,h)):(s.status=i,t=this.parseOrder(s,h)),u.push(t)}return u}async cancelOrders(e,t,i={}){let s;if(void 0===t)throw new o.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),a={market:r.id},n=this.safeBool2(i,"stop","trigger"),d=this.omit(i,["stop","trigger"]),h=[];for(let t=0;t<e.length;t++)h.push(parseInt(e[t]));!0===n?a.stop_ids=h:a.order_ids=h,!0===r.spot?s=!0===n?await this.v2PrivatePostSpotCancelBatchStopOrder(this.extend(a,d)):await this.v2PrivatePostSpotCancelBatchOrder(this.extend(a,d)):(a.market_type="FUTURES",s=!0===n?await this.v2PrivatePostFuturesCancelBatchStopOrder(this.extend(a,d)):await this.v2PrivatePostFuturesCancelBatchOrder(this.extend(a,d)));let c=this.safeList(s,"data",[]),l=[];for(let e=0;e<c.length;e++){let t=this.safeDict(c,e),i=this.safeDict(t,"data",{}),s=this.parseOrder(i,r);l.push(s)}return l}async editOrder(e,t,i,s,r,a,o={}){let n;this.checkRequiredArgument("editOrder",t,"symbol"),void 0===this.markets&&await this.loadMarkets();let d=this.market(t),h={market:d.id};void 0!==r&&(h.amount=this.amountToPrecision(t,r)),void 0!==a&&(h.price=this.priceToPrecision(t,a));let c=this.safeStringN(o,["stopPrice","triggerPrice","trigger_price"]),l=this.omit(o,["stopPrice","triggerPrice"]),u=void 0!==c;u?(h.trigger_price=this.priceToPrecision(t,c),h.stop_id=this.parseToNumeric(e)):h.order_id=this.parseToNumeric(e);let[f,p]=this.handleMarginModeAndParams("editOrder",l);!0===d.spot?(void 0!==f?h.market_type="MARGIN":h.market_type="SPOT",n=u?await this.v2PrivatePostSpotModifyStopOrder(this.extend(h,p)):await this.v2PrivatePostSpotModifyOrder(this.extend(h,p))):(h.market_type="FUTURES",n=u?await this.v2PrivatePostFuturesModifyStopOrder(this.extend(h,p)):await this.v2PrivatePostFuturesModifyOrder(this.extend(h,p)));let m=this.safeDict(n,"data",{});return this.parseOrder(m,d)}async editOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=[],r=[];for(let t=0;t<e.length;t++){let i,a=this.safeDict(e,t),o=this.safeString(a,"symbol"),n=this.market(o);void 0!==o&&r.push(o);let d=this.safeString(a,"id"),h=this.safeNumber(a,"amount"),c=this.safeNumber(a,"price"),l=this.safeDict(a,"params",{});[i,l]=this.handleMarginModeAndParams("editOrders",l);let u="SPOT";!0===n.swap?u="FUTURES":void 0!==i&&(u="MARGIN");let f={order_id:this.parseToNumeric(d),market:n.id,market_type:u};void 0!==h&&(f.amount=this.amountToPrecision(o,h)),void 0!==c&&(f.price=this.priceToPrecision(o,c)),s.push(this.extend(f,l))}r=this.marketSymbols(r,void 0,!1,!0,!0);let a=this.safeString(r,0),n=this.market(a),d={orders:s};i=!0===n.spot?await this.v2PrivatePostSpotBatchModifyOrder(this.extend(d,t)):await this.v2PrivatePostFuturesBatchModifyOrder(this.extend(d,t));let h=this.safeList(i,"data",[]),c=[];for(let e=0;e<h.length;e++){let t=this.safeDict(h,e),i=this.safeString(t,"code"),s=this.safeString(t,"message","");if("0"!==i||"Success"!==s&&"Succeeded"!==s&&"ok"!==s.toLowerCase()&&void 0===h){let e=this.id+" "+s;throw this.throwBroadlyMatchedException(this.exceptions.broad,s,e),this.throwExactlyMatchedException(this.exceptions.exact,i,e),new o.ExchangeError(e)}let r=this.safeDict(t,"data",{}),a=this.parseOrder(r);c.push(a)}return c}async cancelOrder(e,t,i={}){let s,r;if(void 0===t)throw new o.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let a=this.market(t),n=this.safeBool2(i,"stop","trigger"),d=a.swap,h={market:a.id},[c,l]=this.handleMarginModeAndParams("cancelOrder",i);!0===d?h.market_type="FUTURES":void 0!==c?h.market_type="MARGIN":h.market_type="SPOT";let u=this.safeString2(l,"client_id","clientOrderId"),f=this.omit(l,["stop","trigger","clientOrderId"]);if(void 0!==u?(h.client_id=u,s=!0===n?!0===d?await this.v2PrivatePostFuturesCancelStopOrderByClientId(this.extend(h,f)):await this.v2PrivatePostSpotCancelStopOrderByClientId(this.extend(h,f)):!0===d?await this.v2PrivatePostFuturesCancelOrderByClientId(this.extend(h,f)):await this.v2PrivatePostSpotCancelOrderByClientId(this.extend(h,f))):!0===n?(h.stop_id=this.parseToNumeric(e),s=!0===d?await this.v2PrivatePostFuturesCancelStopOrder(this.extend(h,f)):await this.v2PrivatePostSpotCancelStopOrder(this.extend(h,f))):(h.order_id=this.parseToNumeric(e),s=!0===d?await this.v2PrivatePostFuturesCancelOrder(this.extend(h,f)):await this.v2PrivatePostSpotCancelOrder(this.extend(h,f))),void 0!==u){let e=this.safeList(s,"data",[]);r=this.safeDict(e[0],"data",{})}else r=this.safeDict(s,"data",{});return this.parseOrder(r,a)}async cancelAllOrders(e,t={}){let i;if(void 0===e)throw new o.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={market:s.id};if(!0===s.swap)r.market_type="FUTURES",i=await this.v2PrivatePostFuturesCancelAllOrder(this.extend(r,t));else{let[e,s]=this.handleMarginModeAndParams("cancelAllOrders",t);void 0!==e?r.market_type="MARGIN":r.market_type="SPOT",i=await this.v2PrivatePostSpotCancelAllOrder(this.extend(r,s))}return[this.safeOrder({info:i})]}async fetchOrder(e,t,i={}){let s;if(void 0===t)throw new o.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),a={market:r.id,order_id:this.parseToNumeric(e)};s=!0===r.swap?await this.v2PrivateGetFuturesOrderStatus(this.extend(a,i)):await this.v2PrivateGetSpotOrderStatus(this.extend(a,i));let n=this.safeDict(s,"data",{});return this.parseOrder(n,r)}async fetchOrdersByStatus(e,t,i,s,r={}){let a,o;void 0===this.markets&&await this.loadMarkets();let n={};void 0!==t&&(n.market=(a=this.market(t)).id),void 0!==s&&(n.limit=s);let d=this.safeBool2(r,"stop","trigger"),h=this.omit(r,["stop","trigger"]),[c,l]=this.handleMarketTypeAndParams("fetchOrdersByStatus",a,h),u="finished"===e||"closed"===e;if("swap"===c)n.market_type="FUTURES",u?o=!0===d?await this.v2PrivateGetFuturesFinishedStopOrder(this.extend(n,l)):await this.v2PrivateGetFuturesFinishedOrder(this.extend(n,l)):("pending"===e||"open"===e)&&(o=!0===d?await this.v2PrivateGetFuturesPendingStopOrder(this.extend(n,l)):await this.v2PrivateGetFuturesPendingOrder(this.extend(n,l)));else{let[t,i]=this.handleMarginModeAndParams("fetchOrdersByStatus",l);void 0!==t?n.market_type="MARGIN":n.market_type="SPOT",u?o=!0===d?await this.v2PrivateGetSpotFinishedStopOrder(this.extend(n,i)):await this.v2PrivateGetSpotFinishedOrder(this.extend(n,i)):"pending"===e&&(o=!0===d?await this.v2PrivateGetSpotPendingStopOrder(this.extend(n,i)):await this.v2PrivateGetSpotPendingOrder(this.extend(n,i)))}let f=this.safeList(o,"data",[]);return this.parseOrders(f,a,i,s)}async fetchOpenOrders(e,t,i,s={}){let r=await this.fetchOrdersByStatus("pending",e,t,i,s);for(let e=0;e<r.length;e++)r[e].status="open";return r}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrdersByStatus("finished",e,t,i,s)}async createDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s=this.safeString2(t,"chain","network");if(void 0===s)throw new o.ArgumentsRequired(this.id+" createDepositAddress() requires a network parameter");let r=this.omit(t,"network"),a={ccy:i.id,chain:this.networkCodeToId(s,this.safeString(i,"code"))},n=await this.v2PrivatePostAssetsRenewalDepositAddress(this.extend(a,r)),d=this.safeDict(n,"data",{});return this.parseDepositAddress(d,i)}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={ccy:i.id},[r,a]=this.handleNetworkCodeAndParams(t);if(void 0===r)throw new o.ArgumentsRequired(this.id+' fetchDepositAddress() requires a "network" parameter');s.chain=this.networkCodeToId(r,this.safeString(i,"code"));let n=await this.v2PrivateGetAssetsDepositAddress(this.extend(s,a)),d=this.safeDict(n,"data",{});return this.parseDepositAddress(d,i)}parseDepositAddress(e,t){let i,s,r=this.safeString(e,"address",""),a=r.split(":");return a.length>1&&"cfx"!==a[0]?(i=a[0],s=a[1]):i=r,{info:e,currency:this.safeCurrencyCode(void 0,t),network:void 0,address:i,tag:this.safeString(e,"memo",s)}}async fetchMyTrades(e,t,i,s={}){let r;if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let a=this.market(e),n={market:a.id};void 0!==i&&(n.limit=i),void 0!==t&&(n.start_time=t);let[d,h]=this.handleUntilOption("end_time",n,s);if(!0===a.swap)d.market_type="FUTURES",r=await this.v2PrivateGetFuturesUserDeals(this.extend(d,h));else{let[e,t]=this.handleMarginModeAndParams("fetchMyTrades",h);void 0!==e?d.market_type="MARGIN":d.market_type="SPOT",r=await this.v2PrivateGetSpotUserDeals(this.extend(d,t))}let c=this.safeList(r,"data",[]);return this.parseTrades(c,a,t,i)}async fetchPositions(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionStringAndParams(t,"fetchPositions","method","v2PrivateGetFuturesPendingPosition"),n=this.marketSymbols(e),d={market_type:"FUTURES"};if(void 0!==n){let e;if(Array.isArray(n)){if(n.length>1)throw new o.BadRequest(this.id+" fetchPositions() symbols argument cannot contain more than 1 symbol");e=n[0]}else e=n;d.market=(s=this.market(e)).id}i="v2PrivateGetFuturesPendingPosition"===r?await this.v2PrivateGetFuturesPendingPosition(this.extend(d,a)):await this.v2PrivateGetFuturesFinishedPosition(this.extend(d,a));let h=this.safeList(i,"data",[]),c=[];for(let e=0;e<h.length;e++)c.push(this.parsePosition(h[e],s));return this.filterByArrayPositions(c,"symbol",n)}async fetchPosition(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={market_type:"FUTURES",market:i.id},r=await this.v2PrivateGetFuturesPendingPosition(this.extend(s,t)),a=this.safeList(r,"data",[]);return this.parsePosition(a[0],i)}parsePosition(e,t){let i=this.safeString(e,"market"),s=this.safeMarket(i,t,void 0,"swap"),r=this.safeInteger(e,"created_at");return this.safePosition({info:e,id:this.safeInteger(e,"position_id"),symbol:s.symbol,notional:this.safeNumber(e,"settle_value"),marginMode:this.safeString(e,"margin_mode"),liquidationPrice:this.safeNumber(e,"liq_price"),entryPrice:this.safeNumber(e,"avg_entry_price"),unrealizedPnl:this.safeNumber(e,"unrealized_pnl"),realizedPnl:this.safeNumber(e,"realized_pnl"),percentage:void 0,contracts:this.safeNumber(e,"close_avbl"),contractSize:this.safeNumber(s,"contractSize"),markPrice:void 0,lastPrice:void 0,side:this.safeString(e,"side"),hedged:void 0,timestamp:r,datetime:this.iso8601(r),lastUpdateTimestamp:this.safeInteger(e,"updated_at"),maintenanceMargin:this.safeNumber(e,"maintenance_margin_value"),maintenanceMarginPercentage:this.safeNumber(e,"maintenance_margin_rate"),collateral:this.safeNumber(e,"margin_avbl"),initialMargin:void 0,initialMarginPercentage:void 0,leverage:this.safeNumber(e,"leverage"),marginRatio:this.safeNumber(e,"position_margin_rate"),stopLossPrice:this.omitZero(this.safeString(e,"stop_loss_price")),takeProfitPrice:this.omitZero(this.safeString(e,"take_profit_price"))})}async setMarginMode(e,t,i={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");let s=e.toLowerCase();if("isolated"!==s&&"cross"!==s)throw new o.BadRequest(this.id+" setMarginMode() marginMode argument should be isolated or cross");void 0===this.markets&&await this.loadMarkets();let r=this.market(t);if("swap"!==r.type)throw new o.BadSymbol(this.id+" setMarginMode() supports swap contracts only");let a=this.safeInteger(i,"leverage"),n=this.safeInteger(r.limits.leverage,"max",100);if(void 0===a)throw new o.ArgumentsRequired(this.id+" setMarginMode() requires a leverage parameter");if(a<1||a>n)throw new o.BadRequest(this.id+" setMarginMode() leverage should be between 1 and "+n.toString()+" for "+t);let d={market:r.id,market_type:"FUTURES",margin_mode:s,leverage:a};return await this.v2PrivatePostFuturesAdjustPositionLeverage(this.extend(d,i))}async setLeverage(e,t,i={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t);if(!0!==s.swap)throw new o.BadSymbol(this.id+" setLeverage() supports swap contracts only");let[r,a]=this.handleMarginModeAndParams("setLeverage",i,"cross"),n=this.safeInteger(s.limits.leverage,"min",1),d=this.safeInteger(s.limits.leverage,"max",100);if(e<n||e>d)throw new o.BadRequest(this.id+" setLeverage() leverage should be between "+n.toString()+" and "+d.toString()+" for "+t);let h={market:s.id,market_type:"FUTURES",margin_mode:r,leverage:e};return await this.v2PrivatePostFuturesAdjustPositionLeverage(this.extend(h,a))}async fetchLeverageTiers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={};void 0!==e&&(i.market=this.marketIds(e).join(","));let s=await this.v2PublicGetFuturesPositionLevel(this.extend(i,t)),r=this.safeList(s,"data",[]);return this.parseLeverageTiers(r,e,"market")}parseMarketLeverageTiers(e,t){let i=[],s=this.safeList(e,"level",[]),r=0,a=this.safeString(e,"market"),o=this.safeMarket(a,t,void 0,"swap");for(let e=0;e<s.length;e++){let t,n=s[e],d=this.safeNumber(n,"amount");t=!0===o.linear?o.base:o.quote;let h=r;i.push({tier:this.sum(e,1),symbol:this.safeSymbol(a,o,void 0,"swap"),currency:t,minNotional:h,maxNotional:d,maintenanceMarginRate:this.safeNumber(n,"maintenance_margin_rate"),maxLeverage:this.safeInteger(n,"leverage"),info:n}),r=d}return i}async modifyMarginHelper(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=this.amountToPrecision(e,t),o=a;"reduce"===i&&(o=n.Y.stringNeg(a));let d={market:r.id,market_type:"FUTURES",amount:o},h=await this.v2PrivatePostFuturesAdjustPositionMargin(this.extend(d,s)),c=this.safeDict(h,"data",{}),l=this.safeStringLower(h,"message"),u="add";return"reduce"===i&&(u="reduce"),this.extend(this.parseMarginModification(c,r),{type:u,amount:this.parseNumber(t),status:l})}parseMarginModification(e,t){let i=this.safeString(e,"market"),s=this.safeInteger2(e,"updated_at","created_at"),r=this.safeString(e,"margin_change");return{info:e,symbol:this.safeSymbol(i,t,void 0,"swap"),type:void 0,marginMode:"isolated",amount:this.parseNumber(n.Y.stringAbs(r)),total:this.safeNumber(e,"margin_avbl"),code:this.safeString(t,"quote"),status:void 0,timestamp:s,datetime:this.iso8601(s)}}async addMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,"add",i)}async reduceMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,"reduce",i)}async fetchFundingHistory(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchFundingHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r={market:this.market(e).id,market_type:"FUTURES"},[a,n]=this.handleUntilOption("end_time",r,s);void 0!==t&&(a.start_time=t),void 0!==i&&(a.limit=i);let d=await this.v2PrivateGetFuturesPositionFundingHistory(this.extend(a,n)),h=this.safeList(d,"data",[]),c=[];for(let t=0;t<h.length;t++){let i=h[t],s=this.safeInteger(i,"created_at"),r=this.safeString(i,"ccy"),a=this.safeCurrencyCode(r);c.push({info:i,symbol:e,code:a,timestamp:s,datetime:this.iso8601(s),id:this.safeNumber(i,"position_id"),amount:this.safeNumber(i,"funding_value")})}return c}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new o.BadSymbol(this.id+" fetchFundingRate() supports swap contracts only");let s={market:i.id},r=await this.v2PublicGetFuturesFundingRate(this.extend(s,t)),a=this.safeList(r,"data",[]),n=this.safeDict(a,0,{});return this.parseFundingRate(n,i)}async fetchFundingInterval(e,t={}){return await this.fetchFundingRate(e,t)}parseFundingRate(e,t){let i=this.safeInteger(e,"latest_funding_time"),s=this.safeInteger(e,"next_funding_time"),r=this.safeString(e,"latest_funding_time"),a=this.safeString(e,"next_funding_time"),o=n.Y.stringSub(a,r),d=this.safeString(e,"market");return{info:e,symbol:this.safeSymbol(d,t,void 0,"swap"),markPrice:this.safeNumber(e,"mark_price"),indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:this.safeNumber(e,"latest_funding_rate"),fundingTimestamp:i,fundingDatetime:this.iso8601(i),nextFundingRate:this.safeNumber(e,"next_funding_rate"),nextFundingTimestamp:s,nextFundingDatetime:this.iso8601(s),previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:this.parseFundingInterval(o)}}parseFundingInterval(e){return this.safeString({36e5:"1h",144e5:"4h",288e5:"8h",576e5:"16h",864e5:"24h"},e,e)}async fetchFundingRates(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s={};if(void 0!==i){let e=this.safeString(i,0);if(!0!==this.market(e).swap)throw new o.BadSymbol(this.id+" fetchFundingRates() supports swap contracts only");s.market=this.marketIds(i).join(",")}let r=await this.v2PublicGetFuturesFundingRate(this.extend(s,t)),a=this.safeList(r,"data",[]);return this.parseFundingRates(a,i)}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d={ccy:n.id,to_address:i,amount:this.currencyToPrecision(e,t)};void 0!==a&&(d.memo=a);let[h,c]=this.handleNetworkCodeAndParams(o);void 0!==h&&(d.chain=this.networkCodeToId(h,this.safeString(n,"code")));let l=await this.v2PrivatePostAssetsWithdraw(this.extend(d,c)),u=this.safeDict(l,"data",{});return this.parseTransaction(u,n)}parseTransactionStatus(e){return this.safeString({audit:"pending",pass:"pending",audit_required:"pending",processing:"pending",confirming:"pending",not_pass:"failed",cancel:"canceled",finish:"ok",finished:"ok",fail:"failed"},e,e)}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(r)return await this.fetchPaginatedCallDeterministic("fetchFundingRateHistory",e,t,i,"8h",a,1e3);let n=this.market(e),d={market:n.id};void 0!==t&&(d.start_time=t),void 0!==i&&(d.limit=i);let[h,c]=this.handleUntilOption("end_time",d,a),l=await this.v2PublicGetFuturesFundingRateHistory(this.extend(h,c)),u=this.safeList(l,"data",[]),f=[];for(let e=0;e<u.length;e++){let t=u[e],i=this.safeString(t,"market"),s=this.safeSymbol(i,n,void 0,"swap"),r=this.safeInteger(t,"funding_time");f.push({info:t,symbol:s,fundingRate:this.safeNumber(t,"actual_funding_rate"),timestamp:r,datetime:this.iso8601(r)})}let p=this.sortBy(f,"timestamp");return this.filterBySymbolSinceLimit(p,this.safeString(n,"symbol"),t,i)}parseTransaction(e,t){let i=this.safeString(e,"to_address"),s=this.safeString(e,"memo");void 0!==s&&s.length<1&&(s=void 0);let r=this.safeString(e,"remark");void 0!==r&&r.length<1&&(r=void 0);let a=this.safeString(e,"tx_id");void 0!==a&&a.length<1&&(a=void 0);let o=this.safeString(e,"ccy"),n=this.safeCurrencyCode(o,t),d=this.safeInteger(e,"created_at"),h="deposit";"withdraw_id"in e&&(h="withdrawal");let c=this.safeString(e,"chain"),l=this.safeString(e,"tx_fee"),u=this.safeStringLower2(e,"withdraw_method","deposit_method"),f=this.safeNumber(e,"actual_amount");void 0===f&&(f=this.safeNumber(e,"amount")),"deposit"===h&&(l="0");let p=this.safeString2(e,"fee_asset","fee_ccy"),m={cost:this.parseNumber(l),currency:this.safeCurrencyCode(p)};return{info:e,id:this.safeString2(e,"withdraw_id","deposit_id"),txid:a,timestamp:d,datetime:this.iso8601(d),network:this.networkIdToCode(c,n),address:i,addressTo:i,addressFrom:void 0,tag:s,tagTo:void 0,tagFrom:void 0,type:h,amount:f,currency:n,status:this.parseTransactionStatus(this.safeString(e,"status")),updated:void 0,fee:m,comment:r,internal:"local"===u}}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(e),n=this.currencyToPrecision(e,t),d=this.safeDict(this.options,"accountsByType",{}),h=this.safeString(d,i,i),c=this.safeString(d,s,s),l={ccy:a.id,amount:n,from_account_type:h,to_account_type:c},u=r;if(("margin"===i||"margin"===s)&&(u=this.omit(r,"symbol")),"margin"===i||"margin"===s){let e=this.safeString(r,"symbol");if(void 0===e)throw new o.ArgumentsRequired(this.id+" transfer() the symbol parameter must be defined for a margin account");l.market=this.marketId(e)}if("spot"!==i&&"spot"!==s)throw new o.BadRequest(this.id+" transfer() can only be between spot and swap, or spot and margin, either the fromAccount or toAccount must be spot");let f=await this.v2PrivatePostAssetsTransfer(this.extend(l,u));return this.extend(this.parseTransfer(f,a),{amount:this.parseNumber(n),fromAccount:i,toAccount:s})}parseTransferStatus(e){return this.safeString({0:"ok",SUCCESS:"ok",OK:"ok",finished:"ok",FINISHED:"ok"},e,e)}parseTransfer(e,t){let i=this.safeInteger(e,"created_at"),s=this.safeString(e,"ccy"),r=this.safeString(e,"from_account_type"),a=this.safeString(e,"to_account_type"),o=this.safeDict(this.options,"accountsById",{});return{id:void 0,timestamp:i,datetime:this.iso8601(i),currency:this.safeCurrencyCode(s,t),amount:this.safeNumber(e,"amount"),fromAccount:this.safeString(o,r,r),toAccount:this.safeString(o,a,a),status:this.parseTransferStatus(this.safeString2(e,"code","status"))}}async fetchTransfers(e,t,i,s={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new o.ArgumentsRequired(this.id+" fetchTransfers() requires a code argument");let r=this.currency(e),a={ccy:r.id},[n,d]=this.handleMarginModeAndParams("fetchTransfers",s);void 0!==n?a.transfer_type="MARGIN":a.transfer_type="FUTURES",void 0!==t&&(a.start_time=t),void 0!==i&&(a.limit=i);let[h,c]=this.handleUntilOption("end_time",a,d),l=await this.v2PrivateGetAssetsTransferHistory(this.extend(h,c)),u=this.safeList(l,"data",[]);return this.parseTransfers(u,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.ccy=(r=this.currency(e)).id),void 0!==i&&(a.limit=i);let o=await this.v2PrivateGetAssetsWithdraw(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTransactions(n,r,t,i)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.ccy=(r=this.currency(e)).id),void 0!==i&&(a.limit=i);let o=await this.v2PrivateGetAssetsDepositHistory(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTransactions(n,r,t,i)}parseIsolatedBorrowRate(e,t){let i,s,r=this.safeString(e,"market"),a=this.safeMarket(r,t,void 0,"spot"),o=this.safeString(e,"ccy"),n=this.safeNumber(e,"daily_interest_rate");return o===a.baseId?i=n:o===a.quoteId&&(s=n),{symbol:a.symbol,base:a.base,baseRate:i,quote:a.quote,quoteRate:s,period:864e5,timestamp:void 0,datetime:void 0,info:e}}async fetchIsolatedBorrowRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeString(t,"code");if(void 0===i)throw new o.ArgumentsRequired(this.id+" fetchIsolatedBorrowRate() requires a code parameter");let s=this.omit(t,"code"),r=this.currency(i),a=this.market(e),n={market:a.id,ccy:r.id},d=await this.v2PrivateGetAssetsMarginInterestLimit(this.extend(n,s)),h=this.safeDict(d,"data",{});return this.parseIsolatedBorrowRate(h,a)}async fetchBorrowInterest(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o={};void 0!==t&&(o.market=(a=this.market(t)).id),void 0!==s&&(o.limit=s);let n=await this.v2PrivateGetAssetsMarginBorrowHistory(this.extend(o,r)),d=this.safeList(n,"data",[]),h=this.parseBorrowInterests(d,a);return this.filterByCurrencySinceLimit(h,e,i,s)}parseBorrowInterest(e,t){let i=this.safeString(e,"market"),s=this.safeMarket(i,t,void 0,"spot"),r=this.safeInteger(e,"expired_at");return{info:e,symbol:s.symbol,currency:this.safeCurrencyCode(this.safeString(e,"ccy")),interest:this.safeNumber(e,"to_repaied_amount"),interestRate:this.safeNumber(e,"daily_interest_rate"),amountBorrowed:this.safeNumber(e,"borrow_amount"),marginMode:"isolated",timestamp:r,datetime:this.iso8601(r)}}async borrowIsolatedMargin(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=this.currency(t),o=this.safeBool2(s,"isAutoRenew","is_auto_renew",!1),n=this.omit(s,"isAutoRenew"),d={market:r.id,ccy:a.id,borrow_amount:this.currencyToPrecision(t,i),is_auto_renew:o},h=await this.v2PrivatePostAssetsMarginBorrow(this.extend(d,n)),c=this.safeDict(h,"data",{}),l=this.parseMarginLoan(c,a);return this.extend(l,{amount:i,symbol:e})}async repayIsolatedMargin(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=this.currency(t),o={market:r.id,ccy:a.id,amount:this.currencyToPrecision(t,i)},n=await this.v2PrivatePostAssetsMarginRepay(this.extend(o,s)),d=this.safeDict(n,"data",{}),h=this.parseMarginLoan(d,a);return this.extend(h,{amount:i,symbol:e})}parseMarginLoan(e,t){let i=this.safeString(e,"ccy"),s=this.safeString(e,"market"),r=this.safeInteger(e,"expired_at");return{id:this.safeString(e,"borrow_id"),currency:this.safeCurrencyCode(i,t),amount:this.safeNumber(e,"borrow_amount"),symbol:this.safeSymbol(s,void 0,void 0,"spot"),timestamp:r,datetime:this.iso8601(r),info:e}}async fetchDepositWithdrawFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={ccy:i.id},r=await this.v2PublicGetAssetsDepositWithdrawConfig(this.extend(s,t)),a=this.safeDict(r,"data",{});return this.parseDepositWithdrawFee(a,i)}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.v2PublicGetAssetsAllDepositWithdrawConfig(t),s=this.safeList(i,"data",[]),r={};for(let t=0;t<s.length;t++){let i=this.safeDict(s,t),a=this.safeDict(i,"asset",{}),o=this.safeString(a,"ccy");if(void 0===o)continue;let n=this.safeCurrencyCode(o);(void 0===e||this.inArray(n,e))&&void 0!==n&&(r[n]=this.parseDepositWithdrawFee(i))}return r}parseDepositWithdrawFee(e,t){let i={info:e,withdraw:{fee:void 0,percentage:void 0},deposit:{fee:void 0,percentage:void 0},networks:{}},s=this.safeList(e,"chains",[]),r=this.safeDict(e,"asset",{});for(let e=0;e<s.length;e++){let a=this.safeDict(s,e);if(!0===this.safeBool(a,"withdraw_enabled")){i.withdraw.fee=this.safeNumber(a,"withdrawal_fee"),i.withdraw.percentage=!1;let e=this.safeString(a,"chain");if(void 0!==e&&""!==e){let s=this.safeString(r,"ccy"),o=this.safeCurrencyCode(s,t),n=this.networkIdToCode(e,o);void 0!==n&&(i.networks[n]={withdraw:{fee:this.safeNumber(a,"withdrawal_fee"),percentage:!1},deposit:{fee:void 0,percentage:void 0}})}}}return i}async fetchLeverage(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeString(t,"code");if(void 0===i)throw new o.ArgumentsRequired(this.id+" fetchLeverage() requires a code parameter");let s=this.omit(t,"code"),r=this.currency(i),a=this.market(e),n={market:a.id,ccy:r.id},d=await this.v2PrivateGetAssetsMarginInterestLimit(this.extend(n,s)),h=this.safeDict(d,"data",{});return this.parseLeverage(h,a)}parseLeverage(e,t){let i=this.safeString(e,"market"),s=this.safeInteger(e,"leverage");return{info:e,symbol:this.safeSymbol(i,t,void 0,"spot"),marginMode:"isolated",longLeverage:s,shortLeverage:s}}async fetchPositionHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={market_type:"FUTURES",market:this.market(e).id};void 0!==i&&(r.limit=i),void 0!==t&&(r.start_time=t);let[a,o]=this.handleUntilOption("end_time",r,s),n=await this.v2PrivateGetFuturesFinishedPosition(this.extend(a,o)),d=this.safeList(n,"data",[]),h=this.parsePositions(d);return this.filterBySymbolSinceLimit(h,e,t,i)}async closePosition(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=this.safeString(i,"type","market"),a={market:s.id,market_type:"FUTURES",type:r},o=this.safeString2(i,"client_id","clientOrderId");void 0!==o&&(a.client_id=o);let n=this.omit(i,"clientOrderId"),d=await this.v2PrivatePostFuturesClosePosition(this.extend(a,n)),h=this.safeDict(d,"data",{});return this.parseOrder(h,s)}handleMarginModeAndParams(e,t={},i){let s=this.safeString(this.options,"defaultType"),r=this.safeBool(t,"margin",!1),[a,o]=super.handleMarginModeAndParams(e,t,i);return void 0===a&&("margin"===s||!0===r)?["isolated",o]:[a,o]}nonce(){return this.milliseconds()}sign(e,t=[],i="GET",a={},n,d){let h,c,l=this.implodeParams(e,a),u=t[0],f=t[1],p=this.safeString(this.urls.api,f);if(void 0===p)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let m=p+"/"+u+"/"+l,g=this.omit(a,this.extractParams(l)),v=this.nonce().toString();if("POST"===i){let e=l.split("/"),t=this.safeString(e,0,""),i=e.length,s=this.safeString(e,i-1,"").split("_"),r=s.length,o=this.safeString(s,r-1,"");if("order"===t&&("limit"===o||"market"===o)&&void 0===this.safeString(a,"client_id")){let e=this.safeString(this.options,"brokerId","x-167673045");g.client_id=e+"_"+this.uuid16()}}if("perpetualPrivate"===f){this.checkRequiredCredentials(),g=this.extend({access_id:this.apiKey,timestamp:v},g),g=this.keysort(g);let e=this.rawencode(g);h={Authorization:this.hash(this.encode(e+"&secret_key="+this.secret),s.sc).toLowerCase(),AccessId:this.apiKey},"GET"===i||"PUT"===i?m+="?"+e:(h["Content-Type"]="application/x-www-form-urlencoded",c=e)}else if("public"===f||"perpetualPublic"===f)Object.keys(g).length>0&&(m+="?"+this.urlencode(g));else if("v1"===u){this.checkRequiredCredentials(),g=this.extend({access_id:this.apiKey,tonce:v},g),g=this.keysort(g);let e=this.rawencode(g);h={Authorization:this.hash(this.encode(e+"&secret_key="+this.secret),r.Fx).toUpperCase(),"Content-Type":"application/json"},"GET"===i||"DELETE"===i||"PUT"===i?m+="?"+e:c=this.json(g)}else if("v2"===u){this.checkRequiredCredentials(),g=this.keysort(g);let e=this.rawencode(g),t=i+"/"+u+"/"+l;"POST"===i?t+=c=this.json(g):""!==e&&(t+="?"+e),t+=v+this.secret;let r=this.hash(this.encode(t),s.sc);h={"Content-Type":"application/json",Accept:"application/json","X-COINEX-KEY":this.apiKey,"X-COINEX-SIGN":r,"X-COINEX-TIMESTAMP":v},"POST"!==i&&""!==e&&(m+="?"+e)}return{url:m,method:i,body:void 0!==c?c:d,headers:void 0!==h?h:n}}handleErrors(e,t,i,s,r,a,n,d,h){if(void 0===n)return;let c=this.safeString(n,"code"),l=this.safeValue(n,"data"),u=this.safeString(n,"message","");if("0"!==c||"Success"!==u&&"Succeeded"!==u&&"ok"!==u.toLowerCase()&&void 0===l){let e=this.id+" "+u;throw this.throwBroadlyMatchedException(this.exceptions.broad,u,e),this.throwExactlyMatchedException(this.exceptions.exact,c,e),new o.ExchangeError(e)}}async fetchMarginAdjustmentHistory(e,t,i,s,r={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new o.ArgumentsRequired(this.id+" fetchMarginAdjustmentHistory() requires a symbol argument");let a=this.safeInteger2(r,"positionId","position_id"),n=this.omit(r,"positionId");if(void 0===a)throw new o.ArgumentsRequired(this.id+" fetchMarginAdjustmentHistory() requires a positionId parameter");let d={market:this.market(e).id,market_type:"FUTURES",position_id:a},[h,c]=this.handleUntilOption("end_time",d,n);void 0!==i&&(h.start_time=i),void 0!==s&&(h.limit=s);let l=await this.v2PrivateGetFuturesPositionMarginHistory(this.extend(h,c)),u=this.safeList(l,"data",[]),f=this.parseMarginModifications(u,void 0,"market","swap");return this.filterBySymbolSinceLimit(f,e,i,s)}}i.d(t,{A:()=>d})},5990(e,t,i){"use strict";var s=i(4721),r=i(3075),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"coinmate",name:"CoinMate",countries:["GB","CZ","EU"],rateLimit:600,has:{CORS:!0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchDepositsWithdrawals:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!1,fetchTransactions:"emulated",fetchVolatilityHistory:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,withdraw:!0},urls:{logo:"https://user-images.githubusercontent.com/51840849/87460806-1c9f3f00-c616-11ea-8c46-a77018a8f3f4.jpg",api:{rest:"https://coinmate.io/api"},www:"https://coinmate.io",fees:"https://coinmate.io/fees",doc:["https://coinmate.docs.apiary.io","https://coinmate.io/developers"],referral:"https://coinmate.io?referral=YTFkM1RsOWFObVpmY1ZjMGREQmpTRnBsWjJJNVp3PT0"},requiredCredentials:{apiKey:!0,secret:!0,uid:!0},api:{public:{get:{orderBook:{cost:1},ticker:{cost:1},tickerAll:{cost:1},products:{cost:1},transactions:{cost:1},tradingPairs:{cost:1},"system/time":{cost:1}}},private:{post:{currencies:{cost:1},balances:{cost:1},bitcoinCashWithdrawal:{cost:1},bitcoinCashDepositAddresses:{cost:1},bitcoinDepositAddresses:{cost:1},bitcoinWithdrawal:{cost:1},bitcoinWithdrawalFees:{cost:1},buyInstant:{cost:1},buyLimit:{cost:1},cancelOrder:{cost:1},cancelOrderWithInfo:{cost:1},createVoucher:{cost:1},dashDepositAddresses:{cost:1},dashWithdrawal:{cost:1},ethereumWithdrawal:{cost:1},ethereumDepositAddresses:{cost:1},litecoinWithdrawal:{cost:1},litecoinDepositAddresses:{cost:1},openOrders:{cost:1},order:{cost:1},orderHistory:{cost:1},orderById:{cost:1},pusherAuth:{cost:1},redeemVoucher:{cost:1},replaceByBuyLimit:{cost:1},replaceByBuyInstant:{cost:1},replaceBySellLimit:{cost:1},replaceBySellInstant:{cost:1},rippleDepositAddresses:{cost:1},rippleWithdrawal:{cost:1},sellInstant:{cost:1},sellLimit:{cost:1},transactionHistory:{cost:1},traderFees:{cost:1},tradeHistory:{cost:1},transfer:{cost:1},transferHistory:{cost:1},unconfirmedBitcoinDeposits:{cost:1},unconfirmedBitcoinCashDeposits:{cost:1},unconfirmedDashDeposits:{cost:1},unconfirmedEthereumDeposits:{cost:1},unconfirmedLitecoinDeposits:{cost:1},unconfirmedRippleDeposits:{cost:1},cancelAllOpenOrders:{cost:1},withdrawVirtualCurrency:{cost:1},virtualCurrencyDepositAddresses:{cost:1},unconfirmedVirtualCurrencyDeposits:{cost:1},adaWithdrawal:{cost:1},adaDepositAddresses:{cost:1},unconfirmedAdaDeposits:{cost:1},daiWithdrawal:{cost:1},daiDepositAddresses:{cost:1},unconfirmedDaiDeposits:{cost:1},solWithdrawal:{cost:1},solDepositAddresses:{cost:1},unconfirmedSolDeposits:{cost:1},bankWireWithdrawal:{cost:1},lightningDeposit:{cost:1},lightningWithdraw:{cost:1}}}},fees:{trading:{tierBased:!0,percentage:!0,taker:this.parseNumber("0.006"),maker:this.parseNumber("0.004"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.006")],[this.parseNumber("10000"),this.parseNumber("0.003")],[this.parseNumber("100000"),this.parseNumber("0.0023")],[this.parseNumber("250000"),this.parseNumber("0.0021")],[this.parseNumber("500000"),this.parseNumber("0.0018")],[this.parseNumber("1000000"),this.parseNumber("0.0015")],[this.parseNumber("3000000"),this.parseNumber("0.0012")],[this.parseNumber("15000000"),this.parseNumber("0.001")]],maker:[[this.parseNumber("0"),this.parseNumber("0.004")],[this.parseNumber("10000"),this.parseNumber("0.002")],[this.parseNumber("100000"),this.parseNumber("0.0012")],[this.parseNumber("250000"),this.parseNumber("0.0009")],[this.parseNumber("500000"),this.parseNumber("0.0005")],[this.parseNumber("1000000"),this.parseNumber("0.0003")],[this.parseNumber("3000000"),this.parseNumber("0.0002")],[this.parseNumber("15000000"),this.parseNumber("-0.0004")]]}}},options:{withdraw:{fillResponsefromRequest:!0,methods:{BTC:"privatePostBitcoinWithdrawal",LTC:"privatePostLitecoinWithdrawal",BCH:"privatePostBitcoinCashWithdrawal",ETH:"privatePostEthereumWithdrawal",XRP:"privatePostRippleWithdrawal",DASH:"privatePostDashWithdrawal",DAI:"privatePostDaiWithdrawal",ADA:"privatePostAdaWithdrawal",SOL:"privatePostSolWithdrawal"}}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!1,PO:!0,GTD:!1},hedged:!1,trailing:!0,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!0},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:1e5,untilDays:1e5,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:{marginMode:!1,limit:100,daysBack:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:void 0,fetchOHLCV:void 0},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},exceptions:{exact:{"No order with given ID":a.OrderNotFound},broad:{"Not enough account balance available":a.InsufficientFunds,"Incorrect order ID":a.InvalidOrder,"Minimum Order Size ":a.InvalidOrder,"max allowed precision":a.InvalidOrder,"TOO MANY REQUESTS":a.RateLimitExceeded,"Access denied.":a.AuthenticationError}},precisionMode:4})}async fetchTime(e={}){let t=await this.publicGetSystemTime(e);return this.safeInteger(t,"serverTime")}async fetchMarkets(e={}){let t=await this.publicGetTradingPairs(e),i=this.safeList(t,"data",[]),s=[];for(let e=0;e<i.length;e++){let t=i[e],r=this.safeString(t,"name"),a=this.safeString(t,"firstCurrency"),o=this.safeString(t,"secondCurrency"),n=this.safeCurrencyCode(a),d=this.safeCurrencyCode(o);if(void 0===n||void 0===d)continue;let h=n+"/"+d;s.push({id:r,symbol:h,base:n,quote:d,settle:void 0,baseId:a,quoteId:o,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:void 0,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(t,"lotDecimals"))),price:this.parseNumber(this.parsePrecision(this.safeString(t,"priceDecimals")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(t,"minAmount"),max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:t})}return s}parseBalance(e){let t=this.safeDict(e,"data",{}),i={info:e},s=Object.keys(t);for(let e=0;e<s.length;e++){let r=s[e],a=this.safeCurrencyCode(r),o=this.safeDict(t,r),n=this.account();n.free=this.safeString(o,"available"),n.used=this.safeString(o,"reserved"),n.total=this.safeString(o,"balance"),i[a]=n}return this.safeBalance(i)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostBalances(e);return this.parseBalance(t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={currencyPair:s.id,groupByPriceLimit:"False"},a=await this.publicGetOrderBook(this.extend(r,i)),o=this.safeDict(a,"data",{}),n=this.safeTimestamp(o,"timestamp");return this.parseOrderBook(o,s.symbol,n,"bids","asks","price","amount")}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={currencyPair:i.id},r=await this.publicGetTicker(this.extend(s,t)),a=this.safeDict(r,"data");return this.parseTicker(a,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetTickerAll(t),r=this.safeDict(s,"data",{}),a=Object.keys(r),o={};for(let e=0;e<a.length;e++){let t=this.market(a[e]),i=this.parseTicker(this.safeValue(r,a[e]),t);o[t.symbol]=i}return this.filterByArrayTickers(o,"symbol",i)}parseTicker(e,t){let i=this.safeTimestamp(e,"timestamp"),s=this.safeNumber(e,"last");return this.safeTicker({symbol:this.safeString(t,"symbol"),timestamp:i,datetime:this.iso8601(i),high:this.safeNumber(e,"high"),low:this.safeNumber(e,"low"),bid:this.safeNumber(e,"bid"),bidVolume:void 0,ask:this.safeNumber(e,"ask"),vwap:void 0,askVolume:void 0,open:void 0,close:s,last:s,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeNumber(e,"amount"),quoteVolume:void 0,info:e},t)}async fetchDepositsWithdrawals(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={limit:1e3};void 0!==i&&(r.limit=i),void 0!==t&&(r.timestampFrom=t),void 0!==e&&(r.currency=this.currency(e).id);let a=await this.privatePostTransferHistory(this.extend(r,s)),o=this.safeList(a,"data",[]);return this.parseTransactions(o,void 0,t,i)}parseTransactionStatus(e){return this.safeString({COMPLETED:"ok",WAITING:"pending",SENT:"pending",CREATED:"pending",OK:"ok",NEW:"pending",CANCELED:"canceled"},e,e)}parseTransaction(e,t){let i=this.safeInteger(e,"timestamp"),s=this.safeString(e,"amountCurrency"),r=this.safeCurrencyCode(s,t);return{info:e,id:this.safeString2(e,"transactionId","id"),txid:this.safeString(e,"txid"),type:this.safeStringLower(e,"transferType"),currency:r,network:this.safeString(e,"walletType"),amount:this.safeNumber(e,"amount"),status:this.parseTransactionStatus(this.safeString(e,"transferStatus")),timestamp:i,datetime:this.iso8601(i),address:this.safeString(e,"destination"),addressFrom:void 0,addressTo:void 0,tag:this.safeString(e,"destinationTag"),tagFrom:void 0,tagTo:void 0,updated:void 0,comment:void 0,internal:void 0,fee:{cost:this.safeNumber(e,"fee"),currency:r,rate:void 0}}}async withdraw(e,t,i,s,r={}){let o,[n,d]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let h=this.currency(e),c=this.safeDict(this.options,"withdraw",{}),l=this.safeDict(c,"methods",{}),u=this.safeString(l,e);if(void 0===u){let e=Object.keys(l);throw new a.ExchangeError(this.id+" withdraw() only allows withdrawing the following currencies: "+e.join(", "))}let f={amount:this.currencyToPrecision(e,t),address:i};void 0!==n&&(f.destinationTag=n);let p=this.extend(f,d);if("privatePostBitcoinWithdrawal"===u)o=await this.privatePostBitcoinWithdrawal(p);else if("privatePostLitecoinWithdrawal"===u)o=await this.privatePostLitecoinWithdrawal(p);else if("privatePostBitcoinCashWithdrawal"===u)o=await this.privatePostBitcoinCashWithdrawal(p);else if("privatePostEthereumWithdrawal"===u)o=await this.privatePostEthereumWithdrawal(p);else if("privatePostRippleWithdrawal"===u)o=await this.privatePostRippleWithdrawal(p);else if("privatePostDashWithdrawal"===u)o=await this.privatePostDashWithdrawal(p);else if("privatePostDaiWithdrawal"===u)o=await this.privatePostDaiWithdrawal(p);else if("privatePostAdaWithdrawal"===u)o=await this.privatePostAdaWithdrawal(p);else if("privatePostSolWithdrawal"===u)o=await this.privatePostSolWithdrawal(p);else throw new a.ExchangeError(this.id+" withdraw() does not support the "+u+" method");let m=this.safeDict(o,"data",{}),g=this.parseTransaction(m,h);return!0===this.safeBool(c,"fillResponseFromRequest",!0)&&(g.amount=t,g.currency=e,g.address=i,g.tag=n,g.type="withdrawal",g.status="pending"),g}async fetchMyTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=void 0===i?1e3:i,a={limit:r};void 0!==e&&(a.currencyPair=this.market(e).id),void 0!==t&&(a.timestampFrom=t);let o=await this.privatePostTradeHistory(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTrades(n,void 0,t,r)}parseTrade(e,t){let i,s=this.safeString(e,"currencyPair"),r=this.safeMarket(s,t,"_"),a=this.safeString(e,"price"),o=this.safeString(e,"amount"),n=this.safeStringLower2(e,"type","tradeType"),d=this.safeStringLower(e,"orderType"),h=this.safeString(e,"orderId"),c=this.safeString(e,"transactionId"),l=this.safeInteger2(e,"timestamp","createdTimestamp"),u=this.safeString(e,"fee");void 0!==u&&(i={cost:u,currency:r.quote});let f=this.safeString(e,"feeType");return f="MAKER"===f?"maker":"taker",this.safeTrade({id:c,info:e,timestamp:l,datetime:this.iso8601(l),symbol:r.symbol,type:d,side:n,order:h,takerOrMaker:f,price:a,amount:o,cost:void 0,fee:i},r)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={currencyPair:r.id,minutesIntoHistory:10},o=await this.publicGetTransactions(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTrades(n,r,t,i)}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={currencyPair:i.id},r=await this.privatePostTraderFees(this.extend(s,t)),a=this.safeDict(r,"data",{}),n=this.safeString(a,"maker"),d=this.safeString(a,"taker"),h=this.parseNumber(o.Y.stringDiv(n,"100")),c=this.parseNumber(o.Y.stringDiv(d,"100"));return{info:a,symbol:i.symbol,maker:h,taker:c,percentage:!0,tierBased:!0}}async fetchOpenOrders(e,t,i,s={}){let r=await this.privatePostOpenOrders(this.extend({},s)),a=this.safeList(r,"data",[]);return this.parseOrders(a,void 0,t,i,{status:"open"})}async fetchOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={currencyPair:r.id};void 0!==i&&(o.limit=i);let n=await this.privatePostOrderHistory(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseOrders(d,r,t,i)}parseOrderStatus(e){return this.safeString({FILLED:"closed",CANCELLED:"canceled",PARTIALLY_FILLED:"open",OPEN:"open"},e,e)}parseOrderType(e){return this.safeString({LIMIT:"limit",MARKET:"market"},e,e)}parseOrder(e,t){let i=this.safeString(e,"id"),s=this.safeInteger(e,"timestamp"),r=this.safeStringLower(e,"type"),a=this.safeString(e,"price"),o=this.safeString(e,"originalAmount"),n=this.safeString2(e,"remainingAmount","amount"),d=this.parseOrderStatus(this.safeString(e,"status")),h=this.parseOrderType(this.safeString(e,"orderTradeType")),c=this.safeString(e,"avgPrice"),l=this.safeString(e,"currencyPair"),u=this.safeSymbol(l,t,"_"),f=this.safeString(e,"clientOrderId");return this.safeOrder({id:i,clientOrderId:f,timestamp:s,datetime:this.iso8601(s),lastTradeTimestamp:void 0,symbol:u,type:h,timeInForce:void 0,postOnly:void 0,side:r,price:a,triggerPrice:this.safeNumber(e,"stopPrice"),amount:o,cost:void 0,average:c,filled:void 0,remaining:n,status:d,trades:void 0,info:e,fee:void 0},t)}async createOrder(e,t,i,s,r,o={}){let n;void 0===this.markets&&await this.loadMarkets();let d="privatePost"+this.capitalize(i),h=this.market(e),c={currencyPair:h.id};"market"===t?("buy"===i?c.total=this.amountToPrecision(e,s):c.amount=this.amountToPrecision(e,s),d+="Instant"):(c.amount=this.amountToPrecision(e,s),c.price=this.priceToPrecision(e,r),d+=this.capitalize(t));let l=this.extend(c,o);if("privatePostBuyInstant"===d)n=await this.privatePostBuyInstant(l);else if("privatePostSellInstant"===d)n=await this.privatePostSellInstant(l);else if("privatePostBuyLimit"===d)n=await this.privatePostBuyLimit(l);else if("privatePostSellLimit"===d)n=await this.privatePostSellLimit(l);else throw new a.InvalidOrder(this.id+" createOrder() does not support order type "+t);let u=this.safeString(n,"data");return this.safeOrder({info:n,id:u},h)}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&""!==t&&(s=this.market(t));let r=await this.privatePostOrderById(this.extend({orderId:e},i)),a=this.safeDict(r,"data");return this.parseOrder(a,s)}async cancelOrder(e,t,i={}){let s=await this.privatePostCancelOrderWithInfo(this.extend({orderId:e},i)),r=this.safeDict(s,"data");return this.parseOrder(r)}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},o,n){let d,h,c=this.safeString(this.urls.api,"rest");if(void 0===c)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let l=c+"/"+e;if("public"===t)Object.keys(r).length>0&&(l+="?"+this.urlencode(r));else{this.checkRequiredCredentials();let e=this.incrementingNonce().toString(),t=e+this.uid+this.apiKey,i=this.hmac(this.encode(t),this.encode(this.secret),s.sc);d=this.urlencode(this.extend({clientId:this.uid,nonce:e,publicKey:this.apiKey,signature:i.toUpperCase()},r)),h={"Content-Type":"application/x-www-form-urlencoded"}}return{url:l,method:i,body:void 0===d?n:d,headers:void 0===h?o:h}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"errorMessage");if(void 0!==c){let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,c,e),this.throwBroadlyMatchedException(this.exceptions.broad,c,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>n})},6899(e,t,i){"use strict";var s=i(4721),r=i(7436),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"coinone",name:"CoinOne",countries:["KR"],rateLimit:50,version:"v2",pro:!1,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createMarketOrder:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrders:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!1,fetchDepositAddresses:!0,fetchDepositAddressesByNetwork:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchVolatilityHistory:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,ws:!0},urls:{logo:"https://user-images.githubusercontent.com/1294454/38003300-adc12fba-323f-11e8-8525-725f53c4a659.jpg",api:{rest:"https://api.coinone.co.kr",v2Public:"https://api.coinone.co.kr/public/v2",v2Private:"https://api.coinone.co.kr/v2",v2_1Private:"https://api.coinone.co.kr/v2.1"},www:"https://coinone.co.kr",doc:"https://doc.coinone.co.kr"},requiredCredentials:{apiKey:!0,secret:!0},api:{public:{get:{orderbook:{cost:1},ticker:{cost:1},ticker_utc:{cost:1},trades:{cost:1}}},v2Public:{get:{range_units:{cost:1},"markets/{quote_currency}":{cost:1},"markets/{quote_currency}/{target_currency}":{cost:1},"orderbook/{quote_currency}/{target_currency}":{cost:1},"trades/{quote_currency}/{target_currency}":{cost:1},"ticker_new/{quote_currency}":{cost:1},"ticker_new/{quote_currency}/{target_currency}":{cost:1},"ticker_utc_new/{quote_currency}":{cost:1},"ticker_utc_new/{quote_currency}/{target_currency}":{cost:1},currencies:{cost:1},"currencies/{currency}":{cost:1},"chart/{quote_currency}/{target_currency}":{cost:1}}},private:{post:{"account/deposit_address":{cost:1},"account/btc_deposit_address":{cost:1},"account/balance":{cost:1},"account/daily_balance":{cost:1},"account/user_info":{cost:1},"account/virtual_account":{cost:1},"order/cancel_all":{cost:1},"order/cancel":{cost:1},"order/limit_buy":{cost:1},"order/limit_sell":{cost:1},"order/complete_orders":{cost:1},"order/limit_orders":{cost:1},"order/order_info":{cost:1},"transaction/auth_number":{cost:1},"transaction/history":{cost:1},"transaction/krw/history":{cost:1},"transaction/btc":{cost:1},"transaction/coin":{cost:1}}},v2Private:{post:{"account/balance":{cost:1},"account/deposit_address":{cost:1},"account/user_info":{cost:1},"account/virtual_account":{cost:1},"order/cancel":{cost:1},"order/limit_buy":{cost:1},"order/limit_sell":{cost:1},"order/limit_orders":{cost:1},"order/complete_orders":{cost:1},"order/query_order":{cost:1},"transaction/auth_number":{cost:1},"transaction/btc":{cost:1},"transaction/history":{cost:1},"transaction/krw/history":{cost:1}}},v2_1Private:{post:{"account/balance/all":{cost:1},"account/balance":{cost:1},"account/trade_fee":{cost:1},"account/trade_fee/{quote_currency}/{target_currency}":{cost:1},"order/limit":{cost:1},"order/cancel":{cost:1},"order/cancel/all":{cost:1},"order/open_orders":{cost:1},"order/open_orders/all":{cost:1},"order/complete_orders":{cost:1},"order/complete_orders/all":{cost:1},"order/info":{cost:1},"transaction/krw/history":{cost:1},"transaction/coin/history":{cost:1},"transaction/coin/withdrawal/limit":{cost:1},"event/order-reward/programs":{cost:1},"event/order-reward/history":{cost:1}}}},fees:{trading:{tierBased:!1,percentage:!0,taker:.002,maker:.002}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!1,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:void 0},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},precisionMode:4,exceptions:{104:a.OrderNotFound,107:a.BadRequest,108:a.BadSymbol,405:a.OnMaintenance},commonCurrencies:{SOC:"Soda Coin"}})}async fetchCurrencies(e={}){let t=await this.v2PublicGetCurrencies(e),i=this.safeList(t,"currencies",[]);return this.parseCurrencies(i)}parseCurrency(e){let t=this.safeString(e,"symbol"),i=this.safeCurrencyCode(t),s="normal"===this.safeString(e,"withdraw_status",""),r="normal"===this.safeString(e,"deposit_status",""),a="fiat";return"KRW"!==i&&(a="crypto"),this.safeCurrencyStructure({id:t,code:i,info:e,name:this.safeString(e,"name"),active:void 0,deposit:r,withdraw:s,fee:this.safeNumber(e,"withdrawal_fee"),precision:this.parseNumber(this.parsePrecision(this.safeString(e,"max_precision"))),limits:{amount:{min:void 0,max:void 0},withdraw:{min:this.safeNumber(e,"withdrawal_min_amount"),max:void 0}},networks:{},type:a})}async fetchMarkets(e={}){let t=await this.v2PublicGetTickerNewQuoteCurrency({quote_currency:"KRW"}),i=this.safeList(t,"tickers",[]),s=[];for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),r=this.safeString(t,"id"),a=this.safeStringUpper(t,"target_currency"),o=this.safeStringUpper(t,"quote_currency"),n=this.safeCurrencyCode(a),d=this.safeCurrencyCode(o);void 0!==n&&void 0!==d&&s.push({id:r,symbol:n+"/"+d,base:n,quote:d,settle:void 0,baseId:a,quoteId:o,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:void 0,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber("1e-4"),price:this.parseNumber("1e-4"),cost:this.parseNumber("1e-8")},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:t})}return s}parseBalance(e){let t={info:e},i=this.omit(e,["errorCode","result","normalWallets"]),s=Object.keys(i);for(let e=0;e<s.length;e++){let r=s[e],a=this.safeDict(i,r),o=this.safeCurrencyCode(r),n=this.account();n.free=this.safeString(a,"avail"),n.total=this.safeString(a,"balance"),void 0!==o&&(t[o]=n)}return this.safeBalance(t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v2PrivatePostAccountBalance(e);return this.parseBalance(t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={quote_currency:s.quote,target_currency:s.base};void 0!==t&&(r.size=t);let a=await this.v2PublicGetOrderbookQuoteCurrencyTargetCurrency(this.extend(r,i)),o=this.safeInteger(a,"timestamp");return this.parseOrderBook(a,s.symbol,o,"bids","asks","price","qty")}async fetchTickers(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e),a={quote_currency:"KRW"};if(void 0!==r){let e=this.safeString(r,0);a.quote_currency=(i=this.market(e)).quote,a.target_currency=i.base,s=await this.v2PublicGetTickerNewQuoteCurrencyTargetCurrency(this.extend(a,t))}else s=await this.v2PublicGetTickerNewQuoteCurrency(this.extend(a,t));let o=this.safeList(s,"tickers",[]);return this.parseTickers(o,r)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={quote_currency:i.quote,target_currency:i.base},r=await this.v2PublicGetTickerNewQuoteCurrencyTargetCurrency(this.extend(s,t)),a=this.safeList(r,"tickers",[]),o=this.safeDict(a,0,{});return this.parseTicker(o,i)}parseTicker(e,t){let i,s=this.safeInteger(e,"timestamp"),r=this.safeString(e,"last"),a=this.safeList(e,"best_asks",[]),o=this.safeList(e,"best_bids",[]),n=this.safeString(e,"target_currency"),d=this.safeString(e,"quote_currency"),h=this.safeCurrencyCode(n),c=this.safeCurrencyCode(d);return void 0!==h&&void 0!==c&&(i=h+"/"+c),this.safeTicker({symbol:i,timestamp:s,datetime:this.iso8601(s),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(o,"price"),bidVolume:this.safeString(o,"qty"),ask:this.safeString(a,"price"),askVolume:this.safeString(a,"qty"),vwap:void 0,open:this.safeString(e,"first"),close:r,last:r,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"target_volume"),quoteVolume:this.safeString(e,"quote_volume"),info:e},t)}parseTrade(e,t){let i,s,r=this.safeInteger(e,"timestamp"),a=this.safeMarket(void 0,t),n=this.safeBool(e,"is_seller_maker");void 0!==n&&(i=n?"sell":"buy");let d=this.safeString(e,"price"),h=this.safeString(e,"qty"),c=this.safeString(e,"orderId"),l=this.safeString(e,"fee");if(void 0!==l){l=o.Y.stringAbs(l);let t=this.safeString(e,"feeRate");t=o.Y.stringAbs(t),s={cost:l,currency:"sell"===i?a.quote:a.base,rate:t}}return this.safeTrade({id:this.safeString(e,"id"),info:e,timestamp:r,datetime:this.iso8601(r),order:c,symbol:a.symbol,type:void 0,side:i,takerOrMaker:void 0,price:d,amount:h,cost:void 0,fee:s},a)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={quote_currency:r.quote,target_currency:r.base};void 0!==i&&(a.size=Math.min(i,200));let o=await this.v2PublicGetTradesQuoteCurrencyTargetCurrency(this.extend(a,s)),n=this.safeList(o,"transactions",[]);return this.parseTrades(n,r,t,i)}async createOrder(e,t,i,s,r,o={}){let n=t.toUpperCase(),d=i.toUpperCase();if("LIMIT"!==n)throw new a.ExchangeError(this.id+" createOrder() allows limit orders only");if(void 0===r)throw new a.ArgumentsRequired(this.id+" createOrder() requires a price argument for the limit orders");void 0===this.markets&&await this.loadMarkets();let h=this.market(e),c={quote_currency:h.quoteId,target_currency:h.baseId,type:n,side:d,price:this.priceToPrecision(e,r),qty:this.amountToPrecision(e,s)},l=await this.v2_1PrivatePostOrderLimit(this.extend(c,o));return this.parseOrder(l,h)}async fetchOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r={order_id:e,currency:s.id},o=await this.v2PrivatePostOrderQueryOrder(this.extend(r,i));return this.parseOrder(o,s)}parseOrderStatus(e){return this.safeString({live:"open",partially_filled:"open",partially_canceled:"open",filled:"closed",canceled:"canceled"},e,e)}parseOrder(e,t){let i,s,r,a,n=this.safeString2(e,"orderId","order_id"),d=this.safeString2(e,"baseCurrency","target_currency"),h=this.safeString2(e,"targetCurrency","quote_currency");void 0!==d&&(i=this.safeCurrencyCode(d)),void 0!==h&&(s=this.safeCurrencyCode(h)),void 0!==i&&void 0!==s&&(r=i+"/"+s);let c=void 0!==r?this.safeMarket(r,t,"/"):t,l=this.safeTimestamp2(e,"timestamp","updatedAt");void 0===l&&(l=this.safeInteger2(e,"ordered_at","updated_at"));let u=this.safeStringLower2(e,"type","side");("limit"===u||"market"===u||"stop_limit"===u)&&(u=this.safeStringLower(e,"side")),"ask"===u?u="sell":"bid"===u&&(u="buy");let f=this.safeString2(e,"remainQty","remain_qty"),p=this.safeStringN(e,["originalQty","qty","original_qty"]),m=this.safeString(e,"status");"live"===m&&void 0!==f&&void 0!==p&&o.Y.stringLt(f,p)&&(m="canceled"),m=this.parseOrderStatus(m);let g=this.safeString(e,"fee");if(void 0!==g){let t=i;"sell"===u&&(t=s),a={cost:g,rate:this.safeString2(e,"feeRate","fee_rate"),currency:t}}return this.safeOrder({info:e,id:n,clientOrderId:void 0,timestamp:l,datetime:this.iso8601(l),lastTradeTimestamp:void 0,symbol:r,type:"limit",timeInForce:void 0,postOnly:void 0,side:u,price:this.safeString(e,"price"),triggerPrice:void 0,cost:void 0,average:this.safeString2(e,"averageExecutedPrice","average_executed_price"),amount:p,filled:this.safeString2(e,"executedQty","executed_qty"),remaining:f,status:m,fee:a,trades:void 0},c)}async fetchOpenOrders(e,t,i,s={}){if(void 0===e)throw new a.ExchangeError(this.id+" fetchOpenOrders() allows fetching closed orders with a specific symbol");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={quote_currency:r.quoteId,target_currency:r.baseId},n=await this.v2_1PrivatePostOrderOpenOrders(this.extend(o,s)),d=this.safeList2(n,"open_orders","limitOrders",[]);return this.parseOrders(d,r,t,i)}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={currency:r.id},n=await this.v2PrivatePostOrderCompleteOrders(this.extend(o,s)),d=this.safeList(n,"completeOrders",[]);return this.parseTrades(d,r,t,i)}async cancelOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument. To cancel the order, pass a symbol argument and {'price': 12345, 'qty': 1.2345, 'is_ask': 0} in the params argument of cancelOrder.");let s=this.safeNumber(i,"price"),r=this.safeNumber(i,"qty"),o=this.safeInteger(i,"is_ask");if(void 0===s||void 0===r||void 0===o)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires {'price': 12345, 'qty': 1.2345, 'is_ask': 0} in the params argument.");void 0===this.markets&&await this.loadMarkets();let n={order_id:e,price:s,qty:r,is_ask:o,currency:this.marketId(t)},d=await this.v2PrivatePostOrderCancel(this.extend(n,i));return this.safeOrder(d)}async fetchDepositAddresses(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.v2PrivatePostAccountDepositAddress(t),s=this.safeDict(i,"walletAddress",{}),r=Object.keys(s),a={};for(let e=0;e<r.length;e++){let t=r[e],i=this.safeString(s,t);if(null==i||""===i||"-1"===i)continue;let o=t.split("_"),n=this.safeString(o,0),d=this.safeString(o,1),h=this.safeCurrencyCode(n),c=this.safeDict(a,h);void 0===c&&(c={info:i,currency:h,network:void 0,address:void 0,tag:void 0});let l=this.safeString(c,"address",i);this.checkAddress(l),c.address=l,c.info=l,("tag"===d||"memo"===d)&&(c.tag=i,c.info=[l,i]),void 0!==h&&(a[h]=c)}return a}sign(e,t="public",i="GET",r={},o,n){let d,h,c=this.implodeParams(e,r),l=this.omit(r,this.extractParams(e)),u=this.safeString(this.urls.api,"rest");if(void 0===u)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let f=u+"/";if("v2Public"===t){let e=this.safeString(this.urls.api,"v2Public");if(void 0===e)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");f=e+"/"}else if("v2Private"===t){let e=this.safeString(this.urls.api,"v2Private");if(void 0===e)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");f=e+"/"}else if("v2_1Private"===t){let e=this.safeString(this.urls.api,"v2_1Private");if(void 0===e)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");f=e+"/"}if("public"===t||"v2Public"===t)f+=c,Object.keys(l).length>0&&(f+="?"+this.urlencode(l));else{let e;this.checkRequiredCredentials(),f+=c,e="v2_1Private"===t?this.uuid():this.nonce().toString();let i=this.json(this.extend({access_token:this.apiKey,nonce:e},r)),a=this.stringToBase64(i);d=a;let o=this.secret.toUpperCase(),n=this.hmac(this.encode(a),this.encode(o),s.Zf);h={"Content-Type":"application/json","X-COINONE-PAYLOAD":a,"X-COINONE-SIGNATURE":n}}return{url:f,method:i,body:void 0===d?n:d,headers:void 0===h?o:h}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"error_code");if(void 0!==c&&"0"!==c){let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions,c,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>n})},4410(e,t,i){"use strict";var s=i(4721),r=i(2597),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"coinsph",name:"Coins.ph",countries:["PH"],version:"v1",rateLimit:50,certified:!1,pro:!1,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!1,closeAllPositions:!1,closePosition:!1,createDepositAddress:!1,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,deposit:!0,editOrder:!1,fetchAccounts:!1,fetchBalance:!0,fetchBidsAsks:!1,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCanceledOrders:!1,fetchClosedOrder:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:void 0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositWithdrawFee:!1,fetchDepositWithdrawFees:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchL3OrderBook:!1,fetchLedger:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrder:void 0,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrders:!1,fetchOrderTrades:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTradingLimits:!1,fetchTransactionFee:!1,fetchTransactionFees:!1,fetchTransactions:!1,fetchTransfers:!1,fetchVolatilityHistory:!1,fetchWithdrawal:void 0,fetchWithdrawals:!0,fetchWithdrawalWhitelist:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,signIn:!1,transfer:!1,withdraw:!0,ws:!1},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","8h":"8h","12h":"12h","1d":"1d","3d":"3d","1w":"1w","1M":"1M"},urls:{logo:"https://user-images.githubusercontent.com/1294454/225719995-48ab2026-4ddb-496c-9da7-0d7566617c9b.jpg",api:{public:"https://api.pro.coins.ph",private:"https://api.pro.coins.ph"},www:"https://coins.ph/",doc:["https://coins-docs.github.io/rest-api"],fees:"https://support.coins.ph/hc/en-us/sections/4407198694681-Limits-Fees",referral:{url:"https://www.coins.ph/en-ph/register?invite_code=1371062463303277512&broker=9001",discount:.2}},api:{public:{get:{"openapi/v1/ping":{cost:1},"openapi/v1/time":{cost:1},"openapi/v1/user/ip":{cost:1},"openapi/quote/v1/ticker/24hr":{cost:1,noSymbolAndNoSymbols:40,byNumberOfSymbols:[[101,40],[21,20],[0,1]]},"openapi/quote/v1/ticker/price":{cost:1,noSymbol:2},"openapi/quote/v1/ticker/bookTicker":{cost:1,noSymbol:2},"openapi/v1/exchangeInfo":{cost:10},"openapi/quote/v1/depth":{cost:1,byLimit:[[101,5],[0,1]]},"openapi/quote/v1/klines":{cost:1},"openapi/quote/v1/trades":{cost:1},"openapi/v1/pairs":{cost:1},"openapi/quote/v1/avgPrice":{cost:1}}},private:{get:{"openapi/v1/check-sys-status":{cost:1},"openapi/wallet/v1/config/getall":{cost:10},"openapi/wallet/v1/deposit/address":{cost:10},"openapi/wallet/v1/deposit/history":{cost:1},"openapi/wallet/v1/withdraw/history":{cost:1},"openapi/wallet/v1/withdraw/address-whitelist":{cost:1},"openapi/v1/account":{cost:10},"openapi/v1/api-keys":{cost:1},"openapi/v1/openOrders":{cost:3,noSymbol:40},"openapi/v1/asset/tradeFee":{cost:1},"openapi/v1/order":{cost:2},"openapi/v1/historyOrders":{cost:10,noSymbol:40},"openapi/v1/myTrades":{cost:10},"openapi/v1/capital/deposit/history":{cost:1},"openapi/v1/capital/withdraw/history":{cost:1},"openapi/v3/payment-request/get-payment-request":{cost:1},"merchant-api/v1/get-invoices":{cost:1},"openapi/account/v3/crypto-accounts":{cost:1},"openapi/transfer/v3/transfers/{id}":{cost:1},"openapi/v1/sub-account/list":{cost:10},"openapi/v1/sub-account/asset":{cost:10},"openapi/v1/sub-account/transfer/universal-transfer-history":{cost:10},"openapi/v1/sub-account/transfer/sub-history":{cost:10},"openapi/v1/sub-account/apikey/ip-restriction":{cost:10},"openapi/v1/sub-account/wallet/deposit/address":{cost:1},"openapi/v1/sub-account/wallet/deposit/history":{cost:1},"openapi/v1/fund-collect/get-fund-record":{cost:1},"openapi/v1/asset/transaction/history":{cost:20}},post:{"openapi/wallet/v1/withdraw/apply":{cost:600},"openapi/v1/order/test":{cost:1},"openapi/v1/order":{cost:1},"openapi/v1/order/cancelReplace":{cost:1},"openapi/v1/capital/withdraw/apply":{cost:1},"openapi/v1/capital/deposit/apply":{cost:1},"openapi/v3/payment-request/payment-requests":{cost:1},"openapi/v3/payment-request/delete-payment-request":{cost:1},"openapi/v3/payment-request/payment-request-reminder":{cost:1},"openapi/v1/userDataStream":{cost:1},"merchant-api/v1/invoices":{cost:1},"merchant-api/v1/invoices-cancel":{cost:1},"openapi/convert/v1/get-supported-trading-pairs":{cost:1},"openapi/convert/v1/get-quote":{cost:1},"openapi/convert/v1/accept-quote":{cost:1},"openapi/convert/v1/query-order-history":{cost:1},"openapi/otc-trade/v1/get-supported-trading-pairs":{cost:1},"openapi/otc-trade/v1/create-rfq":{cost:1},"openapi/otc-trade/v1/accept-rfq":{cost:1},"openapi/otc-trade/v1/manual-settle":{cost:1},"openapi/otc-trade/v1/query-order-history":{cost:1},"openapi/fiat/v1/support-channel":{cost:1},"openapi/fiat/v1/cash-out":{cost:1},"openapi/fiat/v1/history":{cost:1},"openapi/fiat/v2/history":{cost:1},"openapi/fiat/v1/cancel_qr_code":{cost:1},"openapi/migration/v4/sellorder":{cost:1},"openapi/migration/v4/validate-field":{cost:1},"openapi/transfer/v3/transfers":{cost:1},"openapi/transfer/v4/transfers":{cost:1},"openapi/v1/sub-account/create":{cost:30},"openapi/v1/sub-account/transfer/universal-transfer":{cost:100},"openapi/v1/sub-account/transfer/sub-to-master":{cost:100},"openapi/v1/sub-account/apikey/add-ip-restriction":{cost:30},"openapi/v1/sub-account/apikey/delete-ip-restriction":{cost:30},"openapi/v1/fund-collect/collect-from-sub-account":{cost:1}},put:{"openapi/v1/userDataStream":{cost:1}},delete:{"openapi/v1/order":{cost:1},"openapi/v1/openOrders":{cost:1},"openapi/v1/userDataStream":{cost:1}}}},fees:{trading:{feeSide:"get",tierBased:!0,percentage:!0,maker:this.parseNumber("0.0025"),taker:this.parseNumber("0.003"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.003")],[this.parseNumber("500000"),this.parseNumber("0.0027")],[this.parseNumber("1000000"),this.parseNumber("0.0024")],[this.parseNumber("2500000"),this.parseNumber("0.002")],[this.parseNumber("5000000"),this.parseNumber("0.0018")],[this.parseNumber("10000000"),this.parseNumber("0.0015")],[this.parseNumber("100000000"),this.parseNumber("0.0012")],[this.parseNumber("500000000"),this.parseNumber("0.0009")],[this.parseNumber("1000000000"),this.parseNumber("0.0007")],[this.parseNumber("2500000000"),this.parseNumber("0.0005")]],maker:[[this.parseNumber("0"),this.parseNumber("0.0025")],[this.parseNumber("500000"),this.parseNumber("0.0022")],[this.parseNumber("1000000"),this.parseNumber("0.0018")],[this.parseNumber("2500000"),this.parseNumber("0.0015")],[this.parseNumber("5000000"),this.parseNumber("0.0012")],[this.parseNumber("10000000"),this.parseNumber("0.001")],[this.parseNumber("100000000"),this.parseNumber("0.0008")],[this.parseNumber("500000000"),this.parseNumber("0.0007")],[this.parseNumber("1000000000"),this.parseNumber("0.0006")],[this.parseNumber("2500000000"),this.parseNumber("0.0005")]]}}},precisionMode:4,options:{createMarketBuyOrderRequiresPrice:!0,withdraw:{warning:!1},deposit:{warning:!1},createOrder:{timeInForce:"GTC",newOrderRespType:{market:"FULL",limit:"FULL"}},fetchTicker:{method:"publicGetOpenapiQuoteV1Ticker24hr"},fetchTickers:{method:"publicGetOpenapiQuoteV1Ticker24hr"},networks:{TRC20:"TRX",ERC20:"ETH",BEP20:"BSC",ARBITRUM:"ARBITRUM"}},features:{spot:{sandbox:!1,fetchCurrencies:{private:!0},createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!1,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,selfTradePrevention:!0,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:1e5,untilDays:1e5,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:1e3,daysBack:1e5,daysBackCanceled:1,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!0},fetchOHLCV:{limit:1e3}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},exceptions:{exact:{"-1000":a.BadRequest,"-1001":a.BadRequest,"-1002":a.AuthenticationError,"-1003":a.RateLimitExceeded,"-1004":a.InvalidOrder,"-1006":a.BadResponse,"-1007":a.BadResponse,"-1014":a.InvalidOrder,"-1015":a.RateLimitExceeded,"-1016":a.NotSupported,"-1020":a.NotSupported,"-1021":a.BadRequest,"-1022":a.BadRequest,"-1023":a.AuthenticationError,"-1024":a.BadRequest,"-1025":a.BadRequest,"-1030":a.ExchangeError,"-1100":a.BadRequest,"-1101":a.BadRequest,"-1102":a.BadRequest,"-1103":a.BadRequest,"-1104":a.BadRequest,"-1105":a.BadRequest,"-1106":a.BadRequest,"-1111":a.BadRequest,"-1112":a.BadResponse,"-1114":a.BadRequest,"-1115":a.InvalidOrder,"-1116":a.InvalidOrder,"-1117":a.InvalidOrder,"-1118":a.InvalidOrder,"-1119":a.InvalidOrder,"-1120":a.BadRequest,"-1121":a.BadSymbol,"-1122":a.InvalidOrder,"-1125":a.BadRequest,"-1127":a.BadRequest,"-1128":a.BadRequest,"-1130":a.BadRequest,"-1131":a.InsufficientFunds,"-1132":a.InvalidOrder,"-1133":a.InvalidOrder,"-1134":a.InvalidOrder,"-1135":a.InvalidOrder,"-1136":a.InvalidOrder,"-1137":a.InvalidOrder,"-1138":a.InvalidOrder,"-1139":a.InvalidOrder,"-1140":a.InvalidOrder,"-1141":a.DuplicateOrderId,"-1142":a.InvalidOrder,"-1143":a.OrderNotFound,"-1144":a.InvalidOrder,"-1145":a.InvalidOrder,"-1146":a.InvalidOrder,"-1147":a.InvalidOrder,"-1148":a.InvalidOrder,"-1149":a.InvalidOrder,"-1150":a.InvalidOrder,"-1151":a.BadSymbol,"-1152":a.NotSupported,"-1153":a.AuthenticationError,"-1154":a.BadRequest,"-1155":a.BadRequest,"-1156":a.InvalidOrder,"-1157":a.BadSymbol,"-1158":a.InvalidOrder,"-1159":a.InvalidOrder,"-1160":a.BadRequest,"-1161":a.BadRequest,"-2010":a.InvalidOrder,"-2013":a.OrderNotFound,"-2011":a.BadRequest,"-2014":a.BadRequest,"-2015":a.AuthenticationError,"-2016":a.BadResponse,"-3126":a.InvalidOrder,"-3127":a.InvalidOrder,"-4001":a.BadRequest,"-100011":a.BadSymbol,"-100012":a.BadSymbol,"-30008":a.InsufficientFunds,"-30036":a.InsufficientFunds,403:a.ExchangeNotAvailable},broad:{"Unknown order sent":a.OrderNotFound,"Duplicate order sent":a.DuplicateOrderId,"Market is closed":a.BadSymbol,"Account has insufficient balance for requested action":a.InsufficientFunds,"Market orders are not supported for this symbol":a.BadSymbol,"Iceberg orders are not supported for this symbol":a.BadSymbol,"Stop loss orders are not supported for this symbol":a.BadSymbol,"Stop loss limit orders are not supported for this symbol":a.BadSymbol,"Take profit orders are not supported for this symbol":a.BadSymbol,"Take profit limit orders are not supported for this symbol":a.BadSymbol,"Price* QTY is zero or less":a.BadRequest,"IcebergQty exceeds QTY":a.BadRequest,"This action disabled is on this account":a.PermissionDenied,"Unsupported order combination":a.InvalidOrder,"Order would trigger immediately":a.InvalidOrder,"Cancel order is invalid. Check origClOrdId and orderId":a.InvalidOrder,"Order would immediately match and take":a.OrderImmediatelyFillable,PRICE_FILTER:a.InvalidOrder,LOT_SIZE:a.InvalidOrder,MIN_NOTIONAL:a.InvalidOrder,MAX_NUM_ORDERS:a.InvalidOrder,MAX_ALGO_ORDERS:a.InvalidOrder,BROKER_MAX_NUM_ORDERS:a.InvalidOrder,BROKER_MAX_ALGO_ORDERS:a.InvalidOrder,ICEBERG_PARTS:a.BadRequest}}})}async fetchCurrencies(e={}){if(!this.checkRequiredCredentials(!1))return{};let t=await this.privateGetOpenapiWalletV1ConfigGetall(e);return this.parseCurrencies(t)}parseCurrency(e){let t=this.safeString(e,"coin"),i=this.safeCurrencyCode(t),s=this.safeBool(e,"isLegalMoney"),r=this.safeList(e,"networkList",[]),a={};for(let e=0;e<r.length;e++){let t=r[e],s=this.safeString(t,"network"),o=this.networkIdToCode(s,i);void 0!==o&&(a[o]={info:t,id:s,network:o,active:void 0,deposit:this.safeBool(t,"depositEnable"),withdraw:this.safeBool(t,"withdrawEnable"),fee:this.safeNumber(t,"withdrawFee"),precision:this.safeNumber(t,"withdrawIntegerMultiple"),limits:{withdraw:{min:this.safeNumber(t,"withdrawMin"),max:this.safeNumber(t,"withdrawMax")},deposit:{min:void 0,max:void 0}}})}return this.safeCurrencyStructure({id:t,name:this.safeString(e,"name"),code:i,type:!0===s?"fiat":"crypto",precision:this.parseNumber(this.parsePrecision(this.safeString(e,"transferPrecision"))),info:e,active:void 0,deposit:this.safeBool(e,"depositAllEnable"),withdraw:this.safeBool(e,"withdrawAllEnable"),networks:a,fee:void 0,fees:void 0,limits:{}})}calculateRateLimiterCost(e,t,i,s,r={}){if("noSymbol"in r&&!("symbol"in s))return r.noSymbol;if("noSymbolAndNoSymbols"in r&&!("symbol"in s)&&!("symbols"in s))return r.noSymbolAndNoSymbols;if("byNumberOfSymbols"in r&&"symbols"in s){let e=s.symbols.length,t=this.safeList(r,"byNumberOfSymbols",[]);for(let i=0;i<t.length;i++){let s=t[i];if(e>=s[0])return s[1]}}else if("byLimit"in r&&"limit"in s){let e=s.limit,t=this.safeList(r,"byLimit",[]);for(let i=0;i<t.length;i++){let s=t[i];if(e>=s[0])return s[1]}}return this.safeValue(r,"cost",1)}async fetchStatus(e={}){return{status:"ok",updated:void 0,eta:void 0,url:void 0,info:await this.publicGetOpenapiV1Ping(e)}}async fetchTime(e={}){let t=await this.publicGetOpenapiV1Time(e);return this.safeInteger(t,"serverTime")}async fetchMarkets(e={}){let t=await this.publicGetOpenapiV1ExchangeInfo(e),i=this.safeList(t,"symbols",[]),s=[];for(let e=0;e<i.length;e++){let t=i[e],r=this.safeString(t,"symbol"),a=this.safeString(t,"baseAsset"),o=this.safeString(t,"quoteAsset"),n=this.safeCurrencyCode(a),d=this.safeCurrencyCode(o);if(void 0===n||void 0===d)continue;let h=this.indexBy(this.safeList(t,"filters",[]),"filterType"),c=this.safeDict(h,"LOT_SIZE",{}),l=this.safeDict(h,"PRICE_FILTER",{}),u=this.safeDict(h,"NOTIONAL",{});s.push({id:r,symbol:n+"/"+d,base:n,quote:d,settle:void 0,baseId:a,quoteId:o,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:"trading"===this.safeStringLower(t,"status"),contract:!1,linear:void 0,inverse:void 0,taker:void 0,maker:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.safeString(c,"stepSize")),price:this.parseNumber(this.safeString(l,"tickSize"))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.parseNumber(this.safeString(c,"minQty")),max:this.parseNumber(this.safeString(c,"maxQty"))},price:{min:this.parseNumber(this.safeString(l,"minPrice")),max:this.parseNumber(this.safeString(l,"maxPrice"))},cost:{min:this.parseNumber(this.safeString(u,"minNotional")),max:void 0}},created:void 0,info:t})}return this.setMarkets(s),s}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={};if(void 0!==e){let t=[];for(let i=0;i<e.length;i++){let s=this.market(e[i]).id;t.push(s)}i.symbols=t}let s=this.safeDict(this.options,"fetchTickers",{}),r=this.safeString(s,"method","publicGetOpenapiQuoteV1Ticker24hr"),a=[];return a="publicGetOpenapiQuoteV1TickerPrice"===r?await this.publicGetOpenapiQuoteV1TickerPrice(this.extend(i,t)):"publicGetOpenapiQuoteV1TickerBookTicker"===r?await this.publicGetOpenapiQuoteV1TickerBookTicker(this.extend(i,t)):await this.publicGetOpenapiQuoteV1Ticker24hr(this.extend(i,t)),this.parseTickers(a,e,t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=this.safeDict(this.options,"fetchTicker",{}),a=this.safeString(r,"method","publicGetOpenapiQuoteV1Ticker24hr"),o={};return o="publicGetOpenapiQuoteV1TickerPrice"===a?await this.publicGetOpenapiQuoteV1TickerPrice(this.extend(s,t)):"publicGetOpenapiQuoteV1TickerBookTicker"===a?await this.publicGetOpenapiQuoteV1TickerBookTicker(this.extend(s,t)):await this.publicGetOpenapiQuoteV1Ticker24hr(this.extend(s,t)),this.parseTicker(o,i)}parseTicker(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeInteger(e,"closeTime"),a=this.safeString(e,"bidPrice"),n=this.safeString(e,"askPrice"),d=this.safeString(e,"bidQty"),h=this.safeString(e,"askQty"),c=this.safeString(e,"volume"),l=this.safeString(e,"quoteVolume"),u=this.safeString(e,"openPrice"),f=this.safeString(e,"highPrice"),p=this.safeString(e,"lowPrice"),m=this.safeString(e,"prevClosePrice"),g=this.safeString(e,"weightedAvgPrice"),v=this.safeString(e,"priceChange"),y=this.safeString(e,"priceChangePercent");return y=o.Y.stringMul(y,"100"),this.safeTicker({symbol:s.symbol,timestamp:r,datetime:this.iso8601(r),open:u,high:f,low:p,close:this.safeString2(e,"lastPrice","price"),bid:a,bidVolume:d,ask:n,askVolume:h,vwap:g,previousClose:m,change:v,percentage:y,average:void 0,baseVolume:c,quoteVolume:l,info:e},s)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={symbol:this.market(e).id};void 0!==t&&(s.limit=t);let r=await this.publicGetOpenapiQuoteV1Depth(this.extend(s,i)),a=this.parseOrderBook(r,e);return a.nonce=this.safeInteger(r,"lastUpdateId"),a}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=this.safeString(this.timeframes,t),n=this.safeInteger(r,"until"),d={symbol:a.id,interval:o},h=void 0===s?1e3:s;if(void 0!==i)if(d.startTime=i,void 0!==n)d.endTime=n;else{let e=1e3*this.parseTimeframe(t);d.endTime=Math.min(this.sum(i,e*(h-1)),this.milliseconds())}else void 0!==n&&(d.endTime=n,d.startTime=n-1e3*this.parseTimeframe(t)*(h-1));d.limit=h;let c=this.omit(r,"until"),l=await this.publicGetOpenapiQuoteV1Klines(this.extend(d,c)),u=this.toArray(l);return this.parseOHLCVs(u,a,t,i,h)}parseOHLCV(e,t){return[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id};void 0!==t?a.limit=1e3:void 0!==i&&(a.limit=i);let o=await this.publicGetOpenapiQuoteV1Trades(this.extend(a,s));return this.parseTrades(o,r,t,i)}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={symbol:r.id};void 0!==t?(o.startTime=t,o.limit=1e3):void 0!==i&&(o.limit=i);let n=await this.privateGetOpenapiV1MyTrades(this.extend(o,s));return this.parseTrades(n,r,t,i)}async fetchOrderTrades(e,t,i,s,r={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrderTrades() requires a symbol argument");return await this.fetchMyTrades(t,i,s,this.extend({orderId:e},r))}parseTrade(e,t){let i,s,r,a=this.safeString(e,"symbol"),o=this.safeMarket(a,t),n=o.symbol,d=this.safeString2(e,"id","tradeId"),h=this.safeString(e,"orderId"),c=this.safeInteger(e,"time"),l=this.safeString(e,"price"),u=this.safeString(e,"qty"),f={},p=this.safeString(e,"commission");if(void 0!==p){let t=this.safeString(e,"commissionAsset");f={cost:p,currency:this.safeCurrencyCode(t)}}let m=this.safeBool2(e,"isBuyer","isBuyerMaker");void 0!==m&&(i=!0===m?"buy":"sell");let g=this.safeString(e,"isMaker");return void 0!==g&&(s="true"===g?"maker":"taker"),void 0!==h&&(r=this.safeString(e,"quoteQty")),this.safeTrade({id:d,order:h,timestamp:c,datetime:this.iso8601(c),symbol:n,type:void 0,side:i,takerOrMaker:s,price:l,amount:u,cost:r,fee:f,info:e},o)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetOpenapiV1Account(e);return this.parseBalance(t)}parseBalance(e){let t=this.safeList(e,"balances",[]),i={info:e,timestamp:void 0,datetime:void 0};for(let e=0;e<t.length;e++){let s=this.safeDict(t,e),r=this.safeString(s,"asset"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(s,"free"),o.used=this.safeString(s,"locked"),void 0!==a&&(i[a]=o)}return this.safeBalance(i)}async createOrder(e,t,i,s,r,n={}){let d;void 0===this.markets&&await this.loadMarkets();let h=this.market(e),c=this.safeBool(n,"test",!1),l=this.omit(n,"test"),u=this.safeString(l,"type",t);u=this.encodeOrderType(u);let f=this.omit(l,"type"),p=this.encodeOrderSide(i),m={symbol:h.id,type:u,side:p},g=this.safeDict(this.options,"createOrder",{}),v=this.safeValue(g,"newOrderRespType",{});if("LIMIT"===u||"STOP_LOSS_LIMIT"===u||"TAKE_PROFIT_LIMIT"===u||"LIMIT_MAKER"===u){if(void 0===r)throw new a.ArgumentsRequired(this.id+" createOrder() requires a price argument for a "+t+" order");v=this.safeString(v,"limit","FULL"),m.price=this.priceToPrecision(e,r),m.quantity=this.amountToPrecision(e,s),"LIMIT_MAKER"!==u&&(m.timeInForce=this.safeString(g,"timeInForce","GTC"))}else if("MARKET"===u||"STOP_LOSS"===u||"TAKE_PROFIT"===u){if(v=this.safeString(v,"market","FULL"),"SELL"===p)m.quantity=this.amountToPrecision(e,s);else if("BUY"===p){let t,[i,n]=this.handleOptionBoolAndParams(f,"createOrder","createMarketBuyOrderRequiresPrice",!0),h=this.safeNumber2(n,"cost","quoteOrderQty");if(d=this.omit(n,"cost"),void 0!==h)t=this.costToPrecision(e,h);else if(i)if(void 0===r)throw new a.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument");else{let i=this.numberToString(s),a=this.numberToString(r),n=o.Y.stringMul(i,a);t=this.costToPrecision(e,n)}else t=this.costToPrecision(e,s);m.quoteOrderQty=t}}if("STOP_LOSS"===u||"STOP_LOSS_LIMIT"===u||"TAKE_PROFIT"===u||"TAKE_PROFIT_LIMIT"===u){let t=this.safeString2(f,"triggerPrice","stopPrice");if(void 0===t)throw new a.InvalidOrder(this.id+" createOrder () requires a triggerPrice or stopPrice param for stop_loss, take_profit, stop_loss_limit, and take_profit_limit orders");m.stopPrice=this.priceToPrecision(e,t)}m.newOrderRespType=v;let y=void 0!==d?d:f,b=this.omit(y,"price","stopPrice","triggerPrice","quantity","quoteOrderQty"),w={};return w=!0===c?await this.privatePostOpenapiV1OrderTest(this.extend(m,b)):await this.privatePostOpenapiV1Order(this.extend(m,b)),this.parseOrder(w,h)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={},r=this.safeString2(i,"origClientOrderId","clientOrderId");void 0!==r?s.origClientOrderId=r:s.orderId=e;let a=this.omit(i,["clientOrderId","origClientOrderId"]),o=await this.privateGetOpenapiV1Order(this.extend(s,a));return this.parseOrder(o)}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id);let o=await this.privateGetOpenapiV1OpenOrders(this.extend(a,s));return this.parseOrders(o,r,t,i)}async fetchClosedOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchClosedOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={symbol:r.id};void 0!==t?(o.startTime=t,o.limit=1e3):void 0!==i&&(o.limit=i);let n=await this.privateGetOpenapiV1HistoryOrders(this.extend(o,s));return this.parseOrders(n,r,t,i)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={},r=this.safeString2(i,"origClientOrderId","clientOrderId");void 0!==r?s.origClientOrderId=r:s.orderId=e;let a=this.omit(i,["clientOrderId","origClientOrderId"]),o=await this.privateDeleteOpenapiV1Order(this.extend(s,a));return this.parseOrder(o)}async cancelAllOrders(e,t={}){let i;if(void 0===e)throw new a.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s={};void 0!==e&&(s.symbol=(i=this.market(e)).id);let r=await this.privateDeleteOpenapiV1OpenOrders(this.extend(s,t));return this.parseOrders(r,i)}parseOrder(e,t){let i=this.safeString(e,"orderId"),s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=this.safeInteger2(e,"time","transactTime"),n=this.safeList(e,"fills"),d=this.safeString(e,"stopPrice");return o.Y.stringEq(d,"0")&&(d=void 0),this.safeOrder({id:i,clientOrderId:this.safeString(e,"clientOrderId"),timestamp:a,datetime:this.iso8601(a),lastTradeTimestamp:void 0,status:this.parseOrderStatus(this.safeString(e,"status")),symbol:r.symbol,type:this.parseOrderType(this.safeString(e,"type")),timeInForce:this.parseOrderTimeInForce(this.safeString(e,"timeInForce")),side:this.parseOrderSide(this.safeString(e,"side")),price:this.safeString(e,"price"),triggerPrice:d,average:void 0,amount:this.safeString(e,"origQty"),cost:this.safeString(e,"cummulativeQuoteQty"),filled:this.safeString(e,"executedQty"),remaining:void 0,fee:void 0,fees:void 0,trades:n,info:e},r)}parseOrderSide(e){if(void 0!==e)return this.safeString({BUY:"buy",SELL:"sell"},e,e)}encodeOrderSide(e){if(void 0!==e)return this.safeString({buy:"BUY",sell:"SELL"},e,e)}parseOrderType(e){if(void 0!==e)return this.safeString({MARKET:"market",LIMIT:"limit",LIMIT_MAKER:"limit",STOP_LOSS:"market",STOP_LOSS_LIMIT:"limit",TAKE_PROFIT:"market",TAKE_PROFIT_LIMIT:"limit"},e,e)}encodeOrderType(e){if(void 0!==e)return this.safeString({market:"MARKET",limit:"LIMIT",limit_maker:"LIMIT_MAKER",stop_loss:"STOP_LOSS",stop_loss_limit:"STOP_LOSS_LIMIT",take_profit:"TAKE_PROFIT",take_profit_limit:"TAKE_PROFIT_LIMIT"},e,e)}parseOrderStatus(e){if(void 0!==e)return this.safeString({NEW:"open",FILLED:"closed",CANCELED:"canceled",PARTIALLY_FILLED:"open",PARTIALLY_CANCELED:"canceled",REJECTED:"rejected"},e,e)}parseOrderTimeInForce(e){if(void 0!==e)return this.safeString({GTC:"GTC",FOK:"FOK",IOC:"IOC"},e,e)}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.privateGetOpenapiV1AssetTradeFee(this.extend(s,t)),a=this.safeDict(r,0,{});return this.parseTradingFee(a,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetOpenapiV1AssetTradeFee(e),i={},s=this.toArray(t);for(let e=0;e<s.length;e++){let t=this.parseTradingFee(s[e]),r=t.symbol;void 0!==r&&(i[r]=t)}return i}parseTradingFee(e,t){let i=this.safeString(e,"symbol");return{info:e,symbol:this.safeMarket(i,t).symbol,maker:this.safeNumber(e,"makerCommission"),taker:this.safeNumber(e,"takerCommission"),percentage:void 0,tierBased:void 0}}async withdraw(e,t,i,s,r={}){let o=this.safeDict(this.options,"withdraw");if(!0===this.safeBool(o,"warning",!0))throw new a.InvalidAddress(this.id+" withdraw() makes a withdrawals only to coins_ph account, add .options['withdraw']['warning'] = false to make a withdrawal to your coins_ph account");let n=this.safeString(r,"network"),d=void 0===n?void 0:this.networkCodeToId(n,e);if(void 0===d)throw new a.BadRequest(this.id+" withdraw() require network parameter");void 0===this.markets&&await this.loadMarkets();let h=this.currency(e),c={coin:h.id,amount:this.numberToString(t),network:d,address:i};void 0!==s&&(c.withdrawOrderId=s);let l=this.omit(r,"network"),u=await this.privatePostOpenapiWalletV1WithdrawApply(this.extend(c,l));return this.parseTransaction(u,h)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.coin=(r=this.currency(e)).id),void 0!==t&&(a.startTime=t),void 0!==i&&(a.limit=i);let o=await this.privateGetOpenapiWalletV1DepositHistory(this.extend(a,s));return this.parseTransactions(o,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.coin=(r=this.currency(e)).id),void 0!==t&&(a.startTime=t),void 0!==i&&(a.limit=i);let o=await this.privateGetOpenapiWalletV1WithdrawHistory(this.extend(a,s));return this.parseTransactions(o,r,t,i)}parseTransaction(e,t){let i,s,r,a=this.safeString(e,"id"),o=this.safeString(e,"address"),n=this.safeString(e,"addressTag");void 0!==n&&n.length<1&&(n=void 0);let d=this.safeString(e,"txId"),h=this.safeString(e,"coin"),c=this.safeCurrencyCode(h,t);i=this.safeInteger2(e,"insertTime","applyTime");let l=this.safeString(e,"withdrawOrderId"),u=this.safeString(e,"depositOrderId");void 0!==l?s="withdrawal":void 0!==u&&(s="deposit");let f=this.parseTransactionStatus(this.safeString(e,"status")),p=this.safeNumber(e,"amount"),m=this.safeNumber(e,"transactionFee");void 0!==m&&(r={currency:c,cost:m});let g=this.safeString(e,"network");return{info:e,id:a,txid:d,timestamp:i,datetime:this.iso8601(i),network:g,address:o,addressTo:o,addressFrom:void 0,tag:n,tagTo:n,tagFrom:void 0,type:s,amount:p,currency:c,status:f,updated:void 0,internal:"Internal"===g,comment:void 0,fee:r}}parseTransactionStatus(e){if(void 0!==e)return this.safeString({0:"pending",1:"ok",2:"failed",3:"pending"},e,e)}async fetchDepositAddress(e,t={}){let i=this.safeString(t,"network"),s=void 0===i?void 0:this.networkCodeToId(i,e);if(void 0===s)throw new a.BadRequest(this.id+" fetchDepositAddress() require network parameter");void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),o={coin:r.id,network:s},n=this.omit(t,"network"),d=await this.privateGetOpenapiWalletV1DepositAddress(this.extend(o,n));return this.parseDepositAddress(d,r)}parseDepositAddress(e,t){let i=this.safeString(e,"coin");return{info:e,currency:this.safeCurrencyCode(i,t),network:void 0,address:this.safeString(e,"address"),tag:this.safeString(e,"addressTag")}}urlEncodeQuery(e={}){let t="",i=e,s=Object.keys(e);for(let r=0;r<s.length;r++){let a=s[r];if(Array.isArray(e[a])){0!==r&&(t+="&");let s=e[a];i=this.omit(i,a),t+=this.parseArrayParam(s,a)}}let r=this.urlencode(i);return 0!==r.length?r+"&"+t:t}parseArrayParam(e,t){let i=this.json(e);return t+"="+(i=(i=i.replace("[","%5B")).replace("]","%5D"))}sign(e,t="public",i="GET",r={},o,n){let d=this.safeString(this.urls.api,t);if(void 0===d)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let h=this.omit(r,this.extractParams(e)),c=d+"/"+this.implodeParams(e,r);if("private"===t){if(this.checkRequiredCredentials(),h.timestamp=this.milliseconds(),void 0===this.safeInteger(h,"recvWindow")){let e=this.safeInteger(this.options,"recvWindow");void 0!==e&&(h.recvWindow=e)}let e=this.urlEncodeQuery(h),t=this.hmac(this.encode(e),this.encode(this.secret),s.sc);return{url:c=c+"?"+e+"&signature="+t,method:i,body:n,headers:{"X-COINS-APIKEY":this.apiKey}}}let l=this.urlEncodeQuery(h);return 0!==l.length&&(c+="?"+l),{url:c,method:i,body:n,headers:o}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"code");if(void 0!==c&&"200"!==c&&"0"!==c){let e=this.id+" "+o;throw this.throwBroadlyMatchedException(this.exceptions.broad,o,e),this.throwExactlyMatchedException(this.exceptions.exact,c,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>n})},3051(e,t,i){"use strict";var s=i(4721),r=i(8118),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"coinspot",name:"CoinSpot",countries:["AU"],rateLimit:1e3,pro:!1,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createMarketOrder:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOption:!1,fetchOptionChain:!1,fetchOrderBook:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchVolatilityHistory:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,ws:!1},urls:{logo:"https://user-images.githubusercontent.com/1294454/28208429-3cacdf9a-6896-11e7-854e-4c79a772a30f.jpg",api:{public:"https://www.coinspot.com.au/pubapi",private:"https://www.coinspot.com.au/api"},www:"https://www.coinspot.com.au",doc:"https://www.coinspot.com.au/api",referral:"https://www.coinspot.com.au/register?code=PJURCU"},api:{public:{get:{latest:{cost:1}}},private:{post:{orders:{cost:1},"orders/history":{cost:1},"my/coin/deposit":{cost:1},"my/coin/send":{cost:1},"quote/buy":{cost:1},"quote/sell":{cost:1},"my/balances":{cost:1},"my/orders":{cost:1},"my/buy":{cost:1},"my/sell":{cost:1},"my/buy/cancel":{cost:1},"my/sell/cancel":{cost:1},"ro/my/balances":{cost:1},"ro/my/balances/{cointype}":{cost:1},"ro/my/deposits":{cost:1},"ro/my/withdrawals":{cost:1},"ro/my/transactions":{cost:1},"ro/my/transactions/{cointype}":{cost:1},"ro/my/transactions/open":{cost:1},"ro/my/transactions/{cointype}/open":{cost:1},"ro/my/sendreceive":{cost:1},"ro/my/affiliatepayments":{cost:1},"ro/my/referralpayments":{cost:1}}},v2:{public:{get:{latest:{cost:1},"latest/{cointype}":{cost:1},"latest/{cointype}/{markettype}":{cost:1},"buyprice/{cointype}":{cost:1},"buyprice/{cointype}/{markettype}":{cost:1},"sellprice/{cointype}":{cost:1},"sellprice/{cointype}/{markettype}":{cost:1},"orders/open/{cointype}":{cost:1},"orders/open/{cointype}/{markettype}":{cost:1},"orders/completed/{cointype}":{cost:1},"orders/completed/{cointype}/{markettype}":{cost:1},"orders/summary/completed/{cointype}":{cost:1},"orders/summary/completed/{cointype}/{markettype}":{cost:1}}},private:{post:{status:{cost:1},"my/coin/deposit":{cost:1},"quote/buy/now":{cost:1},"quote/sell/now":{cost:1},"quote/swap/now":{cost:1},"my/buy":{cost:1},"my/buy/edit":{cost:1},"my/sell":{cost:1},"my/sell/edit":{cost:1},"my/buy/now":{cost:1},"my/buy/now/coinlist":{cost:1},"my/sell/now":{cost:1},"my/sell/now/coinlist":{cost:1},"my/swap/now":{cost:1},"my/buy/cancel":{cost:1},"my/buy/cancel/all":{cost:1},"my/sell/cancel":{cost:1},"my/sell/cancel/all":{cost:1},"my/coin/withdraw/senddetails":{cost:1},"my/coin/withdraw/send":{cost:1},"my/coin/withdraw/send/async":{cost:1},"my/coin/withdraw/send/status":{cost:1},"ro/status":{cost:1},"ro/orders/market/open":{cost:1},"ro/orders/market/completed":{cost:1},"ro/my/balances":{cost:1},"ro/my/balance/{cointype}":{cost:1},"ro/my/orders/market/open":{cost:1},"ro/my/orders/limit/open":{cost:1},"ro/my/orders/completed":{cost:1},"ro/my/orders/market/completed":{cost:1},"ro/my/sendreceive":{cost:1},"ro/my/deposits":{cost:1},"ro/my/withdrawals":{cost:1},"ro/my/affiliatepayments":{cost:1},"ro/my/referralpayments":{cost:1}}}}},markets:{"BTC/AUD":this.safeMarketStructure({id:"btc",symbol:"BTC/AUD",base:"BTC",quote:"AUD",baseId:"btc",quoteId:"aud",type:"spot",spot:!0}),"BTC/USDT":this.safeMarketStructure({id:"btc",symbol:"BTC/USDT",base:"BTC",quote:"USDT",baseId:"btc",quoteId:"usdt",type:"spot",spot:!0}),"USDT/AUD":this.safeMarketStructure({id:"usdt",symbol:"USDT/AUD",base:"USDT",quote:"AUD",baseId:"usdt",quoteId:"aud",type:"spot",spot:!0}),"ETH/AUD":this.safeMarketStructure({id:"eth",symbol:"ETH/AUD",base:"ETH",quote:"AUD",baseId:"eth",quoteId:"aud",type:"spot",spot:!0}),"ADA/AUD":this.safeMarketStructure({id:"ada",symbol:"ADA/AUD",base:"ADA",quote:"AUD",baseId:"ada",quoteId:"aud",type:"spot",spot:!0}),"SOL/AUD":this.safeMarketStructure({id:"sol",symbol:"SOL/AUD",base:"SOL",quote:"AUD",baseId:"sol",quoteId:"aud",type:"spot",spot:!0}),"XRP/AUD":this.safeMarketStructure({id:"xrp",symbol:"XRP/AUD",base:"XRP",quote:"AUD",baseId:"xrp",quoteId:"aud",type:"spot",spot:!0}),"DOGE/AUD":this.safeMarketStructure({id:"doge",symbol:"DOGE/AUD",base:"DOGE",quote:"AUD",baseId:"doge",quoteId:"aud",type:"spot",spot:!0}),"LTC/AUD":this.safeMarketStructure({id:"ltc",symbol:"LTC/AUD",base:"LTC",quote:"AUD",baseId:"ltc",quoteId:"aud",type:"spot",spot:!0}),"XLM/AUD":this.safeMarketStructure({id:"xlm",symbol:"XLM/AUD",base:"XLM",quote:"AUD",baseId:"xlm",quoteId:"aud",type:"spot",spot:!0}),"TRX/AUD":this.safeMarketStructure({id:"trx",symbol:"TRX/AUD",base:"TRX",quote:"AUD",baseId:"trx",quoteId:"aud",type:"spot",spot:!0}),"EOS/AUD":this.safeMarketStructure({id:"eos",symbol:"EOS/AUD",base:"EOS",quote:"AUD",baseId:"eos",quoteId:"aud",type:"spot",spot:!0}),"A/AUD":this.safeMarketStructure({id:"eos",symbol:"A/AUD",base:"A",quote:"AUD",baseId:"eos",quoteId:"aud",type:"spot",spot:!0}),"NEO/AUD":this.safeMarketStructure({id:"neo",symbol:"NEO/AUD",base:"NEO",quote:"AUD",baseId:"ans",quoteId:"aud",type:"spot",spot:!0}),"POWR/AUD":this.safeMarketStructure({id:"powr",symbol:"POWR/AUD",base:"POWR",quote:"AUD",baseId:"powr",quoteId:"aud",type:"spot",spot:!0}),"GAS/AUD":this.safeMarketStructure({id:"gas",symbol:"GAS/AUD",base:"GAS",quote:"AUD",baseId:"gas",quoteId:"aud",type:"spot",spot:!0}),"RHOC/AUD":this.safeMarketStructure({id:"rhoc",symbol:"RHOC/AUD",base:"RHOC",quote:"AUD",baseId:"rhoc",quoteId:"aud",type:"spot",spot:!0})},commonCurrencies:{DRK:"DASH"},options:{fetchBalance:"private_post_my_balances"},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!1,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:void 0,daysBack:1e5,untilDays:1e5,symbolRequired:!1},fetchOrder:void 0,fetchOpenOrders:void 0,fetchOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:void 0},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},precisionMode:4})}parseBalance(e){let t={info:e},i=this.safeValue2(e,"balance","balances");if(Array.isArray(i))for(let e=0;e<i.length;e++){let s=i[e],r=Object.keys(s);for(let e=0;e<r.length;e++){let i=r[e],a=this.safeDict(s,i),o=this.safeCurrencyCode(i),n=this.account();n.total=this.safeString(a,"balance"),void 0!==o&&(t[o]=n)}}else{let e=Object.keys(i);for(let s=0;s<e.length;s++){let r=e[s],a=this.safeCurrencyCode(r),o=this.account();o.total=this.safeString(i,r),void 0!==a&&(t[a]=o)}}return this.safeBalance(t)}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let i=this.safeString(this.options,"fetchBalance","private_post_my_balances");return t="private_post_ro_my_balances"===i||"privatePostRoMyBalances"===i?await this.privatePostRoMyBalances(e):await this.privatePostMyBalances(e),this.parseBalance(t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={cointype:s.id},a=await this.privatePostOrders(this.extend(r,i));return this.parseOrderBook(a,s.symbol,void 0,"buyorders","sellorders","rate","amount")}parseTicker(e,t){let i=this.safeSymbol(void 0,t),s=this.safeString(e,"last");return this.safeTicker({symbol:i,timestamp:void 0,datetime:void 0,high:void 0,low:void 0,bid:this.safeString(e,"bid"),bidVolume:void 0,ask:this.safeString(e,"ask"),askVolume:void 0,vwap:void 0,open:void 0,close:s,last:s,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:void 0,quoteVolume:void 0,info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=await this.publicGetLatest(t),r=this.safeString(i,"id","");r=r.toLowerCase();let a=this.safeDict(s,"prices",{}),o=this.safeDict(a,r,{});return this.parseTicker(o,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetLatest(t),s={},r=this.safeDict(i,"prices",{}),a=Object.keys(r);for(let e=0;e<a.length;e++){let t=a[e],i=this.safeMarket(t);if(!0===i.spot){let e=i.symbol,a=r[t];s[e]=this.parseTicker(a,i)}}return this.filterByArrayTickers(s,"symbol",e)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={cointype:r.id},o=await this.privatePostOrdersHistory(this.extend(a,s)),n=this.safeList(o,"orders",[]);return this.parseTrades(n,r,t,i)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(r=this.market(e)),void 0!==t&&(a.startdate=this.yyyymmdd(t));let o=await this.privatePostRoMyTransactions(this.extend(a,s)),n=this.safeList(o,"buyorders",[]);for(let e=0;e<n.length;e++)n[e].side="buy";let d=this.safeList(o,"sellorders",[]);for(let e=0;e<d.length;e++)d[e].side="sell";let h=this.arrayConcat(n,d);return this.parseTrades(h,r,t,i)}parseTrade(e,t){let i,s,r,a=this.safeString(e,"audtotal"),n=this.safeString(e,"total",a),d=this.safeString(e,"side"),h=this.safeString(e,"amount"),c=this.safeString(e,"market"),l=this.safeSymbol(c,t,"/"),u=this.safeInteger(e,"solddate");if(void 0!==u)s=this.safeString(e,"rate"),i=u;else{s=o.Y.stringDiv(n,h);let t=this.safeString(e,"created");i=this.parse8601(t);let a=this.safeString(e,"audfeeExGst"),d=this.safeString(e,"audGst"),c=o.Y.stringAdd(a,d);r={cost:this.parseNumber(c),currency:this.safeCurrencyCode("AUD")}}return this.safeTrade({info:e,id:void 0,symbol:l,timestamp:i,datetime:this.iso8601(i),order:void 0,type:void 0,side:d,takerOrMaker:void 0,price:this.parseNumber(s),amount:this.parseNumber(h),cost:this.parseNumber(n),fee:r},t)}async createOrder(e,t,i,s,r,o={}){let n;void 0===this.markets&&await this.loadMarkets(),this.checkRequiredArgument("createOrder",i,"side");let d=i.toUpperCase();if("market"===t)throw new a.ExchangeError(this.id+" createOrder() allows limit orders only");let h={cointype:this.market(e).id,amount:s,rate:r};if("BUY"===d)n=await this.privatePostMyBuy(this.extend(h,o));else if("SELL"===d)n=await this.privatePostMySell(this.extend(h,o));else throw new a.NotSupported(this.id+" createOrder only support buy/sell side");return this.safeOrder({info:n})}async cancelOrder(e,t,i={}){let s,r=this.safeString(i,"side");if("buy"!==r&&"sell"!==r)throw new a.ArgumentsRequired(this.id+' cancelOrder() requires a side parameter, "buy" or "sell"');let o=this.omit(i,"side"),n={id:e};return s="buy"===r?await this.privatePostMyBuyCancel(this.extend(n,o)):await this.privatePostMySellCancel(this.extend(n,o)),this.safeOrder({info:s})}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0!==n&&"error"===this.safeString(n,"status")){let e=this.id+" "+this.json(n);throw new a.ExchangeError(e)}}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},o,n){let d=o,h=n,c=Array.isArray(t),l=c?t[0]:void 0,u=c?t[1]:t,f="/"+this.implodeParams(e,r),p=f;void 0!==l&&(p="/"+l+f);let m=this.safeString(this.urls.api,u);if(void 0===m)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let g=m+p;if("private"===u){this.checkRequiredCredentials();let e=this.incrementingNonce();h=this.json(this.extend({nonce:e},r)),d={"Content-Type":"application/json",key:this.apiKey,sign:this.hmac(this.encode(h),this.encode(this.secret),s.Zf)}}return{url:g,method:i,body:h,headers:d}}}i.d(t,{A:()=>n})},6214(e,t,i){"use strict";var s=i(4721),r=i(5561),a=i(7749),o=i(1453);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"cryptocom",name:"Crypto.com",countries:["MT"],version:"v2",rateLimit:10,certified:!0,pro:!0,has:{CORS:!1,spot:!0,margin:!0,swap:!0,future:!0,option:!1,addMargin:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,cancelOrdersForSymbols:!0,closeAllPositions:!1,closePosition:!0,createMarketBuyOrderWithCost:!1,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createStopOrder:!0,createTriggerOrder:!0,editOrder:!0,fetchAccounts:!0,fetchBalance:!0,fetchBidsAsks:!1,fetchBorrowInterest:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchClosedOrders:"emulated",fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!0,fetchDeposits:!0,fetchDepositsWithdrawals:!1,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!1,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLedger:!0,fetchLeverage:!1,fetchLeverageTiers:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!0,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsHistory:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!0,fetchStatus:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!1,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTransactionFees:!1,fetchTransactions:!1,fetchTransfers:!1,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,sandbox:!0,setLeverage:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,withdraw:!0},timeframes:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","4h":"4h","6h":"6h","12h":"12h","1d":"1D","1w":"7D","2w":"14D","1M":"1M"},urls:{logo:"https://user-images.githubusercontent.com/1294454/147792121-38ed5e36-c229-48d6-b49a-48d05fc19ed4.jpeg",test:{v1:"https://uat-api.3ona.co/exchange/v1",v2:"https://uat-api.3ona.co/v2",derivatives:"https://uat-api.3ona.co/v2"},api:{base:"https://api.crypto.com",v1:"https://api.crypto.com/exchange/v1",v2:"https://api.crypto.com/v2",derivatives:"https://deriv-api.crypto.com/v1"},www:"https://crypto.com/",referral:{url:"https://crypto.com/exch/kdacthrnxt",discount:.75},doc:["https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html","https://exchange-docs.crypto.com/spot/index.html","https://exchange-docs.crypto.com/derivatives/index.html"],fees:"https://crypto.com/exchange/document/fees-limits"},api:{base:{public:{get:{"v1/public/get-announcements":{cost:1}}}},v1:{public:{get:{"public/auth":{cost:10/3},"public/get-instruments":{cost:10/3},"public/get-book":{cost:1},"public/get-candlestick":{cost:1},"public/get-trades":{cost:1},"public/get-tickers":{cost:1},"public/get-valuations":{cost:1},"public/get-expired-settlement-price":{cost:10/3},"public/get-insurance":{cost:1},"public/get-announcements":{cost:1},"public/get-risk-parameters":{cost:1}},post:{"public/staking/get-conversion-rate":{cost:2}}},private:{post:{"private/set-cancel-on-disconnect":{cost:10/3},"private/get-cancel-on-disconnect":{cost:10/3},"private/user-balance":{cost:10/3},"private/user-balance-history":{cost:10/3},"private/get-positions":{cost:10/3},"private/create-order":{cost:2/3},"private/amend-order":{cost:4/3},"private/create-order-list":{cost:10/3},"private/cancel-order":{cost:2/3},"private/cancel-order-list":{cost:10/3},"private/cancel-all-orders":{cost:2/3},"private/close-position":{cost:10/3},"private/get-order-history":{cost:100},"private/get-open-orders":{cost:10/3},"private/get-order-detail":{cost:1/3},"private/get-trades":{cost:100},"private/change-account-leverage":{cost:10/3},"private/get-transactions":{cost:10/3},"private/create-subaccount-transfer":{cost:10/3},"private/get-subaccount-balances":{cost:10/3},"private/get-order-list":{cost:10/3},"private/create-withdrawal":{cost:10/3},"private/get-currency-networks":{cost:10/3},"private/get-deposit-address":{cost:10/3},"private/get-accounts":{cost:10/3},"private/get-withdrawal-history":{cost:10/3},"private/get-deposit-history":{cost:10/3},"private/get-fee-rate":{cost:2},"private/get-instrument-fee-rate":{cost:2},"private/get-fee-credit-balances":{cost:10/3},"private/fiat/fiat-deposit-info":{cost:10/3},"private/fiat/fiat-deposit-history":{cost:10/3},"private/fiat/fiat-withdraw-history":{cost:10/3},"private/fiat/fiat-create-withdraw":{cost:10/3},"private/fiat/fiat-transaction-quota":{cost:10/3},"private/fiat/fiat-transaction-limit":{cost:10/3},"private/fiat/fiat-get-bank-accounts":{cost:10/3},"private/staking/stake":{cost:2},"private/staking/unstake":{cost:2},"private/staking/get-staking-position":{cost:2},"private/staking/get-staking-instruments":{cost:2},"private/staking/get-open-stake":{cost:2},"private/staking/get-stake-history":{cost:2},"private/staking/get-reward-history":{cost:2},"private/staking/convert":{cost:2},"private/staking/get-open-convert":{cost:2},"private/staking/get-convert-history":{cost:2},"private/create-isolated-margin-transfer":{cost:10/3},"private/change-isolated-margin-leverage":{cost:10/3},"private/bot/create-trading-bot":{cost:10/3},"private/bot/update-trading-bot":{cost:10/3},"private/bot/terminate-trading-bot":{cost:10/3},"private/bot/pause-trading-bot":{cost:10/3},"private/bot/resume-trading-bot":{cost:10/3},"private/bot/get-trading-bots":{cost:10/3},"private/bot/get-trading-bot-executions":{cost:10/3}}}},v2:{public:{get:{"public/auth":{cost:1},"public/get-instruments":{cost:1},"public/get-book":{cost:1},"public/get-candlestick":{cost:1},"public/get-ticker":{cost:1},"public/get-trades":{cost:1},"public/margin/get-transfer-currencies":{cost:1},"public/margin/get-load-currenices":{cost:1},"public/respond-heartbeat":{cost:1}}},private:{post:{"private/set-cancel-on-disconnect":{cost:10/3},"private/get-cancel-on-disconnect":{cost:10/3},"private/create-withdrawal":{cost:10/3},"private/get-withdrawal-history":{cost:10/3},"private/get-currency-networks":{cost:10/3},"private/get-deposit-history":{cost:10/3},"private/get-deposit-address":{cost:10/3},"private/export/create-export-request":{cost:10/3},"private/export/get-export-requests":{cost:10/3},"private/export/download-export-output":{cost:10/3},"private/get-account-summary":{cost:10/3},"private/create-order":{cost:2/3},"private/cancel-order":{cost:2/3},"private/cancel-all-orders":{cost:2/3},"private/create-order-list":{cost:10/3},"private/get-order-history":{cost:10/3},"private/get-open-orders":{cost:10/3},"private/get-order-detail":{cost:1/3},"private/get-trades":{cost:100},"private/get-accounts":{cost:10/3},"private/get-subaccount-balances":{cost:10/3},"private/create-subaccount-transfer":{cost:10/3},"private/otc/get-otc-user":{cost:10/3},"private/otc/get-instruments":{cost:10/3},"private/otc/request-quote":{cost:100},"private/otc/accept-quote":{cost:100},"private/otc/get-quote-history":{cost:10/3},"private/otc/get-trade-history":{cost:10/3},"private/otc/create-order":{cost:10/3}}}},derivatives:{public:{get:{"public/auth":{cost:10/3},"public/get-instruments":{cost:10/3},"public/get-book":{cost:1},"public/get-candlestick":{cost:1},"public/get-trades":{cost:1},"public/get-tickers":{cost:1},"public/get-valuations":{cost:1},"public/get-expired-settlement-price":{cost:10/3},"public/get-insurance":{cost:1}}},private:{post:{"private/set-cancel-on-disconnect":{cost:10/3},"private/get-cancel-on-disconnect":{cost:10/3},"private/user-balance":{cost:10/3},"private/user-balance-history":{cost:10/3},"private/get-positions":{cost:10/3},"private/create-order":{cost:2/3},"private/create-order-list":{cost:10/3},"private/cancel-order":{cost:2/3},"private/cancel-order-list":{cost:10/3},"private/cancel-all-orders":{cost:2/3},"private/close-position":{cost:10/3},"private/convert-collateral":{cost:10/3},"private/get-order-history":{cost:100},"private/get-open-orders":{cost:10/3},"private/get-order-detail":{cost:1/3},"private/get-trades":{cost:100},"private/change-account-leverage":{cost:10/3},"private/get-transactions":{cost:10/3},"private/create-subaccount-transfer":{cost:10/3},"private/get-subaccount-balances":{cost:10/3},"private/get-order-list":{cost:10/3}}}}},fees:{trading:{maker:this.parseNumber("0.0025"),taker:this.parseNumber("0.005"),tiers:{maker:[[this.parseNumber("0"),this.parseNumber("0.0025")],[this.parseNumber("10000"),this.parseNumber("0.002")],[this.parseNumber("50000"),this.parseNumber("0.0015")],[this.parseNumber("250000"),this.parseNumber("0.001")],[this.parseNumber("500000"),this.parseNumber("0.0008")],[this.parseNumber("2500000"),this.parseNumber("0.00065")],[this.parseNumber("10000000"),this.parseNumber("0")],[this.parseNumber("25000000"),this.parseNumber("0")],[this.parseNumber("100000000"),this.parseNumber("0")],[this.parseNumber("250000000"),this.parseNumber("0")],[this.parseNumber("500000000"),this.parseNumber("0")]],taker:[[this.parseNumber("0"),this.parseNumber("0.005")],[this.parseNumber("10000"),this.parseNumber("0.004")],[this.parseNumber("50000"),this.parseNumber("0.0025")],[this.parseNumber("250000"),this.parseNumber("0.002")],[this.parseNumber("500000"),this.parseNumber("0.0018")],[this.parseNumber("2500000"),this.parseNumber("0.001")],[this.parseNumber("10000000"),this.parseNumber("0.0005")],[this.parseNumber("25000000"),this.parseNumber("0.0004")],[this.parseNumber("100000000"),this.parseNumber("0.00035")],[this.parseNumber("250000000"),this.parseNumber("0.00031")],[this.parseNumber("500000000"),this.parseNumber("0.00025")]]}}},options:{defaultType:"spot",accountsById:{funding:"SPOT",spot:"SPOT",margin:"MARGIN",derivatives:"DERIVATIVES",swap:"DERIVATIVES",future:"DERIVATIVES"},networks:{BEP20:"BSC",ERC20:"ETH",TRC20:"TRON",ARBITRUM:"ARB"},broker:"CCXT"},features:{default:{sandbox:!0,createOrder:{marginMode:!0,triggerPrice:!0,triggerPriceType:{last:!0,mark:!0,index:!0},triggerDirection:!1,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,selfTradePrevention:!0,trailing:!1,iceberg:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!0},createOrders:{max:10},fetchMyTrades:{marginMode:!1,limit:100,daysBack:void 0,untilDays:1,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!0,limit:100,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:100,daysBack:void 0,untilDays:1,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:100,daysBack:void 0,daysBackCanceled:void 0,untilDays:1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:300}},spot:{extends:"default",fetchCurrencies:{private:!0}},swap:{linear:{extends:"default"},inverse:{extends:"default"}},future:{linear:{extends:"default"},inverse:{extends:"default"}}},commonCurrencies:{USD_STABLE_COIN:"USDC"},precisionMode:4,exceptions:{exact:{213:o.InvalidOrder,219:o.InvalidOrder,306:o.InsufficientFunds,314:o.InvalidOrder,315:o.InvalidOrder,325:o.InvalidOrder,415:o.InvalidOrder,10001:o.ExchangeError,10002:o.PermissionDenied,10003:o.PermissionDenied,10004:o.BadRequest,10005:o.PermissionDenied,10006:o.DDoSProtection,10007:o.InvalidNonce,10008:o.BadRequest,10009:o.BadRequest,20001:o.BadRequest,20002:o.InsufficientFunds,20005:o.AccountNotEnabled,30003:o.BadSymbol,30004:o.BadRequest,30005:o.BadRequest,30006:o.InvalidOrder,30007:o.InvalidOrder,30008:o.InvalidOrder,30009:o.InvalidOrder,30010:o.BadRequest,30013:o.InvalidOrder,30014:o.InvalidOrder,30016:o.InvalidOrder,30017:o.InvalidOrder,30023:o.InvalidOrder,30024:o.InvalidOrder,30025:o.InvalidOrder,40001:o.BadRequest,40002:o.BadRequest,40003:o.BadRequest,40004:o.BadRequest,40005:o.BadRequest,40006:o.BadRequest,40007:o.BadRequest,40101:o.AuthenticationError,40102:o.InvalidNonce,40103:o.AuthenticationError,40104:o.AuthenticationError,40107:o.BadRequest,40401:o.OrderNotFound,40801:o.RequestTimeout,42901:o.RateLimitExceeded,43005:o.InvalidOrder,43003:o.InvalidOrder,43004:o.InvalidOrder,43012:o.BadRequest,50001:o.ExchangeError,9010001:o.OnMaintenance},broad:{}}})}async fetchCurrencies(e={}){if(!this.checkRequiredCredentials(!1))return{};let[t,i]=this.handleOptionBoolAndParams(e,"fetchCurrencies","skipFetchCurrencies",!1);if(t)return{};let s={};try{s=await this.v1PrivatePostPrivateGetCurrencyNetworks(i)}catch(e){if(this.exceptionMessage(e).indexOf("SYS_ERROR")>=0)return{};throw e}let r=this.safeDict(s,"result",{}),a=this.safeDict(r,"currency_map",{}),o=this.addKeyInArrayItems(a,"_coin_id");return this.parseCurrencies(o)}parseCurrency(e){let t=this.safeString(e,"_coin_id"),i=this.safeCurrencyCode(t),s={},r=this.safeList(e,"network_list",[]);for(let e=0;e<r.length;e++){let t=r[e],a=this.safeString(t,"network_id"),o=this.networkIdToCode(a,i);void 0!==o&&(s[o]={info:t,id:a,network:o,active:void 0,deposit:this.safeBool(t,"deposit_enabled",!1),withdraw:this.safeBool(t,"withdraw_enabled",!1),fee:this.safeNumber(t,"withdrawal_fee"),precision:void 0,limits:{withdraw:{min:this.safeNumber(t,"min_withdrawal_amount"),max:void 0}}})}return this.safeCurrencyStructure({info:e,id:t,code:i,name:this.safeString(e,"full_name"),active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,precision:void 0,limits:{amount:{min:void 0,max:void 0}},type:"crypto",networks:s})}async fetchMarkets(e={}){let t=await this.v1PublicGetPublicGetInstruments(e),i=this.safeDict(t,"result",{}),s=this.safeList(i,"data",[]),r=[];for(let e=0;e<s.length;e++){let t,i,a=s[e],o=this.safeString(a,"inst_type"),n="CCY_PAIR"===o,d="PERPETUAL_SWAP"===o,h="FUTURE"===o,c="WARRANT"===o,l=this.safeString(a,"base_ccy"),u=this.safeString(a,"quote_ccy"),f=n?void 0:u,p=this.safeCurrencyCode(l),m=this.safeCurrencyCode(u);if(void 0===p||void 0===m)continue;let g=n?void 0:this.safeCurrencyCode(f),v=this.safeStringLower(a,"put_call"),y=this.safeString(a,"strike"),b=this.safeBool(a,"margin_buy_enabled"),w=this.safeBool(a,"margin_sell_enabled"),k=this.omitZero(this.safeString(a,"expiry_timestamp_ms")),S=void 0!==k?parseInt(k):void 0,O=p+"/"+m;if("CCY_PAIR"===o)t="spot",i=!1;else if("PERPETUAL_SWAP"===o)t="swap",O=O+":"+m,i=!0;else if("FUTURE"===o)t="future",O=O+":"+m+"-"+this.yymmdd(S),i=!0;else if("WARRANT"===o){t="option";let e="call"===v?"C":"P";O=O+":"+m+"-"+this.yymmdd(S)+"-"+y+"-"+e,i=!0}let T=!0===i||void 0,P=!0!==i&&void 0;r.push({id:this.safeString(a,"symbol"),symbol:O,base:p,quote:m,settle:g,baseId:l,quoteId:u,settleId:f,type:t,spot:n,margin:!0===b||!0===w,swap:d,future:h,option:c,active:this.safeBool(a,"tradable"),contract:i,linear:T,inverse:P,contractSize:this.safeNumber(a,"contract_size"),expiry:S,expiryDatetime:this.iso8601(S),strike:this.parseNumber(y),optionType:v,precision:{price:this.parseNumber(this.safeString(a,"price_tick_size")),amount:this.parseNumber(this.safeString(a,"qty_tick_size"))},limits:{leverage:{min:this.parseNumber("1"),max:this.safeNumber(a,"max_leverage")},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:a})}return r}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={};if(void 0!==e){let t;if(Array.isArray(e)){if(e.length>1)throw new o.BadRequest(this.id+" fetchTickers() symbols argument cannot contain more than 1 symbol");t=e[0]}else t=e;i.instrument_name=this.market(t).id}let s=await this.v1PublicGetPublicGetTickers(this.extend(i,t)),r=this.safeDict(s,"result",{}),a=this.safeList(r,"data",[]);return this.parseTickers(a,e)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.symbol(e),s=await this.fetchTickers([i],t);return this.safeDict(s,i)}async fetchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchOrders","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchOrders",e,t,i,o);let n={};void 0!==e&&(n.instrument_name=(r=this.market(e)).id),void 0!==t&&(n.start_time=t),void 0!==i&&(n.limit=i);let d=this.safeInteger(o,"until"),h=this.omit(o,["until"]);void 0!==d&&(n.end_time=d);let c=await this.v1PrivatePostPrivateGetOrderHistory(this.extend(n,h)),l=this.safeDict(c,"result",{}),u=this.safeList(l,"data",[]);return this.parseOrders(u,r,t,i)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchTrades","paginate",!1);if(r)return await this.fetchPaginatedCallDynamic("fetchTrades",e,t,i,a);let o=this.market(e),n={instrument_name:o.id};void 0!==t&&(n.start_ts=t),void 0!==i&&(n.count=i);let d=this.safeInteger(a,"until"),h=this.omit(a,["until"]);void 0!==d&&(n.end_ts=d);let c=await this.v1PublicGetPublicGetTrades(this.extend(n,h)),l=this.safeDict(c,"result",{}),u=this.safeList(l,"data",[]);return this.parseTrades(u,o,t,i)}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,o,300);let n=this.market(e),d={instrument_name:n.id,timeframe:this.safeString(this.timeframes,t,t)},h=s;void 0!==s&&s>300&&(h=300),void 0!==h&&(d.count=h);let c=this.microseconds(),l=this.parseTimeframe(t),u=this.safeInteger(o,"until",c),f=this.omit(o,["until"]);void 0!==i?(d.start_ts=i-1e3*l,void 0!==h?d.end_ts=this.sum(i,l*h*1e3):d.end_ts=u):d.end_ts=u;let p=await this.v1PublicGetPublicGetCandlestick(this.extend(d,f)),m=this.safeDict(p,"result",{}),g=this.safeList(m,"data",[]);return this.parseOHLCVs(g,n,t,i,h)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={instrument_name:this.market(e).id};void 0!==t&&0!==t&&(s.depth=Math.min(t,50));let r=await this.v1PublicGetPublicGetBook(this.extend(s,i)),a=this.safeDict(r,"result",{}),o=this.safeList(a,"data",[]),n=this.safeDict(o,0),d=this.safeInteger(n,"t");return this.parseOrderBook(n,e,d)}parseBalance(e){let t=this.safeDict(e,"result",{}),i=this.safeList(t,"data",[]),s=this.safeList(i[0],"position_balances",[]),r={info:e};for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),i=this.safeString(t,"instrument_name"),a=this.safeCurrencyCode(i),o=this.account();o.total=this.safeString(t,"quantity"),o.used=this.safeString(t,"reserved_qty"),void 0!==a&&(r[a]=o)}return this.safeBalance(r)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v1PrivatePostPrivateUserBalance(e);return this.parseBalance(t)}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let r=await this.v1PrivatePostPrivateGetOrderDetail(this.extend({order_id:e},i)),a=this.safeDict(r,"result",{});return this.parseOrder(a,s)}createOrderRequest(e,t,i,s,r,n={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new o.ArgumentsRequired(this.id+" requires a side argument");let d=this.market(e),h=t.toUpperCase(),c={instrument_name:d.id,side:i.toUpperCase(),quantity:this.amountToPrecision(e,s)};("LIMIT"===h||"STOP_LIMIT"===h||"TAKE_PROFIT_LIMIT"===h)&&(c.price=this.priceToPrecision(e,r)),c.broker_id=this.safeString(this.options,"broker","CCXT");let[l,u]=this.handleMarketTypeAndParams("createOrder",d,n),[f,p]=this.customHandleMarginModeAndParams("createOrder",u);"margin"===l||void 0!==f?c.spot_margin="MARGIN":"spot"===l&&(c.spot_margin="SPOT");let m=this.safeStringUpper2(p,"timeInForce","time_in_force");void 0!==m&&("GTC"===m?c.time_in_force="GOOD_TILL_CANCEL":"IOC"===m?c.time_in_force="IMMEDIATE_OR_CANCEL":"FOK"===m?c.time_in_force="FILL_OR_KILL":c.time_in_force=m),(!0===this.safeBool(p,"postOnly",!1)||"PO"===m)&&(c.exec_inst=["POST_ONLY"],c.time_in_force="GOOD_TILL_CANCEL");let g=this.safeStringN(p,["stopPrice","triggerPrice","ref_price"]),v=this.safeNumber(p,"stopLossPrice"),y=this.safeNumber(p,"takeProfitPrice"),b=void 0!==v,w=void 0!==y;if(void 0!==g){c.ref_price=this.priceToPrecision(e,g);let t=this.numberToString(r);"LIMIT"===h||"STOP_LIMIT"===h||"TAKE_PROFIT_LIMIT"===h?"buy"===i?a.Y.stringLt(t,g)?c.type="TAKE_PROFIT_LIMIT":c.type="STOP_LIMIT":a.Y.stringLt(t,g)?c.type="STOP_LIMIT":c.type="TAKE_PROFIT_LIMIT":"buy"===i?a.Y.stringLt(t,g)?c.type="TAKE_PROFIT":c.type="STOP_LOSS":a.Y.stringLt(t,g)?c.type="STOP_LOSS":c.type="TAKE_PROFIT"}else b?("LIMIT"===h||"STOP_LIMIT"===h?c.type="STOP_LIMIT":c.type="STOP_LOSS",c.ref_price=this.priceToPrecision(e,v)):w?("LIMIT"===h||"TAKE_PROFIT_LIMIT"===h?c.type="TAKE_PROFIT_LIMIT":c.type="TAKE_PROFIT",c.ref_price=this.priceToPrecision(e,y)):c.type=h;let k=this.omit(p,["postOnly","clientOrderId","timeInForce","stopPrice","triggerPrice","stopLossPrice","takeProfitPrice"]);return this.extend(c,k)}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=this.createOrderRequest(e,t,i,s,r,a),d=await this.v1PrivatePostPrivateCreateOrder(n),h=this.safeDict(d,"result",{});return this.parseOrder(h,o)}async createOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=[];for(let t=0;t<e.length;t++){let s=this.safeDict(e,t),r=this.safeString(s,"symbol"),a=this.safeString(s,"type"),o=this.safeString(s,"side"),n=this.safeValue(s,"amount"),d=this.safeValue(s,"price"),h=this.safeDict(s,"params",{}),c=this.createAdvancedOrderRequest(r,a,o,n,d,h);i.push(c)}let s=this.safeString(t,"contingency_type","LIST"),r=await this.v1PrivatePostPrivateCreateOrderList(this.extend({contingency_type:s,order_list:i},t)),a=this.safeValue(r,"result",[]),o=this.safeString(a,"list_id");return void 0!==o?this.parseOrders([{order_id:o}]):this.parseOrders(a)}createAdvancedOrderRequest(e,t,i,s,r,n={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new o.ArgumentsRequired(this.id+" requires a side argument");let d=this.market(e),h=t.toUpperCase(),c={instrument_name:d.id,side:i.toUpperCase()};("LIMIT"===h||"STOP_LIMIT"===h||"TAKE_PROFIT_LIMIT"===h)&&(c.price=this.priceToPrecision(e,r)),c.broker_id=this.safeString(this.options,"broker","CCXT");let l=this.safeStringUpper2(n,"timeInForce","time_in_force");void 0!==l&&("GTC"===l?c.time_in_force="GOOD_TILL_CANCEL":"IOC"===l?c.time_in_force="IMMEDIATE_OR_CANCEL":"FOK"===l?c.time_in_force="FILL_OR_KILL":c.time_in_force=l),(!0===this.safeBool(n,"postOnly",!1)||"PO"===l)&&(c.exec_inst=["POST_ONLY"],c.time_in_force="GOOD_TILL_CANCEL");let u=this.safeStringN(n,["stopPrice","triggerPrice","ref_price"]),f=this.safeNumber(n,"stopLossPrice"),p=this.safeNumber(n,"takeProfitPrice");if(void 0!==u){let e=this.numberToString(r);"LIMIT"===h||"STOP_LIMIT"===h||"TAKE_PROFIT_LIMIT"===h?"buy"===i?a.Y.stringLt(e,u)?c.type="TAKE_PROFIT_LIMIT":c.type="STOP_LIMIT":a.Y.stringLt(e,u)?c.type="STOP_LIMIT":c.type="TAKE_PROFIT_LIMIT":"buy"===i?a.Y.stringLt(e,u)?c.type="TAKE_PROFIT":c.type="STOP_LOSS":a.Y.stringLt(e,u)?c.type="STOP_LOSS":c.type="TAKE_PROFIT"}else void 0!==f?"LIMIT"===h||"STOP_LIMIT"===h?c.type="STOP_LIMIT":c.type="STOP_LOSS":void 0!==p?"LIMIT"===h||"TAKE_PROFIT_LIMIT"===h?c.type="TAKE_PROFIT_LIMIT":c.type="TAKE_PROFIT":c.type=h;let m=n;if("buy"===i&&("MARKET"===h||"STOP_LOSS"===h||"TAKE_PROFIT"===h)){let t,[i,d]=this.handleOptionBoolAndParams(n,"createOrder","createMarketBuyOrderRequiresPrice",!0),h=this.safeNumber2(d,"cost","notional");if(m=this.omit(d,"cost"),void 0!==h)t=this.costToPrecision(e,h);else if(i)if(void 0===r)throw new o.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend (quote quantity) in the amount argument");else{let i=this.numberToString(s),o=this.numberToString(r),n=a.Y.stringMul(i,o);t=this.costToPrecision(e,n)}else t=this.costToPrecision(e,s);c.notional=t}else c.quantity=this.amountToPrecision(e,s);let g=this.omit(m,["postOnly","clientOrderId","timeInForce","stopPrice","triggerPrice","stopLossPrice","takeProfitPrice"]);return this.extend(c,g)}async editOrder(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.editOrderRequest(e,t,r,a,o),d=await this.v1PrivatePostPrivateAmendOrder(n),h=this.safeDict(d,"result",{});return this.parseOrder(h)}editOrderRequest(e,t,i,s,r={}){let a={};if(void 0!==e)a.order_id=e;else{let e=this.safeString2(r,"orig_client_oid","clientOrderId");if(void 0===e)throw new o.ArgumentsRequired(this.id+" editOrder() requires an id argument or orig_client_oid parameter");a.orig_client_oid=e}let n=void 0===e?this.omit(r,["orig_client_oid","clientOrderId"]):r;if(void 0===i||void 0===s)throw new o.ArgumentsRequired(this.id+" editOrder() requires both amount and price arguments. If you do not want to change the amount or price, you should pass the original values");return a.new_quantity=this.amountToPrecision(t,i),a.new_price=this.priceToPrecision(t,s),this.extend(a,n)}async cancelAllOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={};void 0!==e&&(i.instrument_name=this.market(e).id);let s=await this.v1PrivatePostPrivateCancelAllOrders(this.extend(i,t));return[this.safeOrder({info:s})]}async cancelOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let r=await this.v1PrivatePostPrivateCancelOrder(this.extend({order_id:e},i)),a=this.safeDict(r,"result",{});return this.parseOrder(a,s)}async cancelOrders(e,t,i={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r=[];for(let t=0;t<e.length;t++){let i=e[t],a={instrument_name:s.id,order_id:i.toString()};r.push(a)}let a=await this.v1PrivatePostPrivateCancelOrderList(this.extend({contingency_type:"LIST",order_list:r},i)),n=this.safeList(a,"result",[]);return this.parseOrders(n,s,void 0,void 0,i)}async cancelOrdersForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=[];for(let t=0;t<e.length;t++){let s=this.safeDict(e,t),r=this.safeString(s,"id"),a=this.safeString(s,"symbol"),o={instrument_name:this.market(a).id,order_id:r.toString()};i.push(o)}let s=await this.v1PrivatePostPrivateCancelOrderList(this.extend({contingency_type:"LIST",order_list:i},t)),r=this.safeList(s,"result",[]);return this.parseOrders(r,void 0,void 0,void 0,t)}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.instrument_name=(r=this.market(e)).id);let o=await this.v1PrivatePostPrivateGetOpenOrders(this.extend(a,s)),n=this.safeDict(o,"result",{}),d=this.safeList(n,"data",[]);return this.parseOrders(d,r,t,i)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,o,100);let n={};void 0!==e&&(n.instrument_name=(r=this.market(e)).id),void 0!==t&&(n.start_time=t),void 0!==i&&(n.limit=i);let d=this.safeInteger(o,"until"),h=this.omit(o,["until"]);void 0!==d&&(n.end_time=d);let c=await this.v1PrivatePostPrivateGetTrades(this.extend(n,h)),l=this.safeDict(c,"result",{}),u=this.safeList(l,"data",[]);return this.parseTrades(u,r,t,i)}parseAddress(e){let t,i,s;return e.indexOf("?")>0?([t,s]=e.split("?"),i=s.split("=")[1]):t=e,[t,i]}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);void 0===this.markets&&await this.loadMarkets();let n=this.safeCurrency(e),d={currency:n.id,amount:t,address:i};void 0!==a&&(d.address_tag=a);let[h,c]=this.handleNetworkCodeAndParams(o),l=this.networkCodeToId(h,e);void 0!==l&&(d.network_id=l);let u=await this.v1PrivatePostPrivateCreateWithdrawal(this.extend(d,c)),f=this.safeDict(u,"result");return this.parseTransaction(f,n)}async fetchDepositAddressesByNetwork(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={currency:this.safeCurrency(e).id},s=await this.v1PrivatePostPrivateGetDepositAddress(this.extend(i,t)),r=this.safeDict(s,"result",{}),a=this.safeList(r,"deposit_address_list",[]),n=a.length;if(0===n)throw new o.ExchangeError(this.id+" fetchDepositAddressesByNetwork() generating address...");let d={};for(let e=0;e<n;e++){let t=this.safeDict(a,e),i=this.safeString(t,"address"),s=this.safeString(t,"currency"),r=this.safeCurrencyCode(s),[o,n]=this.parseAddress(i);this.checkAddress(o);let h=this.safeString(t,"network"),c=this.networkIdToCode(h,r);void 0!==c&&(d[c]={info:t,currency:r,network:c,address:o,tag:n})}return d}async fetchDepositAddress(e,t={}){let i=this.safeStringUpper(t,"network"),s=this.omit(t,["network"]),r=await this.fetchDepositAddressesByNetwork(e,s);if(i in r)return r[i];let a=Object.keys(r);return r[a[0]]}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.currency=(r=this.safeCurrency(e)).id),void 0!==t&&(a.start_ts=t),void 0!==i&&(a.page_size=i);let o=this.safeInteger(s,"until"),n=this.omit(s,["until"]);void 0!==o&&(a.end_ts=o);let d=await this.v1PrivatePostPrivateGetDepositHistory(this.extend(a,n)),h=this.safeDict(d,"result",{}),c=this.safeList(h,"deposit_list",[]);return this.parseTransactions(c,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.currency=(r=this.safeCurrency(e)).id),void 0!==t&&(a.start_ts=t),void 0!==i&&(a.page_size=i);let o=this.safeInteger(s,"until"),n=this.omit(s,["until"]);void 0!==o&&(a.end_ts=o);let d=await this.v1PrivatePostPrivateGetWithdrawalHistory(this.extend(a,n)),h=this.safeDict(d,"result",{}),c=this.safeList(h,"withdrawal_list",[]);return this.parseTransactions(c,r,t,i)}parseTicker(e,t){let i=this.safeInteger(e,"t"),s=this.safeString(e,"i"),r=this.safeMarket(s,t,"_"),a=this.safeString(e,"a");return this.safeTicker({symbol:r.symbol,timestamp:i,datetime:this.iso8601(i),high:this.safeNumber(e,"h"),low:this.safeNumber(e,"l"),bid:this.safeNumber(e,"b"),bidVolume:void 0,ask:this.safeNumber(e,"k"),askVolume:void 0,vwap:void 0,open:void 0,close:a,last:a,previousClose:void 0,change:void 0,percentage:this.safeString(e,"c"),average:void 0,baseVolume:this.safeString(e,"v"),quoteVolume:"USD"===r.quote?this.safeString(e,"vv"):void 0,info:e},r)}parseTrade(e,t){let i=this.safeInteger2(e,"t","create_time"),s=this.safeString2(e,"i","instrument_name"),r=this.safeMarket(s,t,"_"),o=this.safeString(e,"fee_instrument_name"),n=this.safeString(e,"fees");return this.safeTrade({info:e,id:this.safeString2(e,"d","trade_id"),timestamp:i,datetime:this.iso8601(i),symbol:r.symbol,order:this.safeString(e,"order_id"),side:this.safeStringLower2(e,"s","side"),takerOrMaker:this.safeStringLower(e,"taker_side"),price:this.safeNumber2(e,"p","traded_price"),amount:this.safeNumber2(e,"q","traded_quantity"),cost:void 0,type:void 0,fee:{currency:this.safeCurrencyCode(o),cost:this.parseNumber(a.Y.stringNeg(n))}},r)}parseOHLCV(e,t){return[this.safeInteger(e,"t"),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}parseOrderStatus(e){return this.safeString({ACTIVE:"open",CANCELED:"canceled",FILLED:"closed",REJECTED:"rejected",EXPIRED:"expired"},e,e)}parseTimeInForce(e){return this.safeString({GOOD_TILL_CANCEL:"GTC",IMMEDIATE_OR_CANCEL:"IOC",FILL_OR_KILL:"FOK"},e,e)}parseOrder(e,t){let i,s=this.safeInteger(e,"code");if(void 0!==s&&0!==s)return this.safeOrder({id:this.safeString(e,"order_id"),clientOrderId:this.safeString(e,"client_oid"),info:e,status:"rejected"});let r=this.safeInteger(e,"create_time"),a=this.safeString(e,"instrument_name"),o=this.safeSymbol(a,t),n=this.safeList(e,"exec_inst");if(void 0!==n){i=!1;for(let e=0;e<n.length;e++)if("POST_ONLY"===this.safeString(n,e)){i=!0;break}}let d=this.safeString(e,"fee_instrument_name");return this.safeOrder({info:e,id:this.safeString(e,"order_id"),clientOrderId:this.safeString(e,"client_oid"),timestamp:r,datetime:this.iso8601(r),lastTradeTimestamp:this.safeInteger(e,"update_time"),status:this.parseOrderStatus(this.safeString(e,"status")),symbol:o,type:this.safeStringLower(e,"order_type"),timeInForce:this.parseTimeInForce(this.safeString(e,"time_in_force")),postOnly:i,side:this.safeStringLower(e,"side"),price:this.safeNumber(e,"limit_price"),amount:this.safeNumber(e,"quantity"),filled:this.safeNumber(e,"cumulative_quantity"),remaining:void 0,average:this.safeNumber(e,"avg_price"),cost:this.safeNumber(e,"cumulative_value"),fee:{currency:this.safeCurrencyCode(d),cost:this.safeNumber(e,"cumulative_fee")},trades:[]},t)}parseDepositStatus(e){return this.safeString({0:"pending",1:"ok",2:"failed",3:"pending"},e,e)}parseWithdrawalStatus(e){return this.safeString({0:"pending",1:"pending",2:"failed",3:"pending",4:"failed",5:"ok",6:"canceled"},e,e)}parseTransaction(e,t){let i,s,r,a=this.safeString(e,"status");"client_wid"in e?(i="withdrawal",s=this.parseWithdrawalStatus(a)):(i="deposit",s=this.parseDepositStatus(a));let o=this.safeString(e,"address"),[n,d]=this.parseAddress(o),h=this.safeString(e,"currency"),c=this.safeCurrencyCode(h,t),l=this.safeInteger(e,"create_time"),u=this.safeNumber(e,"fee");return void 0!==u&&(r={currency:c,cost:u}),{info:e,id:this.safeString(e,"id"),txid:this.safeString(e,"txid"),timestamp:l,datetime:this.iso8601(l),network:void 0,address:n,addressTo:n,addressFrom:void 0,tag:d,tagTo:d,tagFrom:void 0,type:i,amount:this.safeNumber(e,"amount"),currency:c,status:s,updated:this.safeInteger(e,"update_time"),internal:void 0,comment:this.safeString(e,"client_wid"),fee:r}}customHandleMarginModeAndParams(e,t={}){let i,s,r=this.safeString(this.options,"defaultType"),a=this.safeBool(t,"margin",!1),n=this.omit(t,"margin");if([i,s]=this.handleMarginModeAndParams(e,n),void 0!==i){if("cross"!==i)throw new o.NotSupported(this.id+" only cross margin is supported")}else("margin"===r||!0===a)&&(i="cross");return[i,s]}parseDepositWithdrawFee(e,t){let i=this.safeList(e,"network_list",[]),s=i.length,r={info:e,withdraw:{fee:void 0,percentage:void 0},deposit:{fee:void 0,percentage:void 0},networks:{}};if(void 0!==i)for(let e=0;e<s;e++){let a=this.safeDict(i,e),o=this.safeString(a,"network_id"),n=this.safeString(t,"code"),d=this.networkIdToCode(o,n);void 0!==d&&(r.networks[d]={deposit:{fee:void 0,percentage:void 0},withdraw:{fee:this.safeNumber(a,"withdrawal_fee"),percentage:!1}}),1===s&&(r.withdraw.fee=this.safeNumber(a,"withdrawal_fee"),r.withdraw.percentage=!1)}return r}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.v1PrivatePostPrivateGetCurrencyNetworks(t),s=this.safeDict(i,"result"),r=this.safeList(s,"currency_map");return this.parseDepositWithdrawFees(r,e,"full_name")}async fetchLedger(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(r=this.safeCurrency(e)),void 0!==t&&(a.start_time=t),void 0!==i&&(a.limit=i);let o=this.safeInteger(s,"until"),n=this.omit(s,["until"]);void 0!==o&&(a.end_time=o);let d=await this.v1PrivatePostPrivateGetTransactions(this.extend(a,n)),h=this.safeDict(d,"result",{}),c=this.safeList(h,"data",[]);return this.parseLedger(c,r,t,i)}parseLedgerEntry(e,t){let i,s=this.safeInteger(e,"event_timestamp_ms"),r=this.safeString(e,"instrument_name"),o=this.safeCurrencyCode(r,t),n=this.safeCurrency(r,t),d=this.safeString(e,"transaction_qty");return a.Y.stringLt(d,"0")?(i="out",d=a.Y.stringAbs(d)):i="in",this.safeLedgerEntry({info:e,id:this.safeString(e,"order_id"),direction:i,account:this.safeString(e,"account_id"),referenceId:this.safeString(e,"trade_id"),referenceAccount:this.safeString(e,"trade_match_id"),type:this.parseLedgerEntryType(this.safeString(e,"journal_type")),currency:o,amount:this.parseNumber(d),timestamp:s,datetime:this.iso8601(s),before:void 0,after:void 0,status:void 0,fee:{currency:void 0,cost:void 0}},n)}parseLedgerEntryType(e){return this.safeString({TRADING:"trade",TRADE_FEE:"fee",WITHDRAW_FEE:"fee",WITHDRAW:"withdrawal",DEPOSIT:"deposit",ROLLBACK_WITHDRAW:"rollback",ROLLBACK_DEPOSIT:"rollback",FUNDING:"fee",REALIZED_PNL:"trade",INSURANCE_FUND:"insurance",SOCIALIZED_LOSS:"trade",LIQUIDATION_FEE:"fee",SESSION_RESET:"reset",ADJUSTMENT:"adjustment",SESSION_SETTLE:"settlement",UNCOVERED_LOSS:"trade",ADMIN_ADJUSTMENT:"adjustment",DELIST:"delist",SETTLEMENT_FEE:"fee",AUTO_CONVERSION:"conversion",MANUAL_CONVERSION:"conversion"},e,e)}async fetchAccounts(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v1PrivatePostPrivateGetAccounts(e),i=this.safeDict(t,"result",{}),s=this.safeDict(i,"master_account",{}),r=this.safeList(i,"sub_account_list",[]);return r.push(s),this.parseAccounts(r,e)}parseAccount(e){return{id:this.safeString(e,"uuid"),type:this.safeString(e,"label"),code:void 0,info:e}}async fetchSettlementHistory(e,t,i,s={}){let r,a,o;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e)),[a,o]=this.handleMarketTypeAndParams("fetchSettlementHistory",r,s),this.checkRequiredArgument("fetchSettlementHistory",a,"type",["future","option","WARRANT","FUTURE"]),"option"===a&&(a="WARRANT");let n={instrument_type:a.toUpperCase()},d=await this.v1PublicGetPublicGetExpiredSettlementPrice(this.extend(n,o)),h=this.safeDict(d,"result",{}),c=this.safeList(h,"data",[]),l=this.parseSettlements(c,r),u=this.sortBy(l,"timestamp");return this.filterBySymbolSinceLimit(u,e,t,i)}parseSettlement(e,t){let i=this.safeInteger(e,"x"),s=this.safeString(e,"i");return{info:e,symbol:this.safeSymbol(s,t),price:this.safeNumber(e,"v"),timestamp:i,datetime:this.iso8601(i)}}parseSettlements(e,t){let i=[];for(let s=0;s<e.length;s++)i.push(this.parseSettlement(e[s],t));return i}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new o.BadSymbol(this.id+" fetchFundingRate() supports swap contracts only");let s={instrument_name:i.id,valuation_type:"estimated_funding_rate",count:1},r=await this.v1PublicGetPublicGetValuations(this.extend(s,t)),a=this.safeDict(r,"result",{}),n=this.safeList(a,"data",[]),d=this.safeDict(n,0,{});return this.parseFundingRate(d,i)}parseFundingRate(e,t){let i,s=this.safeInteger(e,"t");return void 0!==s&&(i=36e5*Math.ceil(s/36e5)),{info:e,symbol:this.safeSymbol(void 0,t),markPrice:void 0,indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:s,datetime:this.iso8601(s),fundingRate:this.safeNumber(e,"v"),fundingTimestamp:i,fundingDatetime:this.iso8601(i),nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:"1h"}}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(r)return await this.fetchPaginatedCallDeterministic("fetchFundingRateHistory",e,t,i,"8h",a);let n=this.market(e);if(!0!==n.swap)throw new o.BadSymbol(this.id+" fetchFundingRateHistory() supports swap contracts only");let d={instrument_name:n.id,valuation_type:"funding_hist"};void 0!==t&&(d.start_ts=t),void 0!==i&&(d.count=i);let h=this.safeInteger(a,"until"),c=this.omit(a,["until"]);void 0!==h&&(d.end_ts=h);let l=await this.v1PublicGetPublicGetValuations(this.extend(d,c)),u=this.safeDict(l,"result",{}),f=this.safeList(u,"data",[]),p=this.safeString(u,"instrument_name"),m=[];for(let e=0;e<f.length;e++){let t=f[e],i=this.safeInteger(t,"t");m.push({info:t,symbol:this.safeSymbol(p,n),fundingRate:this.safeNumber(t,"v"),timestamp:i,datetime:this.iso8601(i)})}let g=this.sortBy(m,"timestamp");return this.filterBySymbolSinceLimit(g,this.safeString(n,"symbol"),t,i)}async fetchPosition(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instrument_name:i.id},r=await this.v1PrivatePostPrivateGetPositions(this.extend(s,t)),a=this.safeDict(r,"result",{}),o=this.safeList(a,"data",[]);return this.parsePosition(this.safeDict(o,0),i)}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s={};if(void 0!==i){let e;if(Array.isArray(i)){if(i.length>1)throw new o.BadRequest(this.id+" fetchPositions() symbols argument cannot contain more than 1 symbol");e=i[0]}else e=i;s.instrument_name=this.market(e).id}let r=await this.v1PrivatePostPrivateGetPositions(this.extend(s,t)),a=this.safeDict(r,"result",{}),n=this.safeList(a,"data",[]),d=[];for(let e=0;e<n.length;e++){let t=n[e],i=this.safeString(t,"instrument_name"),s=this.safeMarket(i,void 0,void 0,"contract");d.push(this.parsePosition(t,s))}return this.filterByArrayPositions(d,"symbol",void 0)}parsePosition(e,t){let i=this.safeString(e,"instrument_name"),s=this.safeMarket(i,t,void 0,"contract"),r=this.safeSymbol(i,s,void 0,"contract"),o=this.safeInteger(e,"update_timestamp_ms"),n=this.safeString(e,"quantity");return this.safePosition({info:e,id:void 0,symbol:r,timestamp:o,datetime:this.iso8601(o),hedged:void 0,side:a.Y.stringGt(n,"0")?"long":"short",contracts:this.parseNumber(a.Y.stringAbs(n)),contractSize:s.contractSize,entryPrice:void 0,markPrice:void 0,notional:void 0,leverage:void 0,collateral:this.safeNumber(e,"open_pos_cost"),initialMargin:this.safeNumber(e,"cost"),maintenanceMargin:void 0,initialMarginPercentage:void 0,maintenanceMarginPercentage:void 0,unrealizedPnl:this.safeNumber(e,"open_position_pnl"),liquidationPrice:void 0,marginMode:void 0,percentage:void 0,marginRatio:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}nonce(){return this.milliseconds()}paramsToString(e,t){let i;if(t>=3)return e.toString();if("string"==typeof e)return e;let s="";if(Array.isArray(e))i=e;else{let t=Object.keys(e);i=this.sort(t)}for(let r=0;r<i.length;r++){let a=i[r];s+=a;let o=e[a];if("undefined"===o)s+="null";else if(Array.isArray(o))for(let e=0;e<o.length;e++)s+=this.paramsToString(o[e],t+1);else s+=o.toString()}return s}async closePosition(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={instrument_name:s.id,type:"MARKET"},a=this.safeStringUpper(i,"type"),o=this.safeString(i,"price");void 0!==a&&(r.type=a),void 0!==o&&(r.price=this.priceToPrecision(s.symbol,o));let n=await this.v1PrivatePostPrivateClosePosition(this.extend(r,i)),d=this.safeDict(n,"result");return this.parseOrder(d,s)}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instrument_name:i.id},r=await this.v1PrivatePostPrivateGetInstrumentFeeRate(this.extend(s,t)),a=this.safeDict(r,"result",{});return this.parseTradingFee(a,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v1PrivatePostPrivateGetFeeRate(e),i=this.safeDict(t,"result",{});return this.parseTradingFees(i)}parseTradingFees(e){let t={};t.info=e;for(let i=0;i<this.symbols.length;i++){let s=this.symbols[i],r=this.market(s).swap,o="effective_spot_taker_rate_bps";!0===r&&(o="effective_deriv_taker_rate_bps");let n="effective_spot_maker_rate_bps";!0===r&&(n="effective_deriv_maker_rate_bps");let d={info:e,symbol:s,maker:this.parseNumber(a.Y.stringDiv(this.safeString(e,n),"10000")),taker:this.parseNumber(a.Y.stringDiv(this.safeString(e,o),"10000")),percentage:void 0,tierBased:void 0};t[s]=d}return t}parseTradingFee(e,t){let i=this.safeString(e,"instrument_name");return{info:e,symbol:this.safeSymbol(i,t),maker:this.parseNumber(a.Y.stringDiv(this.safeString(e,"effective_maker_rate_bps"),"10000")),taker:this.parseNumber(a.Y.stringDiv(this.safeString(e,"effective_taker_rate_bps"),"10000")),percentage:void 0,tierBased:void 0}}sign(e,t="public",i="GET",r={},a,n){let d=a,h=n,c=this.safeString(t,0),l=this.safeString(t,1),u=this.safeString(this.urls.api,c);if(void 0===u)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let f=u+"/"+e,p=this.omit(r,this.extractParams(e));if("public"===l)Object.keys(p).length>0&&(f+="?"+this.urlencode(p));else{this.checkRequiredCredentials();let t=this.nonce().toString(),i=this.extend({},r),a=Object.keys(i),o=this.paramsToString(i,0),n=e+t+this.apiKey+o+t,c=this.hmac(this.encode(n),this.encode(this.secret),s.sc),l=a.length;h=this.json({id:t,method:e,params:r,api_key:this.apiKey,sig:c,nonce:t}),0===l&&(h=h.replace("[]","{}")),d={"Content-Type":"application/json"}}return{url:f,method:i,body:h,headers:d}}handleErrors(e,t,i,s,r,a,n,d,h){let c=this.safeString(n,"code");if("0"!==c){let e=this.id+" "+a;throw this.throwExactlyMatchedException(this.exceptions.exact,c,e),new o.ExchangeError(this.id+" "+a)}}}i.d(t,{A:()=>n})},9100(e,t,i){"use strict";var s=i(8858),r=i(7835),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"cryptomus",name:"Cryptomus",countries:["CA"],rateLimit:100,version:"v2",certified:!1,pro:!1,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!1,cancelAllOrdersAfter:!1,cancelOrder:!0,cancelOrders:!1,cancelWithdraw:!1,closeAllPositions:!1,closePosition:!1,createConvertTrade:!1,createDepositAddress:!1,createMarketBuyOrderWithCost:!1,createMarketOrder:!1,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createOrderWithTakeProfitAndStopLossWs:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopLossOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,createTakeProfitOrder:!1,createTrailingAmountOrder:!1,createTrailingPercentOrder:!1,createTriggerOrder:!1,fetchAccounts:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCanceledAndClosedOrders:!0,fetchCanceledOrders:!1,fetchClosedOrder:!1,fetchClosedOrders:!1,fetchConvertCurrencies:!1,fetchConvertQuote:!1,fetchConvertTrade:!1,fetchConvertTradeHistory:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!1,fetchDeposits:!1,fetchDepositsWithdrawals:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLedger:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!1,fetchOHLCV:!1,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrder:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!1,fetchOrderTrades:!1,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchStatus:!1,fetchTicker:!1,fetchTickers:!0,fetchTime:!1,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchTransactions:!1,fetchTransfers:!1,fetchVolatilityHistory:!1,fetchWithdrawals:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,repayMargin:!1,sandbox:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,withdraw:!1},timeframes:{},urls:{logo:"https://github.com/user-attachments/assets/cce42038-d22e-49bc-8a9a-b9c92a2859a0",api:{public:"https://api.cryptomus.com",private:"https://api.cryptomus.com"},www:"https://cryptomus.com",doc:"https://doc.cryptomus.com/personal",fees:"https://cryptomus.com/tariffs",referral:"https://app.cryptomus.com/signup/?ref=JRP4yj"},api:{public:{get:{"v2/user-api/exchange/markets":{cost:1},"v2/user-api/exchange/market/price":{cost:1},"v2/user-api/exchange/markets/price":{cost:1},"v1/exchange/market/assets":{cost:1},"v1/exchange/market/order-book/{currencyPair}":{cost:1},"v1/exchange/market/tickers":{cost:1},"v1/exchange/market/trades/{currencyPair}":{cost:1}}},private:{get:{"v2/user-api/exchange/orders":{cost:1},"v2/user-api/exchange/orders/history":{cost:1},"v2/user-api/exchange/account/balance":{cost:1},"v2/user-api/exchange/account/tariffs":{cost:1},"v2/user-api/payment/services":{cost:1},"v2/user-api/payout/services":{cost:1},"v2/user-api/transaction/list":{cost:1},"v2/user-api/balance":{cost:1},"v2/user-api/convert/direction-list":{cost:1},"v2/user-api/convert/order-list":{cost:1},"v2/user-api/aml/check/balance":{cost:1},"v2/user-api/aml/check/currencies":{cost:1},"v2/user-api/aml/check/packages":{cost:1},"v2/user-api/aml/check/request":{cost:1},"v2/user-api/aml/check/request/{id}":{cost:1}},post:{"v2/user-api/exchange/orders":{cost:1},"v2/user-api/exchange/orders/market":{cost:1},"v2/user-api/convert":{cost:1},"v2/user-api/convert/calculate":{cost:1},"v2/user-api/convert/limit":{cost:1},"v2/user-api/aml/check/request":{cost:1},"v2/user-api/aml/check/request/{id}/report/send":{cost:1}},delete:{"v2/user-api/exchange/orders/{orderId}":{cost:1},"v2/user-api/convert/{orderUuid}":{cost:1}}}},fees:{trading:{percentage:!0,feeSide:"get",maker:this.parseNumber("0.02"),taker:this.parseNumber("0.02")}},options:{createMarketBuyOrderRequiresPrice:!0,networks:{BEP20:"bsc",DASH:"dash",POLYGON:"polygon",ARBITRUM:"arbitrum",SOL:"sol",TON:"ton",ERC20:"eth",TRC20:"tron",LTC:"ltc",XMR:"xmr",BCH:"bch",DOGE:"doge",AVAX:"avalanche",BTC:"btc",RUB:"rub"},networksById:{bsc:"BEP20",dash:"DASH",polygon:"POLYGON",arbitrum:"ARBITRUM",sol:"SOL",ton:"TON",eth:"ERC20",tron:"TRC20",ltc:"LTC",xmr:"XMR",bch:"BCH",doge:"DOGE",avalanche:"AVAX",btc:"BTC",rub:"RUB"},fetchOrderBook:{level:0}},commonCurrencies:{},exceptions:{exact:{500:a.ExchangeError,6:a.InsufficientFunds,"Insufficient funds.":a.InsufficientFunds,"Minimum amount 15 USDT":a.InvalidOrder},broad:{}},precisionMode:4,requiredCredentials:{apiKey:!1,uid:!0},features:{}})}async fetchMarkets(e={}){let t=await this.publicGetV2UserApiExchangeMarkets(e),i=this.safeList(t,"result",[]);return this.parseMarkets(i)}parseMarket(e){let t=this.safeString(e,"symbol");if(void 0===t)throw new a.ExchangeError(this.id+" parseMarket() missing marketId");let i=t.split("_"),s=i[0],r=i[1],o=this.safeCurrencyCode(s),n=this.safeCurrencyCode(r);if(void 0===o||void 0===n)return;let d=this.safeDict(this.fees,"trading");return this.safeMarketStructure({id:t,symbol:o+"/"+n,base:o,quote:n,baseId:s,quoteId:r,active:!0,type:"spot",subType:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,contract:!1,settle:void 0,settleId:void 0,contractSize:void 0,linear:void 0,inverse:void 0,taker:this.safeNumber(d,"taker"),maker:this.safeNumber(d,"maker"),percentage:this.safeBool(d,"percentage"),tierBased:void 0,feeSide:this.safeString(d,"feeSide"),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(e,"quotePrec"))),price:this.parseNumber(this.parsePrecision(this.safeString(e,"basePrec")))},limits:{amount:{min:this.safeNumber(e,"quoteMinSize"),max:this.safeNumber(e,"quoteMaxSize")},price:{min:this.safeNumber(e,"baseMinSize"),max:this.safeNumber(e,"baseMaxSize")},leverage:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:e})}async fetchCurrencies(e={}){let t=await this.publicGetV1ExchangeMarketAssets(e),i=this.safeList(t,"result"),s=Object.values(this.groupBy(i,"currency_code"));return this.parseCurrencies(s)}parseCurrency(e){let t,i,s={};for(let r=0;r<e.length;r++){let a=this.safeDict(e,r);void 0===t&&(t=this.safeString(a,"currency_code"),i=this.safeCurrencyCode(t));let o=this.safeString(a,"network_code"),n=this.networkIdToCode(o,i);void 0!==n&&(s[n]={id:o,network:n,limits:{withdraw:{min:this.safeNumber(a,"min_withdraw"),max:this.safeNumber(a,"max_withdraw")},deposit:{min:this.safeNumber(a,"min_deposit"),max:this.safeNumber(a,"max_deposit")}},active:void 0,deposit:this.safeBool(a,"can_deposit"),withdraw:this.safeBool(a,"can_withdraw"),fee:void 0,precision:void 0,info:a})}return this.safeCurrencyStructure({id:t,code:i,networks:s,info:e})}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetV1ExchangeMarketTickers(t),r=this.safeList(s,"data");return this.parseTickers(r,i)}parseTicker(e,t){let i=this.safeString(e,"currency_pair"),s=this.safeMarket(i,t),r=s.symbol,a=this.safeString(e,"last_price");return this.safeTicker({symbol:r,timestamp:void 0,datetime:void 0,high:void 0,low:void 0,bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:void 0,close:a,last:a,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"base_volume"),quoteVolume:this.safeString(e,"quote_volume"),info:e},s)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={currencyPair:this.market(e).id},[r,a]=this.handleOptionIntegerAndParams(i,"fetchOrderBook","level",0);s.level=r;let o=await this.publicGetV1ExchangeMarketOrderBookCurrencyPair(this.extend(s,a)),n=this.safeDict(o,"data",{}),d=this.safeTimestamp(n,"timestamp");return this.parseOrderBook(n,e,d,"bids","asks","price","quantity")}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={currencyPair:r.id},o=await this.publicGetV1ExchangeMarketTradesCurrencyPair(this.extend(a,s)),n=this.safeList(o,"data"),d=[];return void 0!==n&&(d=n),this.parseTrades(d,r,t,i)}parseTrade(e,t){let i=this.safeTimestamp(e,"timestamp");return this.safeTrade({id:this.safeString(e,"trade_id"),timestamp:i,datetime:this.iso8601(i),symbol:this.safeString(t,"symbol"),side:this.safeString(e,"type"),price:this.safeString(e,"price"),amount:this.safeString(e,"quote_volume"),cost:this.safeString(e,"base_volume"),takerOrMaker:void 0,type:void 0,order:void 0,fee:{currency:void 0,cost:void 0},info:e},t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetV2UserApiExchangeAccountBalance(this.extend({},e)),i=this.safeList(t,"result",[]);return this.parseBalance(i)}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"ticker"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(s,"available"),o.used=this.safeString(s,"held"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async createOrder(e,t,i,s,r,n={}){let d;void 0===this.markets&&await this.loadMarkets();let h=this.market(e),c={market:h.id,direction:i,tag:"ccxt"},l=this.safeString(n,"clientOrderId"),u=void 0!==l?this.omit(n,"clientOrderId"):n;void 0!==l&&(c.client_order_id=l);let f="buy"===i,p=this.numberToString(s),m=this.numberToString(r),[g,v]=this.handleParamString(u,"cost"),y=g;if("market"===t){let e=this.handleOptionBoolAndParams(v,"createOrder","createMarketBuyOrderRequiresPrice",!0),t=v;if(f&&(t=e[1]),f){if(e[0])if(void 0===r&&void 0===y)throw new a.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option of param to false and pass the cost to spend in the amount argument");else void 0===y&&(y=o.Y.stringMul(p,m));else y=void 0!==y&&""!==y?y:p;c.value=y}else c.quantity=p;d=await this.privatePostV2UserApiExchangeOrdersMarket(this.extend(c,t))}else if("limit"===t){if(void 0===r)throw new a.ArgumentsRequired(this.id+" createOrder() requires a price parameter for a "+t+" order");c.quantity=p,c.price=r,d=await this.privatePostV2UserApiExchangeOrders(this.extend(c,v))}else throw new a.ArgumentsRequired(this.id+" createOrder() requires a type parameter (limit or market)");return this.parseOrder(d,h)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={};s.orderId=e;let r=await this.privateDeleteV2UserApiExchangeOrdersOrderId(this.extend(s,i));return this.safeOrder({info:r})}async fetchCanceledAndClosedOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.market=(r=this.market(e)).id),void 0!==i&&(a.limit=i);let o=await this.privateGetV2UserApiExchangeOrdersHistory(this.extend(a,s)),n=this.safeList(o,"result",[]),d=[];for(let e=0;e<n.length;e++){let t=n[e];d.push(this.parseOrder(t,r))}return d}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a={};void 0!==r&&(a.market=r.id);let o=await this.privateGetV2UserApiExchangeOrders(this.extend(a,s)),n=this.safeList(o,"result",[]);return this.parseOrders(n,r,void 0,void 0)}parseOrder(e,t){let i,s=this.safeString2(e,"order_id","id"),r=this.safeString(e,"symbol"),a=this.safeMarket(r,t),o=this.safeString(e,"createdAt"),n=this.parse8601(o),d=this.safeDict(e,"deal",{}),h=this.safeNumber(d,"averageFilledPrice"),c=this.safeString(e,"type"),l=this.safeString(e,"direction"),u=this.safeNumber(e,"price"),f=this.safeList(d,"transactions",[]),p=this.safeDict(f,0),m=this.safeString(p,"feeCurrency");void 0!==m&&(i={currency:this.safeCurrencyCode(m),cost:this.safeNumber(p,"fee")}),void 0===u&&(u=this.safeNumber(p,"filledPrice"));let g=this.safeNumber(e,"quantity"),v=this.safeNumber(e,"value"),y=this.parseOrderStatus(this.safeString(e,"state")),b=this.safeString(e,"clientOrderId");return this.safeOrder({id:s,clientOrderId:b,timestamp:n,datetime:this.iso8601(n),lastTradeTimestamp:void 0,symbol:a.symbol,type:c,timeInForce:void 0,postOnly:void 0,side:l,price:u,stopPrice:this.safeString(e,"stopLossPrice"),triggerPrice:this.safeString(e,"stopLossPrice"),amount:g,cost:v,average:h,filled:this.safeString(e,"filledQuantity"),remaining:void 0,status:y,fee:i,trades:void 0,info:e},a)}parseOrderStatus(e){return this.safeString({active:"open",completed:"closed",partially_completed:"open",cancelled:"canceled",expired:"expired",failed:"failed"},e,e)}async fetchTradingFees(e={}){let t=await this.privateGetV2UserApiExchangeAccountTariffs(e),i=this.safeDict(t,"result",{}),s=this.safeDict(i,"current_tariff_step",{}),r=this.safeString(s,"maker_percent"),a=this.safeString(s,"taker_percent");r=o.Y.stringDiv(r,"100"),a=o.Y.stringDiv(a,"100");let n=this.safeList(i,"tariff_steps",[]),d={},h=this.parseFeeTiers(n),c=this.symbols;if(void 0===c)return d;for(let e=0;e<c.length;e++){let i=c[e];d[i]={info:t,symbol:i,maker:this.parseNumber(r),taker:this.parseNumber(a),percentage:!0,tierBased:!0,tiers:h}}return d}parseFeeTiers(e,t){let i=[],s=[];for(let t=0;t<e.length;t++){let r=this.safeDict(e,t),a=this.safeNumber(r,"from_turnover"),n=this.safeString(r,"taker_percent"),d=this.safeString(r,"maker_percent");d=o.Y.stringDiv(d,"100"),n=o.Y.stringDiv(n,"100"),s.push([a,this.parseNumber(d)]),i.push([a,this.parseNumber(n)])}return{maker:s,taker:i}}sign(e,t="public",i="GET",r={},o,n){let d=this.implodeParams(e,r),h=this.omit(r,this.extractParams(e)),c=this.safeString(this.urls.api,t);if(void 0===c)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let l=c+"/"+d;if("private"===t){this.checkRequiredCredentials();let e="",t={userId:this.uid};if("GET"!==i)e=this.json(h),t["Content-Type"]="application/json";else{let e=this.urlencode(h);0!==e.length&&(l+="?"+e)}let r=this.stringToBase64(e)+this.secret;t.sign=this.hash(this.encode(r),s.Fx);let a="GET"!==i?e:n;return{url:l,method:i,body:a,headers:t}}{let e=this.urlencode(h);0!==e.length&&(l+="?"+e)}return{url:l,method:i,body:n,headers:o}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0!==n){if("code"in n){let e=this.safeString(n,"code"),t=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,e,t),new a.ExchangeError(t)}else if("message"in n){let e=this.safeString(n,"message"),t=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,e,t),this.throwBroadlyMatchedException(this.exceptions.broad,e,t),new a.ExchangeError(t)}}}}i.d(t,{A:()=>n})},7929(e,t,i){"use strict";var s=i(4721),r=i(5496),a=i(7749),o=i(1453);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"deepcoin",name:"DeepCoin",countries:["SG"],rateLimit:200,version:"v1",certified:!1,pro:!0,has:{CORS:void 0,spot:!0,margin:!0,swap:!0,future:!1,option:!1,addMargin:!1,cancelAllOrders:!0,cancelAllOrdersAfter:!1,cancelOrder:!0,cancelOrders:!0,cancelWithdraw:!1,closePosition:!0,createConvertTrade:!1,createDepositAddress:!1,createLimitBuyOrder:!0,createLimitOrder:!0,createLimitSellOrder:!0,createMarketBuyOrder:!0,createMarketBuyOrderWithCost:!0,createMarketOrder:!0,createMarketOrderWithCost:!0,createMarketSellOrder:!0,createMarketSellOrderWithCost:!0,createOrder:!0,createOrders:!1,createOrderWithTakeProfitAndStopLoss:!0,createPostOnlyOrder:!0,createReduceOnlyOrder:!0,createStopLossOrder:!1,createTakeProfitOrder:!1,createTrailingAmountOrder:!1,createTrailingPercentOrder:!1,createTriggerOrder:!0,editOrder:!0,fetchAccounts:!1,fetchBalance:!0,fetchCanceledAndClosedOrders:!0,fetchCanceledOrders:!0,fetchClosedOrder:!0,fetchClosedOrders:!0,fetchConvertCurrencies:!1,fetchConvertQuote:!1,fetchConvertTrade:!1,fetchConvertTradeHistory:!1,fetchCurrencies:!1,fetchDepositAddress:!0,fetchDepositAddresses:!0,fetchDeposits:!0,fetchDepositsWithdrawals:!1,fetchDepositWithdrawFees:!1,fetchFundingHistory:!1,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchIndexOHLCV:!0,fetchLedger:!0,fetchLeverage:!1,fetchLeverageTiers:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenOrder:!0,fetchOpenOrders:!0,fetchOrder:!1,fetchOrderBook:!0,fetchOrders:!1,fetchOrderTrades:!0,fetchPosition:!0,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsForSymbol:!0,fetchPositionsHistory:!0,fetchPremiumIndexOHLCV:!1,fetchStatus:!1,fetchTicker:!1,fetchTickers:!0,fetchTime:!1,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTransactions:!1,fetchTransfers:!1,fetchWithdrawals:!0,reduceMargin:!1,sandbox:!1,setLeverage:!0,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!0,withdraw:!1},timeframes:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1H","4h":"4H","12h":"12H","1d":"1D","1w":"1W","1M":"1M","1y":"1Y"},urls:{logo:"https://github.com/user-attachments/assets/ddf3e178-c3b6-409d-8f9f-af8b7cf80454",api:{public:"https://api.deepcoin.com",private:"https://api.deepcoin.com"},www:"https://www.deepcoin.com/",doc:"https://www.deepcoin.com/docs",referral:{url:"https://s.deepcoin.com/UzkyODgy",discount:.1}},api:{public:{get:{"deepcoin/market/books":{cost:1},"deepcoin/market/candles":{cost:1},"deepcoin/market/instruments":{cost:1},"deepcoin/market/tickers":{cost:1},"deepcoin/market/index-candles":{cost:1},"deepcoin/market/trades":{cost:1},"deepcoin/market/mark-price-candles":{cost:1},"deepcoin/market/mark-price":{cost:1},"deepcoin/market/open-interest-volume":{cost:1},"deepcoin/market/long-short-ratio":{cost:1},"deepcoin/market/taker-volume":{cost:1},"deepcoin/market/step-margin":{cost:5},"deepcoin/trade/funding-rate":{cost:5},"deepcoin/trade/fund-rate/current-funding-rate":{cost:5},"deepcoin/trade/fund-rate/history":{cost:5}}},private:{get:{"deepcoin/account/balances":{cost:5},"deepcoin/account/all-balances":{cost:5},"deepcoin/account/bills":{cost:5},"deepcoin/account/positions":{cost:5},"deepcoin/account/trade-fee":{cost:5},"deepcoin/account/leverage-info":{cost:5},"deepcoin/account/positions-history":{cost:5},"deepcoin/trade/fills":{cost:5},"deepcoin/trade/orderByID":{cost:5},"deepcoin/trade/order":{cost:5},"deepcoin/trade/finishOrderByID":{cost:5},"deepcoin/trade/orders-history":{cost:5},"deepcoin/trade/v2/orders-pending":{cost:5},"deepcoin/trade/trigger-orders-pending":{cost:5},"deepcoin/trade/trigger-orders-history":{cost:5},"deepcoin/copytrading/support-contracts":{cost:5},"deepcoin/copytrading/leader-position":{cost:5},"deepcoin/copytrading/estimate-profit":{cost:5},"deepcoin/copytrading/history-profit":{cost:5},"deepcoin/copytrading/follower-rank":{cost:5},"deepcoin/internal-transfer/support":{cost:5},"deepcoin/internal-transfer/history-order":{cost:5},"deepcoin/rebate/config":{cost:5},"deepcoin/agents/users":{cost:5},"deepcoin/agents/users/rebate-list":{cost:5},"deepcoin/agents/users/rebates":{cost:5},"deepcoin/asset/deposit-list":{cost:5},"deepcoin/asset/withdraw-list":{cost:5},"deepcoin/asset/recharge-chain-list":{cost:5},"deepcoin/listenkey/acquire":{cost:5},"deepcoin/listenkey/extend":{cost:5},"deepcoin/sub-account/sub-account-apikey":{cost:5}},post:{"deepcoin/account/set-leverage":{cost:5},"deepcoin/trade/order":{cost:5},"deepcoin/trade/replace-order":{cost:5},"deepcoin/trade/cancel-order":{cost:5},"deepcoin/trade/batch-cancel-order":{cost:5},"deepcoin/trade/cancel-trigger-order":{cost:1/6},"deepcoin/trade/swap/cancel-all":{cost:5},"deepcoin/trade/trigger-order":{cost:5},"deepcoin/trade/amend-trigger-order":{cost:5},"deepcoin/trade/batch-close-position":{cost:5},"deepcoin/trade/replace-order-sltp":{cost:5},"deepcoin/trade/close-position-by-ids":{cost:5},"deepcoin/trade/increase-position":{cost:5},"deepcoin/trade/merge-positions":{cost:5},"deepcoin/copytrading/leader-settings":{cost:5},"deepcoin/copytrading/set-contracts":{cost:5},"deepcoin/internal-transfer":{cost:5},"deepcoin/rebate/config":{cost:5},"deepcoin/asset/transfer":{cost:5},"deepcoin/sub-account/create-sub-account":{cost:5},"deepcoin/sub-account/sub-account-apikey":{cost:5},"deepcoin/sub-account/delete-sub-account-apikey":{cost:5}}}},fees:{trading:{taker:this.parseNumber("0.0015"),maker:this.parseNumber("0.0010")}},features:{spot:{sandbox:!1,createOrder:{marginMode:!0,triggerPrice:!0,triggerPriceType:{last:!0,mark:!1,index:!1},triggerDirection:!1,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:{triggerPriceType:{last:!1,mark:!1,index:!1},price:!0},timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!0,trailing:!1,marketBuyRequiresPrice:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:60,untilDays:void 0,symbolRequired:!0},fetchOrder:void 0,fetchOpenOrders:{marginMode:!1,limit:100,trigger:!0,trailing:!1,symbolRequired:!0},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:100,daysBack:void 0,daysBackCanceled:void 0,untilDays:void 0,trigger:!0,trailing:!1,symbolRequired:!0},fetchOHLCV:{limit:300}},swap:{linear:{extends:"spot"},inverse:{extends:"spot"}}},requiredCredentials:{apiKey:!0,secret:!0,password:!0},precisionMode:4,options:{recvWindow:5e3,defaultNetworks:{ETH:"ERC20",USDT:"TRC20",USDC:"ERC20"},networks:{ERC20:"ERC20",TRC20:"TRC20",ARBITRUM:"ARBITRUM",BSC:"BSC(BEP20)",SOL:"SOL",BTC:"Bitcoin",ADA:"Cardano"},networksById:{},fetchMarkets:{types:["spot","swap"]},timeInForce:{GTC:"GTC",IOC:"IOC",PO:"PO"},exchangeType:{spot:"SPOT",swap:"SWAP",SPOT:"SPOT",SWAP:"SWAP"},accountsByType:{spot:1,fund:2,rebate:3,inverse:5,linear:7,demo:10}},commonCurrencies:{},exceptions:{exact:{24:o.OrderNotFound,31:o.InsufficientFunds,36:o.InsufficientFunds,44:o.BadRequest,49:o.InvalidOrder,194:o.InvalidOrder,195:o.InvalidOrder,199:o.BadRequest,100010:o.InsufficientFunds,unsupportedAction:o.BadRequest,localIDNotExist:o.BadRequest},broad:{"no available":o.NotSupported,"field is required":o.ArgumentsRequired,"not in acceptable range":o.BadRequest,'subscription cluster does not "exist"':o.BadRequest,"must be equal or lesser than":o.BadRequest}}})}handleMarketTypeAndParams(e,t,i={},s){let r=this.safeString(i,"instType"),a=this.omit(i,"instType"),o=this.safeString(a,"type"),n=a;return void 0===o&&void 0!==r&&(n=this.extend(a,{type:r})),super.handleMarketTypeAndParams(e,t,n,s)}convertToInstrumentType(e){let t=this.safeDict(this.options,"exchangeType",{});return this.safeString(t,e,e)}async fetchMarkets(e={}){let t=["spot","swap"],i=this.safeDict(this.options,"fetchMarkets");t=void 0!==i?this.safeList(i,"types",t):this.safeList(this.options,"fetchMarkets",t);let s=[],r=[];for(let i=0;i<t.length;i++)s.push(this.fetchMarketsByType(t[i],e));s=await Promise.all(s);for(let e=0;e<s.length;e++)r=this.arrayConcat(r,s[e]);return r}async fetchMarketsByType(e,t={}){let i={instType:this.convertToInstrumentType(e)},s=await this.publicGetDeepcoinMarketInstruments(this.extend(i,t)),r=this.safeList(s,"data",[]);return this.parseMarkets(r)}parseMarket(e){let t,i,s,r=this.safeString(e,"instId"),o=this.safeStringLower(e,"instType"),n="spot"===o,d="swap"===o,h=this.safeString(e,"baseCcy"),c=this.safeString(e,"quoteCcy",""),l=this.safeCurrencyCode(h),u=this.safeCurrencyCode(c);if(void 0===l||void 0===u)return;let f=l+"/"+u;d&&(t=(s="USD"!==c)?c:h,f=f+":"+(i=this.safeCurrencyCode(t)));let p=this.safeDict2(this.fees,o,"trading",{}),m=this.safeString(e,"lever","1");m=a.Y.stringMax(m,"1");let g=this.safeString(e,"maxMktSz"),v=this.safeString(e,"maxLmtSz"),y=this.parseNumber(a.Y.stringMax(g,v)),b=this.safeString(e,"state"),w=n&&a.Y.stringGt(m,"1"),k=d?!0!==s:void 0;return this.extend(p,{id:r,symbol:f,base:l,quote:u,settle:i,baseId:h,quoteId:c,settleId:t,type:o,spot:n,margin:w,swap:d,future:!1,option:!1,active:"live"===b,contract:d,linear:s,inverse:k,contractSize:d?this.safeNumber(e,"ctVal"):void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,created:void 0,precision:{amount:this.safeNumber(e,"lotSz"),price:this.safeNumber(e,"tickSz")},limits:{leverage:{min:this.parseNumber("1"),max:this.parseNumber(m)},amount:{min:this.safeNumber(e,"minSz"),max:y},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},info:e})}setMarkets(e,t){let i=super.setMarkets(e,t),s=Object.keys(i);for(let e=0;e<s.length;e++){let t=i[s[e]];if(void 0!==t&&!0===t.swap){let e=this.safeString(t,"baseId","")+this.safeString(t,"quoteId","");void 0!==this.markets_by_id&&(this.markets_by_id[e]=[t])}}return i}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={instId:this.market(e).id,sz:void 0===t?400:t},r=await this.publicGetDeepcoinMarketBooks(this.extend(s,i)),a=this.safeDict(r,"data",{});return this.parseOrderBook(a,e,void 0,"bids","asks",0,1)}async fetchOHLCV(e,t="1m",i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(o){let r=this.extend(n,{calculateUntil:!0});return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,r,300)}let d=this.market(e),h=this.safeString(n,"price"),c=this.safeString(this.timeframes,t,t),l={instId:d.id,bar:c};void 0!==s&&(l.limit=s);let u=this.safeInteger(n,"until");void 0!==u&&(l.after=u);let f=this.safeBool(n,"calculateUntil",!1),p=this.omit(n,!0===f?["price","until","calculateUntil"]:["price","until"]);if(!0===f&&void 0!==i){let e=i+this.parseTimeframe(t)*(void 0===s?300:s)*1e3;void 0!==u&&(e=Math.min(e,u)),l.after=Math.min(e,this.milliseconds())}a="mark"===h?await this.publicGetDeepcoinMarketMarkPriceCandles(this.extend(l,p)):"index"===h?await this.publicGetDeepcoinMarketIndexCandles(this.extend(l,p)):await this.publicGetDeepcoinMarketCandles(this.extend(l,p));let m=this.safeList(a,"data",[]);return this.parseOHLCVs(m,d,t,i,s)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=this.getMarketFromSymbols(i),[r,a]=this.handleMarketTypeAndParams("fetchTickers",s,t),o={instType:this.convertToInstrumentType(r)},n=await this.publicGetDeepcoinMarketTickers(this.extend(o,a)),d=this.safeList(n,"data",[]);return this.parseTickers(d,i)}parseTicker(e,t){let i=this.safeIntegerOmitZero(e,"ts"),s=this.safeString(e,"instId"),r=this.safeMarket(s,t,"-"),a=r.symbol,o=this.safeString(e,"last"),n=this.safeString(e,"open24h"),d=this.safeString(e,"volCcy24h"),h=this.safeString(e,"vol24h");if(!0===r.swap&&!0===r.inverse){let e=h;h=d,d=e}let c=this.safeString(e,"high24h"),l=this.safeString(e,"low24h");return this.safeTicker({symbol:a,timestamp:i,datetime:this.iso8601(i),high:c,low:l,bid:this.safeString(e,"bidPx"),bidVolume:this.safeString(e,"bidSz"),ask:this.safeString(e,"askPx"),askVolume:this.safeString(e,"askSz"),vwap:void 0,open:n,close:o,last:o,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:h,quoteVolume:d,markPrice:void 0,indexPrice:void 0,info:e},r)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={instId:r.id};void 0!==i&&(a.limit=Math.min(i,500)),a.productGroup=this.getProductGroupFromMarket(r);let o=await this.publicGetDeepcoinMarketTrades(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTrades(n,r,t,i)}getProductGroupFromMarket(e){let t="Spot";return this.safeBool(e,"swap",!1)&&(t=this.safeBool(e,"linear",!1)?"SwapU":"Swap"),t}parseTrade(e,t){let i,s=this.safeString(e,"instId"),r=this.safeMarket(s,t),a=this.safeInteger(e,"ts"),o=this.safeString(e,"side"),n=this.safeString(e,"execType"),d=this.safeString(e,"fee");if(void 0!==d){let t=this.safeString(e,"feeCcy");i={cost:d,currency:this.safeCurrencyCode(t)}}return this.safeTrade({info:e,timestamp:a,datetime:this.iso8601(a),symbol:r.symbol,id:this.safeString(e,"tradeId"),order:this.safeString(e,"ordId"),type:void 0,takerOrMaker:this.parseTakerOrMaker(n),side:o,price:this.safeString2(e,"fillPx","px"),amount:this.safeString2(e,"fillSz","sz"),cost:void 0,fee:i},r)}parseTakerOrMaker(e){return this.safeString({T:"taker",M:"maker"},e,e)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleMarketTypeAndParams("fetchBalance",void 0,e,void 0),s={instType:this.convertToInstrumentType(t)},r=await this.privateGetDeepcoinAccountBalances(this.extend(s,i));return this.parseBalance(r)}parseBalance(e){let t={info:e,timestamp:void 0,datetime:void 0},i=this.safeList(e,"data",[]);for(let e=0;e<i.length;e++){let s=this.safeDict(i,e),r=this.safeString(s,"ccy"),a=this.safeCurrencyCode(r),o=this.account();o.total=this.safeString(s,"bal"),o.used=this.safeString(s,"frozenBal"),o.free=this.safeString(s,"availBal"),t[a]=o}return this.safeBalance(t)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchDeposits","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchDeposits",e,t,i,o,"code",void 0,1,50);let n={};void 0!==e&&(n.coin=(r=this.currency(e)).id),void 0!==t&&(n.startTime=t),void 0!==i&&(n.size=i);let d=this.safeInteger(o,"until");void 0!==d&&(n.endTime=d);let h=this.omit(o,"until"),c=await this.privateGetDeepcoinAssetDepositList(this.extend(n,h)),l=this.safeDict(c,"data",{}),u=this.safeList(l,"data",[]);return this.parseTransactions(u,r,t,i,{type:"deposit"})}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchWithdrawals","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchWithdrawals",e,t,i,o,"code",void 0,1,50);let n={};void 0!==e&&(n.coin=(r=this.currency(e)).id),void 0!==t&&(n.startTime=t),void 0!==i&&(n.size=i);let d=this.safeInteger(o,"until");void 0!==d&&(n.endTime=d);let h=this.omit(o,"until"),c=await this.privateGetDeepcoinAssetWithdrawList(this.extend(n,h)),l=this.safeDict(c,"data",{}),u=this.safeList(l,"data",[]);return this.parseTransactions(u,r,t,i,{type:"withdrawal"})}parseTransaction(e,t){let i=this.safeString(e,"txHash"),s=this.safeString(e,"coin"),r=this.safeCurrencyCode(s,t),a=this.safeNumber(e,"amount"),o=this.safeTimestamp(e,"createTime"),n=this.safeString(e,"chainName"),d=this.networkIdToCode(n,r),h=this.parseTransactionStatus(this.safeString(e,"status"));return{info:e,id:void 0,currency:r,amount:a,network:d,addressFrom:void 0,addressTo:void 0,address:this.safeString(e,"address"),tagFrom:void 0,tagTo:void 0,tag:void 0,status:h,type:void 0,updated:void 0,txid:i,timestamp:o,datetime:this.iso8601(o),internal:void 0,comment:void 0,fee:{currency:void 0,cost:void 0}}}parseTransactionStatus(e){return this.safeString({confirming:"pending",succeed:"ok"},e,e)}async fetchDepositAddresses(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new o.ArgumentsRequired(this.id+" fetchDepositAddresses requires a list with one currency code");if(1!==e.length)throw new o.NotSupported(this.id+" fetchDepositAddresses requires a list with one currency code");let i=e[0],s={currency_id:this.currency(i).id,lang:"en"},r=await this.privateGetDeepcoinAssetRechargeChainList(this.extend(s,t)),a=this.safeDict(r,"data",{}),n=this.safeList(a,"list",[]);return this.parseDepositAddresses(n,e,!1,{currency:i})}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeString(t,"network"),s=this.safeDict(this.options,"defaultNetworks",{}),r=this.safeString(s,e);(void 0===i||""===i)&&(i=r);let a=void 0!==i?this.omit(t,"network"):t,o=await this.fetchDepositAddresses([e],a),n=o.length,d=this.safeDict(o,0,{});if(void 0!==i&&n>1)for(let e=0;e<n;e++){let t=o[e];t.network===i&&(d=t)}return d}parseDepositAddress(e,t){let i=this.safeString(e,"chain"),s=this.safeString(e,"address");this.checkAddress(s);let r=this.safeString(t,"code");return{info:e,currency:void 0,network:this.networkIdToCode(i,r),address:s,tag:this.safeString(e,"memo")}}async fetchLedger(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleMarketTypeAndParams("fetchLedger",void 0,s,"spot"),n={instType:this.convertToInstrumentType(a)};void 0!==e&&(n.ccy=(r=this.currency(e)).id),void 0!==t&&(n.after=t),void 0!==i&&(n.limit=i);let d=this.safeInteger(o,"until");void 0!==d&&(n.before=d);let h=this.omit(o,"until"),c=await this.privateGetDeepcoinAccountBills(this.extend(n,h)),l=this.safeList(c,"data",[]);return this.parseLedger(l,r,t,i)}parseLedgerEntry(e,t){let i=this.safeInteger(e,"ts"),s=this.safeString(e,"balChg"),r=a.Y.stringAbs(s),o="in";a.Y.stringLt(s,"0")&&(o="out");let n=this.safeString(e,"ccy"),d=this.safeCurrency(n,t),h=this.safeString(e,"type");return this.safeLedgerEntry({info:e,id:this.safeString(e,"billId"),direction:o,account:void 0,referenceAccount:void 0,referenceId:void 0,type:this.parseLedgerEntryType(h),currency:d.code,amount:r,timestamp:i,datetime:this.iso8601(i),before:void 0,after:this.safeString(e,"bal"),status:void 0,fee:void 0},d)}parseLedgerEntryType(e){return this.safeString({1:"trade",2:"trade",3:"transfer",4:"transfer",5:"fee"},e,e)}async transfer(e,t,i,s,r={}){let a,[n,d]=this.handleOptionStringAndParams(r,"transfer","userId");if(void 0===(a=void 0!==n&&""!==n?n:this.safeString(d,"uid")))throw new o.ArgumentsRequired(this.id+" transfer() requires a userId parameter");void 0===this.markets&&await this.loadMarkets();let h=this.currency(e),c=this.safeDict(this.options,"accountsByType",{}),l=this.safeString(c,i,i),u=this.safeString(c,s,s),f={currency_id:h.id,amount:this.currencyToPrecision(e,t),from_id:l,to_id:u,uid:a},p=await this.privatePostDeepcoinAssetTransfer(this.extend(f,d)),m=this.safeDict(p,"data",{}),g=this.parseTransfer(m,h),v=this.safeDict(this.options,"transfer",{});return!0===this.safeBool(v,"fillResponseFromRequest",!0)&&(g.fromAccount=i,g.toAccount=s,g.amount=t),g}parseTransfer(e,t){let i=this.safeString(e,"retCode");return{info:e,id:void 0,timestamp:void 0,datetime:void 0,currency:this.safeCurrencyCode(void 0,t),amount:void 0,fromAccount:void 0,toAccount:void 0,status:this.parseTransferStatus(i)}}parseTransferStatus(e){return"0"===e?"ok":"failed"}async createOrder(e,t,i,s,r,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=this.safeString(a,"triggerPrice"),h=this.createOrderRequest(e,t,i,s,r,a);o=void 0!==d?await this.privatePostDeepcoinTradeTriggerOrder(h):await this.privatePostDeepcoinTradeOrder(h);let c=this.safeDict(o,"data",{});return this.parseOrder(c,n)}createOrderRequest(e,t,i,s,r,a={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new o.ArgumentsRequired(this.id+" requires a side argument");let n=this.market(e),d=this.safeString(a,"triggerPrice");if(void 0!==this.safeString(a,"cost")&&(!0!==n.spot||void 0!==d))throw new o.BadRequest(this.id+" createOrder() accepts a cost parameter for spot non-trigger market orders only");return void 0!==d?this.createTriggerOrderRequest(e,t,i,s,r,a):this.createRegularOrderRequest(e,t,i,s,r,a)}createRegularOrderRequest(e,t,i,s,r,a={}){let n;if(void 0===t)throw new o.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new o.ArgumentsRequired(this.id+" requires a side argument");let d=this.market(e),[h,c]=this.handleTypePostOnlyAndTimeInForce(t,a),l={instId:d.id,side:i,ordType:h},u=[],f=this.safeString(c,"clientOrderId");void 0!==f&&(l.clOrdId=f,u.push("clientOrderId"));let p=this.safeDict(c,"stopLoss",{}),m=this.safeString(p,"triggerPrice");void 0!==m&&(u.push("stopLoss"),l.slTriggerPx=this.priceToPrecision(e,m));let g=this.safeDict(c,"takeProfit",{}),v=this.safeString(g,"triggerPrice");void 0!==v&&(u.push("takeProfit"),l.tpTriggerPx=this.priceToPrecision(e,v));let y="market"===t;if(void 0!==r){if(y)throw new o.BadRequest(this.id+" createOrder() does not require a price argument for market orders");l.px=this.priceToPrecision(e,r)}else if(!y)throw new o.BadRequest(this.id+" createOrder() requires a price argument for limit orders");if(!0===d.spot){let t=this.safeString(c,"cost");if(void 0!==t){if(!y)throw new o.BadRequest(this.id+" createOrder() accepts a cost parameter for spot market orders only");u.push("cost"),l.sz=this.costToPrecision(e,t),l.tgtCcy="quote_ccy"}else l.sz=this.amountToPrecision(e,s),l.tgtCcy="base_ccy";l.side=i,l.tdMode="cash",n=this.omit(c,u)}else{let t;l.sz=this.amountToPrecision(e,s);let r=this.omit(c,u),[a,o]=this.handleMarginModeAndParams("createOrder",r,"cross");l.tdMode=a;let[d,h]=this.handleOptionStringAndParams(o,"createOrder","mrgPosition","merge");n=h,l.mrgPosition=d,!0===this.safeBool(h,"reduceOnly",!1)?"buy"===i?t="short":"sell"===i&&(t="long"):"buy"===i?t="long":"sell"===i&&(t="short"),l.posSide=t}return this.extend(l,n)}createTriggerOrderRequest(e,t,i,s,r,a={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new o.ArgumentsRequired(this.id+" requires a side argument");let n=this.market(e),d={instId:n.id,productGroup:this.capitalize(n.type),sz:this.amountToPrecision(e,s),side:i,orderType:t},h=this.safeString(a,"triggerPrice");if(d.triggerPrice=this.priceToPrecision(e,h),void 0!==r)d.price=this.priceToPrecision(e,r);else if("limit"===t)throw new o.ArgumentsRequired(this.id+" createOrder() requires a price argument for limit trigger orders");let[c,l]=this.handleMarginModeAndParams("createOrder",a,"cross"),u=1;"isolated"===c&&(u=0);let f=this.safeBool(l,"reduceOnly",!1),p=this.omit(l,"reduceOnly");d.isCrossMargin=u,d.tdMode=c,!0===n.swap&&(!0===f?"buy"===i?d.posSide="short":"sell"===i&&(d.posSide="long"):"buy"===i?d.posSide="long":"sell"===i&&(d.posSide="short"));let[m,g]=this.handleOptionStringAndParams(p,"createOrder","mrgPosition","merge");return d.mrgPosition=m,this.extend(d,g)}handleTypePostOnlyAndTimeInForce(e,t){let[i,s]=this.handlePostOnly("market"===e,"post_only"===e,t),r=e;i&&(r="post_only");let a=this.handleTimeInForce(s),o=this.omit(s,"timeInForce"),n=r;return void 0!==a&&"IOC"===a&&(n="ioc"),[n,o]}async createMarketOrderWithCost(e,t,i,s={}){let r=this.extend(s,{cost:i});return await this.createOrder(e,"market",t,0,void 0,r)}async createMarketBuyOrderWithCost(e,t,i={}){let s=this.extend(i,{cost:t});return await this.createOrder(e,"market","buy",0,void 0,s)}async createMarketSellOrderWithCost(e,t,i={}){let s=this.extend(i,{cost:t});return await this.createOrder(e,"market","sell",0,void 0,s)}async fetchClosedOrder(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===t)throw new o.ArgumentsRequired(this.id+" fetchClosedOrder() requires a symbol argument");let s=this.market(t),r={instId:s.id,ordId:e},a=await this.privateGetDeepcoinTradeFinishOrderByID(this.extend(r,i)),n=this.safeList(a,"data",[]),d=this.safeDict(n,0,{});return this.parseOrder(d,s)}async fetchOpenOrder(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===t)throw new o.ArgumentsRequired(this.id+" fetchClosedOrder() requires a symbol argument");let s=this.market(t),r={instId:s.id,ordId:e},a=await this.privateGetDeepcoinTradeOrderByID(this.extend(r,i)),n=this.safeList(a,"data",[]);if(0===n.length)throw new o.OrderNotFound(this.id+" fetchOpenOrder() could not find order id "+e);let d=this.safeDict(n,0,{});return this.parseOrder(d,s)}async fetchCanceledAndClosedOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOptionBoolAndParams(s,"fetchCanceledAndClosedOrders","paginate",!1);if(n)return await this.fetchPaginatedCallDynamic("fetchCanceledAndClosedOrders",e,t,i,d);let h=this.safeBool(d,"trigger",!1),[c,l]=this.handleParamString(d,"methodName","fetchCanceledAndClosedOrders"),u={};void 0!==e&&(u.instId=(r=this.market(e)).id);let[f,p]=this.handleMarketTypeAndParams(c,r,l,"spot");if(u.instType=this.convertToInstrumentType(f),void 0!==i&&(u.limit=i),!0===h){if("fetchCanceledAndClosedOrders"!==c)throw new o.BadRequest(this.id+" "+c+"() does not support trigger orders");if(void 0===r)throw new o.ArgumentsRequired(this.id+" fetchCanceledAndClosedOrders() requires a symbol argument for trigger orders");let e=this.omit(p,"trigger");a=await this.privateGetDeepcoinTradeTriggerOrdersHistory(this.extend(u,e))}else a=await this.privateGetDeepcoinTradeOrdersHistory(this.extend(u,p));let m=this.safeList(a,"data",[]);return this.parseOrders(m,r,t,i)}async fetchCanceledOrders(e,t,i,s={}){let r=this.extend(s,{methodName:"fetchCanceledOrders"}),a=this.extend(r,{state:"canceled"});return await this.fetchCanceledAndClosedOrders(e,t,i,a)}async fetchClosedOrders(e,t,i,s={}){let r=this.extend(s,{methodName:"fetchClosedOrders"}),a=this.extend(r,{state:"filled"});return await this.fetchCanceledAndClosedOrders(e,t,i,a)}async fetchOpenOrders(e,t,i,s={}){let r;if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new o.ArgumentsRequired(this.id+" fetchOpenOrders() requires a symbol argument");let a=this.market(e),n=this.safeInteger(s,"index",1),d={instId:a.id};void 0!==i&&(d.limit=i);let h=this.safeBool(s,"trigger",!1),c=this.omit(s,"trigger");!0===h?(d.instType=this.convertToInstrumentType(a.type),r=await this.privateGetDeepcoinTradeTriggerOrdersPending(this.extend(d,c))):(d.index=n,r=await this.privateGetDeepcoinTradeV2OrdersPending(this.extend(d,s)));let l=this.safeList(r,"data",[]);return this.parseOrders(l,a,t,i,{status:"open"})}async cancelOrder(e,t,i={}){let s;if(void 0===this.markets&&await this.loadMarkets(),void 0===t)throw new o.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");let r=this.market(t),a={instId:r.id,ordId:e};if(!0===this.safeBool(i,"trigger",!1)){let e=this.omit(i,"trigger");s=await this.privatePostDeepcoinTradeCancelTriggerOrder(this.extend(a,e))}else s=await this.privatePostDeepcoinTradeCancelOrder(this.extend(a,i));let n=this.safeDict(s,"data",{});return this.parseOrder(n,r)}async cancelAllOrders(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new o.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument");let i=this.market(e);if(!0===i.spot)throw new o.NotSupported(this.id+" cancelAllOrders() is not supported for spot markets");let s=this.getProductGroupFromMarket(i),r=this.safeString(t,"marginMode"),a=void 0!==r?this.omit(t,"marginMode"):t,[n,d]=this.handleOptionBoolAndParams(a,"cancelAllOrders","merged",!0),h={InstrumentID:i.id,ProductGroup:s,IsCrossMargin:+("isolated"!==r),IsMergeMode:+!!n},c=await this.privatePostDeepcoinTradeSwapCancelAll(this.extend(h,d)),l=this.safeList(c,"data",[]);return this.parseOrders(l,i)}async editOrder(e,t,i,s,r,a,n={}){let d,h,c;void 0===this.markets&&await this.loadMarkets();let l={OrderSysID:e};if(void 0!==t){if(!0===(d=this.market(t)).spot)throw new o.NotSupported(this.id+" editOrder() is not supported for spot markets");h=d.symbol}let u=this.safeNumber(n,"stopLossPrice"),f=this.safeNumber(n,"takeProfitPrice");if(void 0!==u||void 0!==f){if(void 0!==a||void 0!==r)throw new o.BadRequest(this.id+" editOrder() with stopLossPrice or takeProfitPrice cannot have price or amount. Either use stopLossPrice/takeProfitPrice or price/amount to edit order.");void 0!==u&&(l.slTriggerPx=""!==h?this.priceToPrecision(h,u):this.numberToString(u)),void 0!==f&&(l.tpTriggerPx=""!==h?this.priceToPrecision(h,f):this.numberToString(f));let e=this.omit(n,["stopLossPrice","takeProfitPrice"]);c=await this.privatePostDeepcoinTradeReplaceOrderSltp(this.extend(l,e))}else void 0!==a&&(void 0!==h?l.price=this.priceToPrecision(h,a):l.price=this.numberToString(a)),void 0!==r&&(void 0!==h?l.volume=this.amountToPrecision(h,r):l.volume=this.numberToString(r)),c=await this.privatePostDeepcoinTradeReplaceOrder(this.extend(l,n));let p=this.safeDict(c,"data",{});return this.parseOrder(p)}async cancelOrders(e,t,i={}){let s;if(void 0===this.markets&&await this.loadMarkets(),void 0!==t&&!0===(s=this.market(t)).spot)throw new o.NotSupported(this.id+" cancelOrders() is not supported for spot markets");let r=await this.privatePostDeepcoinTradeBatchCancelOrder(this.extend({OrderSysIDs:e},i)),a=this.safeList(r,"data",[]);return this.parseOrders(a,s)}parseOrder(e,t){let i,s=this.safeString(e,"instId"),r=this.safeMarket(s,t),a=this.safeInteger(e,"cTime");this.safeString(e,"cTime","").length<13&&(a=this.safeTimestamp(e,"cTime"));let o=this.safeString(e,"state"),n=this.safeString(e,"ordType"),d=this.safeString(e,"avgPx");""===d&&(d=void 0);let h=this.safeString(e,"feeCcy");if(void 0!==h){let t=this.safeString(e,"fee");i={cost:this.parseNumber(t),currency:this.safeCurrencyCode(h)}}return this.safeOrder({id:this.safeString(e,"ordId"),clientOrderId:this.safeString(e,"clOrdId"),datetime:this.iso8601(a),timestamp:a,lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeInteger(e,"uTime"),status:this.parseOrderStatus(o),symbol:r.symbol,type:this.parseOrderType(n),timeInForce:this.parseOrderTimeInForce(n),side:this.safeString(e,"side"),price:this.safeString2(e,"px","ordPx"),average:d,amount:this.safeString(e,"sz"),filled:this.safeString(e,"accFillSz"),remaining:void 0,triggerPrice:this.omitZero(this.safeString(e,"triggerPx")),takeProfitPrice:this.safeString2(e,"tpTriggerPx","tpTriggerPrice"),stopLossPrice:this.safeString2(e,"slTriggerPx","slTriggerPrice"),cost:void 0,trades:void 0,fee:i,reduceOnly:void 0,postOnly:void 0!==n&&""!==n?"post_only"===n:void 0,info:e},r)}parseOrderStatus(e){return this.safeString({live:"open",filled:"closed",canceled:"canceled",partially_filled:"open"},e,e)}parseOrderType(e){return this.safeString({limit:"limit",market:"market",post_only:"limit",ioc:"market",TPSL:"market"},e,e)}parseOrderTimeInForce(e){return this.safeString({post_only:"PO",ioc:"IOC",limit:"GTC",market:"GTC"},e,e)}async fetchPositionsForSymbol(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instType:this.convertToInstrumentType(i.type),instId:i.id},r=await this.privateGetDeepcoinAccountPositions(this.extend(s,t)),a=this.safeList(r,"data",[]);return this.parsePositions(a,[i.symbol])}async fetchPositions(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!0,!0);if(void 0!==s){let e=this.safeString(s,0);i=this.market(e)}let[r,a]=this.handleMarketTypeAndParams("fetchPositions",i,t,"swap"),o=this.convertToInstrumentType(r),n=await this.privateGetDeepcoinAccountPositions(this.extend({instType:o},a)),d=this.safeList(n,"data",[]);return this.parsePositions(d,s)}parsePosition(e,t){let i=this.safeString(e,"instId"),s=this.safeMarket(i,t),r=this.safeInteger(e,"cTime");return this.safePosition({symbol:s.symbol,id:this.safeString(e,"posId"),timestamp:r,datetime:this.iso8601(r),contracts:this.safeNumber(e,"pos"),contractSize:void 0,side:this.safeString(e,"posSide"),notional:void 0,leverage:this.parseNumber(this.omitZero(this.safeString(e,"lever"))),unrealizedPnl:void 0,realizedPnl:void 0,collateral:void 0,entryPrice:this.safeNumber(e,"avgPx"),markPrice:void 0,liquidationPrice:this.safeNumber(e,"liqPx"),marginMode:this.safeString(e,"mgnMode"),hedged:!0,maintenanceMargin:this.safeNumber(e,"useMargin"),maintenanceMarginPercentage:void 0,initialMargin:void 0,initialMarginPercentage:void 0,marginRatio:void 0,lastUpdateTimestamp:this.safeInteger(e,"uTime"),lastPrice:void 0,stopLossPrice:void 0,takeProfitPrice:void 0,percentage:void 0,info:e})}async setLeverage(e,t,i={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");if(e<1)throw new o.BadRequest(this.id+" setLeverage() leverage should be minimum 1");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),[r,a]=this.handleMarginModeAndParams("setLeverage",i,"cross");if("cross"!==r&&"isolated"!==r)throw new o.BadRequest(this.id+" setLeverage() requires a marginMode parameter that must be either cross or isolated");let[n,d]=this.handleOptionStringAndParams(a,"setLeverage","mrgPosition","merge");if("merge"!==n&&"split"!==n)throw new o.BadRequest(this.id+" setLeverage() mrgPosition parameter must be either merge or split");let h={lever:e,mgnMode:r,instId:s.id,mrgPosition:n};return await this.privatePostDeepcoinAccountSetLeverage(this.extend(h,d))}async fetchFundingRates(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,"swap",!0,!0,!0);if(void 0!==s){let e=this.safeString(s,0);i=this.market(e)}let[r,a]=this.handleSubTypeAndParams("fetchFundingRates",i,t,"linear"),n="SwapU";if("inverse"===r)n="Swap";else if("linear"!==r)throw new o.BadRequest(this.id+" fetchFundingRates() subType parameter must be either linear or inverse");let d={instType:n},h=await this.publicGetDeepcoinTradeFundRateCurrentFundingRate(this.extend(d,a)),c=this.safeDict(h,"data",{}),l=this.safeList(c,"current_fund_rates",[]);return this.parseFundingRates(l,s)}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new o.ExchangeError(this.id+" fetchFundingRate() is only valid for swap markets");let s={instId:i.id,instType:this.getProductGroupFromMarket(i)},r=await this.publicGetDeepcoinTradeFundRateCurrentFundingRate(this.extend(s,t)),a=this.safeDict(r,"data",{}),n=this.safeList(a,"current_fund_rates",[]),d=this.safeDict(n,0,{});return this.parseFundingRate(d,i)}parseFundingRate(e,t){let i=this.safeString2(e,"instrumentId","instrumentID");return{info:e,symbol:this.safeSymbol(i,t),markPrice:void 0,indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:this.safeNumber(e,"fundingRate"),fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:void 0}}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={instId:r.id};void 0!==i&&(a.size=i);let n=await this.publicGetDeepcoinTradeFundRateHistory(this.extend(a,s)),d=this.safeDict(n,"data",{}),h=this.safeList(d,"rows",[]);return this.parseFundingRateHistories(h,r,t,i)}parseFundingRateHistory(e,t){let i=this.safeTimestamp(e,"CreateTime"),s=this.safeString2(e,"instrumentID","instrumentId");return{info:e,symbol:this.safeMarket(s,t,void 0,"swap").symbol,fundingRate:this.safeNumber(e,"rate"),timestamp:i,datetime:this.iso8601(i)}}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,o);void 0!==e&&(r=this.market(e));let[n,d]=this.handleMarketTypeAndParams("fetchMyTrades",r,o,"spot"),h={instType:this.convertToInstrumentType(n)};void 0!==r&&(h.instId=r.id),void 0!==t&&(h.begin=t),void 0!==i&&(h.limit=i);let c=this.safeInteger(d,"until");void 0!==c&&(h.end=c);let l=void 0!==c?this.omit(d,"until"):d,u=await this.privateGetDeepcoinTradeFills(this.extend(h,l)),f=this.safeList(u,"data",[]);return this.parseTrades(f,r,t,i)}async fetchOrderTrades(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.safeString(r,"type");if(void 0===t&&void 0===a)throw new o.ArgumentsRequired(this.id+" fetchOrderTrades requires a symbol argument or a market type in the params");let n=this.extend({ordId:e},r);return await this.fetchMyTrades(t,i,s,n)}async closePosition(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=this.getProductGroupFromMarket(r),o=this.safeString(i,"positionId"),n=this.safeList(i,"positionIds"),d={instId:r.id,productGroup:a};if(void 0===o&&void 0===n)s=await this.privatePostDeepcoinTradeBatchClosePosition(this.extend(d,i));else{void 0!==o&&(d.positionIds=[o]);let e=void 0!==o?this.omit(i,"positionId"):i;s=await this.privatePostDeepcoinTradeClosePositionByIds(this.extend(d,e))}let h=this.safeList(s,"data",[]);return this.parseOrder(h,r)}sign(e,t="public",i="GET",r={},a,n){let d=e;if("GET"===i){let e=this.urlencode(r);e.length>0&&(d+="?"+e)}let h=this.safeString(this.urls.api,t);if(void 0===h)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let c=h+"/"+d;if("private"===t){this.checkRequiredCredentials();let e=this.milliseconds(),t=this.iso8601(e),a=t+i+"/"+d,o={"DC-ACCESS-KEY":this.apiKey,"DC-ACCESS-TIMESTAMP":t,"DC-ACCESS-PASSPHRASE":this.password,appid:"200103"},h="GET"!==i?this.json(r):n;"GET"!==i&&(o["Content-Type"]="application/json",a+=h);let l=this.hmac(this.encode(a),this.encode(this.secret),s.sc,"base64");return o["DC-ACCESS-SIGN"]=l,{url:c,method:i,body:h,headers:o}}return{url:c,method:i,body:n,headers:a}}handleErrors(e,t,i,s,r,a,n,d,h){let c=this.safeDict(n,"data",{}),l=this.safeString(n,"msg"),u=this.safeString(n,"code"),f=this.safeString(c,"sCode"),p=this.safeString(c,"sMsg"),m=this.safeString(c,"errorCode");void 0!==l&&""===l&&void 0!==p&&(l=p);let g=this.safeList(c,"errorList");if(void 0!==g)for(let e=0;e<g.length;e++){let t=this.safeDict(g,e,{});m=this.safeString(t,"errorCode")}let v=this.id+" "+a;void 0===f&&void 0!==m&&(f=m);let y=this.safeString(c,"retCode");if(void 0===f&&void 0!==y&&(f=y),200!==e||"0"!==u||void 0!==f&&"0"!==f)throw this.throwExactlyMatchedException(this.exceptions.exact,u,v),this.throwExactlyMatchedException(this.exceptions.exact,f,v),this.throwExactlyMatchedException(this.exceptions.exact,l,v),this.throwBroadlyMatchedException(this.exceptions.broad,l,v),new o.ExchangeError(v);{let e=this.safeList(c,"list",[]);if("list"in c&&void 0===e)throw new o.NullResponse(v)}}}i.d(t,{A:()=>n})},2638(e,t,i){"use strict";var s=i(4721),r=i(1065),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"delta",name:"Delta Exchange",countries:["VC"],rateLimit:300,version:"v2",has:{CORS:void 0,spot:!0,margin:!1,swap:!0,future:!1,option:!0,addMargin:!0,cancelAllOrders:!0,cancelOrder:!0,closeAllPositions:!0,closePosition:!1,createOrder:!0,createReduceOnlyOrder:!0,editOrder:!0,fetchBalance:!0,fetchClosedOrders:!0,fetchCurrencies:!0,fetchDeposit:void 0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:void 0,fetchFundingHistory:!1,fetchFundingRate:!0,fetchFundingRateHistory:!1,fetchFundingRates:!0,fetchGreeks:!0,fetchIndexOHLCV:!0,fetchLedger:!0,fetchLeverage:!0,fetchLeverageTiers:!1,fetchMarginMode:!0,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenOrders:!0,fetchOption:!0,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchPosition:!0,fetchPositionADLRank:!0,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsADLRank:!0,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!0,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTransfer:void 0,fetchTransfers:void 0,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,fetchWithdrawal:void 0,fetchWithdrawals:void 0,reduceMargin:!0,setLeverage:!0,setMargin:!1,setMarginMode:!0,setPositionMode:!1,transfer:!1,withdraw:!1},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","1d":"1d","7d":"7d","1w":"1w","2w":"2w","1M":"30d"},urls:{logo:"https://user-images.githubusercontent.com/1294454/99450025-3be60a00-2931-11eb-9302-f4fd8d8589aa.jpg",test:{public:"https://testnet-api.delta.exchange",private:"https://testnet-api.delta.exchange"},api:{public:"https://api.delta.exchange",private:"https://api.delta.exchange"},www:"https://www.delta.exchange",doc:["https://docs.delta.exchange"],fees:"https://www.delta.exchange/fees",referral:"https://www.delta.exchange/app/signup/?code=IULYNB"},api:{public:{get:{assets:{cost:1},indices:{cost:1},products:{cost:1},"products/{symbol}":{cost:1},tickers:{cost:1},"tickers/{symbol}":{cost:1},"l2orderbook/{symbol}":{cost:1},"trades/{symbol}":{cost:1},stats:{cost:1},"history/candles":{cost:1},"history/sparklines":{cost:1},settings:{cost:1}}},private:{get:{orders:{cost:1},"orders/{order_id}":{cost:1},"orders/client_order_id/{client_oid}":{cost:1},"products/{product_id}/orders/leverage":{cost:1},"positions/margined":{cost:1},positions:{cost:1},"orders/history":{cost:1},fills:{cost:1},"fills/history/download/csv":{cost:1},"wallet/balances":{cost:1},"wallet/transactions":{cost:1},"wallet/transactions/download":{cost:1},"wallets/sub_accounts_transfer_history":{cost:1},"users/trading_preferences":{cost:1},sub_accounts:{cost:1},profile:{cost:1},"rate_limits/quota":{cost:1},heartbeat:{cost:1},"deposits/address":{cost:1}},post:{orders:{cost:1},"orders/bracket":{cost:1},"orders/batch":{cost:1},"products/{product_id}/orders/leverage":{cost:1},"positions/change_margin":{cost:1},"positions/close_all":{cost:1},"wallets/sub_account_balance_transfer":{cost:1},"heartbeat/create":{cost:1},heartbeat:{cost:1},"orders/cancel_after":{cost:1},"orders/leverage":{cost:1}},put:{orders:{cost:1},"orders/bracket":{cost:1},"orders/batch":{cost:1},"positions/auto_topup":{cost:1},"users/update_mmp":{cost:1},"users/reset_mmp":{cost:1},"users/margin_mode":{cost:1},"users/trading_preferences":{cost:1}},delete:{orders:{cost:1},"orders/all":{cost:1},"orders/batch":{cost:1}}}},fees:{trading:{tierBased:!0,percentage:!0,taker:this.parseNumber("0.0015"),maker:this.parseNumber("0.0010"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.0015")],[this.parseNumber("100"),this.parseNumber("0.0013")],[this.parseNumber("250"),this.parseNumber("0.0013")],[this.parseNumber("1000"),this.parseNumber("0.001")],[this.parseNumber("5000"),this.parseNumber("0.0009")],[this.parseNumber("10000"),this.parseNumber("0.00075")],[this.parseNumber("20000"),this.parseNumber("0.00065")]],maker:[[this.parseNumber("0"),this.parseNumber("0.001")],[this.parseNumber("100"),this.parseNumber("0.001")],[this.parseNumber("250"),this.parseNumber("0.0009")],[this.parseNumber("1000"),this.parseNumber("0.00075")],[this.parseNumber("5000"),this.parseNumber("0.0006")],[this.parseNumber("10000"),this.parseNumber("0.0005")],[this.parseNumber("20000"),this.parseNumber("0.0005")]]}}},userAgent:this.userAgents.chrome39,options:{networks:{TRC20:"TRC20(TRON)",BEP20:"BEP20(BSC)"}},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:{last:!0,mark:!0,index:!0},triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:{triggerPriceType:void 0,price:!0},timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,selfTradePrevention:!1,trailing:!1,iceberg:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,symbolRequired:!1},fetchOrder:void 0,fetchOpenOrders:{marginMode:!1,limit:100,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:500,daysBack:1e5,daysBackCanceled:1,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:2e3}},spot:{extends:"default"},swap:{linear:{extends:"default"},inverse:{extends:"default"}},future:{linear:{extends:"default"},inverse:{extends:"default"}}},precisionMode:4,requiredCredentials:{apiKey:!0,secret:!0},exceptions:{exact:{insufficient_margin:a.InsufficientFunds,order_size_exceed_available:a.InvalidOrder,risk_limits_breached:a.BadRequest,invalid_contract:a.BadSymbol,immediate_liquidation:a.InvalidOrder,out_of_bankruptcy:a.InvalidOrder,self_matching_disrupted_post_only:a.InvalidOrder,immediate_execution_post_only:a.InvalidOrder,bad_schema:a.BadRequest,invalid_api_key:a.AuthenticationError,invalid_signature:a.AuthenticationError,open_order_not_found:a.OrderNotFound,unavailable:a.ExchangeNotAvailable},broad:{}}})}createExpiredOptionMarket(e){let t,i,s,r="USDT",a=e.split("-"),o=e.split("/");e.indexOf("/")>-1?(t=this.safeString(o,0),i=this.safeString(a,1),s=this.safeString(a,3)):(t=this.safeString(a,1),i=this.safeString(a,3),s=this.safeString(a,0)),void 0!==i&&(i=i.slice(4)+i.slice(2,4)+i.slice(0,2));let n=this.safeString(a,2),d=this.convertExpireDate(i),h=this.parse8601(d),c="put";return"C"===s&&(c="call"),this.safeMarketStructure({id:s+"-"+t+"-"+n+"-"+i,symbol:t+"/"+r+":"+r+"-"+i+"-"+n+"-"+s,base:t,quote:r,settle:r,baseId:t,quoteId:r,settleId:r,active:!1,type:"option",linear:void 0,inverse:void 0,spot:!1,swap:!1,future:!1,option:!0,margin:!1,contract:!0,contractSize:this.parseNumber("1"),expiry:h,expiryDatetime:d,optionType:c,strike:this.parseNumber(n),precision:{amount:void 0,price:void 0},limits:{amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},info:void 0})}safeMarket(e,t,i,s){return void 0!==e&&(e.endsWith("-C")||e.endsWith("-P")||e.startsWith("C-")||e.startsWith("P-"))&&(void 0===this.markets_by_id||!(e in this.markets_by_id))?this.createExpiredOptionMarket(e):super.safeMarket(e,t,i,s)}async fetchTime(e={}){let t=await this.publicGetSettings(e),i=this.safeDict(t,"result",{});return this.safeIntegerProduct(i,"server_time",.001)}async fetchStatus(e={}){let t=await this.publicGetSettings(e),i=this.safeDict(t,"result",{}),s=this.safeString(i,"under_maintenance"),r="ok";return"true"===s&&(r="maintenance"),{status:r,updated:this.safeIntegerProduct(i,"server_time",.001,this.milliseconds()),eta:void 0,url:void 0,info:t}}async fetchCurrencies(e={}){let t=await this.publicGetAssets(e),i=this.safeList(t,"result",[]);return this.parseCurrencies(i)}parseCurrency(e){let t=this.safeString(e,"symbol"),i=this.safeInteger(e,"id"),s=this.safeCurrencyCode(t),r=this.safeList(e,"networks",[]),a={};for(let e=0;e<r.length;e++){let t=r[e],i=this.safeString(t,"network"),o=this.networkIdToCode(i,s);void 0!==o&&(a[o]={id:i,network:o,name:this.safeString(t,"name"),info:t,active:"enabled"===this.safeString(t,"status"),deposit:"enabled"===this.safeString(t,"deposit_status"),withdraw:"enabled"===this.safeString(t,"withdrawal_status"),fee:this.safeNumber(t,"base_withdrawal_fee"),limits:{deposit:{min:this.safeNumber(t,"min_deposit_amount"),max:void 0},withdraw:{min:this.safeNumber(t,"min_withdrawal_amount"),max:void 0}}})}return this.safeCurrencyStructure({id:t,numericId:i,code:s,name:this.safeString(e,"name"),info:e,active:void 0,deposit:"enabled"===this.safeString(e,"deposit_status"),withdraw:"enabled"===this.safeString(e,"withdrawal_status"),fee:this.safeNumber(e,"base_withdrawal_fee"),precision:this.parseNumber(this.parsePrecision(this.safeString(e,"precision"))),limits:{amount:{min:void 0,max:void 0},withdraw:{min:this.safeNumber(e,"min_withdrawal_amount"),max:void 0}},networks:a,type:"crypto"})}async loadMarkets(e=!1,t={}){let i=await super.loadMarkets(e,t);return(void 0===this.safeDict(this.options,"currenciesByNumericId")||e)&&(this.options.currenciesByNumericId=this.indexByStringifiedNumericId(this.currencies)),(void 0===this.safeDict(this.options,"marketsByNumericId")||e)&&(this.options.marketsByNumericId=this.indexByStringifiedNumericId(this.markets)),i}indexByStringifiedNumericId(e){let t={};if(void 0===e)return;let i=Object.keys(e);for(let s=0;s<i.length;s++){let r=e[i[s]],a=this.safeString(r,"numericId");void 0!==a&&(t[a]=r)}return t}async fetchMarkets(e={}){let t=await this.publicGetProducts(e),i=this.safeList(t,"result",[]),s=[];for(let e=0;e<i.length;e++){let t,r,a=i[e],o=this.safeString(a,"contract_type");if("options_combos"===o||"binary_call_options"===o||"binary_put_options"===o)continue;let n=this.safeDict(a,"quoting_asset",{}),d=this.safeDict(a,"underlying_asset",{}),h=this.safeDict(a,"settling_asset"),c=this.safeDict(a,"product_specs",{}),l=this.safeString(d,"symbol"),u=this.safeString(n,"symbol"),f=this.safeString(h,"symbol"),p=this.safeString(a,"symbol"),m=this.safeInteger(a,"id"),g=this.safeCurrencyCode(l),v=this.safeCurrencyCode(u);if(void 0===g||void 0===v)continue;let y=this.safeCurrencyCode(f),b="call_options"===o,w="put_options"===o,k="move_options"===o,S="spot"===o,O="perpetual_futures"===o,T="futures"===o,P=b||w||k,I=this.safeString(a,"strike_price"),A=this.safeString(a,"settlement_time"),x=this.parse8601(A),M=this.safeNumber(a,"contract_value");t=S?this.parseNumber(this.parsePrecision(this.safeString(c,"underlying_precision"))):this.parseNumber("1");let _=y===v,C=g+"/"+v;if(O||T||P)if(C=C+":"+y,T||P)if(C=C+"-"+this.yymmdd(x),P){o="option";let e="C";r="call",w?(e="P",r="put"):k&&(e="M",r="move"),C=C+"-"+I+"-"+e}else o="future";else o="swap";let B=this.safeString(a,"state");s.push(this.safeMarketStructure({id:p,numericId:m,symbol:C,base:g,quote:v,settle:y,baseId:l,quoteId:u,settleId:f,type:o,spot:S,margin:!1,swap:O,future:T,option:P,active:"live"===B,contract:!S,linear:S?void 0:_,inverse:S?void 0:!_,taker:this.safeNumber(a,"taker_commission_rate"),maker:this.safeNumber(a,"maker_commission_rate"),contractSize:S?void 0:M,expiry:x,expiryDatetime:this.iso8601(x),strike:this.parseNumber(I),optionType:r,precision:{amount:t,price:this.safeNumber(a,"tick_size")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.parseNumber("1"),max:this.safeNumber(a,"position_size_limit")},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(a,"min_size"),max:void 0}},created:this.parse8601(this.safeString(a,"launch_time")),info:a}))}return s}parseTicker(e,t){let i=this.safeIntegerProduct(e,"timestamp",.001),s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=r.symbol,o=this.safeString(e,"close"),n=this.safeDict(e,"quotes",{}),d=this.safeStringUpper(e,"turnover_symbol"),h=this.safeStringUpper(r,"quoteId"),c=void 0!==d&&void 0!==h&&d!==h?this.safeNumber(e,"turnover_usd"):this.safeNumber(e,"turnover");return this.safeTicker({symbol:a,timestamp:i,datetime:this.iso8601(i),high:this.safeNumber(e,"high"),low:this.safeNumber(e,"low"),bid:this.safeNumber(n,"best_bid"),bidVolume:this.safeNumber(n,"bid_size"),ask:this.safeNumber(n,"best_ask"),askVolume:this.safeNumber(n,"ask_size"),vwap:void 0,open:this.safeString(e,"open"),close:o,last:o,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeNumber(e,"volume"),quoteVolume:c,markPrice:this.safeNumber(e,"mark_price"),indexPrice:this.safeNumber(e,"spot_price"),info:e},r)}async fetchTicker(e,t={}){await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetTickersSymbol(this.extend(s,t)),a=this.safeDict(r,"result",{});return this.parseTicker(a,i)}async fetchTickers(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetTickers(t),r=this.safeList(s,"result",[]),a={};for(let e=0;e<r.length;e++){let t=r[e],i=this.safeString(t,"contract_type");if("options_combos"===i||"binary_call_options"===i||"binary_put_options"===i)continue;let s=this.parseTicker(t),o=s.symbol;void 0!==o&&(a[o]=s)}return this.filterByArrayTickers(a,"symbol",i)}async fetchOrderBook(e,t,i={}){await this.loadMarkets();let s=this.market(e),r={symbol:s.id};void 0!==t&&(r.depth=t);let a=await this.publicGetL2orderbookSymbol(this.extend(r,i)),o=this.safeDict(a,"result",{});return this.parseOrderBook(o,s.symbol,void 0,"buy","sell","price","size")}parseTrade(e,t){let i,s=this.safeString(e,"id"),r=this.safeString(e,"order_id"),a=this.parse8601(this.safeString(e,"created_at"));a=this.safeIntegerProduct(e,"timestamp",.001,a);let o=this.safeString(e,"price"),n=this.safeString(e,"size"),d=this.safeDict(e,"product",{}),h=this.safeString(d,"symbol"),c=this.safeSymbol(h,t),l=this.safeString(e,"seller_role"),u=this.safeString(e,"side");void 0===u&&("taker"===l?u="sell":"maker"===l&&(u="buy"));let f=this.safeString(e,"role"),p=this.safeDict(e,"meta_data",{}),m=this.safeString(p,"order_type");void 0!==m&&(m=m.replace("_order",""));let g=this.safeString(e,"commission");if(void 0!==g){let e=this.safeDict(d,"settling_asset",{}),t=this.safeString(e,"symbol");i={cost:g,currency:this.safeCurrencyCode(t)}}return this.safeTrade({id:s,order:r,timestamp:a,datetime:this.iso8601(a),symbol:c,type:m,side:u,price:o,amount:n,cost:void 0,takerOrMaker:f,fee:i,info:e},t)}async fetchTrades(e,t,i,s={}){await this.loadMarkets();let r=this.market(e),a={symbol:r.id},o=await this.publicGetTradesSymbol(this.extend(a,s)),n=this.safeList(o,"result",[]);return this.parseTrades(n,r,t,i)}parseOHLCV(e,t){return[this.safeTimestamp(e,"time"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchOHLCV(e,t="1m",i,s,r={}){await this.loadMarkets();let o=this.market(e),n={resolution:this.safeString(this.timeframes,t,t)},d=this.parseTimeframe(t),h=2e3;null!=s&&0!==s&&(h=s);let c=this.safeIntegerProduct(r,"until",.001),l=void 0!==c;if(l&&(c=this.parseToInt(c)),void 0===i){let e=l?c:this.seconds();if(n.end=e,void 0===e)throw new a.ExchangeError(this.id+" fetchOHLCV() missing end");n.start=e-h*d}else{let e=this.parseToInt(i/1e3);n.start=e,n.end=l?c:this.sum(e,h*d)}let u=this.safeString(r,"price");"mark"===u?n.symbol="MARK:"+o.id:"index"===u?n.symbol=o.info.spot_index.symbol:n.symbol=o.id;let f=this.omit(r,["price","until"]),p=await this.publicGetHistoryCandles(this.extend(n,f)),m=this.safeList(p,"result",[]);return this.parseOHLCVs(m,o,t,i,h)}parseBalance(e){let t=this.safeList(e,"result",[]),i={info:e},s=this.safeDict(this.options,"currenciesByNumericId",{});for(let e=0;e<t.length;e++){let r=this.safeDict(t,e),a=this.safeString(r,"asset_id"),o=this.safeDict(s,a),n=void 0===o?a:o.code,d=this.account();d.total=this.safeString(r,"balance"),d.free=this.safeString(r,"available_balance"),i[n]=d}return this.safeBalance(i)}async fetchBalance(e={}){await this.loadMarkets();let t=await this.privateGetWalletBalances(e);return this.parseBalance(t)}async fetchPosition(e,t={}){await this.loadMarkets();let i=this.market(e),s={product_id:i.numericId},r=await this.privateGetPositions(this.extend(s,t)),a=this.safeDict(r,"result",{});return this.parsePosition(a,i)}async fetchPositions(e,t={}){await this.loadMarkets();let i=await this.privateGetPositionsMargined(t),s=this.safeList(i,"result",[]);return this.parsePositions(s,e)}parsePosition(e,t){let i,s=this.safeString(e,"product_symbol"),r=this.safeMarket(s,t),a=r.symbol,n=this.safeIntegerProduct(e,"timestamp",.001),d=this.safeString(e,"size");return void 0!==d&&(o.Y.stringGt(d,"0")?i="buy":o.Y.stringLt(d,"0")&&(i="sell")),this.safePosition({info:e,id:void 0,symbol:a,notional:void 0,marginMode:void 0,liquidationPrice:this.safeNumber(e,"liquidation_price"),entryPrice:this.safeNumber(e,"entry_price"),unrealizedPnl:void 0,percentage:void 0,contracts:this.parseNumber(d),contractSize:this.safeNumber(r,"contractSize"),markPrice:void 0,side:i,hedged:void 0,timestamp:n,datetime:this.iso8601(n),maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,collateral:void 0,initialMargin:void 0,initialMarginPercentage:void 0,leverage:void 0,marginRatio:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}parseOrderStatus(e){return this.safeString({open:"open",pending:"open",closed:"closed",cancelled:"canceled"},e,e)}parseOrder(e,t){let i,s,r,a=this.safeString(e,"id"),o=this.safeString(e,"client_order_id"),n=this.safeString(e,"created_at");void 0!==n&&(i=n.indexOf("-")>=0?this.parse8601(n):this.safeIntegerProduct(e,"created_at",.001));let d=this.safeString(e,"product_id"),h=this.safeDict(this.options,"marketsByNumericId",{}),c=this.safeValue(h,d,t);s=void 0===c?d:c.symbol;let l=this.parseOrderStatus(this.safeString(e,"state")),u=this.safeString(e,"side"),f=this.safeString(e,"order_type");void 0!==f&&(f=f.replace("_order",""));let p=this.safeString(e,"limit_price"),m=this.safeString(e,"size"),g=this.safeString(e,"unfilled_size"),v=this.safeString(e,"average_fill_price"),y=this.safeString(e,"paid_commission");if(void 0!==y){let e;if(void 0!==c){let t=this.safeDict(c.info,"settling_asset",{}),i=this.safeString(t,"symbol");e=this.safeCurrencyCode(i)}r={cost:y,currency:e}}return this.safeOrder({info:e,id:a,clientOrderId:o,timestamp:i,datetime:this.iso8601(i),lastTradeTimestamp:void 0,symbol:s,type:f,side:u,price:p,amount:m,cost:void 0,average:v,filled:void 0,remaining:g,status:l,fee:r,trades:void 0},c)}async createOrder(e,t,i,s,r,a={}){await this.loadMarkets();let o=this.market(e),n={product_id:o.numericId,size:this.amountToPrecision(o.symbol,s),side:i,order_type:t+"_order"};"limit"===t&&(n.limit_price=this.priceToPrecision(o.symbol,r));let d=this.safeString2(a,"clientOrderId","client_order_id"),h=this.omit(a,["clientOrderId","client_order_id"]);void 0!==d&&(n.client_order_id=d);let c=this.safeBool(h,"reduceOnly");!0===c&&(n.reduce_only=c);let l=!0===c?this.omit(h,"reduceOnly"):h,u=await this.privatePostOrders(this.extend(n,l)),f=this.safeDict(u,"result",{});return this.parseOrder(f,o)}async editOrder(e,t,i,s,r,a,o={}){await this.loadMarkets();let n=this.market(t),d={id:parseInt(e),product_id:n.numericId};if(void 0!==r){let e=this.amountToPrecision(t,r);void 0===e&&(e="0"),d.size=parseInt(e)}void 0!==a&&(d.limit_price=this.priceToPrecision(t,a));let h=await this.privatePutOrders(this.extend(d,o)),c=this.safeDict(h,"result",{});return this.parseOrder(c,n)}async cancelOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");await this.loadMarkets();let s=this.market(t),r={id:parseInt(e),product_id:s.numericId},o=await this.privateDeleteOrders(this.extend(r,i)),n=this.safeDict(o,"result",{});return this.parseOrder(n,s)}async cancelAllOrders(e,t={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument");await this.loadMarkets();let i={product_id:this.market(e).numericId},s=this.privateDeleteOrdersAll(this.extend(i,t));return[this.safeOrder({info:s})]}async fetchOrder(e,t,i={}){let s,r;await this.loadMarkets(),void 0!==t&&(s=this.market(t));let a=this.safeStringN(i,["clientOrderId","client_oid","clientOid"]),o=this.omit(i,["clientOrderId","client_oid","clientOid"]),n={};void 0!==a?(n.client_oid=a,r=await this.privateGetOrdersClientOrderIdClientOid(this.extend(n,o))):(n.order_id=e,r=await this.privateGetOrdersOrderId(this.extend(n,o)));let d=this.safeDict(r,"result",{});return this.parseOrder(d,s)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrdersWithMethod("privateGetOrders",e,t,i,s)}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrdersWithMethod("privateGetOrdersHistory",e,t,i,s)}async fetchOrdersWithMethod(e,t,i,s,r={}){let a,o;await this.loadMarkets();let n={};void 0!==t&&(n.product_ids=(a=this.market(t)).numericId),void 0!==i&&(n.start_time=i.toString()+"000"),void 0!==s&&(n.page_size=s),"privateGetOrders"===e?o=await this.privateGetOrders(this.extend(n,r)):"privateGetOrdersHistory"===e&&(o=await this.privateGetOrdersHistory(this.extend(n,r)));let d=this.safeList(o,"result",[]);return this.parseOrders(d,a,i,s)}async fetchMyTrades(e,t,i,s={}){let r;await this.loadMarkets();let a={};void 0!==e&&(a.product_ids=(r=this.market(e)).numericId),void 0!==t&&(a.start_time=t.toString()+"000"),void 0!==i&&(a.page_size=i);let o=await this.privateGetFills(this.extend(a,s)),n=this.safeList(o,"result",[]);return this.parseTrades(n,r,t,i)}async fetchLedger(e,t,i,s={}){let r;await this.loadMarkets();let a={};void 0!==e&&(a.asset_id=(r=this.currency(e)).numericId),void 0!==i&&(a.page_size=i);let o=await this.privateGetWalletTransactions(this.extend(a,s)),n=this.safeList(o,"result",[]);return this.parseLedger(n,r,t,i)}parseLedgerEntryType(e){return this.safeString({pnl:"pnl",deposit:"transaction",withdrawal:"transaction",commission:"fee",conversion:"trade",referral_bonus:"referral",commission_rebate:"rebate"},e,e)}parseLedgerEntry(e,t){let i,s=this.safeString(e,"uuid"),r=this.safeDict(e,"meta_data",{}),a=this.safeString(r,"transaction_id"),n=this.safeString(e,"transaction_type");"deposit"===n||"commission_rebate"===n||"referral_bonus"===n||"pnl"===n||"withdrawal_cancellation"===n||"promo_credit"===n?i="in":("withdrawal"===n||"commission"===n||"conversion"===n||"perpetual_futures_funding"===n)&&(i="out"),n=this.parseLedgerEntryType(n);let d=this.safeString(e,"asset_id"),h=this.safeDict(this.options,"currenciesByNumericId"),c=this.safeValue(h,d,t),l=void 0===c?void 0:c.code,u=this.safeString(e,"amount"),f=this.parse8601(this.safeString(e,"created_at")),p=this.safeString(e,"balance"),m=o.Y.stringMax("0",o.Y.stringSub(p,u));return this.safeLedgerEntry({info:e,id:s,direction:i,account:void 0,referenceId:a,referenceAccount:void 0,type:n,currency:l,amount:this.parseNumber(u),before:this.parseNumber(m),after:this.parseNumber(p),status:"ok",timestamp:f,datetime:this.iso8601(f),fee:void 0},c)}async fetchDepositAddress(e,t={}){await this.loadMarkets();let i=this.currency(e),s={asset_symbol:i.id},r=this.safeStringUpper(t,"network");void 0!==r&&(s.network=this.networkCodeToId(r,e));let a=void 0!==r?this.omit(t,"network"):t,o=await this.privateGetDepositsAddress(this.extend(s,a)),n=this.safeDict(o,"result",{});return this.parseDepositAddress(n,i)}parseDepositAddress(e,t){let i=this.safeString(e,"address"),s=this.safeString(e,"asset_symbol"),r=this.safeString(e,"network"),a=this.safeCurrencyCode(s,t);return this.checkAddress(i),{info:e,currency:a,network:this.networkIdToCode(r,a),address:i,tag:this.safeString(e,"memo")}}async fetchFundingRate(e,t={}){await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new a.BadSymbol(this.id+" fetchFundingRate() supports swap contracts only");let s={symbol:i.id},r=await this.publicGetTickersSymbol(this.extend(s,t)),o=this.safeDict(r,"result",{});return this.parseFundingRate(o,i)}async fetchFundingRates(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetTickers(this.extend({contract_types:"perpetual_futures"},t)),r=this.safeList(s,"result",[]);return this.parseFundingRates(r,i)}parseFundingRate(e,t){let i=this.safeIntegerProduct(e,"timestamp",.001),s=this.safeString(e,"symbol"),r=this.safeString(e,"funding_rate"),a=o.Y.stringDiv(r,"100");return{info:e,symbol:this.safeSymbol(s,t),markPrice:this.safeNumber(e,"mark_price"),indexPrice:this.safeNumber(e,"spot_price"),interestRate:void 0,estimatedSettlePrice:void 0,timestamp:i,datetime:this.iso8601(i),fundingRate:this.parseNumber(a),fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:void 0}}async addMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,"add",i)}async reduceMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,"reduce",i)}async modifyMarginHelper(e,t,i,s={}){await this.loadMarkets();let r=this.market(e),a=t.toString(),n="reduce"===i?o.Y.stringMul(a,"-1"):a,d={product_id:r.numericId,delta_margin:n},h=await this.privatePostPositionsChangeMargin(this.extend(d,s)),c=this.safeDict(h,"result",{});return this.parseMarginModification(c,r)}parseMarginModification(e,t){let i=this.safeString(e,"product_symbol");return{info:e,symbol:this.safeMarket(i,t).symbol,type:void 0,marginMode:"isolated",amount:void 0,total:this.safeNumber(e,"margin"),code:void 0,status:void 0,timestamp:void 0,datetime:void 0}}async fetchOpenInterest(e,t={}){await this.loadMarkets();let i=this.market(e);if(!0!==i.contract)throw new a.BadRequest(this.id+" fetchOpenInterest() supports contract markets only");let s={symbol:i.id},r=await this.publicGetTickersSymbol(this.extend(s,t)),o=this.safeDict(r,"result",{});return this.parseOpenInterest(o,i)}parseOpenInterest(e,t){let i=this.safeIntegerProduct(e,"timestamp",.001),s=this.safeString(e,"symbol");return this.safeOpenInterest({symbol:this.safeSymbol(s,t),baseVolume:this.safeNumber(e,"oi_value"),quoteVolume:this.safeNumber(e,"oi_value_usd"),openInterestAmount:this.safeNumber(e,"oi_contracts"),openInterestValue:this.safeNumber(e,"oi"),timestamp:i,datetime:this.iso8601(i),info:e},t)}async fetchLeverage(e,t={}){await this.loadMarkets();let i=this.market(e),s={product_id:i.numericId},r=await this.privateGetProductsProductIdOrdersLeverage(this.extend(s,t)),a=this.safeDict(r,"result",{});return this.parseLeverage(a,i)}parseLeverage(e,t){let i=this.safeString(e,"index_symbol"),s=this.safeInteger(e,"leverage");return{info:e,symbol:this.safeSymbol(i,t),marginMode:this.safeStringLower(e,"margin_mode"),longLeverage:s,shortLeverage:s}}async setLeverage(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");await this.loadMarkets();let s={product_id:this.market(t).numericId,leverage:e};return await this.privatePostProductsProductIdOrdersLeverage(this.extend(s,i))}async fetchSettlementHistory(e,t,i,s={}){let r;await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a={states:"expired"};void 0!==i&&(a.page_size=i);let o=await this.publicGetProducts(this.extend(a,s)),n=this.safeList(o,"result",[]),d=this.parseSettlements(n,r),h=this.sortBy(d,"timestamp");return this.filterBySymbolSinceLimit(h,this.safeString(r,"symbol"),t,i)}parseSettlement(e,t){let i=this.safeString(e,"settlement_time"),s=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(s,t),price:this.safeNumber(e,"settlement_price"),timestamp:this.parse8601(i),datetime:i}}parseSettlements(e,t){let i=[];for(let s=0;s<e.length;s++)i.push(this.parseSettlement(e[s],t));return i}async fetchGreeks(e,t={}){await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetTickersSymbol(this.extend(s,t)),a=this.safeDict(r,"result",{});return this.parseGreeks(a,i)}parseGreeks(e,t){let i=this.safeIntegerProduct(e,"timestamp",.001),s=this.safeString(e,"symbol"),r=this.safeSymbol(s,t),a=this.safeDict(e,"greeks",{}),o=this.safeDict(e,"quotes",{});return{symbol:r,timestamp:i,datetime:this.iso8601(i),delta:this.safeNumber(a,"delta"),gamma:this.safeNumber(a,"gamma"),theta:this.safeNumber(a,"theta"),vega:this.safeNumber(a,"vega"),rho:this.safeNumber(a,"rho"),bidSize:this.safeNumber(o,"bid_size"),askSize:this.safeNumber(o,"ask_size"),bidImpliedVolatility:this.safeNumber(o,"bid_iv"),askImpliedVolatility:this.safeNumber(o,"ask_iv"),markImpliedVolatility:this.safeNumber(o,"mark_iv"),bidPrice:this.safeNumber(o,"best_bid"),askPrice:this.safeNumber(o,"best_ask"),markPrice:this.safeNumber(e,"mark_price"),lastPrice:this.safeNumber(e,"last_price"),underlyingPrice:this.safeNumber(e,"spot_price"),info:e}}async closeAllPositions(e={}){await this.loadMarkets();let t=await this.privatePostPositionsCloseAll(this.extend({close_all_portfolio:!0,close_all_isolated:!0},e));return[this.parsePosition(this.safeDict(t,"result",{}))]}async fetchMarginMode(e,t={}){let i;await this.loadMarkets(),void 0!==e&&(i=this.market(e));let s=await this.privateGetProfile(t),r=this.safeDict(s,"result",{});return this.parseMarginMode(r,i)}parseMarginMode(e,t){let i;return void 0!==t&&(i=t.symbol),{info:e,symbol:i,marginMode:this.safeString(e,"margin_mode")}}async setMarginMode(e,t,i={}){this.checkRequiredArgument("setMarginMode",e,"marginMode",["isolated","portfolio"]);let s=this.safeString(i,"subaccount_user_id");return this.checkRequiredArgument("setMarginMode",s,'params["subaccount_user_id"]'),await this.privatePutUsersMarginMode(this.extend({margin_mode:e},i))}async fetchOption(e,t={}){await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetTickersSymbol(this.extend(s,t)),a=this.safeDict(r,"result",{});return this.parseOption(a,void 0,i)}parseOption(e,t,i){let s=this.safeString(e,"symbol"),r=this.safeMarket(s,i),a=this.safeDict(e,"quotes",{}),o=this.safeIntegerProduct(e,"timestamp",.001);return{info:e,currency:this.safeString(e,"currency"),symbol:r.symbol,timestamp:o,datetime:this.iso8601(o),impliedVolatility:this.safeNumber(a,"mark_iv"),openInterest:this.safeNumber(e,"oi"),bidPrice:this.safeNumber(a,"best_bid"),askPrice:this.safeNumber(a,"best_ask"),midPrice:this.safeNumber(a,"impact_mid_price"),markPrice:this.safeNumber(e,"mark_price"),lastPrice:this.safeNumber(e,"last_price"),underlyingPrice:this.safeNumber(e,"spot_price"),change:this.safeNumber(e,"change"),percentage:this.safeNumber(e,"percentage"),baseVolume:this.safeNumber(e,"volume"),quoteVolume:this.safeNumber(e,"quote_volume")}}async fetchPositionsADLRank(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s=await this.privateGetPositionsMargined(t),r=this.safeList(s,"result",[]);return this.parseADLRanks(r,i)}parseADLRank(e,t){let i=this.safeString(e,"product_symbol"),s=this.safeString(e,"created_at");return{info:e,symbol:this.safeSymbol(i,t,void 0,"contract"),rank:this.safeInteger(e,"adl_level"),rating:void 0,percentage:void 0,timestamp:this.parse8601(s),datetime:s}}sign(e,t="public",i="GET",r={},o={},n){let d,h,c="/"+this.version+"/"+this.implodeParams(e,r),l=this.safeString(this.urls.api,t);if(void 0===l)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let u=l+c,f=this.omit(r,this.extractParams(e));if("public"===t)Object.keys(f).length>0&&(u+="?"+this.urlencode(f));else if("private"===t){this.checkRequiredCredentials();let e=this.seconds().toString();h={"api-key":this.apiKey,timestamp:e};let t=i+e+c;if("GET"===i){if(Object.keys(f).length>0){let e="?"+this.urlencode(f);t+=e,u+=e}}else t+=d=this.json(f),h["Content-Type"]="application/json";let r=this.hmac(this.encode(t),this.encode(this.secret),s.sc);h.signature=r}return{url:u,method:i,body:void 0===d?n:d,headers:void 0===h?o:h}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeDict(n,"error",{}),l=this.safeString(c,"code");if(void 0!==l){let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,l,e),this.throwBroadlyMatchedException(this.exceptions.broad,l,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>n})},3045(e,t,i){"use strict";var s=i(4721),r=i(9458),a=i(1453),o=i(7749),n=i(6637);class d extends r.A{describe(){return this.deepExtend(super.describe(),{id:"deribit",name:"Deribit",countries:["NL"],version:"v2",userAgent:void 0,rateLimit:50,pro:!0,has:{CORS:!0,spot:!0,margin:!1,swap:!0,future:!0,option:!0,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!1,createDepositAddress:!0,createOrder:!0,createReduceOnlyOrder:!0,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,createTrailingAmountOrder:!0,editOrder:!0,fetchAccounts:!0,fetchBalance:!0,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:!1,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositWithdrawFees:!0,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchGreeks:!0,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLeverageTiers:!1,fetchLiquidations:!0,fetchMarginMode:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyLiquidations:!0,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!0,fetchOptionChain:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!1,fetchOrderTrades:!0,fetchPosition:!0,fetchPositionMode:!1,fetchPositions:!0,fetchPremiumIndexOHLCV:!1,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchTransactions:!1,fetchTransfer:!1,fetchTransfers:!0,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!0,fetchWithdrawal:!1,fetchWithdrawals:!0,sandbox:!0,transfer:!0,withdraw:!0},timeframes:{"1m":"1","3m":"3","5m":"5","10m":"10","15m":"15","30m":"30","1h":"60","2h":"120","3h":"180","6h":"360","12h":"720","1d":"1D"},urls:{test:{rest:"https://test.deribit.com"},logo:"https://user-images.githubusercontent.com/1294454/41933112-9e2dd65a-798b-11e8-8440-5bab2959fcb8.jpg",api:{rest:"https://www.deribit.com"},www:"https://www.deribit.com",doc:["https://docs.deribit.com/v2","https://github.com/deribit"],fees:"https://www.deribit.com/pages/information/fees",referral:{url:"https://www.deribit.com/reg-1189.4038",discount:.1}},api:{public:{get:{auth:{cost:1},exchange_token:{cost:1},fork_token:{cost:1},set_heartbeat:{cost:1},disable_heartbeat:{cost:1},get_time:{cost:1},hello:{cost:1},status:{cost:1},test:{cost:1},subscribe:{cost:1},unsubscribe:{cost:1},unsubscribe_all:{cost:1},get_announcements:{cost:1},get_apr_history:{cost:1},get_book_summary_by_currency:{cost:1},get_book_summary_by_instrument:{cost:1},get_contract_size:{cost:1},get_currencies:{cost:1},get_delivery_prices:{cost:1},get_expirations:{cost:1},get_funding_chart_data:{cost:1},get_funding_rate_history:{cost:1},get_funding_rate_value:{cost:1},get_historical_volatility:{cost:1},get_index:{cost:1},get_index_chart_data:{cost:1},get_index_price:{cost:1},get_index_price_names:{cost:1},get_instrument:{cost:1},get_instruments:{cost:1},get_last_settlements_by_currency:{cost:1},get_last_settlements_by_instrument:{cost:1},get_last_trades_by_currency:{cost:1},get_last_trades_by_currency_and_time:{cost:1},get_last_trades_by_instrument:{cost:1},get_last_trades_by_instrument_and_time:{cost:1},get_mark_price_history:{cost:1},get_order_book:{cost:1},get_supported_index_names:{cost:1},get_trade_volumes:{cost:1},get_tradingview_chart_data:{cost:1},get_volatility_index_data:{cost:1},ticker:{cost:1}}},private:{get:{logout:{cost:1},enable_cancel_on_disconnect:{cost:1},disable_cancel_on_disconnect:{cost:1},get_cancel_on_disconnect:{cost:1},subscribe:{cost:1},unsubscribe:{cost:1},unsubscribe_all:{cost:1},change_api_key_name:{cost:1},change_scope_in_api_key:{cost:1},change_subaccount_name:{cost:1},create_api_key:{cost:1},create_subaccount:{cost:1},disable_api_key:{cost:1},disable_tfa_for_subaccount:{cost:1},enable_affiliate_program:{cost:1},enable_api_key:{cost:1},get_access_log:{cost:1},get_account_summary:{cost:1},get_account_summaries:{cost:1},get_affiliate_program_info:{cost:1},get_currencies:{cost:1},get_email_language:{cost:1},get_new_announcements:{cost:1},get_portfolio_margins:{cost:1},get_position:{cost:1},get_positions:{cost:1},get_subaccounts:{cost:1},get_subaccounts_details:{cost:1},get_transaction_log:{cost:1},list_api_keys:{cost:1},remove_api_key:{cost:1},remove_subaccount:{cost:1},reset_api_key:{cost:1},set_announcement_as_read:{cost:1},set_api_key_as_default:{cost:1},set_disabled_trading_products:{cost:1},set_email_for_subaccount:{cost:1},set_email_language:{cost:1},set_password_for_subaccount:{cost:1},simulate_portfolio:{cost:1},toggle_notifications_from_subaccount:{cost:1},toggle_subaccount_login:{cost:1},approve_block_trade:{cost:1},execute_block_trade:{cost:4},get_block_trade:{cost:1},get_block_trade_requests:{cost:1},get_block_trades:{cost:1},get_last_block_trades_by_currency:{cost:1},invalidate_block_trade_signature:{cost:1},reject_block_trade:{cost:1},simulate_block_trade:{cost:4},verify_block_trade:{cost:4},buy:{cost:4},sell:{cost:4},edit:{cost:4},edit_by_label:{cost:4},cancel:{cost:4},cancel_all:{cost:4},cancel_all_by_currency:{cost:4},cancel_all_by_instrument:{cost:4},cancel_by_label:{cost:4},cancel_quotes:{cost:4},close_position:{cost:4},get_margins:{cost:1},get_mmp_config:{cost:1},get_mmp_status:{cost:1},get_open_orders:{cost:1},get_open_orders_by_currency:{cost:1},get_open_orders_by_instrument:{cost:1},get_open_orders_by_label:{cost:1},get_order_history_by_currency:{cost:1},get_order_history_by_instrument:{cost:1},get_order_margin_by_ids:{cost:1},get_order_state:{cost:1},get_order_state_by_label:{cost:1},get_stop_order_history:{cost:1},get_trigger_order_history:{cost:1},get_user_trades_by_currency:{cost:1},get_user_trades_by_currency_and_time:{cost:1},get_user_trades_by_instrument:{cost:1},get_user_trades_by_instrument_and_time:{cost:1},get_user_trades_by_order:{cost:1},mass_quote:{cost:4},move_positions:{cost:4},reset_mmp:{cost:1},set_mmp_config:{cost:1},get_settlement_history_by_instrument:{cost:1},get_settlement_history_by_currency:{cost:1},add_to_address_book:{cost:1},cancel_transfer_by_id:{cost:1},cancel_withdrawal:{cost:1},create_deposit_address:{cost:1},get_address_book:{cost:1},get_current_deposit_address:{cost:1},get_deposits:{cost:1},get_reward_eligibility:{cost:1},get_transfers:{cost:1},get_withdrawals:{cost:1},remove_from_address_book:{cost:1},set_clearance_originator:{cost:1},submit_transfer_to_subaccount:{cost:1},submit_transfer_to_user:{cost:1},update_in_address_book:{cost:1},withdraw:{cost:1}}}},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:{last:!0,mark:!0,index:!0},triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!0},hedged:!1,selfTradePrevention:!1,trailing:!0,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,iceberg:!0},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:100,daysBack:1e5,daysBackCanceled:1,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!0},fetchOHLCV:{limit:1e3}},spot:{extends:"default"},swap:{linear:{extends:"default"},inverse:{extends:"default"}},future:{linear:{extends:"default"},inverse:{extends:"default"}}},exceptions:{9999:a.PermissionDenied,1e4:a.AuthenticationError,10001:a.ExchangeError,10002:a.InvalidOrder,10003:a.InvalidOrder,10004:a.OrderNotFound,10005:a.InvalidOrder,10006:a.InvalidOrder,10007:a.InvalidOrder,10008:a.InvalidOrder,10009:a.InsufficientFunds,10010:a.OrderNotFound,10011:a.InvalidOrder,10012:a.InvalidOrder,10013:a.PermissionDenied,10014:a.PermissionDenied,10015:a.PermissionDenied,10016:a.PermissionDenied,10017:a.PermissionDenied,10018:a.PermissionDenied,10019:a.PermissionDenied,10020:a.ExchangeError,10021:a.InvalidOrder,10022:a.InvalidOrder,10023:a.InvalidOrder,10024:a.InvalidOrder,10025:a.InvalidOrder,10026:a.InvalidOrder,10027:a.InvalidOrder,10028:a.DDoSProtection,10029:a.OrderNotFound,10030:a.ExchangeError,10031:a.ExchangeError,10032:a.InvalidOrder,10033:a.NotSupported,10034:a.InvalidOrder,10035:a.InvalidOrder,10036:a.InvalidOrder,10040:a.ExchangeNotAvailable,10041:a.OnMaintenance,10043:a.InvalidOrder,10044:a.InvalidOrder,10045:a.InvalidOrder,10046:a.InvalidOrder,10047:a.DDoSProtection,10048:a.ExchangeError,11008:a.InvalidOrder,11029:a.BadRequest,11030:a.ExchangeError,11031:a.ExchangeError,11035:a.DDoSProtection,11036:a.InvalidOrder,11037:a.BadRequest,11038:a.InvalidOrder,11039:a.InvalidOrder,11041:a.InvalidOrder,11042:a.PermissionDenied,11043:a.BadRequest,11044:a.InvalidOrder,11045:a.BadRequest,11046:a.BadRequest,11047:a.BadRequest,11048:a.ExchangeError,11049:a.BadRequest,11050:a.BadRequest,11051:a.OnMaintenance,11052:a.ExchangeError,11053:a.ExchangeError,11090:a.InvalidAddress,11091:a.InvalidAddress,11092:a.InvalidAddress,11093:a.DDoSProtection,11094:a.ExchangeError,11095:a.ExchangeError,11096:a.ExchangeError,12e3:a.AuthenticationError,12001:a.DDoSProtection,12002:a.ExchangeError,12998:a.AuthenticationError,12003:a.AuthenticationError,12004:a.AuthenticationError,12005:a.AuthenticationError,12100:a.ExchangeError,12999:a.AuthenticationError,13e3:a.AuthenticationError,13001:a.AuthenticationError,13002:a.PermissionDenied,13003:a.AuthenticationError,13004:a.AuthenticationError,13005:a.AuthenticationError,13006:a.AuthenticationError,13007:a.AuthenticationError,13008:a.ExchangeError,13009:a.AuthenticationError,13010:a.BadRequest,13011:a.BadRequest,13012:a.PermissionDenied,13013:a.BadRequest,13014:a.BadRequest,13015:a.BadRequest,13016:a.BadRequest,13017:a.ExchangeError,13018:a.ExchangeError,13019:a.ExchangeError,13020:a.ExchangeError,13021:a.PermissionDenied,13025:a.ExchangeError,"-32602":a.BadRequest,"-32601":a.BadRequest,"-32700":a.BadRequest,"-32000":a.BadRequest,11054:a.InvalidOrder},precisionMode:4,options:{code:"BTC",fetchBalance:{code:"BTC"},transfer:{method:"privateGetSubmitTransferToSubaccount"}}})}createExpiredOptionMarket(e){let t,i,s,r="USD",o=e.split("-"),n=e.split("/");e.indexOf("/")>-1?(i=this.safeString(n,0),s=this.safeString(o,1),e.indexOf("USDC")>-1&&(i+="_USDC")):(i=this.safeString(o,0),s=this.convertMarketIdExpireDate(this.safeString(o,1))),e.indexOf("USDC")>-1?(r="USDC",t="USDC"):t=i;let d=i;if(void 0===i)throw new a.ExchangeError(this.id+" createExpiredOptionMarket() missing base");if(i.indexOf("_")>-1){let e=i.split("_");d=this.safeString(e,0)}let h=this.safeString(o,2),c=this.safeString(o,3),l=this.convertExpireDate(s),u=this.parse8601(l);return{id:i+"-"+this.convertExpireDateToMarketIdDate(s)+"-"+h+"-"+c,symbol:d+"/"+r+":"+t+"-"+s+"-"+h+"-"+c,base:i,quote:r,settle:t,baseId:i,quoteId:r,settleId:t,active:!1,type:"option",linear:void 0,inverse:void 0,spot:!1,swap:!1,future:!1,option:!0,margin:!1,contract:!0,contractSize:void 0,expiry:u,expiryDatetime:l,optionType:"C"===c?"call":"put",strike:this.parseNumber(h),precision:{amount:void 0,price:void 0},limits:{amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},info:void 0}}safeMarket(e,t,i,s){return void 0!==e&&(e.endsWith("-C")||e.endsWith("-P"))&&(void 0===this.markets_by_id||!(e in this.markets_by_id))?this.createExpiredOptionMarket(e):super.safeMarket(e,t,i,s)}async fetchTime(e={}){let t=await this.publicGetGetTime(e);return this.safeInteger(t,"result")}async fetchCurrencies(e={}){let t=await this.publicGetGetCurrencies(e),i=this.safeList(t,"result",[]);return this.parseCurrencies(i)}parseCurrency(e){let t=this.safeString(e,"currency"),i=this.safeCurrencyCode(t);return this.safeCurrencyStructure({info:e,code:i,id:t,name:this.safeString(e,"currency_long"),active:void 0,deposit:void 0,withdraw:void 0,type:"crypto",fee:this.safeNumber(e,"withdrawal_fee"),precision:void 0,limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},networks:void 0})}codeFromOptions(e,t={}){let i=this.safeString(this.options,"code","BTC"),s=this.safeDict(this.options,e,{}),r=this.safeString(s,"code",i);return this.safeString(t,"code",r)}async fetchStatus(e={}){let t=await this.publicGetStatus(e),i=this.safeDict(t,"result");return{status:"false"===this.safeString(i,"locked")?"ok":"maintenance",updated:this.safeIntegerProduct(t,"usIn",.001,this.milliseconds()),eta:void 0,url:void 0,info:t}}async fetchAccounts(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetGetSubaccounts(e),i=this.safeList(t,"result",[]);return this.parseAccounts(i)}parseAccount(e){return{info:e,id:this.safeString(e,"id"),type:this.safeString(e,"type"),code:void 0}}async fetchMarkets(e={}){let t=[],i=[],s={},[r,o]=this.handleOptionBoolAndParams(e,"fetchMarkets","fetchAllMarkets",!0);if(r){let e=await this.publicGetGetInstruments(o);t.push(e)}else{let e=await this.publicGetGetCurrencies(o),i=this.safeList(e,"result",[]);for(let e=0;e<i.length;e++){let s={currency:this.safeString(i[e],"currency")},r=await this.publicGetGetInstruments(this.extend(s,o));t.push(r)}}for(let e=0;e<t.length;e++){let r=this.safeList(t[e],"result",[]);for(let e=0;e<r.length;e++){let t,o,n,d,h=r[e],c=this.safeString(h,"kind"),l="spot"===c,u=this.safeString(h,"instrument_name"),f=this.safeString(h,"base_currency"),p=this.safeString(h,"counter_currency"),m=this.safeString(h,"settlement_currency"),g=this.safeCurrencyCode(f),v=this.safeCurrencyCode(p);if(void 0===g||void 0===v)continue;let y=this.safeCurrencyCode(m),b="perpetual"===this.safeString(h,"settlement_period");if(void 0===c)throw new a.ExchangeError(this.id+" method() missing kind");let w=!b&&c.indexOf("future")>=0;if(void 0===c)throw new a.ExchangeError(this.id+" method() missing kind");let k=c.indexOf("option")>=0;if(void 0===c)throw new a.ExchangeError(this.id+" method() missing kind");let S=c.indexOf("combo")>=0,O=this.safeInteger(h,"expiration_timestamp"),T=u,P="swap";if(w?P="future":k?P="option":l&&(P="spot"),l)T=g+"/"+v;else if(!S){if(T=g+"/"+v+":"+y,(k||w)&&(T=T+"-"+this.yymmdd(O,""),k)){t=this.safeNumber(h,"strike");let e="call"===(o=this.safeString(h,"option_type"))?"C":"P";T=T+"-"+this.numberToString(t)+"-"+e}n=v!==y,d=y===v}if(void 0!==this.safeBool(s,T))continue;void 0!==T&&(s[T]=!0);let I=this.safeNumber(h,"min_trade_amount"),A=this.safeNumber(h,"tick_size");i.push({id:u,symbol:T,base:g,quote:v,settle:y,baseId:f,quoteId:p,settleId:m,type:P,spot:l,margin:!1,swap:b,future:w,option:k,active:this.safeBool(h,"is_active"),contract:!l,linear:d,inverse:n,taker:this.safeNumber(h,"taker_commission"),maker:this.safeNumber(h,"maker_commission"),contractSize:this.safeNumber(h,"contract_size"),expiry:O,expiryDatetime:this.iso8601(O),strike:t,optionType:o,precision:{amount:I,price:A},limits:{leverage:{min:void 0,max:void 0},amount:{min:I,max:void 0},price:{min:A,max:void 0},cost:{min:void 0,max:void 0}},created:this.safeInteger(h,"creation_timestamp"),info:h})}}return i}parseBalance(e){let t={info:e},i=[];i="summaries"in e?this.safeList(e,"summaries",[]):[e];for(let e=0;e<i.length;e++){let s=this.safeDict(i,e),r=this.safeString(s,"currency"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(s,"available_funds"),o.used=this.safeString(s,"maintenance_margin"),o.total=this.safeString(s,"equity"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let i=this.safeString(e,"code"),s=this.omit(e,"code"),r={};void 0!==i&&(r.currency=this.currencyId(i)),t=void 0===i?await this.privateGetGetAccountSummaries(s):await this.privateGetGetAccountSummary(this.extend(r,s));let a=this.safeDict(t,"result",{});return this.parseBalance(a)}async createDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={currency:this.currency(e).id},s=await this.privateGetCreateDepositAddress(this.extend(i,t)),r=this.safeDict(s,"result",{}),a=this.safeString(r,"address");return this.checkAddress(a),{currency:e,address:a,tag:void 0,network:void 0,info:s}}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={currency:this.currency(e).id},s=await this.privateGetGetCurrentDepositAddress(this.extend(i,t)),r=this.safeDict(s,"result",{}),a=this.safeString(r,"address");return this.checkAddress(a),{info:s,currency:e,network:void 0,address:a,tag:void 0}}parseTicker(e,t){let i=this.safeInteger2(e,"timestamp","creation_timestamp"),s=this.safeString(e,"instrument_name"),r=this.safeSymbol(s,t),a=this.safeString2(e,"last_price","last"),o=this.safeDict(e,"stats",e);return this.safeTicker({symbol:r,timestamp:i,datetime:this.iso8601(i),high:this.safeString2(o,"high","max_price"),low:this.safeString2(o,"low","min_price"),bid:this.safeString2(e,"best_bid_price","bid_price"),bidVolume:this.safeString(e,"best_bid_amount"),ask:this.safeString2(e,"best_ask_price","ask_price"),askVolume:this.safeString(e,"best_ask_amount"),vwap:void 0,open:void 0,close:a,last:a,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(o,"volume"),quoteVolume:this.safeString2(o,"volume_notional","volume_usd"),markPrice:this.safeString(e,"mark_price"),indexPrice:this.safeString(e,"index_price"),info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instrument_name:i.id},r=await this.publicGetTicker(this.extend(s,t)),a=this.safeDict(r,"result",{});return this.parseTicker(a,i)}async fetchTickers(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e),r=this.safeString2(t,"code","currency"),o=this.omit(t,["code"]);if(void 0!==s)for(let e=0;e<s.length;e++){let t=this.market(s[e]);if(void 0!==r&&r!==t.base)throw new a.BadRequest(this.id+" fetchTickers the base currency must be the same for all symbols, this endpoint only supports one base currency at a time. Read more about it here: https://docs.deribit.com/#public-get_book_summary_by_currency");void 0===r&&(r=this.safeString(t,"base"),i=this.safeString(t,"type"))}if(void 0===r)throw new a.ArgumentsRequired(this.id+" fetchTickers requires a currency/code (eg: BTC/ETH/USDT) parameter to fetch tickers for");let n={currency:this.currency(r).id};if(void 0!==i){let e;"spot"===i?e="spot":"future"===i||"contract"===i?e="future":"option"===i&&(e="option"),void 0!==e&&(n.kind=e)}let d=await this.publicGetGetBookSummaryByCurrency(this.extend(n,o)),h=this.safeList(d,"result",[]),c={};for(let e=0;e<h.length;e++){let t=this.parseTicker(h[e]),i=t.symbol;void 0!==i&&(c[i]=t)}return this.filterByArrayTickers(c,"symbol",s)}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,o,5e3);let n=this.market(e),d={instrument_name:n.id,resolution:this.safeString(this.timeframes,t,t)},h=this.parseTimeframe(t),c=this.milliseconds(),l=void 0===s?1e3:s,u=void 0===i?l:s,f=void 0===i?void 0:Math.max(i-1,0);void 0===i?(d.start_timestamp=c-(l-1)*h*1e3,d.end_timestamp=c):(d.start_timestamp=f,void 0===s?d.end_timestamp=c:d.end_timestamp=this.sum(f,s*h*1e3));let p=this.safeInteger(o,"until"),m=void 0!==p?this.omit(o,"until"):o;void 0!==p&&(d.end_timestamp=p);let g=await this.publicGetGetTradingviewChartData(this.extend(d,m)),v=this.safeDict(g,"result",{}),y=this.convertTradingViewToOHLCV(v,"ticks","open","high","low","close","volume",!0);return this.parseOHLCVs(y,n,t,f,u)}parseTrade(e,t){let i,s,r=this.safeString(e,"trade_id"),a=this.safeString(e,"instrument_name"),n=this.safeSymbol(a,t),d=this.safeInteger(e,"timestamp"),h=this.safeString(e,"direction"),c=this.safeString(e,"price"),l=this.safeMarket(a,t),u=this.safeString(e,"amount"),f=o.Y.stringMul(u,c);!0===l.inverse&&(f=o.Y.stringDiv(u,c));let p=this.safeString(e,"liquidity");void 0!==p&&(i="M"===p?"maker":"taker");let m=this.safeString(e,"fee");if(void 0!==m){let t=this.safeString(e,"fee_currency");s={cost:m,currency:this.safeCurrencyCode(t)}}return this.safeTrade({id:r,info:e,timestamp:d,datetime:this.iso8601(d),symbol:n,order:this.safeString(e,"order_id"),type:this.safeString(e,"order_type"),side:h,takerOrMaker:i,price:c,amount:u,cost:f,fee:s},l)}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={instrument_name:a.id,include_old:!0};void 0!==t&&(o.start_timestamp=t),void 0!==i&&(o.count=Math.min(i,1e3));let n=this.safeInteger2(s,"until","end_timestamp"),d=void 0!==n?this.omit(s,["until"]):s;void 0!==n&&(o.end_timestamp=n),r=void 0!==t||"end_timestamp"in o?await this.publicGetGetLastTradesByInstrumentAndTime(this.extend(o,d)):await this.publicGetGetLastTradesByInstrument(this.extend(o,d));let h=this.safeDict(r,"result",{}),c=this.safeList(h,"trades",[]);return this.parseTrades(c,a,t,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=this.codeFromOptions("fetchTradingFees",e),i={currency:this.currency(t).id,extended:!0},s=await this.privateGetGetAccountSummary(this.extend(i,e)),r=this.safeDict(s,"result",{}),a=this.safeList(r,"fees",[]),o={},n={},d={};for(let e=0;e<a.length;e++){let t=a[e],i=this.safeString(t,"instrument_type");"future"===i?n={info:t,maker:this.safeNumber(t,"maker_fee"),taker:this.safeNumber(t,"taker_fee")}:"perpetual"===i?o={info:t,maker:this.safeNumber(t,"maker_fee"),taker:this.safeNumber(t,"taker_fee")}:"option"===i&&(d={info:t,maker:this.safeNumber(t,"maker_fee"),taker:this.safeNumber(t,"taker_fee")})}let h={},c=this.symbols;for(let e=0;e<c.length;e++){let t=c[e],i=this.market(t),s={info:i,symbol:t,percentage:!0,tierBased:!0,maker:i.maker,taker:i.taker};!0===i.swap?s=this.extend(s,o):!0===i.future?s=this.extend(s,n):!0===i.option&&(s=this.extend(s,d)),h[t]=s}return h}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={instrument_name:s.id};void 0!==t&&(r.depth=t);let a=await this.publicGetGetOrderBook(this.extend(r,i)),o=this.safeDict(a,"result",{}),n=this.safeInteger(o,"timestamp"),d=this.safeInteger(o,"change_id"),h=this.parseOrderBook(o,s.symbol,n);return h.nonce=d,h}parseOrderStatus(e){return this.safeString({open:"open",cancelled:"canceled",filled:"closed",rejected:"rejected",untriggered:"open"},e,e)}parseTimeInForce(e){return this.safeString({good_til_cancelled:"GTC",fill_or_kill:"FOK",immediate_or_cancel:"IOC"},e,e)}parseOrderType(e){return this.safeString({stop_limit:"limit",take_limit:"limit",stop_market:"market",take_market:"market"},e,e)}parseOrder(e,t){let i,s,r=this.safeString(e,"instrument_name"),a=this.safeMarket(r,t),n=this.safeInteger(e,"creation_timestamp"),d=this.safeInteger(e,"last_update_timestamp"),h=this.safeString(e,"order_id"),c=this.safeString(e,"price");"market_price"===c&&(c=void 0);let l=this.safeString(e,"average_price"),u=this.safeString(e,"filled_amount"),f=this.safeString(e,"amount"),p=o.Y.stringMul(u,l);this.safeBool(a,"inverse",!1)&&"0"!==l&&(p=o.Y.stringDiv(f,l)),void 0!==u&&o.Y.stringGt(u,"0")&&(i=d);let m=this.parseOrderStatus(this.safeString(e,"order_state")),g=this.safeStringLower(e,"direction"),v=this.safeString(e,"commission");void 0!==v&&(s={cost:v=o.Y.stringAbs(v),currency:a.base});let y=this.safeString(e,"order_type"),b=this.parseOrderType(y),w=this.safeList(e,"trades"),k=this.parseTimeInForce(this.safeString(e,"time_in_force")),S=this.safeBool(e,"post_only");return this.safeOrder({info:e,id:h,clientOrderId:void 0,timestamp:n,datetime:this.iso8601(n),lastTradeTimestamp:i,symbol:a.symbol,type:b,timeInForce:k,postOnly:S,side:g,price:c,triggerPrice:this.safeNumber(e,"stop_price"),amount:f,cost:p,average:l,filled:u,remaining:void 0,status:m,fee:s,trades:w},a)}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let r=await this.privateGetGetOrderState(this.extend({order_id:e},i)),a=this.safeDict(r,"result",{});return this.parseOrder(a,s)}async createOrder(e,t,i,s,r,o={}){let n;void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h={instrument_name:d.id,amount:this.amountToPrecision(e,s),type:t},c=this.safeString(o,"trigger","last_price"),l=this.safeStringUpper(o,"timeInForce"),u=this.safeBool2(o,"reduceOnly","reduce_only"),f=this.safeValue(o,"stopLossPrice"),p=this.safeValue(o,"takeProfitPrice"),m=this.safeString2(o,"trailingAmount","trigger_offset"),g=void 0!==m,v="stop_limit"===t,y="stop_market"===t,b="take_limit"===t,w="take_market"===t,k=v||y||void 0!==f,S=b||w||void 0!==p;if(k&&S)throw new a.InvalidOrder(this.id+" createOrder () only allows one of stopLossPrice or takeProfitPrice to be specified");let O="limit"===t||v||b,T="market"===t||y||w,P=this.safeValue(o,"post_only"),I=this.isPostOnly(T,P,o);O?(h.type="limit",h.price=this.priceToPrecision(e,r)):h.type="market",g?(h.trigger=c,h.type="trailing_stop",h.trigger_offset=this.parseToNumeric(m)):(k||S)&&(h.trigger_price=this.priceToPrecision(e,void 0!==f?f:p),h.trigger=c,k?T?h.type="stop_market":h.type="stop_limit":T?h.type="take_market":h.type="take_limit"),!0===u&&(h.reduce_only=!0),I&&(h.post_only=!0,h.reject_post_only=!0),void 0!==l&&("GTC"===l&&(h.time_in_force="good_til_cancelled"),"IOC"===l&&(h.time_in_force="immediate_or_cancel"),"FOK"===l&&(h.time_in_force="fill_or_kill"));let A=this.omit(o,["timeInForce","stopLossPrice","takeProfitPrice","postOnly","reduceOnly","trailingAmount"]);n="Buy"===this.capitalize(i)?await this.privateGetBuy(this.extend(h,A)):await this.privateGetSell(this.extend(h,A));let x=this.safeDict(n,"result",{}),M=this.safeValue(x,"order");return M.trades=this.safeList(x,"trades",[]),this.parseOrder(M,d)}async editOrder(e,t,i,s,r,o,n={}){if(void 0===r)throw new a.ArgumentsRequired(this.id+" editOrder() requires an amount argument");void 0===this.markets&&await this.loadMarkets();let d={order_id:e,amount:this.amountToPrecision(t,r)};void 0!==o&&(d.price=this.priceToPrecision(t,o));let h=this.safeString2(n,"trailingAmount","trigger_offset"),c=void 0!==h,l=n;c&&(l=this.omit(n,"trigger_offset")),c&&(d.trigger_offset=this.parseToNumeric(h));let u=await this.privateGetEdit(this.extend(d,l)),f=this.safeDict(u,"result",{}),p=this.safeValue(f,"order");return p.trades=this.safeList(f,"trades",[]),this.parseOrder(p)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateGetCancel(this.extend({order_id:e},i)),r=this.safeDict(s,"result",{});return this.parseOrder(r)}async cancelAllOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={};return void 0===e?i=await this.privateGetCancelAll(this.extend(s,t)):(s.instrument_name=this.market(e).id,i=await this.privateGetCancelAllByInstrument(this.extend(s,t))),[this.safeOrder({info:i})]}async fetchOpenOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o={};if(void 0===e){let e=this.codeFromOptions("fetchOpenOrders",s);o.currency=this.currency(e).id,a=await this.privateGetGetOpenOrdersByCurrency(this.extend(o,s))}else o.instrument_name=(r=this.market(e)).id,a=await this.privateGetGetOpenOrdersByInstrument(this.extend(o,s));let n=this.safeList(a,"result",[]);return this.parseOrders(n,r,t,i)}async fetchClosedOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o={};if(void 0!==i?o.count=i:o.count=1e3,void 0===e){let e=this.codeFromOptions("fetchClosedOrders",s);o.currency=this.currency(e).id,a=await this.privateGetGetOrderHistoryByCurrency(this.extend(o,s))}else o.instrument_name=(r=this.market(e)).id,a=await this.privateGetGetOrderHistoryByInstrument(this.extend(o,s));let n=this.safeList(a,"result",[]);return this.parseOrders(n,r,t,i)}async fetchOrderTrades(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=await this.privateGetGetUserTradesByOrder(this.extend({order_id:e},r)),o=this.safeList(a,"result",[]);return this.parseTrades(o,void 0,i,s)}async fetchMyTrades(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o={include_old:!0};if(void 0!==i&&(o.count=i),void 0===e){let e=this.codeFromOptions("fetchMyTrades",s);o.currency=this.currency(e).id,void 0===t?a=await this.privateGetGetUserTradesByCurrency(this.extend(o,s)):(o.start_timestamp=t,a=await this.privateGetGetUserTradesByCurrencyAndTime(this.extend(o,s)))}else o.instrument_name=(r=this.market(e)).id,void 0===t?a=await this.privateGetGetUserTradesByInstrument(this.extend(o,s)):(o.start_timestamp=t,a=await this.privateGetGetUserTradesByInstrumentAndTime(this.extend(o,s)));let n=this.safeDict(a,"result",{}),d=this.safeList(n,"trades",[]);return this.parseTrades(d,r,t,i)}async fetchDeposits(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchDeposits() requires a currency code argument");void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),o={currency:r.id};void 0!==i&&(o.count=i);let n=await this.privateGetGetDeposits(this.extend(o,s)),d=this.safeDict(n,"result",{}),h=this.safeList(d,"data",[]);return this.parseTransactions(h,r,t,i,s)}async fetchWithdrawals(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchWithdrawals() requires a currency code argument");void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),o={currency:r.id};void 0!==i&&(o.count=i);let n=await this.privateGetGetWithdrawals(this.extend(o,s)),d=this.safeDict(n,"result",{}),h=this.safeList(d,"data",[]);return this.parseTransactions(h,r,t,i,s)}parseTransactionStatus(e){return this.safeString({completed:"ok",unconfirmed:"pending"},e,e)}parseTransaction(e,t){let i,s=this.safeString(e,"currency"),r=this.safeCurrencyCode(s,t),a=this.safeInteger2(e,"created_timestamp","received_timestamp"),o=this.safeInteger(e,"updated_timestamp"),n=this.parseTransactionStatus(this.safeString(e,"state")),d=this.safeString(e,"address"),h=this.safeNumber(e,"fee"),c="deposit";return void 0!==h&&(c="withdrawal",i={cost:h,currency:r}),{info:e,id:this.safeString(e,"id"),txid:this.safeString(e,"transaction_id"),timestamp:a,datetime:this.iso8601(a),address:d,addressTo:d,addressFrom:void 0,tag:void 0,tagTo:void 0,tagFrom:void 0,type:c,amount:this.safeNumber(e,"amount"),currency:r,status:n,updated:o,network:void 0,internal:void 0,comment:void 0,fee:i}}parsePosition(e,t){let i=this.safeString(e,"instrument_name"),s=this.safeMarket(i,t),r=this.safeString(e,"direction");r="buy"===r?"long":"short";let a=this.safeString(e,"floating_profit_loss"),n=this.safeString(e,"initial_margin"),d=this.safeString(e,"size_currency"),h=o.Y.stringAbs(d),c=this.safeString(e,"maintenance_margin");return this.safePosition({info:e,id:void 0,symbol:this.safeString(s,"symbol"),timestamp:void 0,datetime:void 0,lastUpdateTimestamp:void 0,initialMargin:this.parseNumber(n),initialMarginPercentage:this.parseNumber(o.Y.stringMul(o.Y.stringDiv(n,h),"100")),maintenanceMargin:this.parseNumber(c),maintenanceMarginPercentage:this.parseNumber(o.Y.stringMul(o.Y.stringDiv(c,h),"100")),entryPrice:this.safeNumber(e,"average_price"),notional:this.parseNumber(h),leverage:this.safeInteger(e,"leverage"),unrealizedPnl:this.parseNumber(a),realizedPnl:this.safeNumber(e,"realized_profit_loss"),contracts:this.safeNumber(e,"size"),contractSize:this.safeNumber(e,"contractSize"),marginRatio:void 0,liquidationPrice:this.safeNumber(e,"estimated_liquidation_price"),markPrice:this.safeNumber(e,"mark_price"),lastPrice:void 0,collateral:void 0,marginMode:void 0,side:r,percentage:void 0,hedged:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}async fetchPosition(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={instrument_name:this.market(e).id},s=await this.privateGetGetPosition(this.extend(i,t)),r=this.safeDict(s,"result",{});return this.parsePosition(r)}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeString(t,"currency"),s={},r=void 0!==i?this.omit(t,"currency"):t;void 0!==i&&(s.currency=this.currency(i).id);let a=await this.privateGetGetPositions(this.extend(s,r)),o=this.safeList(a,"result");return this.parsePositions(o,e)}async fetchVolatilityHistory(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={currency:this.currency(e).id},s=await this.publicGetGetHistoricalVolatility(this.extend(i,t));return this.parseVolatilityHistory(s)}parseVolatilityHistory(e){let t=this.safeList(e,"result",[]),i=[];for(let e=0;e<t.length;e++){let s=this.safeInteger(t[e],0),r=this.safeNumber(t[e],1);i.push({info:r,timestamp:s,datetime:this.iso8601(s),volatility:r})}return i}async fetchTransfers(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchTransfers() requires a currency code argument");void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),o={currency:r.id};void 0!==i&&(o.count=i);let n=await this.privateGetGetTransfers(this.extend(o,s)),d=this.safeDict(n,"result",{}),h=this.safeList(d,"data",[]);return this.parseTransfers(h,r,t,i,s)}async transfer(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.currency(e),n={amount:t,currency:o.id,destination:s},d=this.safeString(r,"method"),h=this.omit(r,"method");if(void 0===d){let e=this.safeDict(this.options,"transfer",{});d=this.safeString(e,"method","privateGetSubmitTransferToSubaccount")}a="privateGetSubmitTransferToUser"===d?await this.privateGetSubmitTransferToUser(this.extend(n,h)):await this.privateGetSubmitTransferToSubaccount(this.extend(n,h));let c=this.safeDict(a,"result",{});return this.parseTransfer(c,o)}parseTransfer(e,t){let i=this.safeInteger(e,"created_timestamp"),s=this.safeString(e,"state"),r=this.safeString(e,"other_side"),a=this.safeString(e,"direction"),o=this.safeString(e,"currency");return{info:e,id:this.safeString(e,"id"),status:this.parseTransferStatus(s),amount:this.safeNumber(e,"amount"),currency:this.safeCurrencyCode(o,t),fromAccount:"payment"!==a?r:void 0,toAccount:"payment"===a?r:void 0,timestamp:i,datetime:this.iso8601(i)}}parseTransferStatus(e){return this.safeString({prepared:"pending",confirmed:"ok",cancelled:"cancelled",waiting_for_admin:"pending"},e,e)}async withdraw(e,t,i,s,r={}){let a=this.handleWithdrawTagAndParams(s,r)[1];this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let o=this.currency(e),d={currency:o.id,address:i,amount:t};void 0!==this.twofa&&(d.tfa=(0,n.O)(this.twofa));let h=await this.privateGetWithdraw(this.extend(d,a));return this.parseTransaction(h,o)}parseDepositWithdrawFee(e,t){return{info:e,withdraw:{fee:this.safeNumber(e,"withdrawal_fee"),percentage:!1},deposit:{fee:void 0,percentage:void 0},networks:{}}}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetGetCurrencies(t),s=this.safeList(i,"result",[]);return this.parseDepositWithdrawFees(s,e,"currency")}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.milliseconds(),r={instrument_name:i.id,start_timestamp:s-288e5,end_timestamp:s},a=await this.publicGetGetFundingRateValue(this.extend(r,t));return this.parseFundingRate(a,i)}async fetchFundingRateHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),[o,n]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(o){let s=this.extend(n,{isDeribitPaginationCall:!0});return await this.fetchPaginatedCallDeterministic("fetchFundingRateHistory",e,t,i,"1h",s,744)}let d=1e3*this.parseTimeframe("1h"),h=this.milliseconds(),c=void 0===t?h-2592e6:t,l=void 0===t?h:t+2592e6,u={instrument_name:r.id,start_timestamp:c-1},f=this.safeInteger2(n,"until","end_timestamp"),p=void 0!==f?this.omit(n,["until"]):n;void 0!==f?u.end_timestamp=f:u.end_timestamp=l;let m="isDeribitPaginationCall"in p,g=p;if(m&&(g=this.omit(p,"isDeribitPaginationCall")),m){if(void 0===i)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a limit argument");let e=this.sum(c,i*d);u.end_timestamp=Math.min(u.end_timestamp,e)}let v=await this.publicGetGetFundingRateHistory(this.extend(u,g)),y=[],b=this.safeList(v,"result",[]);for(let e=0;e<b.length;e++){let t=this.safeDict(b,e),i=this.parseFundingRate(t,r);y.push(i)}return this.filterBySymbolSinceLimit(y,e,c,i)}parseFundingRate(e,t){let i=this.safeInteger(e,"timestamp"),s=this.iso8601(i),r=this.safeNumber2(e,"result","interest_8h");return{info:e,symbol:this.safeSymbol(void 0,t),markPrice:void 0,indexPrice:this.safeNumber(e,"index_price"),interestRate:void 0,estimatedSettlePrice:void 0,timestamp:i,datetime:s,fundingRate:r,fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:"8h"}}async fetchLiquidations(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,o]=this.handleOptionBoolAndParams(s,"fetchLiquidations","paginate",!1);if(r)return await this.fetchPaginatedCallCursor("fetchLiquidations",e,t,i,o,"continuation","continuation",void 0);let n=this.market(e);if(!0===n.spot)throw new a.NotSupported(this.id+" fetchLiquidations() does not support "+n.type+" markets");let d={instrument_name:n.id,type:"bankruptcy"};void 0!==t&&(d.search_start_timestamp=t),void 0!==i&&(d.count=i);let h=await this.publicGetGetLastSettlementsByInstrument(this.extend(d,o)),c=this.safeDict(h,"result",{}),l=this.safeString(c,"continuation"),u=this.safeList(c,"settlements",[]),f=this.addPaginationCursorToResult(l,u);return this.parseLiquidations(f,n,t,i)}addPaginationCursorToResult(e,t){if(void 0!==e){let i=t.length;if(i>0){let s=t[0],r=t[i-1];s.continuation=e,r.continuation=e,t[0]=s,t[i-1]=r}}return t}async fetchMyLiquidations(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyLiquidations() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e);if(!0===r.spot)throw new a.NotSupported(this.id+" fetchMyLiquidations() does not support "+r.type+" markets");let o={instrument_name:r.id,type:"bankruptcy"};void 0!==t&&(o.search_start_timestamp=t),void 0!==i&&(o.count=i);let n=await this.privateGetGetSettlementHistoryByInstrument(this.extend(o,s)),d=this.safeDict(n,"result",{}),h=this.safeList(d,"settlements",[]);return this.parseLiquidations(h,r,t,i)}parseLiquidation(e,t){let i=this.safeInteger(e,"timestamp");return this.safeLiquidation({info:e,symbol:this.safeSymbol(void 0,t),contracts:void 0,contractSize:this.safeNumber(t,"contractSize"),price:void 0,baseValue:this.safeNumber(e,"session_bankrupcy"),quoteValue:void 0,timestamp:i,datetime:this.iso8601(i)})}async fetchGreeks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instrument_name:i.id},r=await this.publicGetTicker(this.extend(s,t)),a=this.safeDict(r,"result",{});return this.parseGreeks(a,i)}parseGreeks(e,t){let i=this.safeInteger(e,"timestamp"),s=this.safeString(e,"instrument_name"),r=this.safeSymbol(s,t),a=this.safeDict(e,"greeks",{});return{symbol:r,timestamp:i,datetime:this.iso8601(i),delta:this.safeNumber(a,"delta"),gamma:this.safeNumber(a,"gamma"),theta:this.safeNumber(a,"theta"),vega:this.safeNumber(a,"vega"),rho:this.safeNumber(a,"rho"),bidSize:this.safeNumber(e,"best_bid_amount"),askSize:this.safeNumber(e,"best_ask_amount"),bidImpliedVolatility:this.safeNumber(e,"bid_iv"),askImpliedVolatility:this.safeNumber(e,"ask_iv"),markImpliedVolatility:this.safeNumber(e,"mark_iv"),bidPrice:this.safeNumber(e,"best_bid_price"),askPrice:this.safeNumber(e,"best_ask_price"),markPrice:this.safeNumber(e,"mark_price"),lastPrice:this.safeNumber(e,"last_price"),underlyingPrice:this.safeNumber(e,"underlying_price"),info:e}}async fetchOption(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instrument_name:i.id},r=await this.publicGetGetBookSummaryByInstrument(this.extend(s,t)),a=this.safeList(r,"result",[]),o=this.safeDict(a,0,{});return this.parseOption(o,void 0,i)}async fetchOptionChain(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={currency:this.currency(e).id,kind:"option"},s=await this.publicGetGetBookSummaryByCurrency(this.extend(i,t)),r=this.safeList(s,"result",[]);return this.parseOptionChain(r,"base_currency","instrument_name")}parseOption(e,t,i){let s=this.safeString(e,"instrument_name"),r=this.safeMarket(s,i),a=this.safeString(e,"base_currency"),o=this.safeCurrencyCode(a,t),n=this.safeInteger(e,"timestamp");return{info:e,currency:o,symbol:r.symbol,timestamp:n,datetime:this.iso8601(n),impliedVolatility:void 0,openInterest:this.safeNumber(e,"open_interest"),bidPrice:this.safeNumber(e,"bid_price"),askPrice:this.safeNumber(e,"ask_price"),midPrice:this.safeNumber(e,"mid_price"),markPrice:this.safeNumber(e,"mark_price"),lastPrice:this.safeNumber(e,"last"),underlyingPrice:this.safeNumber(e,"underlying_price"),change:void 0,percentage:this.safeNumber(e,"price_change"),baseVolume:this.safeNumber(e,"volume"),quoteVolume:this.safeNumber(e,"volume_usd")}}async fetchOpenInterest(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.contract)throw new a.BadRequest(this.id+" fetchOpenInterest() supports contract markets only");let s={instrument_name:i.id},r=await this.publicGetGetBookSummaryByInstrument(this.extend(s,t)),o=this.safeList(r,"result",[]),n=this.safeDict(o,0,{});return this.parseOpenInterest(n,i)}parseOpenInterest(e,t){let i,s,r=this.safeInteger(e,"creation_timestamp"),a=this.safeString(e,"instrument_name"),o=this.safeMarket(a,t),n=this.safeNumber(e,"open_interest");return!0===o.option||!0===o.future&&!0===o.linear?i=n:s=n,this.safeOpenInterest({symbol:this.safeSymbol(a,o),openInterestAmount:i,openInterestValue:s,timestamp:r,datetime:this.iso8601(r),info:e},o)}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},o,n){let d="/api/"+this.version+"/"+t+"/"+e;if("public"===t&&Object.keys(r).length>0&&(d+="?"+this.urlencode(r)),"private"===t){this.checkRequiredCredentials();let e=this.nonce().toString(),t=this.milliseconds().toString();Object.keys(r).length>0&&(d+="?"+this.urlencode(r));let o=i+"\n"+d+"\n\n",h=this.hmac(this.encode(t+"\n"+e+"\n"+o),this.encode(this.secret),s.sc),c={Authorization:"deri-hmac-sha256 id="+this.apiKey+",ts="+t+",sig="+h+",nonce="+e},l=this.safeString(this.urls.api,"rest");if(void 0===l)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");return{url:l+d,method:i,body:n,headers:c}}let h=this.safeString(this.urls.api,"rest");if(void 0===h)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");return{url:h+d,method:i,body:n,headers:o}}handleErrors(e,t,i,s,r,o,n,d,h){if(null==n)return;let c=this.safeDict(n,"error");if(void 0!==c){let e=this.safeString(c,"code"),t=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions,e,t),new a.ExchangeError(t)}}}i.d(t,{A:()=>d})},8025(e,t,i){"use strict";var s=i(6834),r=i(6885),a=i(7196),o=i(7749),n=i(1453),d=i(1093);class h extends a.A{describe(){return this.deepExtend(super.describe(),{id:"derive",name:"Derive",countries:[],version:"v1",rateLimit:50,certified:!1,pro:!0,dex:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!0,future:!1,option:!0,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,cancelAllOrders:!0,cancelAllOrdersAfter:!1,cancelOrder:!0,cancelOrders:!1,cancelOrdersForSymbols:!1,closeAllPositions:!1,closePosition:!1,createMarketBuyOrderWithCost:!1,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!1,createReduceOnlyOrder:!1,createStopOrder:!1,createTriggerOrder:!1,editOrder:!0,fetchAccounts:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchCanceledAndClosedOrders:!1,fetchCanceledOrders:!0,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDeposits:!0,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!1,fetchFundingHistory:!0,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLedger:!0,fetchLeverage:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchMarginMode:void 0,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyLiquidations:!1,fetchMyTrades:!0,fetchOHLCV:!1,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOrder:!1,fetchOrderBook:!1,fetchOrders:!0,fetchOrderTrades:!0,fetchPosition:!1,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchTicker:!0,fetchTickers:!1,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTransfer:!1,fetchTransfers:!1,fetchWithdrawal:!1,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,sandbox:!0,setLeverage:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,withdraw:!1},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","8h":"8h","12h":"12h","1d":"1d","3d":"3d","1w":"1w","1M":"1M"},urls:{logo:"https://github.com/user-attachments/assets/9e640700-c870-41f9-8907-fba58e120fed",api:{public:"https://api.lyra.finance/public",private:"https://api.lyra.finance/private"},test:{public:"https://api-demo.lyra.finance/public",private:"https://api-demo.lyra.finance/private"},www:"https://www.derive.xyz/",doc:"https://docs.derive.xyz/docs/",fees:"https://docs.derive.xyz/reference/fees-1/",referral:"https://www.derive.xyz/invite/3VB0B"},api:{public:{get:{get_all_currencies:{cost:1}},post:{build_register_session_key_tx:{cost:1},register_session_key:{cost:1},deregister_session_key:{cost:1},get_wallets_from_session_key:{cost:1},login:{cost:1},statistics:{cost:1},all_statistics:{cost:1},user_statistics:{cost:1},all_user_statistics:{cost:1},get_all_currencies:{cost:1},get_currency:{cost:1},get_asset:{cost:1},get_assets:{cost:1},get_instrument:{cost:1},get_all_instruments:{cost:1},get_instruments:{cost:1},get_ticker:{cost:1},get_tickers:{cost:1},get_latest_signed_feeds:{cost:1},get_option_settlement_prices:{cost:1},get_spot_feed_history:{cost:1},get_spot_feed_history_candles:{cost:1},get_index_chart_data:{cost:1},get_tradingview_chart_data:{cost:1},get_funding_rate_history:{cost:1},get_trade_history:{cost:1},get_option_settlement_history:{cost:1},get_liquidation_history:{cost:1},get_interest_rate_history:{cost:1},get_perp_impact_twap:{cost:1},get_transaction:{cost:1},get_margin:{cost:1},margin_watch:{cost:1},order_quote:{cost:1},validate_invite_code:{cost:1},get_points:{cost:1},get_all_points:{cost:1},get_points_leaderboard:{cost:1},get_descendant_tree:{cost:1},get_tree_roots:{cost:1},get_swell_percent_points:{cost:1},get_stdrv_snapshots:{cost:1},get_vault_assets:{cost:1},get_etherfi_effective_balances:{cost:1},get_kelp_effective_balances:{cost:1},get_bridge_balances:{cost:1},get_ethena_participants:{cost:1},get_vault_share:{cost:1},get_vault_statistics:{cost:1},get_vault_balances:{cost:1},get_vault_pools:{cost:1},get_vault_rates:{cost:1},estimate_integrator_points:{cost:1},create_subaccount_debug:{cost:1},create_account_with_secret:{cost:1},deposit_debug:{cost:1},withdraw_debug:{cost:1},send_quote_debug:{cost:1},execute_quote_debug:{cost:1},get_invite_code:{cost:1},register_invite:{cost:1},get_all_referral_codes:{cost:1},get_referral_performance:{cost:1},get_time:{cost:1},get_live_incidents:{cost:1},get_maker_programs:{cost:1},get_maker_program_scores:{cost:1},get_detailed_maker_snapshot_history:{cost:1},getRateLimits:{cost:1}}},private:{post:{get_account:{cost:1},create_subaccount:{cost:1},get_subaccount:{cost:1},get_subaccounts:{cost:1},get_all_portfolios:{cost:1},change_subaccount_label:{cost:1},get_notificationsv:{cost:1},get_notifications:{cost:1},update_notifications:{cost:1},deposit:{cost:1},withdraw:{cost:1},transfer_erc20:{cost:1},transfer_position:{cost:1},transfer_positions:{cost:1},order:{cost:1},replace:{cost:1},order_debug:{cost:1},get_order:{cost:1},get_orders:{cost:1},get_open_orders:{cost:1},get_trigger_orders:{cost:1},get_algo_orders:{cost:1},cancel:{cost:1},cancel_by_label:{cost:1},cancel_by_nonce:{cost:1},cancel_by_instrument:{cost:1},cancel_all:{cost:1},cancel_trigger_order:{cost:1},cancel_algo_order:{cost:1},cancel_all_algo_orders:{cost:1},cancel_all_trigger_orders:{cost:1},get_order_history:{cost:1},get_trade_history:{cost:1},get_deposit_history:{cost:1},get_withdrawal_history:{cost:1},send_rfq:{cost:1},cancel_rfq:{cost:1},cancel_batch_rfqs:{cost:1},get_rfqs:{cost:1},poll_rfqs:{cost:1},send_quote:{cost:1},cancel_quote:{cost:1},cancel_batch_quotes:{cost:1},get_quotes:{cost:1},poll_quotes:{cost:1},execute_quote:{cost:1},order_quote:{cost:1},replace_quote:{cost:1},rfq_get_best_quote:{cost:1},get_margin:{cost:1},get_collaterals:{cost:1},get_positions:{cost:1},get_option_settlement_history:{cost:1},get_subaccount_value_history:{cost:1},expired_and_cancelled_history:{cost:1},get_funding_history:{cost:1},get_interest_history:{cost:1},get_erc20_transfer_history:{cost:1},get_liquidation_history:{cost:1},liquidate:{cost:1},get_liquidator_history:{cost:1},session_keys:{cost:1},edit_session_key:{cost:1},change_session_key_label:{cost:1},register_scoped_session_key:{cost:1},get_mmp_config:{cost:1},set_mmp_config:{cost:1},reset_mmp:{cost:1},set_cancel_on_disconnect:{cost:1},get_invite_code:{cost:1},register_invite:{cost:1},get_contact_info:{cost:1},create_contact_info:{cost:1},update_contact_info:{cost:1},delete_contact_info:{cost:1}}}},fees:{},requiredCredentials:{apiKey:!1,secret:!1,walletAddress:!0,privateKey:!0},exceptions:{exact:{"-32000":n.RateLimitExceeded,"-32100":n.RateLimitExceeded,"-32700":n.BadRequest,"-32600":n.BadRequest,"-32601":n.BadRequest,"-32602":n.InvalidOrder,"-32603":n.InvalidOrder,9e3:n.InvalidOrder,1e4:n.BadRequest,10001:n.BadRequest,10002:n.BadRequest,10003:n.BadRequest,10004:n.InvalidOrder,10005:n.BadRequest,10006:n.BadRequest,10007:n.BadRequest,10008:n.BadRequest,10009:n.BadRequest,10010:n.InvalidOrder,10011:n.InsufficientFunds,10012:n.InsufficientFunds,10013:n.ExchangeError,10014:n.ExchangeError,11e3:n.InsufficientFunds,11002:n.InvalidOrder,11003:n.InvalidOrder,11004:n.InvalidOrder,11005:n.InvalidOrder,11006:n.OrderNotFound,11007:n.InvalidOrder,11008:n.InvalidOrder,11009:n.InvalidOrder,11010:n.InvalidOrder,11011:n.InvalidOrder,11012:n.InvalidOrder,11013:n.InvalidOrder,11014:n.InvalidOrder,11015:n.InvalidOrder,11016:n.InvalidOrder,11017:n.InvalidOrder,11018:n.InvalidOrder,11019:n.InvalidOrder,11020:n.InsufficientFunds,11021:n.InvalidOrder,11022:n.InvalidOrder,11023:n.InvalidOrder,11024:n.InvalidOrder,11025:n.InvalidOrder,11026:n.BadRequest,11027:n.InvalidOrder,11028:n.InvalidOrder,11050:n.InvalidOrder,11051:n.InvalidOrder,11052:n.InvalidOrder,11053:n.InvalidOrder,11054:n.InvalidOrder,11055:n.InvalidOrder,11100:n.InvalidOrder,11101:n.InvalidOrder,11102:n.InvalidOrder,11103:n.InvalidOrder,11104:n.InvalidOrder,11105:n.InvalidOrder,11106:n.InvalidOrder,11107:n.InvalidOrder,11200:n.InvalidOrder,11201:n.InvalidOrder,11202:n.InvalidOrder,11203:n.InvalidOrder,12e3:n.InvalidOrder,12001:n.InvalidOrder,12002:n.BadRequest,12003:n.BadRequest,13e3:n.BadRequest,14e3:n.BadRequest,14001:n.InvalidOrder,14002:n.BadRequest,14008:n.BadRequest,14009:n.BadRequest,14010:n.BadRequest,14011:n.BadRequest,14012:n.BadRequest,14013:n.BadRequest,14014:n.InvalidOrder,14015:n.BadRequest,14016:n.BadRequest,14017:n.BadRequest,14018:n.BadRequest,14019:n.BadRequest,14020:n.BadRequest,14021:n.BadRequest,14022:n.AuthenticationError,14023:n.InvalidOrder,14024:n.BadRequest,14025:n.BadRequest,14026:n.BadRequest,14027:n.AuthenticationError,14028:n.BadRequest,14029:n.AuthenticationError,14030:n.BadRequest,14031:n.AuthenticationError,14032:n.BadRequest,16e3:n.AuthenticationError,16001:n.AuthenticationError,16100:n.AuthenticationError,17e3:n.BadRequest,17001:n.BadRequest,17002:n.BadRequest,17003:n.BadRequest,17004:n.BadRequest,17005:n.BadRequest,17006:n.BadRequest,17007:n.BadRequest,18e3:n.BadRequest,18001:n.BadRequest,18002:n.BadRequest,18003:n.BadRequest,18004:n.BadRequest,18005:n.BadRequest,18006:n.BadRequest,18007:n.BadRequest,19e3:n.BadRequest},broad:{}},precisionMode:4,commonCurrencies:{},options:{deriveWalletAddress:"",id:"0x0ad42b8e602c2d3d475ae52d678cf63d84ab2749"}})}setSandboxMode(e){super.setSandboxMode(e),this.options.sandboxMode=e}async fetchTime(e={}){let t=await this.publicPostGetTime(e);return this.safeInteger(t,"result")}async fetchCurrencies(e={}){let t=await this.publicGetGetAllCurrencies(e),i=this.safeList(t,"result",[]);return this.parseCurrencies(i)}parseCurrency(e){let t=this.safeString(e,"currency"),i=this.safeCurrencyCode(t);return this.safeCurrencyStructure({id:t,name:void 0,code:i,precision:void 0,active:void 0,fee:void 0,networks:void 0,deposit:void 0,withdraw:void 0,limits:{deposit:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}},info:e})}async fetchMarkets(e={}){let t=this.fetchSpotMarkets(e),i=this.fetchSwapMarkets(e),s=this.fetchOptionMarkets(e),[r,a,o]=await Promise.all([t,i,s]),n=this.arrayConcat(r,a);return this.arrayConcat(n,o)}async fetchSpotMarkets(e={}){let t=await this.publicPostGetAllInstruments(this.extend({expired:!1,instrument_type:"erc20"},e)),i=this.safeDict(t,"result",{}),s=this.safeList(i,"instruments",[]);return this.parseMarkets(s)}async fetchSwapMarkets(e={}){let t=await this.publicPostGetAllInstruments(this.extend({expired:!1,instrument_type:"perp"},e)),i=this.safeDict(t,"result",{}),s=this.safeList(i,"instruments",[]);return this.parseMarkets(s)}async fetchOptionMarkets(e={}){let t=await this.publicPostGetAllInstruments(this.extend({expired:!1,instrument_type:"option"},e)),i=this.safeDict(t,"result",{}),s=this.safeList(i,"instruments",[]);return this.parseMarkets(s)}parseMarket(e){let t,i,s,r,a,o,n,d,h,c=this.safeString(e,"instrument_type"),l=!1,u=!0,f=!1,p=!1,m=this.safeString(e,"base_currency"),g=this.safeString(e,"quote_currency"),v=this.safeCurrencyCode(m),y=this.safeCurrencyCode(g);if(void 0===v||void 0===y)return;let b=this.safeString(e,"instrument_name"),w=v+"/"+y;if("erc20"===c)l=!0,t="spot";else if("perp"===c)u=!1,r="USDC",w=v+"/"+y+":"+(a=this.safeCurrencyCode(r)),f=!0,i=!0,s=!1,t="swap";else if("option"===c){r="USDC",a=this.safeCurrencyCode(r),u=!1,p=!0,t="option";let c=this.safeDict(e,"option_details");o=this.safeTimestamp(c,"expiry"),n=this.safeInteger(c,"strike"),h=this.safeString(c,"option_type"),w=v+"/"+y+":"+a+"-"+this.yymmdd(o)+"-"+this.numberToString(n)+"-"+h,d="P"===h?"put":"call",i=!0,s=!1}let k=l?void 0:1,S=f||p;return this.safeMarketStructure({id:b,symbol:w,base:v,quote:y,settle:a,baseId:m,quoteId:g,settleId:r,type:t,spot:l,margin:u,swap:f,future:!1,option:p,active:this.safeBool(e,"is_active"),contract:S,linear:i,inverse:s,contractSize:k,expiry:o,expiryDatetime:this.iso8601(o),taker:this.safeNumber(e,"taker_fee_rate"),maker:this.safeNumber(e,"maker_fee_rate"),strike:n,optionType:d,precision:{amount:this.safeNumber(e,"amount_step"),price:this.safeNumber(e,"tick_size")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(e,"minimum_amount"),max:this.safeNumber(e,"maximum_amount")},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:e})}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instrument_name:i.id},r=await this.publicPostGetTicker(this.extend(s,t)),a=this.safeDict(r,"result",{});return this.parseTicker(a,i)}parseTicker(e,t){let i=this.safeString(e,"instrument_name"),s=this.safeIntegerOmitZero(e,"timestamp"),r=this.safeSymbol(i,t),a=this.safeDict(e,"stats"),n=this.safeString(a,"percent_change");return this.safeTicker({symbol:r,timestamp:s,datetime:this.iso8601(s),high:this.safeString(a,"high"),low:this.safeString(a,"low"),bid:this.safeString(e,"best_bid_price"),bidVolume:this.safeString(e,"best_bid_amount"),ask:this.safeString(e,"best_ask_price"),askVolume:this.safeString(e,"best_ask_amount"),vwap:void 0,open:void 0,close:void 0,last:void 0,previousClose:void 0,change:n,percentage:o.Y.stringMul(n,"100"),average:void 0,baseVolume:void 0,quoteVolume:void 0,indexPrice:this.safeString(e,"index_price"),markPrice:this.safeString(e,"mark_price"),info:e},t)}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.instrument_name=(r=this.market(e)).id);let o=i;void 0!==i&&i>1e3&&(o=1e3),void 0!==o&&(a.page_size=o),void 0!==t&&(a.from_timestamp=t);let n=this.safeInteger(s,"until"),d=this.omit(s,["until"]);void 0!==n&&(a.to_timestamp=n);let h=await this.publicPostGetTradeHistory(this.extend(a,d)),c=this.safeDict(h,"result",{}),l=this.safeList(c,"trades",[]);return this.parseTrades(l,r,t,o)}parseTrades(e,t,i,s,r={}){let a=this.toArray(e),o=[];for(let e=0;e<a.length;e++){let i=a[e],s=!("order_id"in i),n=this.safeString(i,"liquidity_role");if(s&&"maker"===n)continue;let d=this.parseTrade(i,t),h=this.extend(d,r);o.push(h)}o=this.sortBy2(o,"timestamp","id");let n=this.safeString(t,"symbol");return this.filterBySymbolSinceLimit(o,n,i,s)}parseTrade(e,t){let i=this.safeString(e,"instrument_name"),s=this.safeSymbol(i,t),r=this.safeInteger(e,"timestamp"),a={currency:"USDC",cost:this.safeString(e,"trade_fee")};return this.safeTrade({info:e,id:this.safeString(e,"trade_id"),order:this.safeString(e,"order_id"),symbol:s,side:this.safeStringLower(e,"direction"),type:void 0,takerOrMaker:this.safeString(e,"liquidity_role"),price:this.safeString(e,"trade_price"),amount:this.safeString(e,"trade_amount"),cost:void 0,timestamp:r,datetime:this.iso8601(r),fee:a},t)}async fetchFundingRateHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={instrument_name:r.id};void 0!==t&&(a.start_timestamp=t);let o=this.safeInteger(s,"until"),n=this.omit(s,["until"]);void 0!==o&&(a.to_timestamp=o);let d=await this.publicPostGetFundingRateHistory(this.extend(a,n)),h=this.safeDict(d,"result",{}),c=this.safeList(h,"funding_rate_history",[]),l=[];for(let e=0;e<c.length;e++){let t=c[e],i=this.safeInteger(t,"timestamp");l.push({info:t,symbol:r.symbol,fundingRate:this.safeNumber(t,"funding_rate"),timestamp:i,datetime:this.iso8601(i)})}let u=this.sortBy(l,"timestamp");return this.filterBySymbolSinceLimit(u,this.safeString(r,"symbol"),t,i)}async fetchFundingRate(e,t={}){let i=await this.fetchFundingRateHistory(e,void 0,1,t),s=this.safeDict(i,0);return this.parseFundingRate(s)}parseFundingRate(e,t){let i=this.safeString(e,"symbol"),s=this.safeInteger(e,"timestamp");return{info:e,symbol:i,markPrice:void 0,indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:this.safeNumber(e,"fundingRate"),fundingTimestamp:s,fundingDatetime:this.iso8601(s),nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:void 0}}hashOrderMessage(e){let t=this.hash(this.ethAbiEncode(["bytes32","uint256","uint256","address","bytes32","uint256","address","address"],e),s.lY,"binary"),i=this.safeBool(this.options,"sandboxMode",!1),r="d96e5f90797da7ec8dc4e276260c7f3f87fedf68775fbe1ef116e996fc60441b";!0===i&&(r="9bcf4dc06df5d8bf23af818d5716491b995020f377d3b7b64c29ed14e3dd1105");let a=this.base16ToBinary(r),o=this.base16ToBinary("1901");return this.hash(this.binaryConcat(o,a,t),s.lY,"hex")}signOrder(e,t){let i=this.hashOrderMessage(e);return this.signHash(i.slice(-64),t.slice(-64))}hashMessage(e){let t=this.encode(e),i=this.binaryLength(t),r=this.base16ToBinary("19"),a=this.base16ToBinary("0a"),o=this.binaryConcat(r,this.encode("Ethereum Signed Message:"),a,this.encode(this.numberToString(i)));return"0x"+this.hash(this.binaryConcat(o,t),s.lY,"hex")}signHash(e,t){this.checkRequiredCredentials();let i=(0,d.h1)(e.slice(-64),t.slice(-64),r.bI,void 0),s=i.r,a=i.s,o=this.intToBase16(this.sum(27,i.v));return"0x"+s.padStart(64,"0")+a.padStart(64,"0")+o}signMessage(e,t){return this.signHash(this.hashMessage(e),t.slice(-64))}parseUnits(e,t="1000000000000000000"){return o.Y.stringMul(e,t)}async createOrder(e,t,i,r,a,o={}){let d,h;void 0===this.markets&&await this.loadMarkets();let c=this.market(e);if(void 0===a)throw new n.ArgumentsRequired(this.id+" createOrder() requires a price argument");let[l,u]=this.handleDeriveSubaccountId("createOrder",o),f=this.safeBool(u,"test",!1),p=this.safeBool2(u,"reduceOnly","reduce_only"),m=this.safeStringLower2(u,"timeInForce","time_in_force"),g=this.safeBool(u,"postOnly"),v=t.toLowerCase(),y=i.toLowerCase(),b="buy"===y,w=this.incrementingNonce(),k=this.safeInteger(u,"signature_expiry_sec",this.seconds()+7776e3),S=this.base16ToBinary("4d7a9f27c403ff9c0f19bce61d76d82f9aa29f8d6d4b0c5474607d9770d1af17"),O=this.safeBool(this.options,"sandboxMode",!1),T="0xB8D20c2B7a1Ad2EE33Bc50eF10876eD3035b5e7b";!0===O&&(T="0x87F2863866D85E3192a35A73b388BD625D83f2be");let P=this.numberToString(a),I={};if([h,I]=this.handleOptionAndParams(u,"createOrder","max_fee"),void 0===h)throw new n.ArgumentsRequired(this.id+" createOrder() requires a max_fee argument in params");let A=this.numberToString(h),x=this.numberToString(r),M=this.hash(this.ethAbiEncode(["address","uint","int","int","uint","uint","bool"],[c.info.base_asset_address,this.parseToNumeric(c.info.base_asset_sub_id),this.convertToBigInt(this.parseUnits(P)),this.convertToBigInt(this.parseUnits(this.amountToPrecision(e,x))),this.convertToBigInt(this.parseUnits(A)),l,b]),s.lY,"binary"),[_,C]=this.handleDeriveWalletAddress("createOrder",I),B=this.signOrder([S,l,w,T,M,k,_,this.walletAddress],this.privateKey),E={instrument_name:c.id,direction:y,order_type:v,nonce:w,amount:x,limit_price:P,max_fee:A,subaccount_id:l,signature_expiry_sec:k,referral_code:this.safeString(this.options,"id","0x0ad42b8e602c2d3d475ae52d678cf63d84ab2749"),signer:this.walletAddress};if(void 0!==p&&(E.reduce_only=p,p&&!0===g))throw new n.InvalidOrder(this.id+" cannot use reduce only with post only time in force");void 0!==g?E.time_in_force="post_only":void 0!==m&&(E.time_in_force=m);let R=this.safeValue(C,"stopLoss"),L=this.safeValue(C,"takeProfit"),N=this.safeString(C,"trigger_price_type","mark");void 0!==R?(E.trigger_price=this.safeString(R,"triggerPrice",R),E.trigger_type="stoploss",E.trigger_price_type=N):void 0!==L&&(E.trigger_price=this.safeString(L,"triggerPrice",L),E.trigger_type="takeprofit",E.trigger_price_type=N);let D=this.safeString(C,"clientOrderId");void 0!==D&&(E.label=D),E.signature=B;let q=this.omit(C,["reduceOnly","reduce_only","timeInForce","time_in_force","postOnly","test","clientOrderId","stopPrice","triggerPrice","trigger_price","stopLoss","takeProfit","trigger_price_type"]);d=!0===f?await this.privatePostOrderDebug(this.extend(E,q)):await this.privatePostOrder(this.extend(E,q));let F=this.safeDict(d,"result"),V=this.safeDict(F,"raw_data");void 0===V&&(V=this.safeDict(F,"order",{}));let G=this.parseOrder(V,c);return G.type=t,G}async editOrder(e,t,i,r,a,o,d={}){void 0===this.markets&&await this.loadMarkets();let h=this.market(t),[c,l]=this.handleDeriveSubaccountId("editOrder",d),u=this.safeBool2(l,"reduceOnly","reduce_only"),f=this.safeStringLower2(l,"timeInForce","time_in_force"),p=this.safeBool(l,"postOnly"),m=i.toLowerCase(),g=r.toLowerCase(),v="buy"===g,y=this.incrementingNonce(),b=this.safeNumber(l,"signature_expiry_sec",this.seconds()+7776e3),w=this.base16ToBinary("4d7a9f27c403ff9c0f19bce61d76d82f9aa29f8d6d4b0c5474607d9770d1af17"),k=this.safeBool(this.options,"sandboxMode",!1),S="0xB8D20c2B7a1Ad2EE33Bc50eF10876eD3035b5e7b";!0===k&&(S="0x87F2863866D85E3192a35A73b388BD625D83f2be");let O=this.numberToString(o),T=this.safeString(l,"max_fee","0"),P=this.numberToString(a),I=this.hash(this.ethAbiEncode(["address","uint","int","int","uint","uint","bool"],[h.info.base_asset_address,this.parseToNumeric(h.info.base_asset_sub_id),this.convertToBigInt(this.parseUnits(O)),this.convertToBigInt(this.parseUnits(this.amountToPrecision(t,P))),this.convertToBigInt(this.parseUnits(T)),c,v]),s.lY,"binary"),[A,x]=this.handleDeriveWalletAddress("editOrder",l),M=this.signOrder([w,c,y,S,I,b,A,this.walletAddress],this.privateKey),_={instrument_name:h.id,order_id_to_cancel:e,direction:g,order_type:m,nonce:y,amount:P,limit_price:O,max_fee:T,subaccount_id:c,signature_expiry_sec:b,signer:this.walletAddress};if(void 0!==u&&(_.reduce_only=u,u&&!0===p))throw new n.InvalidOrder(this.id+" cannot use reduce only with post only time in force");void 0!==p?_.time_in_force="post_only":void 0!==f&&(_.time_in_force=f);let C=this.safeString(x,"clientOrderId");void 0!==C&&(_.label=C),_.signature=M;let B=this.omit(x,["reduceOnly","reduce_only","timeInForce","time_in_force","postOnly","clientOrderId"]),E=await this.privatePostReplace(this.extend(_,B)),R=this.safeDict(E,"result"),L=this.safeDict(R,"order",{});return this.parseOrder(L,h)}async cancelOrder(e,t,i={}){let s;if(void 0===t)throw new n.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),a=this.safeBool2(i,"trigger","stop",!1),[o,d]=this.handleDeriveSubaccountId("cancelOrder",i),h=this.omit(d,["trigger","stop"]),c={instrument_name:r.id,subaccount_id:o},l=this.safeString(h,"clientOrderId"),u=this.safeString(h,"label",l),f=void 0!==u;if(f){c.label=u;let e=this.omit(h,["clientOrderId","label"]);s=await this.privatePostCancelByLabel(this.extend(c,e))}else c.order_id=e,s=!0===a?await this.privatePostCancelTriggerOrder(this.extend(c,h)):await this.privatePostCancel(this.extend(c,h));let p={symbol:t},m=this.safeDict(s,"result",{});return f&&(p.client_order_id=u),this.extend(this.parseOrder(m,r),p)}async cancelAllOrders(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(s=this.market(e));let[r,a]=this.handleDeriveSubaccountId("cancelAllOrders",t),o={subaccount_id:r};return void 0!==s?(o.instrument_name=s.id,i=await this.privatePostCancelByInstrument(this.extend(o,a))):i=await this.privatePostCancelAll(this.extend(o,a)),[this.safeOrder({info:i})]}async fetchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchOrders","paginate",!1);if(a)return await this.fetchPaginatedCallIncremental("fetchOrders",e,t,i,o,"page",500);let n=this.safeBool2(o,"trigger","stop",!1),d=this.omit(o,["trigger","stop"]),[h,c]=this.handleDeriveSubaccountId("fetchOrders",d),l={subaccount_id:h};void 0!==e&&(l.instrument_name=(r=this.market(e)).id),void 0!==i?l.page_size=i:l.page_size=500,!0===n&&(l.status="untriggered");let u=await this.privatePostGetOrders(this.extend(l,c)),f=this.safeDict(u,"result"),p=this.safeInteger(c,"page");if(void 0!==p){let e=this.safeDict(f,"pagination");if(p>this.safeInteger(e,"num_pages",0))return[]}let m=this.safeList(f,"orders",[]);return this.parseOrders(m,r,t,i)}async fetchOpenOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.extend(s,{status:"open"});return await this.fetchOrders(e,t,i,r)}async fetchClosedOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.extend(s,{status:"filled"});return await this.fetchOrders(e,t,i,r)}async fetchCanceledOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.extend(s,{status:"cancelled"});return await this.fetchOrders(e,t,i,r)}parseTimeInForce(e){return this.safeString({ioc:"IOC",fok:"FOK",gtc:"GTC",post_only:"PO"},e)}parseOrderStatus(e){if(void 0!==e)return this.safeString({open:"open",untriggered:"open",filled:"closed",cancelled:"canceled",expired:"rejected"},e,e)}parseOrder(e,t){let i,s,r,a=this.safeDict(e,"data");void 0===a&&(a=e);let o=this.safeInteger2(e,"creation_timestamp","nonce"),n=this.safeString(a,"order_id"),d=this.safeString(a,"instrument_name"),h=void 0!==d?this.safeMarket(d,t):t,c=this.safeString(h,"symbol"),l=this.safeString(a,"limit_price"),u=this.safeString(a,"average_price"),f=this.safeString(a,"desired_amount"),p=this.safeString(a,"filled_amount"),m=this.safeString(a,"order_fee"),g=this.safeStringLower(a,"order_type"),v=this.safeBool(a,"is_bid"),y=this.safeString(a,"direction");void 0===y&&(y=!0===v?"buy":"sell");let b=this.safeString(a,"trigger_type");void 0!==b&&(r=this.safeString(a,"trigger_price"),"stoploss"===b?i=r:s=r);let w=this.safeInteger(e,"last_update_timestamp"),k=this.safeString(a,"order_status"),S=this.safeString(a,"time_in_force");return this.safeOrder({id:n,clientOrderId:this.safeString(a,"label"),timestamp:o,datetime:this.iso8601(o),lastTradeTimestamp:void 0,lastUpdateTimestamp:w,status:this.parseOrderStatus(k),symbol:c,type:g,timeInForce:this.parseTimeInForce(S),postOnly:void 0,reduceOnly:this.safeBool(a,"reduce_only"),side:y,price:l,triggerPrice:r,takeProfitPrice:s,stopLossPrice:i,average:u,amount:f,filled:p,remaining:void 0,cost:void 0,trades:void 0,fee:{cost:m,currency:"USDC"},info:a},h)}async fetchOrderTrades(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleDeriveSubaccountId("fetchOrderTrades",r),d={order_id:e,subaccount_id:o};void 0!==t&&(d.instrument_name=(a=this.market(t)).id),void 0!==s&&(d.page_size=s),void 0!==i&&(d.from_timestamp=i);let h=await this.privatePostGetTradeHistory(this.extend(d,n)),c=this.safeDict(h,"result",{}),l=this.safeList(c,"trades",[]);return this.parseTrades(l,a,i,s,n)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(a)return await this.fetchPaginatedCallIncremental("fetchMyTrades",e,t,i,o,"page",500);let[n,d]=this.handleDeriveSubaccountId("fetchMyTrades",o),h={subaccount_id:n};void 0!==e&&(h.instrument_name=(r=this.market(e)).id),void 0!==i&&(h.page_size=i),void 0!==t&&(h.from_timestamp=t);let c=await this.privatePostGetTradeHistory(this.extend(h,d)),l=this.safeDict(c,"result",{}),u=this.safeInteger(d,"page");if(void 0!==u){let e=this.safeDict(l,"pagination");if(u>this.safeInteger(e,"num_pages",0))return[]}let f=this.safeList(l,"trades",[]);return this.parseTrades(f,r,t,i,d)}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleDeriveSubaccountId("fetchPositions",t),r=this.omit(s,["subaccount_id"]),a=await this.privatePostGetPositions(this.extend({subaccount_id:i},r)),o=this.safeDict(a,"result",{}),n=this.safeList(o,"positions",[]);return this.parsePositions(n,e)}parsePosition(e,t){let i,s=this.safeString(e,"instrument_name"),r=this.safeMarket(s,t),a=this.safeString(e,"amount");i=o.Y.stringGt(a,"0")?"long":"short";let n=this.safeString(r,"contractSize"),d=this.safeString(e,"mark_price"),h=this.safeInteger(e,"creation_timestamp"),c=this.safeString(e,"unrealized_pnl");a=o.Y.stringAbs(a);let l=o.Y.stringMul(a,d);return this.safePosition({info:e,id:void 0,symbol:this.safeString(r,"symbol"),timestamp:h,datetime:this.iso8601(h),lastUpdateTimestamp:void 0,initialMargin:this.safeNumber(e,"initial_margin"),initialMarginPercentage:void 0,maintenanceMargin:this.safeNumber(e,"maintenance_margin"),maintenanceMarginPercentage:void 0,entryPrice:void 0,notional:this.parseNumber(l),leverage:this.safeNumber(e,"leverage"),unrealizedPnl:this.parseNumber(c),contracts:this.parseNumber(a),contractSize:this.parseNumber(n),marginRatio:void 0,liquidationPrice:this.safeNumber(e,"liquidation_price"),markPrice:this.parseNumber(d),lastPrice:void 0,collateral:void 0,marginMode:void 0,side:i,percentage:void 0,hedged:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}async fetchFundingHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchFundingHistory","paginate",!1);if(a)return await this.fetchPaginatedCallIncremental("fetchFundingHistory",e,t,i,o,"page",500);let[n,d]=this.handleDeriveSubaccountId("fetchFundingHistory",o),h={subaccount_id:n};void 0!==e&&(h.instrument_name=(r=this.market(e)).id),void 0!==t&&(h.start_timestamp=t),void 0!==i&&(h.page_size=i);let c=await this.privatePostGetFundingHistory(this.extend(h,d)),l=this.safeDict(c,"result",{}),u=this.safeInteger(d,"page");if(void 0!==u){let e=this.safeDict(l,"pagination");if(u>this.safeInteger(e,"num_pages",0))return[]}let f=this.safeList(l,"events",[]);return this.parseIncomes(f,r,t,i)}parseIncome(e,t){let i=this.safeString(e,"instrument_name"),s=this.safeSymbol(i,t),r=this.safeString(e,"funding"),a=this.safeCurrencyCode("USDC"),o=this.safeInteger(e,"timestamp");return{info:e,symbol:s,code:a,timestamp:o,datetime:this.iso8601(o),id:void 0,amount:void 0,rate:r}}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleDeriveWalletAddress("fetchBalance",e),s=await this.privatePostGetAllPortfolios(this.extend({wallet:t},i)),r=this.safeList(s,"result");return this.parseBalance(r)}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeList(s,"collaterals",[]);for(let e=0;e<r.length;e++){let i=this.safeDict(r,e),s=this.safeCurrencyCode(this.safeString(i,"currency")),a=this.safeDict(t,s);if(void 0===a)(a=this.account()).total=this.safeString(i,"amount");else{let e=this.safeString(i,"amount");a.total=o.Y.stringAdd(a.total,e)}void 0!==s&&(t[s]=a)}}return this.safeBalance(t)}async fetchDeposits(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleDeriveSubaccountId("fetchDeposits",s),o={subaccount_id:r};void 0!==t&&(o.start_timestamp=t);let n=await this.privatePostGetDepositHistory(this.extend(o,a)),d=this.safeCurrency(e),h=this.safeDict(n,"result",{}),c=this.safeList(h,"events",[]);return this.parseTransactions(c,d,t,i,a)}async fetchWithdrawals(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleDeriveSubaccountId("fetchWithdrawals",s),o={subaccount_id:r};void 0!==t&&(o.start_timestamp=t);let n=await this.privatePostGetWithdrawalHistory(this.extend(o,a)),d=this.safeCurrency(e),h=this.safeDict(n,"result",{}),c=this.safeList(h,"events",[]);return this.parseTransactions(c,d,t,i,a)}parseTransaction(e,t){let i=this.safeString(e,"asset"),s=this.safeInteger(e,"timestamp"),r=this.safeString(e,"tx_hash");return"0x0"===r&&(r=void 0),{info:e,id:void 0,txid:r,timestamp:s,datetime:this.iso8601(s),address:void 0,addressFrom:void 0,addressTo:void 0,tag:void 0,tagFrom:void 0,tagTo:void 0,type:void 0,amount:this.safeNumber(e,"amount"),currency:i,status:this.parseTransactionStatus(this.safeString(e,"tx_status")),updated:void 0,comment:void 0,internal:void 0,fee:void 0,network:void 0}}parseTransactionStatus(e){return this.safeString({settled:"ok",reverted:"failed"},e,e)}handleDeriveSubaccountId(e,t){let[i,s]=this.handleOptionAndParams(t,e,"subaccount_id");if(void 0!==i&&""!==i)return this.options.subaccount_id=i,[i,s];let r=this.safeString(this.options,"subaccount_id");if(void 0!==r)return[r,s];throw new n.ArgumentsRequired(this.id+" "+e+"() requires a subaccount_id parameter inside 'params' or exchange.options['subaccount_id']=ID.")}handleDeriveWalletAddress(e,t){let[i,s]=this.handleOptionStringAndParams(t,e,"deriveWalletAddress");if(void 0!==i&&""!==i)return this.options.deriveWalletAddress=i,[i,s];let r=this.safeString(this.options,"deriveWalletAddress");if(void 0!==r)return[r,s];throw new n.ArgumentsRequired(this.id+" "+e+"() requires a deriveWalletAddress parameter inside 'params' or exchange.options['deriveWalletAddress'] = ADDRESS, the address can find in HOME => Developers tab.")}handleErrors(e,t,i,s,r,a,o,d,h){if(void 0===o)return;let c=this.safeDict(o,"error");if(void 0!==c){let e=this.safeString(c,"code"),t=this.id+" "+this.json(o);throw this.throwBroadlyMatchedException(this.exceptions.broad,a,t),this.throwExactlyMatchedException(this.exceptions.exact,e,t),new n.ExchangeError(t)}}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",s={},r,a){let o=this.safeString(this.urls.api,t);if(void 0===o)throw new n.ExchangeError(this.id+" sign() has no API URL for this endpoint");let d=o+"/"+e;if("POST"===i){let e={"Content-Type":"application/json"};if("private"===t){let t=this.milliseconds().toString(),i=this.signMessage(t,this.privateKey);e["X-LyraWallet"]=this.safeString(this.options,"deriveWalletAddress"),e["X-LyraTimestamp"]=t,e["X-LyraSignature"]=i}return{url:d,method:i,body:this.json(s),headers:e}}return{url:d,method:i,body:a,headers:r}}}i.d(t,{A:()=>h})},3645(e,t,i){"use strict";var s=i(4721),r=i(7854),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"digifinex",name:"DigiFinex",countries:["SG"],version:"v3",rateLimit:900,has:{CORS:void 0,spot:!0,margin:!0,swap:!0,future:!1,option:!1,addMargin:!0,cancelOrder:!0,cancelOrders:!0,cancelOrdersForSymbols:!0,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createPostOnlyOrder:!0,createReduceOnlyOrder:!0,createStopLimitOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,fetchBalance:!0,fetchBorrowInterest:!0,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchCrossBorrowRate:!0,fetchCrossBorrowRates:!0,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!0,fetchFundingInterval:!0,fetchFundingIntervals:!1,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLedger:!0,fetchLeverage:!1,fetchLeverageTiers:!0,fetchMarginMode:!1,fetchMarketLeverageTiers:!0,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!0,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!1,fetchTransfers:!0,fetchWithdrawals:!0,reduceMargin:!0,setLeverage:!0,setMargin:!1,setMarginMode:!0,setPositionMode:!1,transfer:!0,withdraw:!0},timeframes:{"1m":"1","5m":"5","15m":"15","30m":"30","1h":"60","4h":"240","12h":"720","1d":"1D","1w":"1W"},urls:{logo:"https://user-images.githubusercontent.com/51840849/87443315-01283a00-c5fe-11ea-8628-c2a0feaf07ac.jpg",api:{rest:"https://openapi.digifinex.com"},www:"https://www.digifinex.com",doc:["https://docs.digifinex.com"],fees:"https://digifinex.zendesk.com/hc/en-us/articles/360000328422-Fee-Structure-on-DigiFinex",referral:"https://www.digifinex.com/en-ww/from/DhOzBg?channelCode=ljaUPp"},api:{public:{spot:{get:{"{market}/symbols":{cost:1},kline:{cost:1},"margin/currencies":{cost:1},"margin/symbols":{cost:1},markets:{cost:1},order_book:{cost:1},ping:{cost:1},"spot/symbols":{cost:1},time:{cost:1},trades:{cost:1},"trades/symbols":{cost:1},ticker:{cost:1},currencies:{cost:1}}},swap:{get:{"public/api_weight":{cost:1},"public/candles":{cost:1},"public/candles_history":{cost:1},"public/depth":{cost:1},"public/funding_rate":{cost:1},"public/funding_rate_history":{cost:1},"public/instrument":{cost:1},"public/instruments":{cost:1},"public/ticker":{cost:1},"public/tickers":{cost:1},"public/time":{cost:1},"public/trades":{cost:1}}}},private:{spot:{get:{"{market}/financelog":{cost:1},"{market}/mytrades":{cost:1},"{market}/order":{cost:1},"{market}/order/detail":{cost:1},"{market}/order/current":{cost:1},"{market}/order/history":{cost:1},"margin/assets":{cost:1},"margin/financelog":{cost:1},"margin/mytrades":{cost:1},"margin/order":{cost:1},"margin/order/current":{cost:1},"margin/order/history":{cost:1},"margin/positions":{cost:1},"otc/financelog":{cost:1},"spot/assets":{cost:1},"spot/financelog":{cost:1},"spot/mytrades":{cost:1},"spot/order":{cost:1},"spot/order/current":{cost:1},"spot/order/history":{cost:1},"deposit/address":{cost:1},"deposit/history":{cost:1},"withdraw/history":{cost:1}},post:{"{market}/order/cancel":{cost:1},"{market}/order/new":{cost:1},"{market}/order/batch_new":{cost:1},"margin/order/cancel":{cost:1},"margin/order/new":{cost:1},"margin/position/close":{cost:1},"spot/order/cancel":{cost:1},"spot/order/new":{cost:1},transfer:{cost:1},"withdraw/new":{cost:1},"withdraw/cancel":{cost:1}}},swap:{get:{"account/balance":{cost:1},"account/positions":{cost:1},"account/finance_record":{cost:1},"account/trading_fee_rate":{cost:1},"account/transfer_record":{cost:1},"account/funding_fee":{cost:1},"trade/history_orders":{cost:1},"trade/history_trades":{cost:1},"trade/open_orders":{cost:1},"trade/order_info":{cost:1}},post:{"account/transfer":{cost:1},"account/leverage":{cost:1},"account/position_mode":{cost:1},"account/position_margin":{cost:1},"trade/batch_cancel_order":{cost:1},"trade/batch_order":{cost:1},"trade/cancel_order":{cost:1},"trade/order_place":{cost:1},"follow/sponsor_order":{cost:1},"follow/close_order":{cost:1},"follow/cancel_order":{cost:1},"follow/user_center_current":{cost:1},"follow/user_center_history":{cost:1},"follow/expert_current_open_order":{cost:1},"follow/add_algo":{cost:1},"follow/cancel_algo":{cost:1},"follow/account_available":{cost:1},"follow/plan_task":{cost:1},"follow/instrument_list":{cost:1}}}}},features:{default:{sandbox:!1,createOrder:{marginMode:!0,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!0,GTD:!1},hedged:!1,selfTradePrevention:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,iceberg:!1},createOrders:{max:10},fetchMyTrades:{marginMode:!0,limit:500,daysBack:1e5,untilDays:30,symbolRequired:!1},fetchOrder:{marginMode:!0,trigger:!1,trailing:!1,marketType:!0,symbolRequired:!0},fetchOpenOrders:{marginMode:!0,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!0,limit:100,daysBack:1e5,untilDays:30,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:void 0,fetchOHLCV:{limit:500}},spot:{extends:"default"},forDerivatives:{extends:"default",createOrders:{max:20,marginMode:!1},fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5},fetchOrder:{marginMode:!1},fetchOpenOrders:{marginMode:!1,limit:100},fetchOrders:{marginMode:!1,daysBack:1e5},fetchOHLCV:{limit:100}},swap:{linear:{extends:"forDerivatives"},inverse:{extends:"forDerivatives"}},future:{linear:void 0,inverse:void 0}},fees:{trading:{tierBased:!0,percentage:!0,maker:this.parseNumber("0.002"),taker:this.parseNumber("0.002")}},precisionMode:4,exceptions:{exact:{10001:[a.BadRequest,"Wrong request method, please check it's a GET ot POST request"],10002:[a.AuthenticationError,"Invalid ApiKey"],10003:[a.AuthenticationError,"Sign doesn't match"],10004:[a.BadRequest,"Illegal request parameters"],10005:[a.DDoSProtection,"Request frequency exceeds the limit"],10006:[a.PermissionDenied,"Unauthorized to execute this request"],10007:[a.PermissionDenied,"IP address Unauthorized"],10008:[a.InvalidNonce,"Timestamp for this request is invalid, timestamp must within 1 minute"],10009:[a.NetworkError,"Unexist endpoint, please check endpoint URL"],10011:[a.AccountSuspended,"ApiKey expired. Please go to client side to re-create an ApiKey"],20001:[a.PermissionDenied,"Trade is not open for this trading pair"],20002:[a.PermissionDenied,"Trade of this trading pair is suspended"],20003:[a.InvalidOrder,"Invalid price or amount"],20007:[a.InvalidOrder,"Price precision error"],20008:[a.InvalidOrder,"Amount precision error"],20009:[a.InvalidOrder,"Amount is less than the minimum requirement"],20010:[a.InvalidOrder,"Cash Amount is less than the minimum requirement"],20011:[a.InsufficientFunds,"Insufficient balance"],20012:[a.BadRequest,"Invalid trade type, valid value: buy/sell)"],20013:[a.InvalidOrder,"No order info found"],20014:[a.BadRequest,"Invalid date, Valid format: 2018-07-25)"],20015:[a.BadRequest,"Date exceeds the limit"],20018:[a.PermissionDenied,"Your trading rights have been banned by the system"],20019:[a.BadSymbol,'Wrong trading pair symbol. Correct format:"usdt_btc". Quote asset is in the front'],20020:[a.DDoSProtection,"You have violated the API operation trading rules and temporarily forbid trading. At present, we have certain restrictions on the user's transaction rate and withdrawal rate."],5e4:[a.ExchangeError,"Exception error"],20021:[a.BadRequest,"Invalid currency"],20022:[a.BadRequest,"The ending timestamp must be larger than the starting timestamp"],20023:[a.BadRequest,"Invalid transfer type"],20024:[a.BadRequest,"Invalid amount"],20025:[a.BadRequest,"This currency is not transferable at the moment"],20026:[a.InsufficientFunds,"Transfer amount exceed your balance"],20027:[a.PermissionDenied,"Abnormal account status"],20028:[a.PermissionDenied,"Blacklist for transfer"],20029:[a.PermissionDenied,"Transfer amount exceed your daily limit"],20030:[a.BadRequest,"You have no position on this trading pair"],20032:[a.PermissionDenied,"Withdrawal limited"],20033:[a.BadRequest,"Wrong Withdrawal ID"],20034:[a.PermissionDenied,"Withdrawal service of this crypto has been closed"],20035:[a.PermissionDenied,"Withdrawal limit"],20036:[a.ExchangeError,"Withdrawal cancellation failed"],20037:[a.InvalidAddress,"The withdrawal address, Tag or chain type is not included in the withdrawal management list"],20038:[a.InvalidAddress,"The withdrawal address is not on the white list"],20039:[a.ExchangeError,"Can't be canceled in current status"],20040:[a.RateLimitExceeded,"Withdraw too frequently; limitation: 3 times a minute, 100 times a day"],20041:[a.PermissionDenied,"Beyond the daily withdrawal limit"],20042:[a.BadSymbol,"Current trading pair does not support API trading"],400002:[a.BadRequest,"Invalid Parameter"]},broad:{}},options:{defaultType:"spot",types:["spot","margin","otc"],createMarketBuyOrderRequiresPrice:!0,accountsByType:{spot:"1",margin:"2",OTC:"3"},networks:{ARBITRUM:"Arbitrum",AVALANCEC:"AVAX-CCHAIN",AVALANCEX:"AVAX-XCHAIN",BEP20:"BEP20",BSC:"BEP20",CARDANO:"Cardano",CELO:"Celo",CHILIZ:"Chiliz",COSMOS:"COSMOS",CRC20:"Crypto.com",CRONOS:"Crypto.com",DOGECOIN:"DogeChain",ERC20:"ERC20",ETH:"ERC20",ETHW:"ETHW",IOTA:"MIOTA",KLAYTN:"KLAY",METIS:"MetisDAO",MOONBEAM:"GLMR",MOONRIVER:"Moonriver",OPTIMISM:"OPETH",POLYGON:"Polygon",MATIC:"Polygon",RIPPLE:"XRP",SOL:"SOL",XLM:"Stella",TERRACLASSIC:"TerraClassic",TERRA:"Terra",TON:"Ton",TRC20:"TRC20",TRX:"TRC20",VECHAIN:"Vechain"},networksById:{TRC20:"TRC20",TRX:"TRC20",BEP20:"BEP20",BSC:"BEP20",ERC20:"ERC20",ETH:"ERC20",Polygon:"POLYGON","Crypto.com":"CRONOS"}},commonCurrencies:{BHT:"Black House Test",EPS:"Epanus",FREE:"FreeRossDAO",MBN:"Mobilian Coin",TEL:"TEL666"}})}async fetchCurrencies(e={}){let t=await this.publicSpotGetCurrencies(e),i=this.safeList(t,"data",[]),s=Object.values(this.groupBy(i,"currency"));return this.parseCurrencies(s)}parseCurrency(e){let t=this.safeDict(e,0,{}),i=this.safeString(t,"currency"),s=this.safeCurrencyCode(i),r={};for(let t=0;t<e.length;t++){let i=e[t],a=this.safeString2(i,"chain","currency"),o=this.networkIdToCode(a,s);void 0!==o&&(r[o]={id:a,network:o,active:void 0,deposit:1===this.safeInteger(i,"deposit_status"),withdraw:1===this.safeInteger(i,"withdraw_status"),fee:this.safeNumber(i,"min_withdraw_fee"),precision:void 0,limits:{withdraw:{min:this.safeNumber(i,"min_withdraw_amount"),max:void 0},deposit:{min:this.safeNumber(i,"min_deposit_amount"),max:void 0}},info:i})}return this.safeCurrencyStructure({id:i,code:s,info:e,networks:r})}async fetchMarkets(e={}){let t=this.safeDict(this.options,"fetchMarkets",{});return"fetch_markets_v2"===this.safeString(t,"method","fetch_markets_v2")?await this.fetchMarketsV2(e):await this.fetchMarketsV1(e)}async fetchMarketsV2(e={}){let t=this.safeString(this.options,"defaultType"),[i,s]=this.handleMarginModeAndParams("fetchMarketsV2",e),r=[];void 0!==i?r.push(this.publicSpotGetMarginSymbols(s)):r.push(this.publicSpotGetTradesSymbols(s)),r.push(this.publicSwapGetPublicInstruments(e));let a=await Promise.all(r),o=this.safeDict(a,0),n=this.safeDict(a,1),d=this.safeList(o,"symbol_list",[]),h=this.safeList(n,"data",[]),c=this.arrayConcat(d,h),l=[];for(let e=0;e<c.length;e++){let s,r,a=c[e],o=this.safeString2(a,"symbol","instrument_id"),n=this.safeString2(a,"base_asset","base_currency"),d=this.safeString2(a,"quote_asset","quote_currency"),h=this.safeString(a,"clear_currency"),u=this.safeCurrencyCode(n),f=this.safeCurrencyCode(d);if(void 0===u||void 0===f)continue;let p=this.safeCurrencyCode(h),m=this.safeInteger(a,"is_allow",1),g="margin"===t?"margin":"spot",v=void 0===p,y=!v,b=void 0!==i||void 0,w=u+"/"+f;y&&(g="swap",w=u+"/"+f+":"+p,r=!0!==(s=this.safeBool(a,"is_inverse")),!0===this.safeBool(a,"isTrading")&&(m=1));let k=0!==m;l.push({id:o,symbol:w,base:u,quote:f,settle:p,baseId:n,quoteId:d,settleId:h,type:g,spot:v,margin:b,swap:y,future:!1,option:!1,active:k,contract:y,linear:r,inverse:s,contractSize:this.safeNumber(a,"contract_value"),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(a,"amount_precision"))),price:this.parseNumber(this.parsePrecision(this.safeString(a,"price_precision")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber2(a,"minimum_amount","min_order_amount"),max:void 0},price:{min:this.safeNumber(a,"tick_size"),max:void 0},cost:{min:this.safeNumber(a,"minimum_value"),max:void 0}},created:void 0,info:a})}return l}async fetchMarketsV1(e={}){let t=await this.publicSpotGetMarkets(e),i=this.safeList(t,"data",[]),s=[];for(let e=0;e<i.length;e++){let t=i[e],r=this.safeString(t,"market");if(void 0===r)throw new a.ExchangeError(this.id+" fetchMarketsV1() missing id");let[o,n]=r.split("_"),d=this.safeCurrencyCode(o),h=this.safeCurrencyCode(n);void 0!==d&&void 0!==h&&s.push({id:r,symbol:d+"/"+h,base:d,quote:h,settle:void 0,baseId:o,quoteId:n,settleId:void 0,type:"spot",spot:!0,margin:void 0,swap:!1,future:!1,option:!1,active:void 0,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{price:this.parseNumber(this.parsePrecision(this.safeString(t,"price_precision"))),amount:this.parseNumber(this.parsePrecision(this.safeString(t,"volume_precision")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(t,"min_volume"),max:void 0},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(t,"min_amount"),max:void 0}},info:t})}return s}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"currency"),a=this.safeCurrencyCode(r),n=this.account(),d=this.safeString2(s,"free","avail_balance"),h=this.safeString2(s,"total","equity");n.free=d,n.used=o.Y.stringSub(h,d),n.total=h,void 0!==a&&(t[a]=n)}return this.safeBalance(t)}async fetchBalance(e={}){let t,i,s;void 0===this.markets&&await this.loadMarkets(),[t,i]=this.handleMarketTypeAndParams("fetchBalance",void 0,e);let[r,o]=this.handleMarginModeAndParams("fetchBalance",i);if(void 0!==r||"margin"===t)t="margin",s=await this.privateSpotGetMarginAssets(o);else if("spot"===t)s=await this.privateSpotGetSpotAssets(o);else if("swap"===t)s=await this.privateSwapGetAccountBalance(o);else throw new a.NotSupported(this.id+" fetchBalance() not support this market type");let n="list";"swap"===t&&(n="data");let d=this.safeList(s,n,[]);return this.parseBalance(d)}async fetchOrderBook(e,t,i={}){let s,r,a;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),[n,d]=this.handleMarketTypeAndParams("fetchOrderBook",o,i),h={};return void 0!==t&&(h.limit=t),"swap"===n?(h.instrument_id=o.id,s=await this.publicSwapGetPublicDepth(this.extend(h,d))):(h.symbol=o.id,s=await this.publicSpotGetOrderBook(this.extend(h,d))),"swap"===n?(a=this.safeDict(s,"data",{}),r=this.safeInteger(a,"timestamp")):(a=s,r=this.safeTimestamp(s,"date")),this.parseOrderBook(a,o.symbol,r)}async fetchTickers(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e),a=this.safeString(r,0);void 0!==a&&(i=this.market(a));let[o,n]=this.handleMarketTypeAndParams("fetchTickers",i,t),d={};s="swap"===o?await this.publicSwapGetPublicTickers(this.extend(d,n)):await this.publicSpotGetTicker(this.extend(d,n));let h={},c=this.safeList2(s,"ticker","data",[]),l=this.safeInteger(s,"date");for(let e=0;e<c.length;e++){let t=this.extend({date:l},c[e]),i=this.parseTicker(t),s=i.symbol;void 0!==s&&(h[s]=i)}return this.filterByArrayTickers(h,"symbol",r)}async fetchTicker(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={};!0===r.swap?(o.instrument_id=r.id,i=await this.publicSwapGetPublicTicker(this.extend(o,t))):(o.symbol=r.id,i=await this.publicSpotGetTicker(this.extend(o,t)));let n=this.safeInteger(i,"date"),d=this.safeList(i,"ticker",[]),h=this.safeDict(i,"data",{}),c=this.safeDict(d,0,{});if(void 0===(s=!0===r.swap?h:this.extend({date:n},c)))throw new a.NullResponse(this.id+" fetchTicker() returned empty response");return this.parseTicker(s,r)}parseTicker(e,t){let i=this.safeNumber(e,"index_price"),s="spot";void 0!==i&&(s="contract");let r=this.safeStringUpper2(e,"symbol","instrument_id"),a=this.safeSymbol(r,t,void 0,s),n=this.safeMarket(r,t,void 0,s),d=this.safeTimestamp(e,"date");!0===n.swap&&(d=this.safeInteger(e,"timestamp"));let h=this.safeString(e,"last"),c=this.safeString2(e,"change","price_change_percent");return!0===n.swap&&(c=o.Y.stringMul(c,"100")),this.safeTicker({symbol:a,timestamp:d,datetime:this.iso8601(d),high:this.safeString2(e,"high","high_24h"),low:this.safeString2(e,"low","low_24h"),bid:this.safeString2(e,"buy","best_bid"),bidVolume:this.safeString(e,"best_bid_size"),ask:this.safeString2(e,"sell","best_ask"),askVolume:this.safeString(e,"best_ask_size"),vwap:void 0,open:this.safeString(e,"open_24h"),close:h,last:h,previousClose:void 0,change:void 0,percentage:c,average:void 0,baseVolume:this.safeString2(e,"vol","volume_24h"),quoteVolume:this.safeString(e,"base_vol"),markPrice:this.safeString(e,"mark_price"),indexPrice:i,info:e},n)}parseTrade(e,t){let i,s,r,o=this.safeString2(e,"id","trade_id"),n=this.safeString(e,"order_id"),d=this.safeString(e,"price"),h=this.safeStringN(e,["amount","volume","size"]),c=this.safeStringUpper2(e,"symbol","instrument_id"),l=this.safeSymbol(c,t),u=this.safeMarket(void 0===t?c:void 0,t),f=this.safeTimestamp2(e,"date","timestamp"),p=this.safeString2(e,"type","side");if("swap"===u.type){f=this.safeInteger(e,"trade_time");let t=this.safeString(e,"order_type"),r=this.safeString(e,"match_role"),a=this.safeString(e,"direction");void 0!==t&&"0"===t&&(i="limit"),s="1"===r?"taker":"2"===r?"maker":void 0,"1"===p||"1"===a?p="buy":"2"===p||"2"===a||"3"===p||"3"===a?p="sell":("4"===p||"4"===a)&&(p="buy")}else{if(void 0===p)throw new a.ExchangeError(this.id+" parseTrade() returned no side");let t=p.split("_");p=this.safeString(t,0),void 0===(i=this.safeString(t,1))&&(i="limit"),s=!0===this.safeBool(e,"is_maker")?"maker":"taker"}let m=this.safeString(e,"fee");if(void 0!==m){let t,i=this.safeString(e,"fee_currency");void 0!==i&&(t=this.safeCurrencyCode(i)),r={cost:m,currency:t}}return this.safeTrade({id:o,info:e,timestamp:f,datetime:this.iso8601(f),symbol:l,type:i,order:n,side:p,price:d,amount:h,cost:void 0,takerOrMaker:s,fee:r},u)}async fetchTime(e={}){let t=await this.publicSpotGetTime(e);return this.safeTimestamp(t,"server_time")}async fetchStatus(e={}){let t=await this.publicSpotGetPing(e),i=this.safeInteger(t,"code"),s="maintenance";return 0===i&&(s="ok"),{status:s,updated:void 0,eta:void 0,url:void 0,info:t}}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={};void 0!==i&&(o.limit=!0===a.swap?Math.min(i,100):i),!0===a.swap?(o.instrument_id=a.id,r=await this.publicSwapGetPublicTrades(this.extend(o,s))):(o.symbol=a.id,r=await this.publicSpotGetTrades(this.extend(o,s)));let n=this.safeList(r,"data",[]);return this.parseTrades(n,a,t,i)}parseOHLCV(e,t){return this.safeBool(t,"swap",!1)?[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]:[this.safeTimestamp(e,0),this.safeNumber(e,5),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,2),this.safeNumber(e,1)]}async fetchOHLCV(e,t="1m",i,s,r={}){let o,n;void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h={};if(!0===d.swap)h.instrument_id=d.id,h.granularity=t,void 0!==s&&(h.limit=Math.min(s,100)),o=await this.publicSwapGetPublicCandles(this.extend(h,r));else{let e=this.safeInteger(r,"until");h.symbol=d.id,h.period=this.safeString(this.timeframes,t,t);let n=i,c=this.parseTimeframe(t);if(void 0===n&&(void 0!==s||void 0!==e)&&(n=(void 0!==e?e:this.milliseconds())-(void 0!==s?s:200)*c*1e3),void 0!==n&&(h.start_time=n=this.parseToInt(n/1e3),void 0!==s||void 0!==e))if(void 0!==e){let t=this.parseToInt(e/1e3);void 0!==s?h.end_time=Math.min(this.sum(n,s*c),t):h.end_time=t}else{if(void 0===s)throw new a.ArgumentsRequired(this.id+" fetchOHLCV() requires a limit argument");h.end_time=this.sum(n,s*c)}let l=this.omit(r,"until");o=await this.publicSpotGetKline(this.extend(h,l))}if(!0===d.swap){let e=this.safeDict(o,"data",{});n=this.safeList(e,"candles",[])}else n=this.safeList(o,"data",[]);return this.parseOHLCVs(n,d,t,i,s)}async createOrder(e,t,i,s,r,o={}){let n;void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h=this.handleMarginModeAndParams("createOrder",o)[0],c=this.createOrderRequest(e,t,i,s,r,o);if(void 0===(n=!0===d.swap?await this.privateSwapPostTradeOrderPlace(c):void 0!==h?await this.privateSpotPostMarginOrderNew(c):await this.privateSpotPostSpotOrderNew(c)))throw new a.NullResponse(this.id+" createOrder() returned empty response");let l=this.parseOrder(n,d);return l.symbol=d.symbol,l.type=t,l.side=i,l.amount=s,l.price=r,l}async createOrders(e,t={}){let i,s,r;void 0===this.markets&&await this.loadMarkets();let o=[];for(let t=0;t<e.length;t++){let r=this.safeDict(e,t),n=this.safeString(r,"symbol");if(void 0===i)i=n;else if(i!==n)throw new a.BadRequest(this.id+" createOrders() requires all orders to have the same symbol");let d=this.safeString(r,"type"),h=this.safeString(r,"side"),c=this.safeValue(r,"amount"),l=this.safeValue(r,"price"),u=this.safeDict(r,"params",{}),f=this.handleMarginModeAndParams("createOrders",u)[0];if(void 0!==f){if(void 0===s)s=f;else if(s!==f)throw new a.BadRequest(this.id+" createOrders() requires all orders to have the same margin mode (isolated or cross)")}let p=this.createOrderRequest(n,d,h,c,l,u);o.push(p)}let n=this.market(i),d={};!0===n.swap?r=await this.privateSwapPostTradeBatchOrder(o):(d.market=void 0!==s?"margin":"spot",d.symbol=n.id,d.list=this.json(o),r=await this.privateSpotPostMarketOrderBatchNew(d));let h=[];h=!0===n.swap?this.safeList(r,"data",[]):this.safeList(r,"order_ids",[]);let c=[];for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s={};s.order_id=h[t],s.instrument_id=n.id,s.amount=this.safeNumber(i,"amount"),s.price=this.safeNumber(i,"price"),c.push(s)}return this.parseOrders(c,n)}createOrderRequest(e,t,i,s,r,n={}){let d,h;if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let c=this.market(e),[l,u]=this.handleMarketTypeAndParams("createOrderRequest",c,n),[f,p]=this.handleMarginModeAndParams("createOrderRequest",u),m=void 0!==f?"margin":l,g={},v="swap"===m,y="market"===t,b="symbol";v&&(b="instrument_id"),g[b]=c.id;let w=this.isPostOnly(y,!1,p);if(v){let a,o=this.safeBool(p,"reduceOnly",!1),n=this.safeString(p,"timeInForce");"buy"===i?g.type=!0===o?4:1:g.type=!0===o?3:2,"limit"===t&&(a=0),"FOK"===n?a=y?15:9:"IOC"===n?a=y?13:4:"GTC"===n||y?a=14:"PO"===n&&(w=!0),void 0!==r&&(g.price=this.priceToPrecision(e,r)),g.order_type=a,g.size=s,h=this.omit(p,["reduceOnly","timeInForce","postOnly"])}else{let n,c;d=!0===w?1:2,g.market=m;let l="";"market"===t?l="_market":g.price=this.priceToPrecision(e,r),g.type=i+l;let[u,f]=this.handleOptionBoolAndParams(p,"createOrderRequest","createMarketBuyOrderRequiresPrice",!0),v=y&&"buy"===i;if(c=v?["cost","postOnly"]:["postOnly"],h=this.omit(f,c),v){let t=this.safeNumber(f,"cost");if(void 0!==t)n=this.costToPrecision(e,t);else if(u)if(void 0===r)throw new a.InvalidOrder(this.id+" createOrder() requires a price argument for market buy orders on spot markets to calculate the total amount to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument");else{let t=this.numberToString(s),i=this.numberToString(r),a=this.parseNumber(o.Y.stringMul(t,i));n=this.costToPrecision(e,a)}else n=this.costToPrecision(e,s)}else n=this.amountToPrecision(e,s);g.amount=n}return w&&(void 0!==d&&0!==d?g.post_only=d:g.post_only=w),this.extend(g,h)}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new a.NotSupported(this.id+" createMarketBuyOrderWithCost() supports spot orders only");return i.createMarketBuyOrderRequiresPrice=!1,await this.createOrder(e,"market","buy",t,void 0,i)}async cancelOrder(e,t,i={}){let s,r,o,n;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let d=e.toString();[r,o]=this.handleMarketTypeAndParams("cancelOrder",s,i);let h={order_id:d};if("swap"===r){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");h.instrument_id=this.safeString(s,"id")}else h.market=r;let[c,l]=this.handleMarginModeAndParams("cancelOrder",o);if(void 0!==c||"margin"===r)r="margin",n=await this.privateSpotPostMarginOrderCancel(this.extend(h,l));else if("spot"===r)n=await this.privateSpotPostSpotOrderCancel(this.extend(h,l));else if("swap"===r)n=await this.privateSwapPostTradeCancelOrder(this.extend(h,l));else throw new a.NotSupported(this.id+" cancelOrder() not support this market type");if("spot"!==r&&"margin"!==r)return this.safeOrder({info:n,id:this.safeString(n,"data")});{if(1!==this.safeList(n,"success",[]).length)throw new a.OrderNotFound(this.id+" cancelOrder() "+d+" not found");let e=this.parseCancelOrders(n);return this.safeDict(e,0)}}parseCancelOrders(e,t={}){let i=this.safeList(e,"success",[]),s=this.safeList(e,"error",[]),r=[];for(let e=0;e<i.length;e++){let s=i[e];r.push(this.safeOrder({info:s,id:s,symbol:this.safeString(t,s),status:"canceled"}))}for(let e=0;e<s.length;e++){let i=s[e];r.push(this.safeOrder({info:i,id:i,symbol:this.safeString(t,i),status:"failed"}))}return r}async cancelOrders(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let[r,o]=this.handleMarketTypeAndParams("cancelOrders",s,i);if("swap"===r){if(void 0===s)throw new a.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument for swap markets");let t=s.symbol,i=[];for(let s=0;s<e.length;s++){let r={id:e[s],symbol:t};i.push(r)}return await this.cancelOrdersForSymbols(i,o)}let n={market:r,order_id:e.join(",")},d=await this.privateSpotPostSpotOrderCancel(this.extend(n,o));return this.parseCancelOrders(d)}async cancelOrdersForSymbols(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=[],r=[],o={};for(let t=0;t<e.length;t++){let n=e[t],d=this.safeString(n,"id");if(void 0===d)throw new a.ArgumentsRequired(this.id+" cancelOrdersForSymbols() requires an id for each order");let h=this.safeString(n,"symbol");if(void 0===h)throw new a.ArgumentsRequired(this.id+" cancelOrdersForSymbols() requires a symbol for each order");let c=this.market(h),l=c.type;if(void 0===i)i=l;else if(i!==l)throw new a.BadRequest(this.id+" cancelOrdersForSymbols() requires all orders to be of the same market type (spot or swap)");s.push(d),r.push(c.symbol),o[d]=c.symbol}if("swap"===i){if(s.length>20)throw new a.BadRequest(this.id+" cancelOrdersForSymbols() accepts up to 20 orders for swap markets");let e=[];for(let t=0;t<s.length;t++){let i=this.market(r[t]).id,a=s[t];e.push({instrument_id:i,order_id:a})}let t=await this.privateSwapPostTradeBatchCancelOrder(e),i=this.safeList(t,"data",[]),o=[];for(let e=0;e<s.length;e++){let t=s[e],a=this.inArray(t,i)?"canceled":"failed";o.push(this.safeOrder({info:t,id:t,symbol:r[e],status:a}))}return o}let[n,d]=this.handleMarketTypeAndParams("cancelOrdersForSymbols",void 0,t,"spot"),h={market:n,order_id:s.join(",")},c=await this.privateSpotPostSpotOrderCancel(this.extend(h,d));return this.parseCancelOrders(c,o)}parseOrderStatus(e){return this.safeString({"-1":"canceled",0:"open",1:"open",2:"closed",3:"canceled",4:"canceled"},e,e)}parseOrder(e,t){let i,s,r,a,o,n=this.safeString(e,"type"),d=this.safeString2(e,"symbol","instrument_id"),h=this.safeSymbol(d,t),c=this.market(h);if("swap"===c.type){let t=this.safeInteger(e,"order_type");void 0!==t&&(9===t||10===t||11===t||12===t||15===t?r="FOK":1===t||2===t||3===t||4===t||13===t?r="IOC":(6===t||7===t||8===t||14===t)&&(r="GTC"),a=0===t||1===t||4===t||5===t||9===t||10===t?"limit":"market"),"1"===n?(n="buy",o=!1):"2"===n?(n="sell",o=!1):"3"===n?(n="sell",o=!0):"4"===n&&(n="buy",o=!0),i=this.safeInteger(e,"insert_time"),s=this.safeInteger(e,"time_stamp")}else if(i=this.safeTimestamp(e,"created_date"),s=this.safeTimestamp(e,"finished_date"),void 0!==n){let e=n.split("_");e.length>1?(n=e[0],a=e[1]):a="limit"}return this.safeOrder({info:e,id:this.safeString2(e,"order_id","data"),clientOrderId:void 0,timestamp:i,datetime:this.iso8601(i),lastTradeTimestamp:s,symbol:h,type:a,timeInForce:r,postOnly:void 0,side:n,price:this.safeNumber(e,"price"),triggerPrice:void 0,reduceOnly:o,amount:this.safeNumber2(e,"amount","size"),filled:this.safeNumber2(e,"executed_amount","filled_qty"),remaining:void 0,cost:void 0,average:this.safeNumber2(e,"avg_price","price_avg"),status:this.parseOrderStatus(this.safeString2(e,"status","state")),fee:{cost:this.safeNumber(e,"fee")},trades:void 0},c)}async fetchOpenOrders(e,t,i,s={}){let r,o,n,d;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e)),[o,n]=this.handleMarketTypeAndParams("fetchOpenOrders",r,s);let[h,c]=this.handleMarginModeAndParams("fetchOpenOrders",n),l={},u="swap"===o;if(u?(void 0!==t&&(l.start_timestamp=t),void 0!==i&&(l.limit=i)):l.market=o,void 0!==r){let e="symbol";u&&(e="instrument_id"),l[e]=r.id}if(void 0!==h||"margin"===o)o="margin",d=await this.privateSpotGetMarginOrderCurrent(this.extend(l,c));else if("spot"===o)d=await this.privateSpotGetSpotOrderCurrent(this.extend(l,c));else if("swap"===o)d=await this.privateSwapGetTradeOpenOrders(this.extend(l,c));else throw new a.NotSupported(this.id+" fetchOpenOrders() not support this market type");let f=this.safeList(d,"data",[]);return this.parseOrders(f,r,t,i)}async fetchOrders(e,t,i,s={}){let r,o,n,d;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e)),[o,n]=this.handleMarketTypeAndParams("fetchOrders",r,s);let[h,c]=this.handleMarginModeAndParams("fetchOrders",n),l={};if("swap"===o?void 0!==t&&(l.start_timestamp=t):(l.market=o,void 0!==t&&(l.start_time=this.parseToInt(t/1e3))),void 0!==r){let e="symbol";"swap"===o&&(e="instrument_id"),l[e]=r.id}if(void 0!==i&&(l.limit=i),void 0!==h||"margin"===o)o="margin",d=await this.privateSpotGetMarginOrderHistory(this.extend(l,c));else if("spot"===o)d=await this.privateSpotGetSpotOrderHistory(this.extend(l,c));else if("swap"===o)d=await this.privateSwapGetTradeHistoryOrders(this.extend(l,c));else throw new a.NotSupported(this.id+" fetchOrders() not support this market type");let u=this.safeList(d,"data",[]);return this.parseOrders(u,r,t,i)}async fetchOrder(e,t,i={}){let s,r,o,n;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t)),[r,o]=this.handleMarketTypeAndParams("fetchOrder",s,i);let[d,h]=this.handleMarginModeAndParams("fetchOrder",o),c={order_id:e};if("swap"===r?void 0!==s&&(c.instrument_id=s.id):c.market=r,void 0!==d||"margin"===r)r="margin",n=await this.privateSpotGetMarginOrder(this.extend(c,h));else if("spot"===r)n=await this.privateSpotGetSpotOrder(this.extend(c,h));else if("swap"===r)n=await this.privateSwapGetTradeOrderInfo(this.extend(c,h));else throw new a.NotSupported(this.id+" fetchOrder() not support this market type");let l=this.safeValue(n,"data"),u="swap"===r?l:this.safeValue(l,0);if(void 0===u)throw new a.OrderNotFound(this.id+" fetchOrder() order "+e.toString()+" not found");return this.parseOrder(u,s)}async fetchMyTrades(e,t,i,s={}){let r,o,n,d;void 0===this.markets&&await this.loadMarkets();let h={};void 0!==e&&(r=this.market(e)),[o,n]=this.handleMarketTypeAndParams("fetchMyTrades",r,s);let[c,l]=this.handleMarginModeAndParams("fetchMyTrades",n);"swap"===o?void 0!==t&&(h.start_timestamp=t):(h.market=o,void 0!==t&&(h.start_time=this.parseToInt(t/1e3)));let u="symbol";if("swap"===o&&(u="instrument_id"),void 0!==e&&(h[u]=this.safeString(r,"id")),void 0!==i&&(h.limit=i),void 0!==c||"margin"===o)o="margin",d=await this.privateSpotGetMarginMytrades(this.extend(h,l));else if("spot"===o)d=await this.privateSpotGetSpotMytrades(this.extend(h,l));else if("swap"===o)d=await this.privateSwapGetTradeHistoryTrades(this.extend(h,l));else throw new a.NotSupported(this.id+" fetchMyTrades() not support this market type");let f="list";"swap"===o&&(f="data");let p=this.safeList(d,f,[]);return this.parseTrades(p,r,t,i)}parseLedgerEntryType(e){return this.safeString({},e,e)}parseLedgerEntry(e,t){let i=this.parseLedgerEntryType(this.safeString2(e,"type","finance_type")),s=this.safeString2(e,"currency_mark","currency"),r=this.safeCurrencyCode(s,t),a=this.safeCurrency(s,t),o=this.safeNumber2(e,"num","change"),n=this.safeNumber(e,"balance"),d=this.safeTimestamp(e,"time");return void 0===d&&(d=this.safeInteger(e,"timestamp")),this.safeLedgerEntry({info:e,id:void 0,direction:void 0,account:void 0,referenceId:void 0,referenceAccount:void 0,type:i,currency:r,amount:o,before:void 0,after:n,status:void 0,timestamp:d,datetime:this.iso8601(d),fee:void 0},a)}async fetchLedger(e,t,i,s={}){let r,o,n,d,h;void 0===this.markets&&await this.loadMarkets();let c={};[r,o]=this.handleMarketTypeAndParams("fetchLedger",void 0,s);let[l,u]=this.handleMarginModeAndParams("fetchLedger",o);"swap"===r?void 0!==t&&(c.start_timestamp=t):(c.market=r,void 0!==t&&(c.start_time=this.parseToInt(t/1e3)));let f="currency_mark";if("swap"===r&&(f="currency"),void 0!==e&&(n=this.currency(e),c[f]=n.id),void 0!==i&&(c.limit=i),void 0!==l||"margin"===r)r="margin",d=await this.privateSpotGetMarginFinancelog(this.extend(c,u));else if("spot"===r)d=await this.privateSpotGetSpotFinancelog(this.extend(c,u));else if("swap"===r)d=await this.privateSwapGetAccountFinanceRecord(this.extend(c,u));else throw new a.NotSupported(this.id+" fetchLedger() not support this market type");if("swap"===r)h=this.safeList(d,"data",[]);else{let e=this.safeDict(d,"data",{});h=this.safeList(e,"finance",[])}return this.parseLedger(h,n,t,i)}parseDepositAddress(e,t){let i=this.safeString(e,"address"),s=this.safeString(e,"addressTag"),r=this.safeStringUpper(e,"currency");return{info:e,currency:this.safeCurrencyCode(r),network:void 0,address:i,tag:s}}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={currency:i.id},r=await this.privateSpotGetDepositAddress(this.extend(s,t)),o=this.safeList(r,"data",[]),n=this.parseDepositAddresses(o,[i.code]),d=this.safeDict(n,e);if(void 0===d)throw new a.InvalidAddress(this.id+" fetchDepositAddress() did not return an address for "+e+" - create the deposit address in the user settings on the exchange website first.");return d}async fetchTransactionsByType(e,t,i,s,r={}){let a,o;void 0===this.markets&&await this.loadMarkets();let n={};void 0!==t&&(n.currency=(a=this.currency(t)).id),void 0!==s&&(n.size=Math.min(500,s)),o="deposit"===e?await this.privateSpotGetDepositHistory(this.extend(n,r)):await this.privateSpotGetWithdrawHistory(this.extend(n,r));let d=this.safeList(o,"data",[]);return this.parseTransactions(d,a,i,s,{type:e})}async fetchDeposits(e,t,i,s={}){return await this.fetchTransactionsByType("deposit",e,t,i,s)}async fetchWithdrawals(e,t,i,s={}){return await this.fetchTransactionsByType("withdrawal",e,t,i,s)}parseTransactionStatus(e){return this.safeString({1:"pending",2:"pending",3:"ok",4:"failed"},e,e)}parseTransaction(e,t){let i,s=this.safeString2(e,"id","withdraw_id"),r=this.safeString(e,"address"),a=this.safeString(e,"memo"),o=this.safeString(e,"hash"),n=this.safeStringUpper(e,"currency"),d=this.safeCurrencyCode(n,t),h=this.parse8601(this.safeString(e,"created_date")),c=this.parse8601(this.safeString(e,"finished_date")),l=this.parseTransactionStatus(this.safeString(e,"state")),u=this.safeNumber(e,"amount"),f=this.safeNumber(e,"fee");void 0!==f&&(i={currency:d,cost:f});let p=this.safeString(e,"chain");return{info:e,id:s,txid:o,timestamp:h,datetime:this.iso8601(h),network:p,address:r,addressTo:r,addressFrom:void 0,tag:a,tagTo:a,tagFrom:void 0,type:void 0,amount:u,currency:d,status:l,updated:c,internal:void 0,comment:void 0,fee:i}}parseTransferStatus(e){return this.safeString({0:"ok"},e,e)}parseTransfer(e,t){let i,s,r=this.safeDict(e,"data",e),a=this.safeInteger(r,"type");1===a?(i="spot",s="swap"):2===a&&(i="swap",s="spot");let o=this.safeInteger(e,"timestamp");return{info:e,id:this.safeString(e,"transfer_id"),timestamp:o,datetime:this.iso8601(o),currency:this.safeCurrencyCode(this.safeString(r,"currency"),t),amount:this.safeNumber2(r,"amount","transfer_amount"),fromAccount:i,toAccount:s,status:this.parseTransferStatus(this.safeString(e,"code"))}}async transfer(e,t,i,s,r={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d=n.id,h=this.safeDict(this.options,"accountsByType",{}),c=this.safeString(h,i,i),l=this.safeString(h,s,s),u={},f="swap"===i,p="swap"===s,m=this.currencyToPrecision(e,t);if(f||p){if("1"!==c&&"1"!==l)throw new a.ExchangeError(this.id+" transfer() supports transferring between spot and swap, spot and margin, spot and OTC only");u.type=p?1:2,u.currency=d,u.transfer_amount=m,o=await this.privateSwapPostAccountTransfer(this.extend(u,r))}else u.currency_mark=d,u.num=m,u.from=c,u.to=l,o=await this.privateSpotPostTransfer(this.extend(u,r));if(void 0===o)throw new a.NullResponse(this.id+" transfer() returned empty response");return this.parseTransfer(o,n)}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d={address:i,amount:this.currencyToPrecision(e,t),currency:n.id};void 0!==a&&(d.memo=a);let h=await this.privateSpotPostWithdrawNew(this.extend(d,o));return this.parseTransaction(h,n)}async fetchBorrowInterest(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o={};void 0!==t&&(o.symbol=(a=this.market(t)).id);let n=await this.privateSpotGetMarginPositions(this.extend(o,r)),d=this.safeList(n,"positions"),h=this.parseBorrowInterests(d,a);return this.filterByCurrencySinceLimit(h,e,i,s)}parseBorrowInterest(e,t){let i=this.safeString(e,"symbol"),s=this.safeString(e,"amount"),r=this.safeString(e,"leverage_ratio"),a=o.Y.stringDiv(s,r),n=o.Y.stringSub(s,a),d=void 0===t?void 0:t.base;return{info:e,symbol:this.safeSymbol(i,t),currency:d,interest:void 0,interestRate:.001,amountBorrowed:this.parseNumber(n),marginMode:void 0,timestamp:void 0,datetime:void 0}}async fetchCrossBorrowRate(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=await this.privateSpotGetMarginAssets(this.extend({},t)),r=this.safeList(s,"list",[]);for(let t=0;t<r.length;t++){let s=r[t];this.safeString(s,"currency")===e&&(i=s)}let a=this.currency(e);return this.parseBorrowRate(i,a)}async fetchCrossBorrowRates(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateSpotGetMarginAssets(e),i=this.safeList(t,"list",[]);return this.parseBorrowRates(i,"currency")}parseBorrowRate(e,t){let i=this.safeString(e,"currency");return{currency:this.safeCurrencyCode(i,t),rate:.001,period:864e5,timestamp:void 0,datetime:void 0,info:e}}parseBorrowRates(e,t){let i={};for(let s=0;s<e.length;s++){let r=e[s],a=this.safeString(r,t),o=this.safeCurrencyCode(a),n=this.parseBorrowRate(r);void 0!==o&&(i[o]=n)}return i}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new a.BadSymbol(this.id+" fetchFundingRate() supports swap contracts only");let s={instrument_id:i.id},r=await this.publicSwapGetPublicFundingRate(this.extend(s,t)),o=this.safeDict(r,"data",{});return this.parseFundingRate(o,i)}async fetchFundingInterval(e,t={}){return await this.fetchFundingRate(e,t)}parseFundingRate(e,t){let i=this.safeString(e,"instrument_id"),s=this.safeInteger(e,"funding_time"),r=this.safeInteger(e,"next_funding_time"),a=this.safeString(e,"funding_time"),n=this.safeString(e,"next_funding_time"),d=o.Y.stringSub(n,a);return{info:e,symbol:this.safeSymbol(i,t),markPrice:void 0,indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:this.safeNumber(e,"funding_rate"),fundingTimestamp:s,fundingDatetime:this.iso8601(s),nextFundingRate:this.safeNumber(e,"next_funding_rate"),nextFundingTimestamp:r,nextFundingDatetime:this.iso8601(r),previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:this.parseFundingInterval(d)}}parseFundingInterval(e){return this.safeString({36e5:"1h",144e5:"4h",288e5:"8h",576e5:"16h",864e5:"24h"},e,e)}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e);if(!0!==r.swap)throw new a.BadSymbol(this.id+" fetchFundingRateHistory() supports swap contracts only");let o={instrument_id:r.id};void 0!==t&&(o.start_timestamp=t),void 0!==i&&(o.limit=i);let n=await this.publicSwapGetPublicFundingRateHistory(this.extend(o,s)),d=this.safeDict(n,"data",{}),h=this.safeList(d,"funding_rates",[]),c=[];for(let e=0;e<h.length;e++){let t=h[e],i=this.safeString(d,"instrument_id"),s=this.safeSymbol(i),r=this.safeInteger(t,"time");c.push({info:t,symbol:s,fundingRate:this.safeNumber(t,"rate"),timestamp:r,datetime:this.iso8601(r)})}let l=this.sortBy(c,"timestamp");return this.filterBySymbolSinceLimit(l,e,t,i)}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new a.BadRequest(this.id+" fetchTradingFee() supports swap markets only");let s={instrument_id:i.id},r=await this.privateSwapGetAccountTradingFeeRate(this.extend(s,t)),o=this.safeDict(r,"data",{});return this.parseTradingFee(o,i)}parseTradingFee(e,t){let i=this.safeString(e,"instrument_id");return{info:e,symbol:this.safeSymbol(i,t),maker:this.safeNumber(e,"maker_fee_rate"),taker:this.safeNumber(e,"taker_fee_rate"),percentage:void 0,tierBased:void 0}}async fetchPositions(e,t={}){let i,s,r,o;void 0===this.markets&&await this.loadMarkets();let n=this.marketSymbols(e),d={};if(void 0!==n){let e;if(Array.isArray(n)){if(n.length>1)throw new a.BadRequest(this.id+" fetchPositions() symbols argument cannot contain more than 1 symbol");e=n[0]}else e=n;i=this.market(e)}[s,r]=this.handleMarketTypeAndParams("fetchPositions",i,t);let[h,c]=this.handleMarginModeAndParams("fetchPositions",r);if(void 0!==h&&(s="margin"),void 0!==i){let e="symbol";"swap"===s&&(e="instrument_id"),d[e]=i.id}if("spot"===s||"margin"===s)o=await this.privateSpotGetMarginPositions(this.extend(d,c));else if("swap"===s)o=await this.privateSwapGetAccountPositions(this.extend(d,c));else throw new a.NotSupported(this.id+" fetchPositions() not support this market type");let l="positions";"swap"===s&&(l="data");let u=this.safeList(o,l,[]),f=[];for(let e=0;e<u.length;e++)f.push(this.parsePosition(u[e],i));return this.filterByArrayPositions(f,"symbol",n)}async fetchPosition(e,t={}){let i,s,r;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={};[i,s]=this.handleMarketTypeAndParams("fetchPosition",o,t);let[d,h]=this.handleMarginModeAndParams("fetchPosition",s);void 0!==d&&(i="margin");let c="symbol";if("swap"===i&&(c="instrument_id"),n[c]=o.id,"spot"===i||"margin"===i)r=await this.privateSpotGetMarginPositions(this.extend(n,h));else if("swap"===i)r=await this.privateSwapGetAccountPositions(this.extend(n,h));else throw new a.NotSupported(this.id+" fetchPosition() not support this market type");let l="positions";"swap"===i&&(l="data");let u=this.safeList(r,l,[]),f=this.parsePosition(u[0],o);return"swap"===i||(f.collateral=this.safeNumber(r,"margin"),f.marginRatio=this.safeNumber(r,"margin_rate")),f}parsePosition(e,t){let i=this.safeString2(e,"instrument_id","symbol"),s=this.safeMarket(i,t),r=s.symbol,a=this.safeString(e,"margin_mode");a=void 0!==a?"crossed"===a?"cross":"isolated":"crossed";let o=this.safeInteger(e,"timestamp"),n=this.safeString(e,"side");return"go_long"===n?n="long":"go_short"===n&&(n="short"),this.safePosition({info:e,id:void 0,symbol:r,notional:this.safeNumber(e,"amount"),marginMode:a,liquidationPrice:this.safeNumber(e,"liquidation_price"),entryPrice:this.safeNumber2(e,"avg_cost","entry_price"),unrealizedPnl:this.safeNumber(e,"unrealized_pnl"),contracts:this.safeNumber(e,"avail_position"),contractSize:this.safeNumber(s,"contractSize"),markPrice:this.safeNumber(e,"last"),side:n,hedged:void 0,timestamp:o,datetime:this.iso8601(o),maintenanceMargin:this.safeNumber(e,"margin"),maintenanceMarginPercentage:this.safeNumber(e,"maint_margin_ratio"),collateral:void 0,initialMargin:void 0,initialMarginPercentage:void 0,leverage:this.safeNumber2(e,"leverage","leverage_ratio"),marginRatio:this.safeNumber(e,"margin_ratio"),percentage:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}async setLeverage(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t);if("swap"!==s.type)throw new a.BadSymbol(this.id+" setLeverage() supports swap contracts only");if(e<1||e>100)throw new a.BadRequest(this.id+" leverage should be between 1 and 100");let r={instrument_id:s.id,leverage:e},o=this.safeString2(this.options,"marginMode","defaultMarginMode"),n=this.safeStringLower2(i,"marginMode","defaultMarginMode",o);void 0!==n&&(r.margin_mode=n="cross"===n?"crossed":"isolated");let d=[];void 0!==n&&(d.push("marginMode"),d.push("defaultMarginMode"));let h=this.safeString(i,"side"),c="isolated"===n;c&&(void 0!==h?r.side=h:this.checkRequiredArgument("setLeverage",h,"side",["long","short"])),c&&void 0!==h&&d.push("side");let l=this.omit(i,d);return await this.privateSwapPostAccountLeverage(this.extend(r,l))}async fetchTransfers(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o={};if(void 0!==e){if(void 0===(r=this.currency(e)))throw new a.ExchangeError(this.id+" fetchTransfers() could not resolve currency");o.currency=this.safeString(r,"id")}void 0!==t&&(o.start_timestamp=t),void 0!==i&&(o.limit=i);let n=await this.privateSwapGetAccountTransferRecord(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTransfers(d,r,t,i)}async fetchLeverageTiers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicSwapGetPublicInstruments(t),s=this.safeList(i,"data",[]),r=this.marketSymbols(e);return this.parseLeverageTiers(s,r,"instrument_id")}async fetchMarketLeverageTiers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new a.BadRequest(this.id+" fetchMarketLeverageTiers() supports swap markets only");let s={instrument_id:i.id},r=await this.publicSwapGetPublicInstrument(this.extend(s,t)),o=this.safeDict(r,"data",{});return this.parseMarketLeverageTiers(o,i)}parseMarketLeverageTiers(e,t){let i=[],s=this.safeList(e,"open_max_limits",[]),r=this.safeString(e,"instrument_id"),a=this.safeMarket(r,t);for(let e=0;e<s.length;e++){let t=this.safeDict(s,e);i.push({tier:this.sum(e,1),symbol:this.safeSymbol(r,a,void 0,"swap"),currency:a.settle,minNotional:void 0,maxNotional:this.safeNumber(t,"max_limit"),maintenanceMarginRate:void 0,maxLeverage:this.safeNumber(t,"leverage"),info:t})}return i}handleMarginModeAndParams(e,t={},i){let s=this.safeString(this.options,"defaultType"),r=this.safeBool(t,"margin",!1),[o,n]=super.handleMarginModeAndParams(e,t,i);if(void 0!==o){if("cross"!==o)throw new a.NotSupported(this.id+" only cross margin is supported")}else if("margin"===s||!0===r)return["cross",n];return[o,n]}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicSpotGetCurrencies(t),s=this.safeList(i,"data");return this.parseDepositWithdrawFees(s,e)}parseDepositWithdrawFees(e,t,i){let s={},r=this.marketCodes(t);for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),a=this.safeString(i,"currency"),o=this.safeCurrencyCode(a);if(void 0!==o&&(void 0===r||this.inArray(o,r))){void 0===this.safeDict(s,o)&&(s[o]=this.depositWithdrawFee({}),s[o].info=[]),s[o].info.push(i);let e=this.safeString(i,"chain"),t=this.safeValue(i,"min_withdraw_fee"),r={fee:t,percentage:void 0===t&&void 0},a={fee:void 0,percentage:void 0};if(void 0!==e){let t=this.networkIdToCode(e,o);void 0!==t&&(s[o].networks[t]={withdraw:r,deposit:a})}else s[o].withdraw=r,s[o].deposit=a}}let a=Object.keys(s);for(let e=0;e<a.length;e++){let t=a[e],i=this.currency(t);s[t]=this.assignDefaultDepositWithdrawFees(s[t],i)}return s}async addMargin(e,t,i={}){let s=this.safeString(i,"side");return this.checkRequiredArgument("addMargin",s,"side",["long","short"]),await this.modifyMarginHelper(e,t,1,i)}async reduceMargin(e,t,i={}){let s=this.safeString(i,"side");return this.checkRequiredArgument("reduceMargin",s,"side",["long","short"]),await this.modifyMarginHelper(e,t,2,i)}async modifyMarginHelper(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.safeString(s,"side"),a=this.market(e),o={instrument_id:a.id,amount:this.numberToString(t),type:i,side:r},n=await this.privateSwapPostAccountPositionMargin(this.extend(o,s)),d=this.safeInteger(n,"code"),h="failed";0===d&&(h="ok");let c=this.safeDict(n,"data",{});return this.extend(this.parseMarginModification(c,a),{status:h})}parseMarginModification(e,t){let i=this.safeString(e,"instrument_id"),s=this.safeInteger(e,"type");return{info:e,symbol:this.safeSymbol(i,t,void 0,"swap"),type:1===s?"add":"reduce",marginMode:"isolated",amount:this.safeNumber(e,"amount"),total:void 0,code:this.safeString(t,"settle"),status:void 0,timestamp:void 0,datetime:void 0}}async fetchFundingHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleUntilOption("end_timestamp",{},s);void 0!==e&&(a.instrument_id=(r=this.market(e)).id),void 0!==i&&(a.limit=i),void 0!==t&&(a.start_timestamp=t);let n=await this.privateSwapGetAccountFundingFee(this.extend(a,o)),d=this.safeList(n,"data",[]);return this.parseIncomes(d,r,t,i)}parseIncome(e,t){let i=this.safeString(e,"instrument_id"),s=this.safeString(e,"currency"),r=this.safeInteger(e,"timestamp");return{info:e,symbol:this.safeSymbol(i,t,void 0,"swap"),code:this.safeCurrencyCode(s),timestamp:r,datetime:this.iso8601(r),id:void 0,amount:this.safeNumber(e,"amount")}}async setMarginMode(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r=e.toLowerCase(),o={instrument_id:s.id,margin_mode:"cross"===r?"crossed":r};return await this.privateSwapPostAccountPositionMode(this.extend(o,i))}sign(e,t=[],i="GET",r={},o,n){let d,h="private"===this.safeString(t,0),c=this.safeString(t,1),l="/swap/v2";"spot"===c&&(l="/v3");let u=l+"/"+this.implodeParams(e,r),f=this.safeString(this.urls.api,"rest");if(void 0===f)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let p=f+u,m=this.omit(r,this.extractParams(e));if(d=h&&"/swap/v2"===l&&"POST"===i?JSON.stringify(r):this.urlencode(this.keysort(m)),h){let e,t;"/swap/v2"===l?(e=(t=this.milliseconds().toString())+i+u,"GET"===i?void 0!==d&&""!==d&&(e+="?"+d):"POST"===i&&(e+=d)):(t=this.nonce().toString(),e=d);let r=this.hmac(this.encode(e),this.encode(this.secret),s.sc);"GET"===i&&void 0!==d&&""!==d&&(p+="?"+d);let a=n;return"POST"===i&&void 0!==d&&""!==d&&(a=d),{url:p,method:i,body:a,headers:{"ACCESS-KEY":this.apiKey,"ACCESS-SIGN":r,"ACCESS-TIMESTAMP":t}}}return void 0!==d&&""!==d&&(p+="?"+d),{url:p,method:i,body:n,headers:o}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"code");if("0"===c||"200"===c)return;let l=this.id+" "+o;if(void 0===c)throw new a.BadResponse(l);let u=[a.ExchangeError,l],[f,p]=this.safeValue(this.exceptions.exact,c,u);throw new f(p)}}i.d(t,{A:()=>n})},3397(e,t,i){"use strict";var s=i(6834),r=i(6885),a=i(6760),o=i(1453),n=i(7749),d=i(1093);class h extends a.A{describe(){return this.deepExtend(super.describe(),{id:"dydx",name:"dYdX",countries:["US"],rateLimit:100,version:"v4",certified:!1,dex:!0,pro:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!1,option:!1,addMargin:!1,cancelAllOrders:!1,cancelAllOrdersAfter:!1,cancelOrder:!0,cancelOrders:!0,cancelWithdraw:!1,closeAllPositions:!1,closePosition:!1,createConvertTrade:!1,createDepositAddress:!1,createMarketBuyOrderWithCost:!1,createMarketOrder:!1,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!1,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopLossOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,createTakeProfitOrder:!1,createTrailingAmountOrder:!1,createTrailingPercentOrder:!1,createTriggerOrder:!1,fetchAccounts:!0,fetchBalance:!0,fetchCanceledOrders:!1,fetchClosedOrder:!1,fetchClosedOrders:!0,fetchConvertCurrencies:!1,fetchConvertQuote:!1,fetchConvertTrade:!1,fetchConvertTradeHistory:!1,fetchCurrencies:!1,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchIndexOHLCV:!1,fetchLedger:!0,fetchLeverage:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyTrades:!1,fetchOHLCV:!0,fetchOpenInterestHistory:!1,fetchOpenOrder:!1,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchOrderTrades:!1,fetchPosition:!0,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsHistory:!1,fetchPremiumIndexOHLCV:!1,fetchStatus:!1,fetchTicker:!1,fetchTickers:!1,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTransactions:!1,fetchTransfers:!0,fetchWithdrawals:!0,reduceMargin:!1,sandbox:!1,setLeverage:!1,setMargin:!1,setPositionMode:!1,transfer:!0,withdraw:!0},timeframes:{"1m":"1MIN","5m":"5MINS","15m":"15MINS","30m":"30MINS","1h":"1HOUR","4h":"4HOURS","1d":"1DAY"},urls:{logo:"https://github.com/user-attachments/assets/def0a54a-020a-4286-ba95-0f84e50a944d",api:{indexer:"https://indexer.dydx.trade/v4",nodeRpc:"https://dydx-ops-rpc.kingnodes.com",nodeRest:"https://dydx-rest.publicnode.com"},test:{indexer:"https://indexer.v4testnet.dydx.exchange/v4",nodeRpc:"https://test-dydx-rpc.kingnodes.com",nodeRest:"https://test-dydx-rest.kingnodes.com"},www:"https://www.dydx.xyz",doc:["https://docs.dydx.xyz"],fees:["https://docs.dydx.exchange/introduction-trading_fees"],referral:"https://dydx.trade?ref=ccxt"},api:{indexer:{get:{"addresses/{address}":{cost:1},"addresses/{address}/parentSubaccountNumber/{number}":{cost:1},"addresses/{address}/subaccountNumber/{subaccountNumber}":{cost:1},assetPositions:{cost:1},"assetPositions/parentSubaccountNumber":{cost:1},"candles/perpetualMarkets/{market}":{cost:1},"compliance/screen/{address}":{cost:1},fills:{cost:1},"fills/parentSubaccountNumber":{cost:1},fundingPayments:{cost:1},"fundingPayments/parentSubaccount":{cost:1},height:{cost:.1},"historical-pnl":{cost:1},"historical-pnl/parentSubaccountNumber":{cost:1},"historicalBlockTradingRewards/{address}":{cost:1},"historicalFunding/{market}":{cost:1},"historicalTradingRewardAggregations/{address}":{cost:1},"orderbooks/perpetualMarket/{market}":{cost:1},orders:{cost:1},"orders/parentSubaccountNumber":{cost:1},"orders/{orderId}":{cost:1},perpetualMarkets:{cost:1},perpetualPositions:{cost:1},"perpetualPositions/parentSubaccountNumber":{cost:1},screen:{cost:1},sparklines:{cost:1},time:{cost:1},"trades/perpetualMarket/{market}":{cost:1},transfers:{cost:1},"transfers/between":{cost:1},"transfers/parentSubaccountNumber":{cost:1},"vault/v1/megavault/historicalPnl":{cost:1},"vault/v1/megavault/positions":{cost:1},"vault/v1/vaults/historicalPnl":{cost:1},perpetualMarketSparklines:{cost:1},"perpetualMarkets/{ticker}":{cost:1},"perpetualMarkets/{ticker}/orderbook":{cost:1},"trades/perpetualMarket/{ticker}":{cost:1},"historicalFunding/{ticker}":{cost:1},"candles/{ticker}/{resolution}":{cost:1},"addresses/{address}/subaccounts":{cost:1},"addresses/{address}/subaccountNumber/{subaccountNumber}/assetPositions":{cost:1},"addresses/{address}/subaccountNumber/{subaccountNumber}/perpetualPositions":{cost:1},"addresses/{address}/subaccountNumber/{subaccountNumber}/orders":{cost:1},"fills/parentSubaccount":{cost:1},"historical-pnl/parentSubaccount":{cost:1},pnl:{cost:1},"pnl/parentSubaccountNumber":{cost:1},tradeHistory:{cost:1},"tradeHistory/parentSubaccountNumber":{cost:1}},post:{"turnkey/signin":{cost:1},"turnkey/uploadAddress":{cost:1}}},nodeRpc:{get:{abci_info:{cost:1},block:{cost:1},broadcast_tx_async:{cost:1},broadcast_tx_sync:{cost:1},tx:{cost:1}}},nodeRest:{get:{"cosmos/auth/v1beta1/account_info/{dydxAddress}":{cost:1}},post:{"cosmos/tx/v1beta1/encode":{cost:1},"cosmos/tx/v1beta1/simulate":{cost:1}}}},fees:{trading:{tierBased:!0,percentage:!0,maker:this.parseNumber("0.0001"),taker:this.parseNumber("0.0005")}},requiredCredentials:{apiKey:!1,secret:!1,privateKey:!1},options:{privateKey:void 0,chainName:"dydx-mainnet-1",chainId:1,sandboxMode:!1,defaultFeeDenom:"uusdc",defaultFeeMultiplier:"1.6",feeDenom:{USDC_DENOM:"ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",USDC_GAS_DENOM:"uusdc",USDC_DECIMALS:6,USDC_GAS_PRICE:"0.025",CHAINTOKEN_DENOM:"adydx",CHAINTOKEN_DECIMALS:18,CHAINTOKEN_GAS_PRICE:"25000000000"}},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:{last:!0,mark:!0,index:!1},triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!0},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:500,daysBack:90,untilDays:1e4,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!0,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:500,trigger:!0,trailing:!0,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:500,daysBack:void 0,untilDays:1e5,trigger:!0,trailing:!0,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:500,daysBack:void 0,daysBackCanceled:void 0,untilDays:1e5,trigger:!0,trailing:!0,symbolRequired:!1},fetchOHLCV:{limit:1e3}},forSwap:{extends:"default",createOrder:{hedged:!0}},swap:{linear:{extends:"forSwap"},inverse:void 0},future:{linear:void 0,inverse:void 0}},commonCurrencies:{},exceptions:{exact:{9:o.InvalidOrder,10:o.InvalidOrder,11:o.InvalidOrder,12:o.InvalidOrder,13:o.InvalidOrder,14:o.InvalidOrder,15:o.InvalidOrder,16:o.InvalidOrder,17:o.InvalidOrder,18:o.InvalidOrder,19:o.InvalidOrder,20:o.InvalidOrder,21:o.InvalidOrder,22:o.InvalidOrder,23:o.InvalidOrder,24:o.InvalidOrder,25:o.InvalidOrder,26:o.InvalidOrder,27:o.InvalidOrder,28:o.InvalidOrder,29:o.InvalidOrder,30:o.InvalidOrder,31:o.InvalidOrder,32:o.InvalidOrder,33:o.InvalidOrder,34:o.InvalidOrder,35:o.InvalidOrder,36:o.InvalidOrder,37:o.InvalidOrder,39:o.InvalidOrder,40:o.InvalidOrder,41:o.InvalidOrder,42:o.InvalidOrder,43:o.InvalidOrder,44:o.InvalidOrder,45:o.InvalidOrder,46:o.InvalidOrder,47:o.InvalidOrder,48:o.InvalidOrder,49:o.InvalidOrder,50:o.InvalidOrder,1e3:o.BadRequest,1001:o.BadRequest,1002:o.BadRequest,1003:o.InvalidOrder,1004:o.InvalidOrder,1005:o.InvalidOrder,1006:o.InvalidOrder,1007:o.InvalidOrder,1008:o.InvalidOrder,1009:o.InvalidOrder,1010:o.InvalidOrder,1011:o.InvalidOrder,1012:o.InvalidOrder,1013:o.InvalidOrder,1014:o.InvalidOrder,1015:o.InvalidOrder,1017:o.InvalidOrder,1018:o.InvalidOrder,1019:o.InvalidOrder,1020:o.InvalidOrder,1021:o.InvalidOrder,1022:o.InvalidOrder,2e3:o.InvalidOrder,2001:o.InvalidOrder,2002:o.InvalidOrder,2003:o.InvalidOrder,2004:o.InvalidOrder,2005:o.InvalidOrder,3e3:o.InvalidOrder,3001:o.InvalidOrder,3002:o.InvalidOrder,3003:o.InvalidOrder,3004:o.InvalidOrder,3005:o.InvalidOrder,3006:o.InvalidOrder,3007:o.InvalidOrder,3008:o.InvalidOrder,3009:o.InvalidOrder,3010:o.InvalidOrder,4e3:o.InvalidOrder,4001:o.InvalidOrder,4002:o.InvalidOrder,4003:o.InvalidOrder,4004:o.InvalidOrder,4005:o.InvalidOrder,4006:o.InvalidOrder,4007:o.InvalidOrder,4008:o.InvalidOrder,5e3:o.InvalidOrder,5001:o.InvalidOrder,6e3:o.InvalidOrder,6001:o.InvalidOrder,6002:o.InvalidOrder,9e3:o.InvalidOrder,9001:o.InvalidOrder,9002:o.InvalidOrder,9003:o.InvalidOrder,1e4:o.InvalidOrder,10001:o.InvalidOrder,11e3:o.InvalidOrder},broad:{"insufficient funds":o.InsufficientFunds}},precisionMode:4})}async fetchTime(e={}){let t=await this.indexerGetTime(e);return this.safeInteger(t,"epoch")}parseMarket(e){let t="USDC",i=this.safeString(e,"ticker");if(void 0===i)throw new o.ExchangeError(this.id+" parseMarket() missing marketId");let s=i.split("-"),r=this.safeString(s,0),a=this.safeString(e,"baseId",r),n=this.safeCurrencyCode(a),d=this.safeCurrencyCode(t);if(void 0===n||void 0===d)return;let h="USDC",c=this.safeCurrencyCode(h),l=this.safeString(e,"stepSize"),u=this.safeString(e,"tickSize"),f=this.safeString(e,"status"),p=!0;return"ACTIVE"!==f&&(p=!1),this.safeMarketStructure({id:this.safeString(e,"ticker"),symbol:n+"/"+d+":"+c,base:n,quote:d,settle:c,baseId:a,baseName:r,quoteId:t,settleId:h,type:"swap",spot:!1,margin:void 0,swap:!0,future:!1,option:!1,active:p,contract:!0,contractSize:this.parseNumber("1"),linear:!0,inverse:!1,taker:void 0,maker:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(l),price:this.parseNumber(u)},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:e})}async fetchMarkets(e={}){let t=await this.indexerGetPerpetualMarkets(this.extend({},e)),i=Object.values(this.safeDict(t,"markets",{}));return this.parseMarkets(i)}parseTrade(e,t){let i=this.parse8601(this.safeString(e,"createdAt")),s=this.safeString(t,"symbol"),r=this.safeString(e,"price"),a=this.safeString(e,"size"),o=this.safeStringLower(e,"side"),n=this.safeString(e,"id");return this.safeTrade({id:n,timestamp:i,datetime:this.iso8601(i),symbol:s,side:o,price:r,amount:a,cost:void 0,order:void 0,takerOrMaker:void 0,type:void 0,fee:void 0,info:e},t)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={market:r.id};void 0!==i&&(a.limit=Math.min(i,1e3));let o=await this.indexerGetTradesPerpetualMarketMarket(this.extend(a,s)),n=this.safeList(o,"trades",[]);return this.parseTrades(n,r,t,i)}parseOHLCV(e,t){return[this.parse8601(this.safeString(e,"startedAt")),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"baseTokenVolume")]}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={market:a.id,resolution:this.safeString(this.timeframes,t,t)};void 0!==s&&(o.limit=Math.min(s,1e3)),void 0!==i&&(o.fromIso=this.iso8601(i));let n=this.safeInteger(r,"until"),d=this.omit(r,"until");void 0!==n&&(o.toIso=this.iso8601(n));let h=await this.indexerGetCandlesPerpetualMarketsMarket(this.extend(o,d)),c=this.safeList(h,"candles",[]);return this.parseOHLCVs(c,a,t,i,s)}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={market:r.id};void 0!==i&&(a.limit=i);let n=this.safeInteger(s,"until");void 0!==n&&(a.effectiveBeforeOrAt=this.iso8601(n));let d=await this.indexerGetHistoricalFundingMarket(this.extend(a,s)),h=[],c=this.safeList(d,"historicalFunding",[]);for(let e=0;e<c.length;e++){let t=c[e],i=this.parse8601(this.safeString(t,"effectiveAt")),s=this.safeString(t,"ticker");h.push({info:t,symbol:this.safeSymbol(s,r),fundingRate:this.safeNumber(t,"rate"),timestamp:i,datetime:this.iso8601(i)})}let l=this.sortBy(h,"timestamp");return this.filterBySymbolSinceLimit(l,e,t,i)}handlePublicAddress(e,t){let[i,s]=this.handleOptionStringAndParams(t,e,"user"),[r,a]=this.handleOptionStringAndParams(s,e,"address",i);if(void 0!==r&&""!==r)return[r,a];if(void 0!==this.walletAddress&&""!==this.walletAddress)return[this.walletAddress,a];throw new o.ArgumentsRequired(this.id+" "+e+"() requires a user parameter inside 'params' or the walletAddress set")}parseOrder(e,t){let i=this.parseOrderStatus(this.safeStringUpper(e,"status")),s=this.safeString(e,"ticker"),r=this.safeSymbol(s,t),a=this.safeString(e,"totalFilled"),o=this.parse8601(this.safeString(e,"updatedAt")),n=this.safeString(e,"price"),d=this.safeString(e,"size"),h=this.parseOrderType(this.safeStringUpper(e,"type")),c=this.safeStringLower(e,"side"),l=this.safeStringUpper(e,"timeInForce");return this.safeOrder({info:e,id:this.safeString(e,"id"),clientOrderId:this.safeString(e,"clientId"),timestamp:o,datetime:this.iso8601(o),lastTradeTimestamp:void 0,lastUpdateTimestamp:o,symbol:r,type:h,timeInForce:l,postOnly:this.safeBool(e,"postOnly"),reduceOnly:this.safeBool(e,"reduceOnly"),side:c,price:n,triggerPrice:void 0,amount:d,cost:void 0,average:void 0,filled:a,remaining:void 0,status:i,fee:void 0,trades:void 0},t)}parseOrderStatus(e){return this.safeString({UNTRIGGERED:"open",OPEN:"open",FILLED:"closed",CANCELED:"canceled",BEST_EFFORT_CANCELED:"canceling"},e,e)}parseOrderType(e){return this.safeStringUpper({LIMIT:"LIMIT",STOP_LIMIT:"LIMIT",TAKE_PROFIT_LIMIT:"LIMIT",MARKET:"MARKET",STOP_MARKET:"MARKET",TAKE_PROFIT_MARKET:"MARKET",TRAILING_STOP:"MARKET"},e,e)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.indexerGetOrdersOrderId(this.extend({orderId:e},i));return this.parseOrder(s)}async fetchOrders(e,t,i,s={}){let r,[a,o]=this.handlePublicAddress("fetchOrders",s),[n,d]=this.handleOptionStringAndParams(o,"fetchOrders","subAccountNumber","0");void 0===this.markets&&await this.loadMarkets();let h={address:a,subaccountNumber:n};void 0!==e&&(h.ticker=(r=this.market(e)).id),void 0!==i&&(h.limit=i);let c=await this.indexerGetOrders(this.extend(h,d));return this.parseOrders(c,r,t,i)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({status:"OPEN"},s))}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({status:"FILLED"},s))}parsePosition(e,t){let i=this.safeString(e,"market"),s=this.safeMarket(i,t).symbol,r=this.safeStringLower(e,"side"),a=this.safeString(e,"size");"long"!==r&&(a=n.A.stringMul("-1",a));let o=this.parse8601(this.safeString(e,"createdAt"));return this.safePosition({info:e,id:void 0,symbol:s,entryPrice:this.safeNumber(e,"entryPrice"),markPrice:void 0,notional:void 0,collateral:void 0,unrealizedPnl:this.safeNumber(e,"unrealizedPnl"),side:r,contracts:this.parseNumber(a),contractSize:void 0,timestamp:o,datetime:this.iso8601(o),hedged:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,initialMargin:void 0,initialMarginPercentage:void 0,leverage:void 0,liquidationPrice:void 0,marginRatio:void 0,marginMode:void 0,percentage:void 0})}async fetchPosition(e,t={}){let i=await this.fetchPositions([e],t);return this.safeDict(i,0,{})}async fetchPositions(e,t={}){let[i,s]=this.handlePublicAddress("fetchPositions",t),[r,a]=this.handleOptionStringAndParams(s,"fetchPositions","subAccountNumber","0");void 0===this.markets&&await this.loadMarkets();let o=await this.indexerGetPerpetualPositions(this.extend({address:i,subaccountNumber:r,status:"OPEN"},a)),n=this.safeList(o,"positions",[]);return this.parsePositions(n,e)}hashMessage(e){return this.hash(e,s.lY,"hex")}signHash(e,t){let i=(0,d.h1)(e.slice(-64),t.slice(-64),r.bI,void 0),s=i.r,a=i.s;return{r:s.padStart(64,"0"),s:a.padStart(64,"0"),v:this.sum(27,i.v)}}signMessage(e,t){return this.signHash(this.hashMessage(e),t.slice(-64))}signOnboardingAction(){let e=this.safeInteger(this.options,"chainId"),t=this.ethEncodeStructuredData({chainId:e,name:"dYdX Chain"},{dYdX:[{name:"action",type:"string"}]},{action:"dYdX Chain Onboarding"});if(void 0===this.privateKey||""===this.privateKey)throw new o.ArgumentsRequired(this.id+" signOnboardingAction() requires a privateKey to be set.");return this.signMessage(t,this.privateKey)}signDydxTx(e,t,i,s,r,a,o){let[n,d]=this.encodeDydxTxForSigning(t,i,s,r,a,o),h=this.signHash(n,e);return this.encodeDydxTxRaw(d,h.r+h.s)}retrieveCredentials(){let e=this.safeDict(this.options,"dydxCredentials");if(void 0!==e)return e;let t=this.safeString(this.options,"privateKey");if(void 0===t){let e=this.signOnboardingAction();t=this.hashMessage(this.base16ToBinary(e.r+e.s))}return(e=this.retrieveDydxCredentials(t)).privateKey=this.binaryToBase16(e.privateKey),e.publicKey=this.binaryToBase16(e.publicKey),this.options.dydxCredentials=e,e}async fetchDydxAccount(){await this.loadDydxProtos();let e=this.safeDict(this.options,"dydxAccount");if(void 0!==e)return e;if(void 0===this.walletAddress)throw new o.ArgumentsRequired(this.id+" fetchDydxAccount() requires the walletAddress to be set using the dydx chain address eg: dydx1cpb4tedmwq304c2kc9pwzjwq0sc6z2a4tasxrz");if(!this.walletAddress.startsWith("dydx"))throw new o.ArgumentsRequired(this.id+" fetchDydxAccount() requires a valid dydx chain address, starting with dydx, not the l1 address.");let t={dydxAddress:this.walletAddress},i=await this.nodeRestGetCosmosAuthV1beta1AccountInfoDydxAddress(t),s=this.safeDict(i,"info",{});return s.pub_key={key:s.pub_key.key},this.options.dydxAccount=s,s}pow(e,t){let i=n.A.stringMul(e,"1"),s=this.parseToInt(t);for(let t=1;t<s;t++)i=n.A.stringMul(i,e);return i}createOrderRequest(e,t,i,s,r,a={}){let d,h,c;if(void 0===t)throw new o.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new o.ArgumentsRequired(this.id+" requires a side argument");let l=this.safeBool2(a,"reduceOnly","reduce_only",!1),u=t.toUpperCase(),f=this.market(e);if(void 0===i)throw new o.ArgumentsRequired(this.id+" createOrderRequest() requires a side argument");let p=i.toUpperCase(),[m,g]=this.handleOptionIntegerAndParams(a,"createOrder","subAccountId",0),v=this.safeString2(g,"triggerPrice","stopPrice"),y=this.safeValue(g,"stopLossPrice",v),b=this.safeValue(g,"takeProfitPrice"),w=void 0!==v||void 0!==y||void 0!==b,k=this.safeStringUpper(g,"timeInForce","GTT"),S=this.isPostOnly("MARKET"===u,void 0,g),O=this.amountToPrecision(e,s),T=this.priceToPrecision(e,r),P=this.safeDict(f,"info",{}),I=P.atomicResolution,A=this.pow("10",n.A.stringNeg(I)),x=n.A.stringMul(O,A),M=P.quantumConversionExponent,_=this.pow("10",n.A.stringSub(n.A.stringSub(I,M),"-6")),C=n.A.stringMul(T,_),B=0,E=0,R="0";if("FOK"===k)throw new o.InvalidOrder(this.id+" timeInForce fok has been deprecated");if("MARKET"===u)d=0,B=1,void 0!==k&&(h=1);else if("LIMIT"===u)if("GTT"===k)d=64,h=2*!!S;else if(d=0,"IOC"===k)h=1;else throw new o.InvalidOrder("unexpected code path: timeInForce");w&&(d=32,void 0!==y?(E=1,R=this.priceToPrecision(e,y)):void 0!==b&&(E=2,R=this.priceToPrecision(e,b)),R=n.A.stringMul(R,_));let L=this.safeInteger(g,"latestBlockHeight"),N=this.safeInteger(g,"goodTillBlock"),[D,q]=this.handleOptionIntegerAndParams(g,"createOrder","goodTillBlockTimeInSeconds",2592e3);if(0===d){if(void 0===N){if(void 0===L)throw new o.ExchangeError(this.id+" method() missing latestBlockHeight");N=L+20}}else{if(void 0===D)throw new o.ArgumentsRequired("goodTillBlockTimeInSeconds is required.");c=this.seconds()+D}let F=this.randNumber(9),V=this.safeInteger(q,"clientOrderId",F),G={order:{orderId:{subaccountId:{owner:this.getWalletAddress(),number:m},clientId:V,orderFlags:d,clobPairId:P.clobPairId},side:"BUY"===p?1:2,quantums:this.toDydxLong(x),subticks:this.toDydxLong(C),goodTilBlock:N,goodTilBlockTime:c,timeInForce:h,reduceOnly:l,clientMetadata:B,conditionType:E,conditionalOrderTriggerSubticks:this.toDydxLong(R),orderRouterAddress:this.safeString(this.options,"routerAddress","dydx165sfn2k3vucvq7gklauy2r3agyjw4c3m60ascn")}},H=this.omit(q,["reduceOnly","reduce_only","clientOrderId","postOnly","timeInForce","stopPrice","triggerPrice","stopLoss","takeProfit","latestBlockHeight","goodTillBlock","goodTillBlockTimeInSeconds","subaccountId"]),U=this.getWalletAddress(),W=this.safeInteger(P,"clobPairId",0),j=void 0===d?0:d;return[this.createOrderIdFromParts(U,void 0===m?0:m,void 0===V?0:V,j,void 0===W?0:W),this.extend({typeUrl:"/dydxprotocol.clob.MsgPlaceOrder",value:G},H)]}createOrderIdFromParts(e,t,i,s,r){let a=this.safeString(this.options,"namespace","0f9da948-a6fb-4c45-9edc-4685c3f3317d"),o=e+"-"+t.toString(),n=this.uuid5(a,o)+"-"+this.numberToString(i)+"-"+this.numberToString(r)+"-"+this.numberToString(s);return this.uuid5(a,n)}async fetchLatestBlockHeight(e={}){let t=await this.nodeRpcGetAbciInfo(e),i=this.safeDict(t,"result"),s=this.safeDict(i,"response"),r=this.safeInteger(s,"last_block_height");if(void 0===r)throw new o.ExchangeError(this.id+" fetchLatestBlockHeight() could not parse last_block_height");return r}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.retrieveCredentials(),n=await this.fetchDydxAccount(),d=await this.fetchLatestBlockHeight(),h=this.extend(a,{latestBlockHeight:d}),c=this.createOrderRequest(e,t,i,s,r,h),l=c[0],u=c[1],f=this.safeString(this.options,"chainName"),p=this.signDydxTx(o.privateKey,u,"",f,n,void 0),m=await this.nodeRpcGetBroadcastTxSync({tx:p}),g=this.safeDict(m,"result");return this.safeOrder({info:g,id:l,clientOrderId:u.value.order.orderId.clientId})}async cancelOrder(e,t,i={}){let s,r=this.safeBool2(i,"trigger","stop",!1),a=this.omit(i,["trigger","stop"]);if(!0!==r&&void 0===t)throw new o.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let n=this.market(t),d=this.safeString2(a,"clientOrderId","clientId",e);if(void 0===d)throw new o.ArgumentsRequired(this.id+" cancelOrder() requires a clientOrderId parameter, cancelling using id is not currently supported.");if(e.toString().indexOf("-")>-1)throw new o.NotSupported(this.id+" cancelOrder() cancelling using id is not currently supported, please use provide the clientOrderId parameter.");let h=this.safeInteger(a,"goodTillBlock"),[c,l]=this.handleOptionIntegerAndParams(a,"cancelOrder","goodTillBlockTimeInSeconds",2592e3),u=this.safeInteger(l,"orderFlags",!0===r?32:64),f=this.handleOptionIntegerAndParams(l,"cancelOrder","subAccountId",0)[0];if(0!==u&&64!==u&&32!==u)throw new o.InvalidOrder(this.id+" invalid orderFlags, allowed values are (0, 64, 32).");if(u>0){if(void 0===c)throw new o.ArgumentsRequired(this.id+" goodTillBlockTimeInSeconds is required in params for long term or conditional order.");if(void 0!==h&&h>0)throw new o.InvalidOrder(this.id+" goodTillBlock should be 0 for long term or conditional order.");s=this.seconds()+c}else void 0===h&&(h=await this.fetchLatestBlockHeight()+20);let p=this.retrieveCredentials(),m=await this.fetchDydxAccount(),g={orderId:{subaccountId:{owner:this.getWalletAddress(),number:f},clientId:d,orderFlags:u,clobPairId:n.info.clobPairId},goodTilBlock:h,goodTilBlockTime:s},v=this.safeString(this.options,"chainName"),y=this.signDydxTx(p.privateKey,{typeUrl:"/dydxprotocol.clob.MsgCancelOrder",value:g},"",v,m,void 0),b=await this.nodeRpcGetBroadcastTxSync({tx:y}),w=this.safeDict(b,"result");return this.safeOrder({info:w})}async cancelOrders(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r=this.safeList(i,"clientOrderIds");if(void 0===r)throw new o.NotSupported(this.id+" cancelOrders only support clientOrderIds.");let[a,n]=this.handleOptionIntegerAndParams(i,"cancelOrders","subAccountId",0),d=this.safeInteger(n,"goodTillBlock");void 0===d&&(d=await this.fetchLatestBlockHeight()+20);let h=this.retrieveCredentials(),c=await this.fetchDydxAccount(),l={clientIds:r,clobPairId:s.info.clobPairId},u={subaccountId:{owner:this.getWalletAddress(),number:a},shortTermCancels:[l],goodTilBlock:d},f=this.safeString(this.options,"chainName"),p=this.signDydxTx(h.privateKey,{typeUrl:"/dydxprotocol.clob.MsgBatchCancel",value:u},"",f,c,void 0),m=await this.nodeRpcGetBroadcastTxSync({tx:p}),g=this.safeDict(m,"result");return[this.safeOrder({info:g})]}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={market:s.id},a=await this.indexerGetOrderbooksPerpetualMarketMarket(this.extend(r,i));return this.parseOrderBook(a,s.symbol,void 0,"bids","asks","price","size")}parseLedgerEntry(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeCurrencyCode(s,t),a=this.safeCurrency(s,t),o=this.safeStringUpper(e,"type");void 0!==o&&("TRANSFER_IN"===o||"DEPOSIT"===o?i="in":("TRANSFER_OUT"===o||"WITHDRAWAL"===o)&&(i="out"));let n=this.safeString(e,"size"),d=this.parse8601(this.safeString(e,"createdAt")),h=this.safeDict(e,"sender"),c=this.safeDict(e,"recipient");return this.safeLedgerEntry({info:e,id:this.safeString(e,"id"),direction:i,account:this.safeString(h,"address"),referenceAccount:this.safeString(c,"address"),referenceId:this.safeString(e,"transactionHash"),type:this.parseLedgerEntryType(o),currency:r,amount:this.parseNumber(n),timestamp:d,datetime:this.iso8601(d),before:void 0,after:void 0,status:void 0,fee:void 0},a)}parseLedgerEntryType(e){return this.safeString({TRANSFER_IN:"transfer",TRANSFER_OUT:"transfer",DEPOSIT:"deposit",WITHDRAWAL:"withdrawal"},e,e)}async fetchLedger(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.currency(e));let a=await this.fetchTransactionsHelper(e,t,i,this.extend(s,{methodName:"fetchLedger"}));return this.parseLedger(a,r,t,i)}async estimateTxFee(e,t,i){let s,r,a=this.encodeDydxTxForSimulation(e,t,i.sequence,i.pub_key),d=await this.nodeRestPostCosmosTxV1beta1Simulate({txBytes:a}),h=this.safeDict(d,"gas_info");if(void 0===h)throw new o.ExchangeError(this.id+" failed to simulate transaction.");let c=this.safeString(h,"gas_used");if(void 0===c)throw new o.ExchangeError(this.id+" failed to simulate transaction.");let l=this.safeString(this.options,"defaultFeeDenom"),u=this.safeString(this.options,"defaultFeeMultiplier"),f=this.safeDict(this.options,"feeDenom",{});"uusdc"===l?(s=this.safeString(f,"USDC_GAS_PRICE"),r=this.safeString(f,"USDC_DENOM")):(s=this.safeString(f,"CHAINTOKEN_GAS_PRICE"),r=this.safeString(f,"CHAINTOKEN_DENOM"));let p=Math.ceil(this.parseToNumeric(n.A.stringMul(c,u))),m=n.A.stringMul(this.numberToString(p),s);if(void 0===m)throw new o.ExchangeError(this.id+" estimateTxFee() missing feeAmount");return m.indexOf(".")>=0&&(m=this.numberToString(Math.ceil(this.parseToNumeric(m)))),{amount:[{amount:m,denom:r}],gasLimit:p}}async transfer(e,t,i,s,r={}){let a;if("USDC"!==e)throw new o.NotSupported(this.id+" transfer() only support USDC");void 0===this.markets&&await this.loadMarkets();let d=this.safeInteger(r,"fromSubaccountId"),h=this.safeInteger(r,"toSubaccountId");if("main"!==i){if(void 0===i)throw new o.NotSupported(this.id+" transfer only support main > subaccount and subaccount <> subaccount.");if(void 0===d||void 0===h)throw new o.ArgumentsRequired(this.id+" transfer requires fromSubaccountId and toSubaccountId.")}let c=this.retrieveCredentials(),l=await this.fetchDydxAccount(),u=this.parseToInt(n.A.stringMul(this.numberToString(t),"1000000"));if("main"===i){if(void 0===h)throw new o.ArgumentsRequired(this.id+" transfer() requeire toSubaccoutnId.");a={typeUrl:"/dydxprotocol.sending.MsgDepositToSubaccount",value:{sender:this.getWalletAddress(),recipient:{owner:this.getWalletAddress(),number:h},assetId:0,quantums:u}}}else a={typeUrl:"/dydxprotocol.sending.MsgCreateTransfer",value:{transfer:{sender:{owner:i,number:d},recipient:{owner:s,number:h},assetId:0,amount:u}}};let f=await this.estimateTxFee(a,"",l),p=this.safeString(this.options,"chainName"),m=this.signDydxTx(c.privateKey,a,"",p,l,void 0,f),g=await this.nodeRpcGetBroadcastTxSync({tx:m});return this.parseTransfer(g)}parseTransfer(e,t){let i=this.safeString(e,"id"),s=this.safeString(e,"symbol"),r=this.safeCurrencyCode(s,t),a=this.safeNumber(e,"size"),o=this.safeDict(e,"sender"),n=this.safeDict(e,"recipient"),d=this.safeString(o,"address"),h=this.safeString(n,"address"),c=this.parse8601(this.safeString(e,"createdAt"));return{info:e,id:i,timestamp:c,datetime:this.iso8601(c),currency:r,amount:a,fromAccount:d,toAccount:h,status:void 0}}async fetchTransfers(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.currency(e));let a=await this.fetchTransactionsHelper(e,t,i,this.extend(s,{methodName:"fetchTransfers"})),o=this.filterBy(a,"type","TRANSFER_IN"),n=this.filterBy(a,"type","TRANSFER_OUT"),d=this.arrayConcat(o,n);return this.parseTransfers(d,r,t,i)}parseTransaction(e,t){let i=this.safeString(e,"id"),s=this.safeDict(e,"sender"),r=this.safeDict(e,"recipient"),a=this.safeString(r,"address"),o=this.safeString(s,"address"),n=this.safeString(e,"transactionHash"),d=this.safeString(e,"symbol"),h=this.safeCurrencyCode(d,t),c=this.parse8601(this.safeString(e,"createdAt")),l=this.safeNumber(e,"size");return{info:e,id:i,txid:n,timestamp:c,datetime:this.iso8601(c),network:void 0,address:a,addressTo:a,addressFrom:o,tag:void 0,tagTo:void 0,tagFrom:void 0,type:this.safeStringLower(e,"type"),amount:l,currency:h,status:void 0,updated:void 0,internal:void 0,comment:void 0,fee:void 0}}async withdraw(e,t,i,s,r={}){if("USDC"!==e)throw new o.NotSupported(this.id+" withdraw() only support USDC");void 0===this.markets&&await this.loadMarkets(),this.checkAddress(i);let a=this.safeInteger(r,"subaccountId");if(void 0===a)throw new o.ArgumentsRequired(this.id+" withdraw requires subaccountId.");let d=this.currency(e),h=this.retrieveCredentials(),c=await this.fetchDydxAccount(),l=this.parseToInt(n.A.stringMul(this.numberToString(t),"1000000")),u={typeUrl:"/dydxprotocol.sending.MsgWithdrawFromSubaccount",value:{sender:{owner:this.getWalletAddress(),number:a},recipient:i,assetId:0,quantums:l}},f=await this.estimateTxFee(u,s,c),p=this.safeString(this.options,"chainName"),m=this.signDydxTx(h.privateKey,u,s,p,c,void 0,f),g=await this.nodeRpcGetBroadcastTxSync({tx:m}),v=this.safeDict(g,"result",{});return this.parseTransaction(v,d)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.currency(e));let a=await this.fetchTransactionsHelper(e,t,i,this.extend(s,{methodName:"fetchWithdrawals"})),o=this.filterBy(a,"type","WITHDRAWAL");return this.parseTransactions(o,r,t,i)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.currency(e));let a=await this.fetchTransactionsHelper(e,t,i,this.extend(s,{methodName:"fetchDeposits"})),o=this.filterBy(a,"type","DEPOSIT");return this.parseTransactions(o,r,t,i)}async fetchDepositsWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.currency(e));let a=await this.fetchTransactionsHelper(e,t,i,this.extend(s,{methodName:"fetchDepositsWithdrawals"})),o=this.filterBy(a,"type","WITHDRAWAL"),n=this.filterBy(a,"type","DEPOSIT"),d=this.arrayConcat(o,n);return this.parseTransactions(d,r,t,i)}async fetchTransactionsHelper(e,t,i,s={}){let r=this.safeString(s,"methodName"),a=this.omit(s,"methodName"),[o,n]=this.handlePublicAddress(r,a),[d,h]=this.handleOptionStringAndParams(n,r,"subAccountNumber","0"),c=await this.indexerGetTransfers(this.extend({address:o,subaccountNumber:d},h));return this.safeList(c,"transfers",[])}async fetchAccounts(e={}){let[t,i]=this.handlePublicAddress("fetchAccounts",e),s=await this.indexerGetAddressesAddress(this.extend({address:t},i)),r=this.safeList(s,"subaccounts",[]),a=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.safeString(t,"subaccountNumber");a.push({id:i,type:void 0,currency:void 0,info:t,code:void 0})}return a}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handlePublicAddress("fetchBalance",e),[s,r]=this.handleOptionIntegerAndParams(i,"fetchBalance","subaccountNumber",0),a=await this.indexerGetAddressesAddressSubaccountNumberSubaccountNumber(this.extend({address:t,subaccountNumber:s},r)),o=this.safeDict(a,"subaccount");return this.parseBalance(o)}parseBalance(e){let t=this.account();return t.free=this.safeString(e,"freeCollateral"),this.safeBalance({info:e,USDC:t})}nonce(){let e=this.safeInteger(this.options,"timeDifference");if(void 0===e)throw new o.ExchangeError(this.id+' nonce() requires a numeric options["timeDifference"]');return this.milliseconds()-e}getWalletAddress(){if(void 0!==this.walletAddress&&""!==this.walletAddress)return this.walletAddress;let e=this.safeDict(this.options,"dydxAccount");if(void 0!==e){let t=this.safeString(e,"address");if(void 0!==t)return t}throw new o.ArgumentsRequired(this.id+" getWalletAddress() requires a wallet address. Set `walletAddress` or `dydxAccount` in exchange options.")}sign(e,t="public",i="GET",s={},r,a){let n,d,h=this.implodeParams(e,s),c=this.safeString(this.urls.api,t);if(void 0===c)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let l=c,u=this.omit(s,this.extractParams(e)),f=this.keysort(u);return l+="/"+h,"GET"===i?Object.keys(f).length>0&&(l+="?"+this.urlencode(f)):(d=this.json(f),n={"Content-type":"application/json"}),{url:l,method:i,body:void 0!==d?d:a,headers:void 0!==n?n:r}}handleErrors(e,t,i,s,r,a,n,d,h){if(null==n)return;let c=this.safeDict(n,"result"),l=this.safeString(c,"code");if((void 0===l||""===l)&&(l=this.safeString(n,"code")),void 0!==l&&""!==l&&this.parseToNumeric(l)>0){let e=this.id+" "+this.json(n);throw this.throwExactlyMatchedException(this.exceptions.exact,l,e),this.throwBroadlyMatchedException(this.exceptions.broad,a,e),new o.ExchangeError(e)}}setSandboxMode(e){super.setSandboxMode(e),this.options.chainName="dydx-testnet-4",this.options.chainId=0xaa36a7,this.options.feeDenom.CHAINTOKEN_DENOM="adv4tnt"}}i.d(t,{A:()=>h})},1223(e,t,i){"use strict";var s=i(3226),r=i(7749),a=i(1453);class o extends s.A{describe(){return this.deepExtend(super.describe(),{id:"extended",name:"Extended",countries:["SG"],version:"v2",rateLimit:600,precisionMode:4,certified:!1,pro:!0,dex:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,cancelAllOrders:!0,cancelAllOrdersAfter:!0,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!1,closePosition:!1,createConvertTrade:!1,createDepositAddress:!1,createMarketBuyOrderWithCost:!1,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!1,createOrderWithTakeProfitAndStopLoss:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopLossOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,createTakeProfitOrder:!1,createTrailingAmountOrder:!1,createTrailingPercentOrder:!1,createTriggerOrder:!1,editOrder:!0,fetchAccounts:!0,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchCanceledAndClosedOrders:!1,fetchCanceledOrders:!0,fetchClosedOrders:!0,fetchConvertCurrencies:!1,fetchConvertQuote:!1,fetchConvertTrade:!1,fetchConvertTradeHistory:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:!1,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!1,fetchDepositWithdrawFee:!1,fetchDepositWithdrawFees:!1,fetchFundingHistory:!0,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchIndexOHLCV:!0,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLedger:!0,fetchLeverage:!0,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMarkPrice:!1,fetchMyLiquidations:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrders:!0,fetchOrderTrades:!1,fetchPosition:!0,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsHistory:!0,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchStatus:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!1,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTransactions:!0,fetchTransfer:!1,fetchTransfers:!0,fetchWithdrawAddresses:!1,fetchWithdrawal:!1,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!0,setMargin:!1,setMarginMode:!1,setPositionMode:!1,signIn:!1,transfer:!0,withdraw:!0},features:{},timeframes:{"1m":"PT1M","5m":"PT5M","15m":"PT15M","30m":"PT30M","1h":"PT1H","2h":"PT2H","4h":"PT4H","8h":"PT8H","12h":"PT12H","1d":"PT24H","1w":"P7D","1M":"P30D"},hostname:"extended.exchange",urls:{logo:"https://github.com/user-attachments/assets/e2fe2bdf-6b28-4af8-b30f-38db496dc079",api:{rest:"https://api.starknet.{hostname}"},test:{rest:"https://api.starknet.sepolia.{hostname}"},www:"https://app.extended.exchange",doc:"https://api.docs.extended.exchange",fees:"https://docs.extended.exchange/extended-resources/trading/trading-fees-and-rebates",referral:""},api:{v1:{public:{get:{"info/markets":{cost:1},"info/assets":{cost:1},"info/assets/{asset}/price":{cost:1},"info/markets/{market}/stats":{cost:1},"info/markets/{market}/orderbook":{cost:1},"info/markets/{market}/trades":{cost:1},"info/candles/{market}/{candleType}":{cost:1},"info/{market}/funding":{cost:1},"info/{market}/open-interests":{cost:1},"info/builder/dashboard":{cost:1},"interest/info/rate-curves":{cost:1},"interest/info/latest-rate-curves":{cost:1}}},private:{get:{"user/accounts":{cost:1},"user/account/info":{cost:1},"user/balance":{cost:1},"user/spot/balances":{cost:1},"user/assetOperations":{cost:1},"user/positions":{cost:1},"user/positions/history":{cost:1},"user/orders":{cost:1},"user/orders/history":{cost:1},"user/orders/{id}":{cost:1},"user/orders/external/{externalId}":{cost:1},"user/trades":{cost:1},"user/funding/history":{cost:1},"user/rebates/stats":{cost:1},"user/leverage":{cost:1},"user/fees":{cost:1},"user/bridge/config":{cost:1},"user/bridge/quote":{cost:1},"user/affiliate":{cost:1},"user/referrals/status":{cost:1},"user/referrals/links":{cost:1},"user/referrals/dashboard":{cost:1},"user/rewards/earned":{cost:1},"user/rewards/leaderboard/stats":{cost:1},"portfolio/charts/equities":{cost:1},"portfolio/charts/pnl":{cost:1},"portfolio/charts/pnl/percentage":{cost:1},"portfolio/charts/pnl/cumulative":{cost:1},"portfolio/charts/pnl/cumulative/percentage":{cost:1},"portfolio/charts/vault-equities":{cost:1},"portfolio/charts/max-drawdown":{cost:1},"portfolio/charts/funding":{cost:1},"portfolio/accounts/summary":{cost:1},"portfolio/accounts/health":{cost:1},"portfolio/accounts/performance":{cost:1},"portfolio/funding/stats":{cost:1},"portfolio/funding/history":{cost:1},"vault/public/performance":{cost:1},"vault/public/summary":{cost:1},"builder/trades":{cost:1},"interest/key-metrics":{cost:1},"interest/daily-metrics":{cost:1},"interest/payment-chart":{cost:1},"interest/payments":{cost:1}},post:{"user/order":{cost:1},"user/order/rfq":{cost:1},"user/order/massCancel":{cost:1},"user/deadmanswitch":{cost:1},"user/bridge/quote":{cost:1},"user/withdrawal":{cost:1},"user/transfer":{cost:1},"user/referrals/use":{cost:1},"user/referrals":{cost:1}},put:{"user/referrals":{cost:1}},patch:{"user/leverage":{cost:1}},delete:{"user/order/{id}":{cost:1},"user/order":{cost:1}}}}},fees:{taker:this.parseNumber("0.002"),maker:this.parseNumber("0.002")},requiredCredentials:{apiKey:!0,secret:!1,privateKey:!0},exceptions:{exact:{1e3:a.InvalidOrder,1001:a.InvalidOrder,1002:a.InvalidOrder,1003:a.InvalidOrder,1004:a.InvalidOrder,1005:a.InvalidOrder,1006:a.ExchangeError,1008:a.InvalidOrder,1009:a.InvalidOrder,1010:a.ExchangeError,1011:a.InvalidOrder,1012:a.InvalidOrder,1013:a.InvalidOrder,1014:a.InvalidOrder,1049:a.InvalidOrder,1050:a.InvalidOrder,10501:a.InvalidOrder,1052:a.InvalidOrder,1053:a.InvalidOrder,1100:a.InvalidOrder,1101:a.InvalidOrder,1102:a.InvalidOrder,1120:a.InvalidOrder,1121:a.InvalidOrder,1122:a.InvalidOrder,1123:a.InvalidOrder,1124:a.InvalidOrder,1125:a.InvalidOrder,1126:a.InvalidOrder,1127:a.InvalidOrder,1128:a.InvalidOrder,1129:a.InvalidOrder,1130:a.InvalidOrder,1131:a.InvalidOrder,1132:a.InvalidOrder,1133:a.InvalidOrder,1134:a.InvalidOrder,1135:a.InvalidOrder,1136:a.InvalidOrder,1137:a.InvalidOrder,1138:a.InvalidOrder,1139:a.InvalidOrder,1140:a.InsufficientFunds,1141:a.InvalidOrder,1142:a.InvalidOrder,1143:a.InvalidOrder,1144:a.InvalidOrder,1145:a.InvalidOrder,1146:a.InvalidOrder,1147:a.InvalidOrder,1148:a.InvalidOrder,1500:a.InvalidOrder,1600:a.BadRequest,1601:a.BadRequest,1602:a.BadRequest,1604:a.BadRequest,1605:a.BadRequest,1607:a.BadRequest,1608:a.BadRequest,1650:a.BadRequest,1700:a.BadRequest,1701:a.BadRequest,1703:a.BadRequest,1704:a.BadRequest},broad:{}},options:{builderFee:!0,builderFeeRate:"0.0001",builderId:"257624"}})}async loadMarkets(e=!1,t={}){let i=await super.loadMarkets(e,t);return(void 0===this.safeDict(this.options,"currenciesByNumericId")||e)&&(this.options.currenciesByNumericId=this.indexByStringifiedNumericId(this.currencies)),i}indexByStringifiedNumericId(e){let t={};if(void 0===e)return;let i=Object.keys(e);for(let s=0;s<i.length;s++){let r=e[i[s]],a=this.safeString(r,"numericId");void 0!==a&&(t[a]=r)}return t}async fetchMarkets(e={}){let t=await this.v1PublicGetInfoMarkets(e),i=this.safeList(t,"data",[]);return this.parseMarkets(i)}parseMarket(e){let t,i,s,r,a,o=this.safeDict(e,"tradingConfig",{}),n=this.safeString(e,"name"),d=this.safeString(e,"assetName","");d.indexOf("SPOT")>=0&&(d=d.replace("SPOT",""));let h=this.safeString(e,"collateralAssetName"),c=this.safeCurrencyCode(d),l=this.safeCurrencyCode(h);if("USD"===h&&(l="USDC"),void 0===c||void 0===l)return;let u=this.safeString(e,"status"),f=this.safeNumber(o,"minOrderSizeChange"),p=this.safeNumber(o,"minPriceChange"),m=this.safeNumber(o,"maxLeverage"),g=this.safeNumber(o,"minOrderSize"),v=this.safeNumber(o,"maxLimitOrderValue"),y=this.safeInteger(e,"createdAt"),b=c+"/"+l,w=!1,k=this.safeStringLower(e,"type");return"spot"===k?w=!0:(k="swap",t=h,b+=":"+(i=l),s=this.parseNumber("1"),r=!0,a=!1),this.safeMarketStructure({id:n,symbol:b,base:c,quote:l,settle:i,baseId:d,quoteId:h,settleId:t,type:k,spot:w,margin:!1,swap:!w,future:!1,option:!1,active:"ACTIVE"===u,contract:!w,linear:r,inverse:a,taker:this.safeNumber(this.fees,"taker"),maker:this.safeNumber(this.fees,"maker"),contractSize:s,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:f,price:p},limits:{leverage:{min:this.parseNumber("1"),max:m},amount:{min:g,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:v}},created:y,info:e})}async fetchCurrencies(e={}){let t=await this.v1PublicGetInfoAssets(e),i=this.safeList(t,"data",[]);return this.parseCurrencies(i)}parseCurrency(e){let t=this.safeString(e,"symbol");void 0!==t&&t.indexOf("SPOT")>=0&&(t=t.replace("SPOT",""));let i=this.safeCurrencyCode(t);"USD"===t&&(i="USDC");let s=this.safeString(e,"name"),r=this.safeInteger(e,"precision",0),a=this.safeBool(e,"isActive");return this.safeCurrencyStructure({id:t,code:i,numericId:this.safeInteger(e,"id"),name:s,active:a,deposit:!0,withdraw:!0,precision:Math.pow(10,-1*r),type:"other",margin:this.safeBool(e,"canBeUsedAsCollateral"),info:e})}async fetchTicker(e,t={}){await this.loadMarkets();let i=this.market(e),s={market:i.id},r=await this.v1PublicGetInfoMarketsMarketStats(this.extend(s,t)),a=this.safeDict(r,"data",{});return this.parseTicker(a,i)}async fetchTickers(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e),s={};if(void 0!==i){let e=[];for(let t=0;t<i.length;t++){let s=this.market(i[t]);e.push(s.id)}s.market=e}let r=await this.v1PublicGetInfoMarkets(this.extend(s,t)),a=this.safeList(r,"data",[]),o={};for(let e=0;e<a.length;e++){let t=this.safeDict(a,e),i=this.safeString(t,"name"),s=this.safeMarket(i),r=this.safeDict(t,"marketStats",{}),n=this.parseTicker(r,s),d=n.symbol;void 0!==d&&(o[d]=n)}return this.filterByArrayTickers(o,"symbol",i)}parseTicker(e,t){let i=this.safeSymbol(void 0,t),s=this.safeNumber(e,"lastPrice"),a=this.safeString(e,"dailyPriceChangePercentage"),o=void 0!==a?r.Y.stringMul(a,"100"):void 0;return this.safeTicker({symbol:i,timestamp:void 0,datetime:void 0,high:this.safeNumber(e,"dailyHigh"),low:this.safeNumber(e,"dailyLow"),bid:this.safeNumber(e,"bidPrice"),bidVolume:void 0,ask:this.safeNumber(e,"askPrice"),askVolume:void 0,vwap:void 0,open:void 0,close:s,last:s,previousClose:void 0,change:this.safeNumber(e,"dailyPriceChange"),percentage:o,average:void 0,baseVolume:this.safeNumber(e,"dailyVolumeBase"),quoteVolume:this.safeNumber(e,"dailyVolume"),markPrice:this.safeNumber(e,"markPrice"),indexPrice:this.safeNumber(e,"indexPrice"),info:e},t)}async fetchOrderBook(e,t,i={}){await this.loadMarkets();let s=this.market(e),r={market:s.id},a=await this.v1PublicGetInfoMarketsMarketOrderbook(this.extend(r,i)),o=this.safeDict(a,"data",{}),n=this.milliseconds(),d=this.parseOrderBook(o,s.symbol,n,"bid","ask","price","qty");return void 0!==t&&(d.bids=this.arraySlice(d.bids,0,t),d.asks=this.arraySlice(d.asks,0,t)),d}async fetchTrades(e,t,i,s={}){await this.loadMarkets();let r=this.market(e),a={market:r.id},o=await this.v1PublicGetInfoMarketsMarketTrades(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTrades(n,r,t,i)}async fetchMyTrades(e,t,i,s={}){let r;await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchMyTrades",e,t,i,o,"cursor","cursor",void 0,100);let n={};void 0!==e&&(n.market=(r=this.market(e)).id),void 0!==i&&(n.limit=i);let d=await this.v1PrivateGetUserTrades(this.extend(o,n)),h=this.safeList(d,"data",[]),c=this.safeDict(d,"pagination",{}),l=this.safeString(c,"cursor"),u=[],f=h.length;for(let e=0;e<f;e++){let t=h[e];void 0!==l&&e===f-1&&(t=this.extend(t,{cursor:l})),u.push(t)}return this.parseTrades(u,r,t,i)}async fetchFundingHistory(e,t,i,s={}){let r;await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchFundingHistory","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchFundingHistory",e,t,i,o,"cursor","cursor",void 0,100);let n={};void 0!==e&&(n.market=(r=this.market(e)).id),void 0!==t&&(n.startTime=t),void 0!==i&&(n.limit=i);let d=await this.v1PrivateGetUserFundingHistory(this.extend(o,n)),h=this.safeList(d,"data",[]),c=this.safeDict(d,"pagination",{}),l=this.safeString(c,"cursor"),u=[],f=h.length;for(let e=0;e<f;e++){let t=h[e];void 0!==l&&e===f-1&&(t=this.extend(t,{cursor:l})),u.push(t)}return this.parseFundingHistories(u,r,t,i)}parseFundingHistory(e,t){let i=this.safeString(e,"market"),s=this.safeMarket(i,t),r=this.safeInteger(e,"paidTime");return{info:e,symbol:s.symbol,code:s.settle,timestamp:r,datetime:this.iso8601(r),id:this.safeString(e,"id"),amount:this.safeNumber(e,"fundingFee"),rate:this.safeNumber(e,"fundingRate")}}parseFundingHistories(e,t,i,s){let r=[];for(let i=0;i<e.length;i++)r.push(this.parseFundingHistory(e[i],t));let a=void 0===t?void 0:this.safeString(t,"symbol");return this.filterBySymbolSinceLimit(r,a,i,s)}parseTrade(e,t){let i,s=this.safeString2(e,"m","market"),r=this.safeMarket(s,t),a=this.safeInteger2(e,"T","createdTime"),o=this.safeString2(e,"p","price"),n=this.safeString2(e,"q","qty"),d=this.safeString2(e,"S","side"),h=void 0!==d?d.toLowerCase():void 0,c=this.safeString(e,"fee"),l=void 0===c?void 0:{cost:c,currency:void 0===r?void 0:r.settle},u=this.safeBool(e,"isTaker");return void 0!==u&&(i=u?"taker":"maker"),this.safeTrade({id:this.safeString2(e,"i","id"),info:e,timestamp:a,datetime:this.iso8601(a),symbol:r.symbol,order:this.safeString(e,"orderId"),type:void 0,side:h,takerOrMaker:i,price:o,amount:n,cost:this.safeString(e,"value"),fee:l},r)}async fetchOHLCV(e,t="1m",i,s,r={}){await this.loadMarkets();let a=this.market(e),o=this.safeString(r,"price"),n=this.safeString(r,"candleType");void 0===n&&(n="mark"===o?"mark-prices":"index"===o?"index-prices":"trades");let d=this.safeInteger(r,"until"),h=this.omit(r,["candleType","price","until"]),c={market:a.id,candleType:n,interval:this.safeString(this.timeframes,t,t),limit:void 0!==s?s:100};void 0!==d&&(c.endTime=d);let l=await this.v1PublicGetInfoCandlesMarketCandleType(this.extend(c,h)),u=this.safeList(l,"data",[]);return this.parseOHLCVs(u,a,t,i,s)}parseOHLCV(e,t){return[this.safeInteger(e,"T"),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");await this.loadMarkets();let[r,o]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(r)return await this.fetchPaginatedCallCursor("fetchFundingRateHistory",e,t,i,o,"cursor","cursor",void 0,1e4);let n=this.market(e),d=n.symbol,h=void 0===i?100:i,c=this.safeInteger(o,"until",this.milliseconds()),l=this.safeInteger(o,"endTime",c),u=this.omit(o,["endTime","until"]),f=void 0===t?l-60*h*6e4:t,p={market:n.id,startTime:f,endTime:l,limit:h},m=await this.v1PublicGetInfoMarketFunding(this.extend(p,u)),g=this.safeList(m,"data",[]),v=this.safeDict(m,"pagination",{}),y=this.safeString(v,"cursor"),b=[],w=g.length;for(let e=0;e<w;e++){let t=g[e];void 0!==y&&e===w-1&&(t=this.extend(t,{cursor:y})),b.push(this.parseFundingRateHistory(t,n))}let k=this.sortBy(b,"timestamp");return this.filterBySymbolSinceLimit(k,d,f,h)}parseFundingRateHistory(e,t){let i=this.safeString(e,"m"),s=this.safeMarket(i,t),r=this.safeInteger(e,"T");return{info:e,symbol:s.symbol,fundingRate:this.safeNumber(e,"f"),timestamp:r,datetime:this.iso8601(r)}}async fetchOpenInterestHistory(e,t="1h",i,s,r={}){await this.loadMarkets();let o=this.market(e),n=this.safeString(this.timeframes,t);if(!this.inArray(n,["PT1H","P1D"]))throw new a.BadRequest(this.id+" fetchOpenInterestHistory() supports 1h and 1d timeframes only");let d=void 0===s?100:s,h=this.safeInteger(r,"until",this.milliseconds()),c=this.safeInteger(r,"endTime",h),l=this.omit(r,["endTime","until"]),u=void 0===i?c-d*this.parseTimeframe(t)*1e3:i,f={market:o.id,interval:n,startTime:u,endTime:c,limit:d},p=await this.v1PublicGetInfoMarketOpenInterests(this.extend(f,l)),m=this.safeList(p,"data",[]);return this.parseOpenInterestsHistory(m,o,u,d)}parseOpenInterest(e,t){let i=this.safeInteger(e,"t");return this.safeOpenInterest({symbol:this.safeString(t,"symbol"),openInterestAmount:this.safeNumber(e,"I"),openInterestValue:this.safeNumber(e,"i"),baseVolume:this.safeNumber(e,"I"),quoteVolume:this.safeNumber(e,"i"),timestamp:i,datetime:this.iso8601(i),info:e},t)}async fetchBalance(e={}){await this.loadMarkets();let t=await this.v1PrivateGetUserSpotBalances(e),i=this.safeList(t,"data",[]);return this.parseBalance(i)}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i,{}),r=this.safeString(s,"asset"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(s,"availableToWithdraw"),o.total=this.safeString(s,"balance"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async fetchAccount(e={}){let t=await this.v1PrivateGetUserAccountInfo(e),i=this.safeDict(t,"data",{});return this.parseAccount(i)}async fetchAccounts(e={}){let t=await this.v1PrivateGetUserAccounts(e),i=this.safeList(t,"data",[]);return this.parseAccounts(i)}parseAccount(e){let t,i=this.safeInteger(e,"accountIndex");return void 0!==i&&(t=0===i?"main":"subaccount"),{id:this.safeString2(e,"accountId","id"),type:t,code:void 0,info:e}}async fetchLedger(e,t,i,s={}){let r;await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchLedger","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchLedger",e,t,i,o,"cursor","cursor",void 0,50);void 0!==e&&(r=this.currency(e));let n={};void 0!==i&&(n.limit=i);let d=await this.v1PrivateGetUserAssetOperations(this.extend(n,o)),h=this.safeList(d,"data",[]),c=this.safeDict(d,"pagination",{}),l=this.safeString(c,"cursor"),u=[],f=h.length;for(let e=0;e<f;e++){let t=h[e];void 0!==l&&e===f-1&&(t=this.extend(t,{cursor:l})),u.push(t)}return this.parseLedger(u,r,t,i)}parseLedgerEntry(e,t){let i,s,a=this.safeInteger(e,"time"),o=this.safeString(e,"asset"),n=this.getExtendedCurrencyCodeById(o,t),d=this.safeCurrency(n,t),h=this.safeString(e,"amount");void 0!==h&&(i=r.Y.stringLt(h,"0")?"out":"in");let c=this.safeString(e,"fee");return void 0!==c&&(s={currency:n,cost:this.parseNumber(r.Y.stringAbs(c))}),this.safeLedgerEntry({info:e,id:this.safeString(e,"id"),timestamp:a,datetime:this.iso8601(a),direction:i,account:this.safeString(e,"accountId"),referenceId:this.safeString(e,"transactionHash"),referenceAccount:this.safeString(e,"counterpartyAccountId"),type:this.parseTransactionType(this.safeString(e,"type")),currency:n,amount:void 0===h?void 0:this.parseNumber(r.Y.stringAbs(h)),before:void 0,after:void 0,status:this.parseTransactionStatus(this.safeString(e,"status")),fee:s},d)}async fetchTransactions(e,t,i,s={}){let r;await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchTransactions","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchTransactions",e,t,i,o,"cursor","cursor",void 0,50);void 0!==e&&(r=this.currency(e));let n={};void 0!==i&&(n.limit=i);let d=await this.v1PrivateGetUserAssetOperations(this.extend(n,o)),h=this.safeList(d,"data",[]),c=this.safeDict(d,"pagination",{}),l=this.safeString(c,"cursor"),u=[],f=h.length;for(let e=0;e<f;e++){let t=h[e];void 0!==l&&e===f-1&&(t=this.extend(t,{cursor:l})),u.push(t)}return this.parseTransactions(u,r,t,i)}async fetchDeposits(e,t,i,s={}){return await this.fetchTransactions(e,t,i,this.extend({type:"DEPOSIT"},s))}async fetchWithdrawals(e,t,i,s={}){return await this.fetchTransactions(e,t,i,this.extend({type:"WITHDRAWAL"},s))}async withdraw(e,t,i,s,r={}){this.checkRequiredCredentials(),await this.loadMarkets();let o=this.currency(e),n=this.safeStringUpper2(r,"chainId","network","STRK");if("STRK"!==n)throw new a.BadRequest(this.id+" withdraw() only supports Starknet withdrawals with chainId STRK");if(i.length<=42)throw new a.BadRequest(this.id+" withdraw() requires a Starknet address for STRK withdrawals, EVM withdrawals require the bridge quote flow");let d=await this.fetchExtendedAccount(),h=this.currencyToPrecision(e,t),c=this.safeString(d,"accountId"),l=this.createWithdrawalSettlementData(i,h,o,d,r),u={accountId:c,amount:h,chainId:n,asset:o.id,settlement:l},f=this.omit(r,["chainId","network","settlementExpiration","nonce","recipient","positionId","l2Vault","collateralId","resolution"]),p=await this.v1PrivatePostUserWithdrawal(this.extend(u,f)),m=this.milliseconds();return{info:p,id:this.safeString(p,"data"),txid:void 0,timestamp:m,datetime:this.iso8601(m),address:i,addressFrom:void 0,addressTo:i,tag:s,tagFrom:void 0,tagTo:s,type:"withdrawal",amount:this.parseNumber(h),currency:o.code,status:"pending",updated:m,fee:void 0,network:n,comment:void 0,internal:!1}}async fetchTransfers(e,t,i,s={}){let r;await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchTransfers","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchTransfers",e,t,i,o,"cursor","cursor",void 0,50);void 0!==e&&(r=this.currency(e));let n={type:"TRANSFER"};void 0!==i&&(n.limit=i);let d=await this.v1PrivateGetUserAssetOperations(this.extend(n,o)),h=this.safeList(d,"data",[]),c=this.safeDict(d,"pagination",{}),l=this.safeString(c,"cursor"),u=[],f=h.length;for(let e=0;e<f;e++){let t=h[e];void 0!==l&&e===f-1&&(t=this.extend(t,{cursor:l})),u.push(t)}return this.parseTransfers(u,r,t,i)}async transfer(e,t,i,s,r={}){this.checkRequiredCredentials(),await this.loadMarkets();let o=this.currency(e),n=await this.fetchExtendedAccount(),d=this.safeString(n,"accountId",""),h=void 0===i?d:i;if(h!==d)throw new a.BadRequest(this.id+" transfer() can only transfer from the authenticated account");let c=this.safeString2(r,"toVault","receiverPositionId"),l=this.safeString2(r,"toL2Key","receiverPublicKey");if(void 0===c||void 0===l)throw new a.ArgumentsRequired(this.id+' transfer() requires a toAccount argument and params["toVault"] and params["toL2Key"]');let u=this.currencyToPrecision(e,t),f=this.createTransferSettlementData(u,o,n,c,l,r),p={fromAccount:h,toAccount:s,amount:u,transferredAsset:o.id,settlement:f},m=this.omit(r,["fromVault","senderPositionId","fromL2Key","senderPublicKey","toVault","receiverPositionId","toL2Key","receiverPublicKey","settlementExpiration","nonce","assetId","collateralId","resolution"]),g=await this.v1PrivatePostUserTransfer(this.extend(p,m)),v=this.safeDict(g,"data",{}),y=this.safeBool(v,"validSignature"),b=this.milliseconds(),w="pending";return void 0!==y&&(w=y?"ok":"failed"),{info:g,id:this.safeString(v,"id"),timestamp:b,datetime:this.iso8601(b),currency:o.code,amount:this.parseNumber(u),fromAccount:h,toAccount:s,status:w}}parseTransfer(e,t){let i,s=this.safeInteger(e,"time"),a=this.safeString(e,"asset"),o=this.getExtendedCurrencyCodeById(a,t),n=this.safeString(e,"amount"),d=void 0===n?void 0:this.parseNumber(r.Y.stringAbs(n)),h=this.safeString(e,"accountId"),c=this.safeString(e,"counterpartyAccountId"),l=h,u=c;void 0===n||r.Y.stringLt(n,"0")||(l=c,u=h);let f=this.safeBool(e,"validSignature");return i=void 0!==f?f?"ok":"failed":this.parseTransactionStatus(this.safeString(e,"status")),{info:e,id:this.safeString(e,"id"),timestamp:s,datetime:this.iso8601(s),currency:o,amount:d,fromAccount:l,toAccount:u,status:i}}getExtendedCurrencyCodeById(e,t){if(void 0===e)return this.safeString(t,"code");let i=this.safeDict(this.options,"currenciesByNumericId",{}),s=this.safeDict(i,e);if(void 0!==s)return this.safeString(s,"code");if(void 0!==t)return t.code;let r=this.safeCurrencyCode(e);return"USD"===r&&(r="USDC"),r}parseTransactionStatus(e){return this.safeString({CREATED:"pending",IN_PROGRESS:"pending",COMPLETED:"ok",REJECTED:"failed"},e,e)}parseTransactionType(e){return this.safeString({DEPOSIT:"deposit",WITHDRAWAL:"withdrawal",TRANSFER:"transfer",CLAIM:"claim"},e,e)}parseTransaction(e,t){let i,s=this.safeInteger(e,"time"),a=this.safeString(e,"asset"),o=this.getExtendedCurrencyCodeById(a,t),n=this.safeString(e,"amount"),d=void 0===n?void 0:this.parseNumber(r.Y.stringAbs(n)),h=this.safeString(e,"fee");void 0!==h&&(i={currency:o,cost:this.parseNumber(r.Y.stringAbs(h))});let c=this.parseTransactionType(this.safeString(e,"type")),l=this.safeString(e,"chain");return{info:e,id:this.safeString(e,"id"),txid:this.safeString(e,"transactionHash"),timestamp:s,datetime:this.iso8601(s),address:void 0,addressFrom:void 0,addressTo:void 0,tag:void 0,tagFrom:void 0,tagTo:void 0,type:c,amount:d,currency:o,status:this.parseTransactionStatus(this.safeString(e,"status")),updated:s,fee:i,network:l,comment:void 0,internal:"transfer"===c}}async fetchTradingFee(e,t={}){await this.loadMarkets();let i=this.market(e),s={market:i.id},r=await this.v1PrivateGetUserFees(this.extend(s,t)),a=this.safeList(r,"data",[]),o=this.safeDict(a,0,{});return this.parseTradingFee(o,i)}async fetchTradingFees(e={}){await this.loadMarkets();let t=await this.v1PrivateGetUserFees(e),i=this.safeList(t,"data",[]),s={};for(let e=0;e<i.length;e++){let t=this.safeDict(i,e,{}),r=this.parseTradingFee(t),a=this.safeString(r,"symbol");void 0!==a&&(s[a]=r)}return s}parseTradingFee(e,t){let i=this.safeString(e,"market");return{info:e,symbol:this.safeMarket(i,t).symbol,maker:this.safeNumber(e,"makerFeeRate"),taker:this.safeNumber(e,"takerFeeRate"),percentage:!0,tierBased:void 0}}async fetchLeverage(e,t={}){await this.loadMarkets();let i=this.market(e),s={market:i.id},r=await this.v1PrivateGetUserLeverage(this.extend(s,t)),a=this.safeList(r,"data",[]);return this.parseLeverage(this.safeDict(a,0,{}),i)}async setLeverage(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");await this.loadMarkets();let s=this.market(t),r={market:s.id,leverage:this.numberToString(e)},o=await this.v1PrivatePatchUserLeverage(this.extend(r,i)),n=this.safeDict(o,"data",{});return this.parseLeverage(n,s)}parseLeverage(e,t){let i=this.safeString(e,"market"),s=this.safeMarket(i,t),r=this.safeNumber(e,"leverage");return{info:e,symbol:s.symbol,marginMode:void 0,longLeverage:r,shortLeverage:r}}async fetchPositions(e,t={}){await this.loadMarkets();let i={};void 0!==e&&(i.market=this.marketIds(e));let s=await this.v1PrivateGetUserPositions(this.extend(i,t)),r=this.safeList(s,"data",[]);return this.parsePositions(r,e)}async fetchPosition(e,t={}){let i=await this.fetchPositions([e],t);return this.safeDict(i,0)}async fetchPositionsHistory(e,t,i,s={}){await this.loadMarkets();let r=e;"string"==typeof e&&(r=[e]);let[a,o]=this.handleOptionBoolAndParams(s,"fetchPositionsHistory","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchPositionsHistory",r,t,i,o,"cursor","cursor",void 0,1e4);let n={};void 0!==r&&(n.market=this.marketIds(r));let d=await this.v1PrivateGetUserPositionsHistory(this.extend(n,o)),h=this.safeList(d,"data",[]),c=this.safeDict(d,"pagination",{}),l=this.safeString(c,"cursor"),u=[],f=h.length;for(let e=0;e<f;e++){let t=h[e];void 0!==l&&e===f-1&&(t=this.extend(t,{cursor:l})),u.push(t)}let p=this.parsePositions(u,r);return this.filterBySinceLimit(p,t,i,"timestamp")}parsePosition(e,t){let i=this.safeString(e,"market"),s=this.safeMarket(i,t),r=this.safeInteger2(e,"createdAt","createdTime"),a=this.safeInteger2(e,"updatedAt","updatedTime");a=this.safeInteger(e,"closedTime",a);let o=this.safeStringLower(e,"side"),n=this.safeString(e,"margin");return this.safePosition({info:e,id:this.safeString(e,"id"),symbol:s.symbol,timestamp:r,datetime:this.iso8601(r),lastUpdateTimestamp:a,initialMargin:n,initialMarginPercentage:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,entryPrice:this.safeString(e,"openPrice"),notional:this.safeString(e,"value"),leverage:this.safeString(e,"leverage"),unrealizedPnl:this.safeString(e,"unrealisedPnl"),realizedPnl:this.safeString(e,"realisedPnl"),contracts:this.safeString(e,"size"),contractSize:this.safeString(s,"contractSize"),marginRatio:void 0,liquidationPrice:this.safeString(e,"liquidationPrice"),markPrice:this.safeString(e,"markPrice"),lastPrice:this.safeString(e,"exitPrice"),collateral:n,marginMode:void 0,side:o,percentage:void 0,hedged:void 0,stopLossPrice:this.safeString(e,"slTriggerPrice"),takeProfitPrice:this.safeString(e,"tpTriggerPrice")})}getExtendedStarkAmount(e,t,i=!1){let s=this.numberToString(t),a=r.Y.stringMul(e,s),o=this.decimalToPrecision(a,0,0,2,5);return i&&r.Y.stringGt(a,o)&&(o=r.Y.stringAdd(o,"1")),o}async fetchExtendedAccount(e={}){let t=this.safeDict(this.options,"account");return void 0!==t||(t=(await this.fetchAccount(e)).info,this.options.account=t),t}createOrderSettlementData(e,t,i,s={}){let a=this.safeString(s,"totalFee"),o=this.safeInteger(s,"settlementExpiration"),n=this.safeInteger(s,"nonce"),d=this.safeString(s,"starkKey"),h=this.safeString(s,"collateralPosition"),c=this.safeString(s,"syntheticId"),l=this.safeString(s,"collateralId"),u=this.safeInteger(s,"syntheticResolution"),f=this.safeInteger(s,"collateralResolution"),p=r.Y.stringMul(t,i),m=this.getExtendedStarkAmount(t,u,e),g=this.getExtendedStarkAmount(p,f,e);e?g=r.Y.stringNeg(g):m=r.Y.stringNeg(m);let v={starkKey:d,collateralPosition:h,baseAssetId:c,baseAmount:m,quoteAssetId:l,quoteAmount:g,feeAssetId:l,feeAmount:this.getExtendedStarkAmount(r.Y.stringMul(a,p),f,!0),expiration:this.numberToString(o),salt:n},y=this.getExtendedOrderMsgHash(v),b=JSON.parse(this.extendedStarknetSign(y,this.privateKey)),w=this.getExtendedSignatureHex(b[0]),k=this.getExtendedSignatureHex(b[1]);return v.r=w,v.s=k,v}createWithdrawalSettlementData(e,t,i,s,r={}){let o=this.milliseconds(),n=this.safeInteger(r,"settlementExpiration",this.parseToInt((o+999)/1e3)+1209600+60),d=this.safeInteger(r,"nonce",this.nonce()),h=this.safeString2(r,"positionId","l2Vault",this.safeString(s,"l2Vault")),c=this.safeString(r,"recipient",e),l=this.safeDict(i,"info",{}),u=this.safeString(r,"collateralId",this.safeString2(l,"starkexId","l1Id")),f=this.safeInteger(r,"resolution",this.safeValue2(l,"starkexResolution","l1Resolution")),p=this.safeString(s,"l2Key");if(void 0===h||void 0===u||void 0===f||void 0===p)throw new a.BadRequest(this.id+" withdraw() requires currency starkexId/starkexResolution, account l2Vault and account l2Key");let m={recipient:c,positionId:h,collateralId:u,amount:this.getExtendedStarkAmount(t,f),expiration:{seconds:n},salt:d},g=this.getExtendedWithdrawalMsgHash(m,p),v=JSON.parse(this.extendedStarknetSign(g,this.privateKey));return m.signature={r:this.getExtendedSignatureHex(v[0]),s:this.getExtendedSignatureHex(v[1])},m}createTransferSettlementData(e,t,i,s,r,o={}){let n=this.milliseconds(),d=this.safeInteger(o,"settlementExpiration",this.parseToInt((n+999)/1e3)+1814400),h=this.safeInteger(o,"nonce",this.nonce()),c=this.safeString2(o,"fromVault","senderPositionId",this.safeString(i,"l2Vault")),l=this.safeString2(o,"fromL2Key","senderPublicKey",this.safeString(i,"l2Key")),u=this.safeDict(t,"info",{}),f=this.safeString2(o,"assetId","collateralId",this.safeString2(u,"starkexId","l1Id")),p=this.safeInteger(o,"resolution",this.safeValue2(u,"starkexResolution","l1Resolution"));if(void 0===c||void 0===l||void 0===f||void 0===p)throw new a.BadRequest(this.id+" transfer() requires currency starkexId/starkexResolution, account l2Vault and account l2Key");let m={amount:this.getExtendedStarkAmount(e,p),assetId:f,expirationTimestamp:d,nonce:h,receiverPositionId:s,receiverPublicKey:r,senderPositionId:c,senderPublicKey:l},g=this.getExtendedTransferMsgHash(m),v=JSON.parse(this.extendedStarknetSign(g,this.privateKey));return m.signature={r:this.getExtendedSignatureHex(v[0]),s:this.getExtendedSignatureHex(v[1])},m}async createExtendedOrderRequest(e,t,i,s,o,n={}){let d,h,c;if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");await this.loadMarkets();let l=this.market(e),u=t.toUpperCase(),f=i.toUpperCase();if(!0===l.spot&&"LIMIT"!==u)throw new a.BadRequest(this.id+" createOrder() supports limit orders for spot markets only");if(!this.inArray(u,["LIMIT","MARKET","CONDITIONAL","TPSL"]))throw new a.BadRequest(this.id+" createOrder() supports limit, market, conditional and tpsl orders only");if(void 0===o)throw new a.ArgumentsRequired(this.id+" createOrder() requires a price argument");let p=this.amountToPrecision(e,s),m=this.priceToPrecision(e,o),g=this.isPostOnly("MARKET"===u,void 0,n),v=this.safeBool2(n,"reduceOnly","reduce_only",!1),y=this.safeStringUpper(n,"timeInForce");void 0===y&&(y="MARKET"===u?"IOC":"GTT");let b=this.safeString(n,"fee","0.0005");if(this.isSandboxModeEnabled)d=this.safeString2(n,"builderFeeRate","defaultBuilderFeeRate"),h=this.safeString2(n,"builderId","defaultBuilderId"),c=this.omit(n,["builderFeeRate","defaultBuilderFeeRate","builderId","defaultBuilderId"]);else{let e;[d,e]=this.handleOptionStringAndParams(n,"createOrder","builderFeeRate","0.0001"),[h,c]=this.handleOptionStringAndParams(e,"createOrder","builderId")}let w=b;void 0!==d&&(w=r.Y.stringAdd(b,d));let k=this.milliseconds(),S=this.safeInteger(c,"expiryEpochMillis",k+36e5),O=this.safeInteger(c,"settlementExpiration",this.parseToInt((S+999)/1e3)+1209600),T=this.numberToString(this.nonce()),P=await this.fetchExtendedAccount(),I=this.safeString(P,"l2Key"),A=this.safeString(P,"l2Vault"),x=this.safeDict(l,"info",{}),M=this.safeDict(x,"l2Config",{}),_=this.safeString(M,"syntheticId"),C=this.safeString(M,"collateralId"),B=this.safeInteger(M,"syntheticResolution"),E=this.safeInteger(M,"collateralResolution");if(void 0===_||void 0===C||void 0===B||void 0===E)throw new a.BadRequest(this.id+" createOrder() requires l2Config in market info");let R={totalFee:w,starkKey:I,syntheticId:_,syntheticResolution:B,collateralId:C,collateralResolution:E,settlementExpiration:O,nonce:T,collateralPosition:A},L="BUY"===f,N=this.safeString2(c,"clientOrderId","client_id",this.uuid()),D={id:N,market:l.id,type:u,side:f,qty:p,price:m,timeInForce:y,expiryEpochMillis:S,fee:b,nonce:T,postOnly:g,reduceOnly:v,selfTradeProtectionLevel:"ACCOUNT"};void 0!==d&&(D.builderFee=d),void 0!==h&&(D.builderId=h);let q=this.safeString2(c,"cancelId","previousOrderId");void 0!==q&&(D.cancelId=q);let F=this.createOrderSettlementData(L,p,m,R);D.settlement={signature:{r:F.r,s:F.s},starkKey:I,collateralPosition:A};let V=this.safeString2(c,"triggerPrice","stopPrice"),G=this.safeString(c,"stopLossPrice"),H=this.safeString(c,"takeProfitPrice"),U=void 0!==G,W=void 0!==H,j=this.safeDict(c,"stopLoss"),K=this.safeDict(c,"takeProfit"),z=void 0!==j,Y=void 0!==K;if(z||Y){if(D.tpSlType="ORDER",z){let t=this.safeString(j,"triggerPrice"),i=this.safeString(j,"triggerPriceType"),s=this.safeString(j,"price"),r=this.safeString(j,"type"),a=this.createOrderSettlementData(!L,p,s,R),o={triggerPrice:this.priceToPrecision(e,t),price:this.priceToPrecision(e,s),settlement:{signature:{r:a.r,s:a.s},starkKey:I,collateralPosition:A}};void 0!==i&&(o.triggerPriceType=i),void 0!==r&&(o.priceType=r),D.stopLoss=o}if(Y){let t=this.safeString(K,"triggerPrice"),i=this.safeString(K,"triggerPriceType"),s=this.safeString(K,"price"),r=this.safeString(K,"type"),a=this.createOrderSettlementData(!L,p,s,R),o={triggerPrice:this.priceToPrecision(e,t),price:this.priceToPrecision(e,s),settlement:{signature:{r:a.r,s:a.s},starkKey:I,collateralPosition:A}};void 0!==i&&(o.triggerPriceType=i),void 0!==r&&(o.priceType=r),D.takeProfit=o}}else if(void 0!==V){let t=this.safeStringUpper(c,"triggerDirection");if(void 0===t)throw new a.ArgumentsRequired(this.id+" createOrder() requires triggerDirection for trigger order");let i={triggerPrice:this.priceToPrecision(e,V)};i.direction=t,D.type="CONDITIONAL",D.trigger=i}else if(U||W){V=U?G:H;let t={triggerPrice:this.priceToPrecision(e,V)};L?t.direction=U?"UP":"DOWN":t.direction=U?"DOWN":"UP",D.type="CONDITIONAL",D.trigger=t}let X=this.omit(c,["clientOrderId","client_id","timeInForce","postOnly","reduceOnly","reduce_only","fee","nonce","expiryEpochMillis","settlementExpiration","cancelId","previousOrderId","brokerId","referralCode","triggerPrice","stopPrice","triggerDirection","stopLossPrice","takeProfitPrice","stopLoss","takeProfit"]);return{request:this.extend(D,X),market:l,timestamp:k,clientOrderId:N,price:m,amount:p}}async createOrder(e,t,i,s,r,a={}){this.checkRequiredCredentials();let o=await this.createExtendedOrderRequest(e,t,i,s,r,a),n=this.safeDict(o,"request",{}),d=await this.v1PrivatePostUserOrder(n),h=this.safeDict(d,"data",{}),c=this.market(e);return h.timestamp=this.safeInteger(o,"timestamp"),h.status="NEW",this.parseOrder(this.extend(n,h),c)}async editOrder(e,t,i,s,r,o,n={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" editOrder() requires an id argument");let d=r,h=o,c=this.safeInteger(n,"expiryEpochMillis"),l=this.safeBool(n,"postOnly"),u=this.safeBool2(n,"reduceOnly","reduce_only"),f=this.safeString2(n,"cancelId","previousOrderId");if(void 0===d||void 0===h||void 0===c||void 0===l||void 0===u||void 0===f){let t=await this.v1PrivateGetUserOrdersId({id:e}),i=this.safeDict(t,"data",{});void 0===d&&(d=this.safeNumber(i,"qty")),void 0===h&&(h=this.safeNumber(i,"price")),void 0===c&&(c=this.safeInteger(i,"expireTime")),void 0===l&&(l=this.safeBool(i,"postOnly",!1)),void 0===u&&(u=this.safeBool(i,"reduceOnly",!1)),void 0===f&&(f=this.safeString(i,"externalId"))}if(void 0===d)throw new a.ArgumentsRequired(this.id+" editOrder() requires an amount argument or an existing order with qty");if(void 0===h)throw new a.ArgumentsRequired(this.id+" editOrder() requires a price argument or an existing order with price");let p=this.extend({postOnly:l,reduceOnly:u},n),m=this.extend(p,{cancelId:f,expiryEpochMillis:c}),g=await this.createExtendedOrderRequest(t,i,s,d,h,m),v=this.safeDict(g,"request",{}),y=await this.v1PrivatePostUserOrder(v),b=this.safeDict(y,"data",{}),w=this.market(t);return b.timestamp=this.safeInteger(g,"timestamp"),b.status="NEW",this.parseOrder(this.extend(v,b),w)}async cancelOrder(e,t,i={}){let s,r;await this.loadMarkets(),void 0!==t&&(s=this.market(t));let o=this.safeString2(i,"clientOrderId","client_id"),n=this.omit(i,["clientOrderId","client_id"]);if(void 0!==o)r=await this.v1PrivateDeleteUserOrder(this.extend({externalId:o},n));else{if(void 0===e)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires an id argument");r=await this.v1PrivateDeleteUserOrderId(this.extend({id:e},n))}let d=void 0===o?e:void 0,h=void 0===s?t:s.symbol;return this.safeOrder({info:r,id:d,clientOrderId:o,timestamp:void 0,datetime:void 0,symbol:h,status:"canceled"},s)}async cancelOrders(e,t,i={}){await this.loadMarkets();let s=this.safeListN(i,["clientOrderIds","client_order_ids","externalOrderIds","external_order_ids"]),r=this.safeString2(i,"clientOrderId","client_id"),o=this.omit(i,["clientOrderIds","client_order_ids","clientOrderId","client_id","externalOrderIds","external_order_ids","orderIds","order_ids","markets","cancelAll","cancel_all"]),n={},d=void 0!==e;d&&e.length>0&&(n.orderIds=e),void 0===s&&void 0!==r&&(s=[r]);let h=void 0!==s;if(void 0!==s&&s.length>0&&(n.externalOrderIds=s),!d&&!h)throw new a.ArgumentsRequired(this.id+" cancelOrders() requires an ids argument or clientOrderIds parameter");return await this.v1PrivatePostUserOrderMassCancel(this.extend(n,o)),[]}async cancelAllOrders(e,t={}){await this.loadMarkets();let i={cancelAll:!0};return void 0!==e&&(i.markets=[this.market(e).id]),await this.v1PrivatePostUserOrderMassCancel(this.extend(i,t)),[]}async cancelAllOrdersAfter(e,t={}){await this.loadMarkets();let i={countdownTime:e>0?this.parseToInt(e/1e3):0};return{info:await this.v1PrivatePostUserDeadmanswitch(this.extend(i,t))}}async fetchOrder(e,t,i={}){let s,r,o;await this.loadMarkets(),void 0!==t&&(s=this.market(t));let n=this.safeString2(i,"clientOrderId","client_id"),d=this.omit(i,["clientOrderId","client_id"]);if(void 0!==n){r=await this.v1PrivateGetUserOrdersExternalExternalId(this.extend({externalId:n},d));let e=this.safeList(r,"data",[]);o=this.safeDict(e,0,{})}else{if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires an id argument");r=await this.v1PrivateGetUserOrdersId(this.extend({id:e},d)),o=this.safeDict(r,"data",{})}return this.parseOrder(o,s)}async fetchOpenOrders(e,t,i,s={}){let r;await this.loadMarkets();let a={};void 0!==e&&(a.market=(r=this.market(e)).id);let o=await this.v1PrivateGetUserOrders(this.extend(a,s)),n=this.safeList(o,"data",[]),d=this.parseOrders(n,r,t,i);return this.filterBySymbolSinceLimit(d,e,t,i)}async fetchOrders(e,t,i,s={}){let r;await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchOrders","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchOrders",e,t,i,o,"cursor","cursor",void 0,100);let n={};void 0!==e&&(n.market=(r=this.market(e)).id),void 0!==i&&(n.limit=i);let d=await this.v1PrivateGetUserOrdersHistory(this.extend(o,n)),h=this.safeList(d,"data",[]),c=this.safeDict(d,"pagination",{}),l=this.safeString(c,"cursor"),u=[],f=h.length;for(let e=0;e<f;e++){let t=h[e];void 0!==l&&e===f-1&&(t=this.extend(t,{cursor:l})),u.push(t)}let p=this.parseOrders(u,r,t,i);return this.filterBySymbolSinceLimit(p,e,t,i)}async fetchClosedOrders(e,t,i,s={}){let r=await this.fetchOrders(e,t,void 0,s),a=this.filterBy(r,"status","closed");return this.filterBySymbolSinceLimit(a,e,t,i)}async fetchCanceledOrders(e,t,i,s={}){let r=await this.fetchOrders(e,t,void 0,s),a=this.filterBy(r,"status","canceled");return this.filterBySymbolSinceLimit(a,e,t,i)}parseOrderStatus(e){return this.safeString({NEW:"open",PARTIALLY_FILLED:"open",UNTRIGGERED:"open",TRIGGERED:"open",FILLED:"closed",CANCELLED:"canceled",REJECTED:"rejected",EXPIRED:"expired"},e,e)}parseOrder(e,t){let i=this.safeString(e,"market"),s=this.safeMarket(i,t),r=this.safeInteger2(e,"createdTime","timestamp"),a=this.safeInteger(e,"updatedTime"),o=this.parseOrderStatus(this.safeString(e,"status")),n=this.safeStringLower(e,"side"),d=this.safeStringLower(e,"type"),h=this.safeString(e,"qty"),c=this.safeString(e,"filledQty"),l=this.safeString(e,"payedFee"),u=this.safeDict(e,"trigger",{}),f=this.safeDict(e,"takeProfit",{}),p=this.safeDict(e,"stopLoss",{}),m={cost:l,currency:void 0===s?void 0:s.settle};return this.safeOrder({info:e,id:this.safeString(e,"id"),clientOrderId:this.safeString(e,"externalId"),timestamp:r,datetime:this.iso8601(r),lastTradeTimestamp:void 0,lastUpdateTimestamp:a,symbol:s.symbol,type:d,timeInForce:this.safeString(e,"timeInForce"),postOnly:this.safeBool(e,"postOnly"),reduceOnly:this.safeBool(e,"reduceOnly"),side:n,price:this.safeString(e,"price"),triggerPrice:this.safeString(u,"triggerPrice"),takeProfitPrice:this.safeString(f,"triggerPrice"),stopLossPrice:this.safeString(p,"triggerPrice"),amount:h,cost:void 0,average:this.safeString(e,"averagePrice"),filled:c,remaining:void 0,status:o,fee:m,trades:void 0},s)}getExtendedStringToFelt(e){return this.convertToBigInt(this.stringToBase16(e))}getExtendedEncodeI64(e){let t=this.numberToString(e);return r.Y.stringLt(t,"0")?r.Y.stringAdd("3618502788666131213697322783095070105623107215331596699973092056135872020481",t):e}getExtendedDecimalToBase16(e){let t="";t="string"==typeof e?e:this.numberToString(e);let i=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],s="";for(;r.Y.stringGt(t,"0");)s=i[this.parseToInt(r.Y.stringMod(t,"16"))]+s,t=r.Y.stringDiv(t,"16",0);return""===s?"0":s}getExtendedSignatureHex(e){if("string"==typeof e)return 0===e.indexOf("0x")?e:"0x"+this.getExtendedDecimalToBase16(e);let t=this.numberToString(e);return 0===t.indexOf("0x")?t:"0x"+this.getExtendedDecimalToBase16(t)}getExtendedDomainHash(){let e=this.convertToBigInt(this.extendedStarknetGetSelectorFromName('"StarknetDomain"("name":"shortstring","version":"shortstring","chainId":"shortstring","revision":"shortstring")')),t=this.urls.api.rest.indexOf("sepolia")>=0,i="SN_MAIN";t&&(i="SN_SEPOLIA");let s=this.safeString(this.options,"chainId",i);return this.convertToBigInt(this.extendedStarknetComputePoseidonHashOnElements([e,this.getExtendedStringToFelt("Perpetuals"),this.getExtendedStringToFelt("v0"),this.getExtendedStringToFelt(s),this.convertToBigInt("1")]))}getExtendedOrderMsgHash(e){let t=this.convertToBigInt(this.extendedStarknetGetSelectorFromName('"Order"("position_id":"felt","base_asset_id":"AssetId","base_amount":"i64","quote_asset_id":"AssetId","quote_amount":"i64","fee_asset_id":"AssetId","fee_amount":"u64","expiration":"Timestamp","salt":"felt")"PositionId"("value":"u32")"AssetId"("value":"felt")"Timestamp"("seconds":"u64")')),i=this.getExtendedDomainHash(),s=this.convertToBigInt(this.safeString(e,"collateralPosition","0")),r=this.safeString(e,"baseAssetId","0"),a=this.convertToBigInt(this.safeString(e,"baseAmount","0")),o=this.safeString(e,"quoteAssetId","0"),n=this.convertToBigInt(this.safeString(e,"quoteAmount","0")),d=this.safeString(e,"feeAssetId","0"),h=this.convertToBigInt(this.safeString(e,"feeAmount","0")),c=this.convertToBigInt(this.safeString2(e,"expiration","expirationTimestamp","0")),l=this.convertToBigInt(this.safeString2(e,"salt","nonce","0")),u=this.convertToBigInt(this.safeString(e,"starkKey","0")),f=this.convertToBigInt(this.extendedStarknetComputePoseidonHashOnElements([t,s,this.convertToBigInt(r),this.getExtendedEncodeI64(a),this.convertToBigInt(o),this.getExtendedEncodeI64(n),this.convertToBigInt(d),h,c,l]));return this.extendedStarknetComputePoseidonHashOnElements([this.getExtendedStringToFelt("StarkNet Message"),i,u,f])}getExtendedWithdrawalMsgHash(e,t){let i=this.convertToBigInt(this.extendedStarknetGetSelectorFromName('"Withdrawal"("recipient":"felt","position_id":"PositionId","collateral_id":"AssetId","amount":"u64","expiration":"Timestamp","salt":"felt")"PositionId"("value":"u32")"AssetId"("value":"felt")"Timestamp"("seconds":"u64")')),s=this.getExtendedDomainHash(),r=this.safeDict(e,"expiration",{}),a=this.convertToBigInt(this.extendedStarknetComputePoseidonHashOnElements([i,this.convertToBigInt(this.safeString(e,"recipient","0")),this.convertToBigInt(this.safeString(e,"positionId","0")),this.convertToBigInt(this.safeString(e,"collateralId","0")),this.convertToBigInt(this.safeString(e,"amount","0")),this.convertToBigInt(this.safeString(r,"seconds","0")),this.convertToBigInt(this.safeString(e,"salt","0"))]));return this.extendedStarknetComputePoseidonHashOnElements([this.getExtendedStringToFelt("StarkNet Message"),s,this.convertToBigInt(t),a])}getExtendedTransferMsgHash(e){let t=this.convertToBigInt(this.extendedStarknetGetSelectorFromName('"Transfer"("sender_position_id":"PositionId","receiver_position_id":"PositionId","asset_id":"AssetId","amount":"u64","expiration":"Timestamp","salt":"felt")"PositionId"("value":"u32")"AssetId"("value":"felt")"Timestamp"("seconds":"u64")')),i=this.getExtendedDomainHash(),s=this.convertToBigInt(this.safeString(e,"senderPublicKey","0")),r=this.convertToBigInt(this.extendedStarknetComputePoseidonHashOnElements([t,this.convertToBigInt(this.safeString(e,"senderPositionId","0")),this.convertToBigInt(this.safeString(e,"receiverPositionId","0")),this.convertToBigInt(this.safeString(e,"assetId","0")),this.convertToBigInt(this.safeString(e,"amount","0")),this.convertToBigInt(this.safeString(e,"expirationTimestamp","0")),this.convertToBigInt(this.safeString(e,"nonce","0"))]));return this.extendedStarknetComputePoseidonHashOnElements([this.getExtendedStringToFelt("StarkNet Message"),i,s,r])}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0!==n&&"error"===this.safeStringLower(n,"status")){let e=this.safeDict(n,"error"),t=this.safeString(e,"code"),i=this.id+" "+this.json(n);throw this.throwBroadlyMatchedException(this.exceptions.broad,o,i),this.throwExactlyMatchedException(this.exceptions.exact,t,i),new a.ExchangeError(i)}}sign(e,t="public",i="GET",s={},r,o){let n=r,d=o,h=this.safeString(t,0),c=this.safeString(t,1),l="/"+this.implodeParams(e,s),u=this.omit(s,this.extractParams(e)),f="user/deadmanswitch"===e,p=this.safeString(this.urls.api,"rest");if(void 0===p)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");if("private"===c){if(void 0===this.apiKey)throw new a.AuthenticationError(this.id+" sign() requires an apiKey for private endpoints");n={"X-Api-Key":this.apiKey},"POST"!==i&&"PATCH"!==i||f||(d=this.json(u),n["Content-Type"]="application/json")}let m=this.implodeHostname(p)+"/api/"+h+l;return("GET"===i||"DELETE"===i||f)&&Object.keys(u).length>0&&(m+="?"+this.urlencodeWithArrayRepeat(u)),{url:m,method:i,body:d,headers:n}}}i.d(t,{A:()=>o})},2604(e,t,i){"use strict";var s=i(3030);class r extends s.A{describe(){return this.deepExtend(super.describe(),{id:"fmfwio",name:"FMFW.io",countries:["KN"],urls:{logo:"https://user-images.githubusercontent.com/1294454/159177712-b685b40c-5269-4cea-ac83-f7894c49525d.jpg",api:{public:"https://api.fmfw.io/api/3",private:"https://api.fmfw.io/api/3"},www:"https://fmfw.io",doc:"https://api.fmfw.io/",fees:"https://fmfw.io/fees-and-limits",referral:"https://fmfw.io/referral/da948b21d6c92d69"},fees:{trading:{maker:this.parseNumber("0.005"),taker:this.parseNumber("0.005")}}})}}i.d(t,{A:()=>r})},6110(e,t,i){"use strict";var s=i(4721),r=i(7749),a=i(4139),o=i(1453);class n extends a.A{describe(){return this.deepExtend(super.describe(),{id:"foxbit",name:"Foxbit",countries:["pt-BR"],rateLimit:33.334,version:"1",comment:"Foxbit Exchange",certified:!1,pro:!1,has:{CORS:!0,spot:!0,margin:void 0,swap:void 0,future:void 0,option:void 0,cancelAllOrders:!0,cancelOrder:!0,createLimitBuyOrder:!0,createLimitSellOrder:!0,createMarketBuyOrder:!0,createMarketSellOrder:!0,createOrder:!0,createOrders:!0,editOrder:!0,fetchBalance:!0,fetchCanceledOrders:!0,fetchClosedOrders:!0,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDeposits:!0,fetchL2OrderBook:!0,fetchLedger:!0,fetchMarkets:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchOrdersByStatus:!0,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTransactions:!0,fetchWithdrawals:!0,loadMarkets:!0,sandbox:!1,withdraw:!0,ws:!1},timeframes:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","12h":"12h","1d":"1d","1w":"1w","2w":"2w","1M":"1M"},urls:{logo:"https://github.com/user-attachments/assets/1f8faca2-ae2f-4222-b33e-5671e7d873dd",api:{public:"https://api.foxbit.com.br",private:"https://api.foxbit.com.br",status:"https://metadata-v2.foxbit.com.br/api"},www:"https://app.foxbit.com.br",doc:["https://docs.foxbit.com.br"]},precisionMode:4,exceptions:{exact:{400:o.BadRequest,429:o.RateLimitExceeded,404:o.BadRequest,500:o.ExchangeError,2001:o.AuthenticationError,2002:o.AuthenticationError,2003:o.AuthenticationError,2004:o.BadRequest,2005:o.PermissionDenied,3001:o.PermissionDenied,3002:o.PermissionDenied,3003:o.AccountSuspended,4001:o.BadRequest,4002:o.InsufficientFunds,4003:o.InvalidOrder,4004:o.BadSymbol,4005:o.BadRequest,4007:o.ExchangeError,4008:o.InvalidOrder,4009:o.PermissionDenied,4011:o.RateLimitExceeded,4012:o.ExchangeError,5001:o.ExchangeNotAvailable,5002:o.OnMaintenance,5003:o.OnMaintenance,5004:o.InvalidOrder,5005:o.InvalidOrder,5006:o.InvalidOrder},broad:{}},requiredCredentials:{apiKey:!0,secret:!0},api:{v3:{public:{get:{currencies:{cost:5},markets:{cost:5},"markets/ticker/24hr":{cost:60},"markets/{market}/orderbook":{cost:6},"markets/{market}/candlesticks":{cost:12},"markets/{market}/trades/history":{cost:12},"markets/{market}/ticker/24hr":{cost:15},"markets/sparkline/{window}":{cost:20},"travel_rule/operation_reasons":{cost:30}}},private:{get:{accounts:{cost:2},"accounts/{symbol}/transactions":{cost:60},orders:{cost:2},"orders/by-order-id/{id}":{cost:2},trades:{cost:6},"deposits/address":{cost:10},deposits:{cost:10},withdrawals:{cost:10},"me/fees/trading":{cost:60},"prime_desk/executions/{quote_id}":{cost:10}},post:{orders:{cost:2},"orders/batch":{cost:7.5},"orders/cancel-replace":{cost:3},withdrawals:{cost:10},"deposits/{deposit_sn}/travel_rule":{cost:30}},put:{"orders/cancel":{cost:2}}}},status:{public:{get:{status:{cost:30}}}}},fees:{trading:{feeSide:"get",tierBased:!1,percentage:!0,taker:this.parseNumber("0.005"),maker:this.parseNumber("0.0025")}},options:{sandboxMode:!1,networksById:{algorand:"ALGO",arbitrum:"ARBITRUM",avalanchecchain:"AVAX",bitcoin:"BTC",bitcoincash:"BCH",bsc:"BEP20",cardano:"ADA",cosmos:"ATOM",dogecoin:"DOGE",erc20:"ETH",hedera:"HBAR",litecoin:"LTC",near:"NEAR",optimism:"OPTIMISM",polkadot:"DOT",polygon:"MATIC",ripple:"XRP",solana:"SOL",stacks:"STX",stellar:"XLM",tezos:"XTZ",trc20:"TRC20"},networks:{ALGO:"algorand",ARBITRUM:"arbitrum",AVAX:"avalanchecchain",BTC:"bitcoin",BCH:"bitcoincash",BEP20:"bsc",ADA:"cardano",ATOM:"cosmos",DOGE:"dogecoin",ETH:"erc20",HBAR:"hedera",LTC:"litecoin",NEAR:"near",OPTIMISM:"optimism",DOT:"polkadot",MATIC:"polygon",XRP:"ripple",SOL:"solana",STX:"stacks",XLM:"stellar",XTZ:"tezos",TRC20:"trc20"}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:{last:!0,mark:!1,index:!1},triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{GTC:!0,FOK:!0,IOC:!0,PO:!0,GTD:!1},hedged:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:{expire_maker:!0,expire_taker:!0,expire_both:!0,none:!0},trailing:!1,icebergAmount:!1},createOrders:{max:5},fetchMyTrades:{marginMode:!1,limit:100,daysBack:90,untilDays:1e4,symbolRequired:!0},fetchOrder:{marginMode:!1,limit:1,daysBack:90,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:100,daysBack:90,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!0,limit:100,daysBack:90,untilDays:1e4,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!0,limit:100,daysBack:90,daysBackCanceled:90,untilDays:1e4,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:500}}}})}async fetchCurrencies(e={}){let t=await this.v3PublicGetCurrencies(e),i=this.safeList(t,"data",[]);return this.parseCurrencies(i)}parseCurrency(e){let t=this.safeString(e,"symbol"),i=this.safeString(e,"name"),s=this.safeCurrencyCode(t),r=this.safeDict(e,"deposit_info"),a=this.safeDict(e,"withdraw_info"),o=this.safeList(e,"networks",[]),n=this.safeStringLower(e,"type"),d={};for(let t=0;t<o.length;t++){let i=this.safeDict(o,t),n=this.safeString(i,"code"),h=this.networkIdToCode(n,s),c=this.safeDict(i,"withdraw_info"),l=this.safeDict(i,"deposit_info"),u="ENABLED"===this.safeString(c,"status"),f="ENABLED"===this.safeString(l,"status");void 0!==h&&(d[h]={info:e,id:n,network:h,name:this.safeString(i,"name"),deposit:f,withdraw:u,active:!0,precision:void 0,fee:this.safeNumber(c,"fee"),limits:{amount:{min:void 0,max:void 0},deposit:{min:this.safeNumber(r,"min_amount"),max:void 0},withdraw:{min:this.safeNumber(a,"min_amount"),max:void 0}}})}return this.safeCurrencyStructure({id:t,code:s,info:e,name:i,active:!0,type:n,deposit:this.safeBool(r,"enabled",!1),withdraw:this.safeBool(a,"enabled",!1),fee:this.safeNumber(a,"fee"),precision:this.parseNumber(this.parsePrecision(this.safeString(e,"precision"))),limits:{amount:{min:void 0,max:void 0},deposit:{min:this.safeNumber(r,"min_amount"),max:void 0},withdraw:{min:this.safeNumber(a,"min_amount"),max:void 0}},networks:d})}async fetchMarkets(e={}){let t=await this.v3PublicGetMarkets(e),i=this.safeList(t,"data",[]);return this.parseMarkets(i)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={market:i.id},r=await this.v3PublicGetMarketsMarketTicker24hr(this.extend(s,t)),a=this.safeList(r,"data",[]),o=this.safeDict(a,0,{});return this.parseTicker(o,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.v3PublicGetMarketsTicker24hr(t),r=this.safeList(s,"data",[]);return this.parseTickers(r,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v3PrivateGetMeFeesTrading(e),i=this.safeList(t,"data",[]),s={};for(let e=0;e<i.length;e++){let t=i[e],r=this.safeString(t,"market_symbol"),a=this.safeMarket(r);s[a.symbol]=this.parseTradingFee(t,a)}return s}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={market:this.market(e).id,depth:void 0===t?20:t},r=await this.v3PublicGetMarketsMarketOrderbook(this.extend(s,i)),a=this.safeInteger(r,"timestamp");return this.parseOrderBook(r,e,a)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={market:r.id};void 0!==i&&(a.page_size=i,i>200&&(a.page_size=200));let o=await this.v3PublicGetMarketsMarketTradesHistory(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTrades(n,r,t,i)}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=this.safeString(this.timeframes,t,t),n={market:a.id,interval:o};void 0!==i&&(n.start_time=this.iso8601(i)),void 0!==s&&(n.limit=s,s>500&&(n.limit=500));let d=await this.v3PublicGetMarketsMarketCandlesticks(this.extend(n,r));return this.parseOHLCVs(this.toArray(d),a,o,i,s)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v3PrivateGetAccounts(e),i=this.safeList(t,"data",[]),s={info:t};for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),r=this.safeString(t,"currency_symbol"),a=this.safeCurrencyCode(r),o=this.safeString(t,"balance"),n=this.safeString(t,"balance_locked"),d={free:this.safeString(t,"balance_available"),used:n,total:o};void 0!==a&&(s[a]=d)}return this.safeBalance(s)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrdersByStatus("ACTIVE",e,t,i,s)}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrdersByStatus("FILLED",e,t,i,s)}async fetchCanceledOrders(e,t,i,s={}){return await this.fetchOrdersByStatus("CANCELED",e,t,i,s)}async fetchOrdersByStatus(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a={state:e};void 0!==t&&(a.market_symbol=this.market(t).id),void 0!==i&&(a.start_time=this.iso8601(i)),void 0!==s&&(a.page_size=s,s>100&&(a.page_size=100));let o=await this.v3PrivateGetOrders(this.extend(a,r)),n=this.safeList(o,"data",[]);return this.parseOrders(n)}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=t.toUpperCase();if("LIMIT"!==d&&"MARKET"!==d&&"STOP_MARKET"!==d&&"STOP_LIMIT"!==d&&"INSTANT"!==d)throw new o.InvalidOrder("Invalid order type: "+d+". Must be one of: limit, market, stop_market, stop_limit, instant.");let h=this.safeStringUpper(a,"timeInForce"),c=this.safeBool(a,"postOnly",!1),l=this.safeNumber(a,"triggerPrice");this.checkRequiredArgument("createOrder",i,"side");let u={market_symbol:n.id,side:i.toUpperCase(),type:d};if(("STOP_MARKET"===d||"STOP_LIMIT"===d)&&void 0===l)throw new o.InvalidOrder("Invalid order type: "+d+". Must have triggerPrice.");void 0!==h&&("PO"===h?u.post_only=!0:u.time_in_force=h),!0===c&&(u.post_only=!0),void 0!==l&&(u.stop_price=this.priceToPrecision(e,l)),"INSTANT"===d?u.amount=this.priceToPrecision(e,s):u.quantity=this.amountToPrecision(e,s),("LIMIT"===d||"STOP_LIMIT"===d)&&(u.price=this.priceToPrecision(e,r));let f=this.safeString(a,"clientOrderId");void 0!==f&&(u.client_order_id=f);let p=this.omit(a,["timeInForce","postOnly","triggerPrice","clientOrderId"]),m=await this.v3PrivatePostOrders(this.extend(u,p));return this.parseOrder(m,n)}async createOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=[];for(let t=0;t<e.length;t++){let s=this.safeDict(e,t),r=this.safeString(s,"symbol"),a=this.market(r),n=this.safeStringUpper(s,"type"),d=this.safeDict(s,"params",{});if("LIMIT"!==n&&"MARKET"!==n&&"STOP_MARKET"!==n&&"STOP_LIMIT"!==n&&"INSTANT"!==n)throw new o.InvalidOrder("Invalid order type: "+n+". Must be one of: limit, market, stop_market, stop_limit, instant.");let h=this.safeStringUpper(d,"timeInForce"),c=this.safeBool(d,"postOnly",!1),l=this.safeNumber(d,"triggerPrice"),u={market_symbol:a.id,side:this.safeStringUpper(s,"side"),type:n};if(("STOP_MARKET"===n||"STOP_LIMIT"===n)&&void 0===l)throw new o.InvalidOrder("Invalid order type: "+n+". Must have triggerPrice.");void 0!==h&&("PO"===h?u.post_only=!0:u.time_in_force=h,delete d.timeInForce),!0===c&&(u.post_only=!0,delete d.postOnly),void 0!==l&&(u.stop_price=this.priceToPrecision(r,l),delete d.triggerPrice),"INSTANT"===n?u.amount=this.priceToPrecision(r,this.safeString(s,"amount")):u.quantity=this.amountToPrecision(r,this.safeString(s,"amount")),("LIMIT"===n||"STOP_LIMIT"===n)&&(u.price=this.priceToPrecision(r,this.safeString(s,"price"))),i.push(this.extend(u,d))}let s=await this.v3PrivatePostOrdersBatch(this.extend({data:i},t)),r=this.safeList(s,"data",[]);return this.parseOrders(r)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={id:this.parseNumber(e),type:"ID"},r=await this.v3PrivatePutOrdersCancel(this.extend(s,i)),a=this.safeList(r,"data",[]),o=this.safeDict(a,0,{});return this.parseOrder(o)}async cancelAllOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={type:"ALL"};if(void 0!==e){let t=this.market(e);i.type="MARKET",i.market_symbol=t.id}let s=await this.v3PrivatePutOrdersCancel(this.extend(i,t));return[this.safeOrder({info:s})]}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.v3PrivateGetOrdersByOrderIdId(this.extend({id:e},i));return this.parseOrder(s)}async fetchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.market_symbol=(r=this.market(e)).id),void 0!==t&&(a.start_time=this.iso8601(t)),void 0!==i&&(a.page_size=i,i>100&&(a.page_size=100));let o=await this.v3PrivateGetOrders(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseOrders(n,r,t,i)}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={market_symbol:r.id};void 0!==t&&(a.start_time=this.iso8601(t)),void 0!==i&&(a.page_size=i,i>100&&(a.page_size=100));let n=await this.v3PrivateGetTrades(this.extend(a,s)),d=this.safeList(n,"data",[]);return this.parseTrades(d,r,t,i)}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={currency_symbol:i.id},[r,a]=this.handleNetworkCodeAndParams(t);void 0!==r&&(s.network_code=this.networkCodeToId(r,e));let o=await this.v3PrivateGetDepositsAddress(this.extend(s,a));return this.parseDepositAddress(o,i)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(r=this.currency(e)),void 0!==i&&(a.page_size=i,i>100&&(a.page_size=100)),void 0!==t&&(a.start_time=this.iso8601(t));let o=await this.v3PrivateGetDeposits(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTransactions(n,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(r=this.currency(e)),void 0!==i&&(a.page_size=i,i>100&&(a.page_size=100)),void 0!==t&&(a.start_time=this.iso8601(t));let o=await this.v3PrivateGetWithdrawals(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTransactions(n,r,t,i)}async fetchTransactions(e,t,i,s={}){let r=await this.fetchWithdrawals(e,t,i,s),a=await this.fetchDeposits(e,t,i,s),o=this.arrayConcat(r,a);return this.sortBy(o,"timestamp")}async fetchStatus(e={}){let t=await this.statusPublicGetStatus(e),i=this.safeDict(t,"data",{}),s=this.safeDict(i,"attributes",{}),r=this.safeString(s,"status");return{status:this.safeString({NORMAL:"ok",UNDER_MAINTENANCE:"maintenance"},r,r),updated:this.parse8601(this.safeString(s,"updatedAt")),eta:void 0,url:void 0,info:t}}async editOrder(e,t,i,s,r,a,n={}){this.checkRequiredArgument("editOrder",t,"symbol");let d=i.toUpperCase();if("LIMIT"!==d&&"MARKET"!==d&&"STOP_MARKET"!==d&&"INSTANT"!==d)throw new o.InvalidOrder("Invalid order type: "+d+". Must be one of: LIMIT, MARKET, STOP_MARKET, INSTANT.");void 0===this.markets&&await this.loadMarkets();let h=this.market(t);this.checkRequiredArgument("editOrder",s,"side");let c={mode:"ALLOW_FAILURE",cancel:{type:"ID",id:this.parseNumber(e)},create:{type:d,side:s.toUpperCase(),market_symbol:h.id}};("LIMIT"===d||"MARKET"===d)&&(c.create.quantity=this.amountToPrecision(t,r),"LIMIT"===d&&(c.create.price=this.priceToPrecision(t,a))),"STOP_MARKET"===d&&(c.create.stop_price=this.priceToPrecision(t,a),c.create.quantity=this.amountToPrecision(t,r)),"INSTANT"===d&&(c.create.amount=this.priceToPrecision(t,r));let l=await this.v3PrivatePostOrdersCancelReplace(this.extend(c,n)),u=this.safeDict(l,"create",{});return this.parseOrder(u,h)}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);void 0===this.markets&&await this.loadMarkets();let n={currency_symbol:this.currency(e).id,amount:this.numberToString(t),destination_address:i};void 0!==a&&(n.destination_tag=a);let[d,h]=this.handleNetworkCodeAndParams(o);void 0!==d&&(n.network_code=this.networkCodeToId(d,e));let c=await this.v3PrivatePostWithdrawals(this.extend(n,h));return this.parseTransaction(c)}async fetchLedger(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={};if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchLedger() requires a code argument");void 0!==i&&(r.page_size=i,i>100&&(r.page_size=100)),void 0!==t&&(r.start_time=this.iso8601(t));let a=this.currency(e);r.symbol=a.id;let n=await this.v3PrivateGetAccountsSymbolTransactions(this.extend(r,s)),d=this.safeList(n,"data",[]);return this.parseLedger(d,a,t,i)}parseMarket(e){let t=this.safeString(e,"symbol"),i=this.safeDict(e,"base"),s=this.safeString(i,"symbol"),r=this.safeDict(e,"quote"),a=this.safeString(r,"symbol"),o=this.safeCurrencyCode(s),n=this.safeCurrencyCode(a);if(void 0===o||void 0===n)return;let d=this.safeDict(e,"default_fees");return this.safeMarketStructure({id:t,symbol:o+"/"+n,base:o,quote:n,baseId:s,quoteId:a,active:!0,type:"spot",spot:!0,margin:!1,future:!1,swap:!1,option:!1,contract:!1,settle:void 0,settleId:void 0,contractSize:void 0,linear:void 0,inverse:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,taker:this.safeNumber(d,"taker"),maker:this.safeNumber(d,"maker"),percentage:!0,tierBased:!1,feeSide:"get",precision:{price:this.safeNumber(e,"price_increment"),amount:this.safeNumber(e,"quantity_increment")},limits:{amount:{min:this.safeNumber(e,"quantity_min"),max:void 0},price:{min:this.safeNumber(e,"price_min"),max:void 0},cost:{min:void 0,max:void 0},leverage:{min:void 0,max:void 0}},info:e})}parseTradingFee(e,t){return{info:e,symbol:this.safeString(t,"symbol"),maker:this.safeNumber(e,"maker"),taker:this.safeNumber(e,"taker"),percentage:!0,tierBased:!0}}parseTicker(e,t){let i=this.safeString(e,"market_symbol"),s=this.safeSymbol(i,t,void 0,"spot"),r=this.safeDict(e,"rolling_24h"),a=this.safeDict(e,"best"),o=this.safeDict(a,"ask"),n=this.safeDict(a,"bid"),d=this.safeDict(e,"last_trade"),h=this.safeString(d,"price");return this.safeTicker({symbol:s,timestamp:this.parseDate(this.safeString(d,"date")),datetime:this.iso8601(this.parseDate(this.safeString(d,"date"))),high:this.safeNumber(r,"high"),low:this.safeNumber(r,"low"),bid:this.safeNumber(n,"price"),bidVolume:this.safeNumber(n,"volume"),ask:this.safeNumber(o,"price"),askVolume:this.safeNumber(o,"volume"),vwap:void 0,open:this.safeNumber(r,"open"),close:h,last:h,previousClose:void 0,change:this.safeString(r,"price_change"),percentage:this.safeString(r,"price_change_percent"),average:void 0,baseVolume:this.safeString(r,"volume"),quoteVolume:this.safeString(r,"quote_volume"),info:e},t)}parseOHLCV(e,t){return[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,6)]}parseTrade(e,t){let i=this.parseDate(this.safeString(e,"created_at")),s=this.safeString(e,"price"),a=this.safeString(e,"volume",this.safeString(e,"quantity")),o=this.safeStringLower(e,"side"),n=this.safeStringLower(e,"taker_side",o),d=r.Y.stringMul(s,a),h={currency:this.safeSymbol(this.safeString(e,"fee_currency_symbol")),cost:this.safeNumber(e,"fee"),rate:void 0};return this.safeTrade({id:this.safeString(e,"id"),info:e,timestamp:i,datetime:this.iso8601(i),symbol:this.safeString(t,"symbol"),order:void 0,type:void 0,side:n,takerOrMaker:void 0,price:s,amount:a,cost:d,fee:h},t)}parseOrderStatus(e){return this.safeString({PARTIALLY_CANCELED:"open",ACTIVE:"open",PARTIALLY_FILLED:"open",FILLED:"closed",PENDING_CANCEL:"canceled",CANCELED:"canceled"},e,e)}parseOrder(e,t){let i,s=this.safeString(e,"market_symbol"),a=t;void 0===t&&void 0!==s&&(a=this.market(s)),void 0!==a&&(s=this.safeString(a,"symbol"));let o=this.parseDate(this.safeString(e,"created_at")),n=this.safeString(e,"price"),d=this.safeString(e,"quantity_executed"),h=this.safeString(e,"quantity");void 0!==h&&void 0!==d&&(i=r.Y.stringAdd(h,d));let c=this.safeString(e,"funds_received");if(void 0===c||""===c){let t=this.safeString(e,"price_avg"),s=this.safeString(e,"price",t);c=r.Y.stringMul(s,i)}let l=this.safeStringLower(e,"side"),u=this.safeStringUpper(a,"quoteId");return"buy"===l&&(u=this.safeStringUpper(a,"baseId")),this.safeOrder({id:this.safeString(e,"id"),info:e,clientOrderId:this.safeString(e,"client_order_id"),timestamp:o,datetime:this.iso8601(o),lastTradeTimestamp:void 0,status:this.parseOrderStatus(this.safeString(e,"state")),symbol:this.safeString(a,"symbol"),type:this.safeString(e,"type"),timeInForce:this.safeString(e,"time_in_force"),postOnly:this.safeBool(e,"post_only"),reduceOnly:void 0,side:l,price:this.parseNumber(n),triggerPrice:this.safeNumber(e,"stop_price"),takeProfitPrice:void 0,stopLossPrice:void 0,cost:this.parseNumber(c),average:this.safeNumber(e,"price_avg"),amount:this.parseNumber(i),filled:this.parseNumber(d),remaining:this.parseNumber(h),trades:void 0,fee:{currency:u,cost:this.safeNumber(e,"fee_paid")}})}parseDepositAddress(e,t){let i=this.safeDict(e,"network"),s=this.safeString(i,"code"),r=this.safeCurrencyCode(void 0,t),a=this.networkIdToCode(s,r);return{address:this.safeString(e,"address"),tag:this.safeString(e,"tag"),currency:r,network:a,info:e}}parseTransactionStatus(e){return this.safeString({SUBMITTING:"pending",SUBMITTED:"pending",REJECTED:"failed",CANCELLED:"canceled",ACCEPTED:"ok",WARNING:"pending",UNBLOCKED:"pending",BLOCKED:"pending",PROCESSING:"pending",CANCELED:"canceled",FAILED:"failed",DONE:"ok"},e,e)}parseTransaction(e,t,i,s){let a=this.safeDict(e,"details_crypto"),o=this.safeString2(a,"receiving_address","destination_address"),n=this.safeString(e,"sn"),d="withdrawal";void 0!==n&&"D"===n[0]&&(d="deposit");let h=this.safeString(e,"fee","0"),c=this.safeString(e,"amount"),l=this.safeString(e,"currency_symbol"),u=c,f=this.safeCurrencyCode(l),p=this.parseTransactionStatus(this.safeString(e,"state")),m=this.safeString(e,"created_at"),g=this.parseDate(m),v=this.iso8601(g);void 0!==h&&void 0!==c&&(u=r.Y.stringSub(c,h));let y=r.Y.stringDiv(h,u),b={cost:this.parseNumber(h),currency:f,rate:this.parseNumber(y)};return{info:e,id:this.safeString(e,"sn"),txid:this.safeString(a,"transaction_id"),timestamp:g,datetime:v,network:this.safeString(e,"network_code"),address:o,addressTo:o,addressFrom:void 0,tag:this.safeString(e,"destination_tag"),tagTo:this.safeString(e,"destination_tag"),tagFrom:void 0,type:d,amount:this.parseNumber(c),currency:f,status:p,updated:void 0,fee:b,comment:void 0,internal:void 0}}parseLedgerEntryType(e){return this.safeString({DEPOSITING:"transaction",WITHDRAWING:"transaction",TRADING:"trade",INTERNAL_TRANSFERING:"transfer",OTHERS:"transaction"},e,e)}parseLedgerEntry(e,t){let i=this.safeString(e,"uuid"),s=this.safeString(e,"created_at"),r=this.parse8601(s),a=this.safeString(e,"reason_type"),n=this.parseLedgerEntryType(a),d=this.safeString(e,"currency_symbol"),h=this.safeCurrencyCode(d),c="in",l=this.safeNumber(e,"amount"),u=l,f=this.safeNumber(e,"balance"),p={cost:this.safeNumber(e,"fee"),currency:h};if(void 0===l)throw new o.ArgumentsRequired(this.id+" parseLedgerEntry() requires a amount argument");if(l<0){if(c="out",void 0===l)throw new o.ArgumentsRequired(this.id+" parseLedgerEntry() requires a amount argument");u=-1*l}if(void 0===f)throw new o.ExchangeError(this.id+" parseLedgerEntry() missing balance");if(void 0===l)throw new o.ArgumentsRequired(this.id+" parseLedgerEntry() requires a amount argument");return{id:i,info:e,timestamp:r,datetime:this.iso8601(r),direction:c,account:void 0,referenceId:void 0,referenceAccount:void 0,type:n,currency:h,amount:u,before:f-l,after:f,status:"ok",fee:p}}sign(e,t=[],i="GET",r={},a,n){let d=t[0],h=t[1],c="/rest/"+d+"/"+this.implodeParams(e,r);"status"===d&&(c="/status",h="status");let l=this.safeString(this.urls.api,h);if(void 0===l)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let u=l+c,f=this.omit(r,this.extractParams(e)),p=this.milliseconds(),m="";if("GET"===i){let e=Object.keys(f),t=e.length;t>0&&(u+="?"+this.urlencode(f));for(let i=0;i<e.length;i++){let s=e[i],r=this.safeString(f,s);void 0!==r&&(m+=s+"="+r),i<t-1&&(m+="&")}}let g=n;("POST"===i||"PUT"===i)&&(g=this.json(f));let v="";void 0!==g&&(v=g);let y={"Content-Type":"application/json","X-FB-CLIENT":"ccxt","X-FB-CLIENT-VERSION":this.getCcxtVersion()};if("private"===h){this.checkRequiredCredentials();let e=this.numberToString(p)+i+c+m+v,t=this.hmac(this.encode(e),this.encode(this.secret),s.sc,"hex");y["X-FB-ACCESS-KEY"]=this.apiKey,y["X-FB-ACCESS-TIMESTAMP"]=this.numberToString(p),y["X-FB-ACCESS-SIGNATURE"]=t}return{url:u,method:i,body:g,headers:y}}handleErrors(e,t,i,s,r,a,n,d,h){if(void 0===n)return;let c=this.safeDict(n,"error"),l=this.safeString(c,"code"),u=this.safeList(c,"details"),f=this.safeString(c,"message"),p="";if(void 0!==u)for(let e=0;e<u.length;e++)p=p+u[e]+" ";if(void 0!==c){let e=this.id+" "+f+" details: "+p;throw this.throwBroadlyMatchedException(this.exceptions.broad,f,e),this.throwBroadlyMatchedException(this.exceptions.broad,p,e),this.throwExactlyMatchedException(this.exceptions.exact,l,e),new o.ExchangeError(e)}}}i.d(t,{A:()=>n})},1305(e,t,i){"use strict";var s=i(4721),r=i(3032),a=i(7749),o=i(1453);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"gate",name:"Gate",countries:["KR"],rateLimit:50,version:"v4",certified:!0,pro:!0,urls:{logo:"https://github.com/user-attachments/assets/b4fd9d41-eaed-46fe-8a7b-b2677edface0",doc:"https://www.gate.com/docs/developers/apiv4/en",www:"https://gate.com",api:{public:{wallet:"https://api.gateio.ws/api/v4",futures:"https://api.gateio.ws/api/v4",margin:"https://api.gateio.ws/api/v4",delivery:"https://api.gateio.ws/api/v4",spot:"https://api.gateio.ws/api/v4",options:"https://api.gateio.ws/api/v4",sub_accounts:"https://api.gateio.ws/api/v4",earn:"https://api.gateio.ws/api/v4"},private:{withdrawals:"https://api.gateio.ws/api/v4",wallet:"https://api.gateio.ws/api/v4",futures:"https://api.gateio.ws/api/v4",margin:"https://api.gateio.ws/api/v4",delivery:"https://api.gateio.ws/api/v4",spot:"https://api.gateio.ws/api/v4",options:"https://api.gateio.ws/api/v4",subAccounts:"https://api.gateio.ws/api/v4",unified:"https://api.gateio.ws/api/v4",rebate:"https://api.gateio.ws/api/v4",earn:"https://api.gateio.ws/api/v4",account:"https://api.gateio.ws/api/v4",loan:"https://api.gateio.ws/api/v4",otc:"https://api.gateio.ws/api/v4"}},test:{public:{futures:"https://api-testnet.gateapi.io/api/v4",delivery:"https://api-testnet.gateapi.io/api/v4",options:"https://api-testnet.gateapi.io/api/v4",spot:"https://api-testnet.gateapi.io/api/v4",wallet:"https://api-testnet.gateapi.io/api/v4",margin:"https://api-testnet.gateapi.io/api/v4",sub_accounts:"https://api-testnet.gateapi.io/api/v4",account:"https://api-testnet.gateapi.io/api/v4"},private:{futures:"https://api-testnet.gateapi.io/api/v4",delivery:"https://api-testnet.gateapi.io/api/v4",options:"https://api-testnet.gateapi.io/api/v4",spot:"https://api-testnet.gateapi.io/api/v4",wallet:"https://api-testnet.gateapi.io/api/v4",margin:"https://api-testnet.gateapi.io/api/v4",sub_accounts:"https://api-testnet.gateapi.io/api/v4",account:"https://api-testnet.gateapi.io/api/v4"}},referral:{url:"https://www.gate.com/share/CCXTGATE",discount:.2}},has:{CORS:void 0,spot:!0,margin:!0,swap:!0,future:!0,option:!0,addMargin:!0,borrowCrossMargin:!0,borrowIsolatedMargin:!0,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,cancelOrdersForSymbols:!0,closePosition:!0,createMarketBuyOrderWithCost:!0,createMarketOrder:!0,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createPostOnlyOrder:!0,createReduceOnlyOrder:!0,createStopLimitOrder:!0,createStopLossOrder:!0,createStopMarketOrder:!1,createStopOrder:!0,createTakeProfitOrder:!0,createTriggerOrder:!0,editOrder:!0,fetchBalance:!0,fetchBorrowInterest:!0,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!0,fetchDeposits:!0,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!0,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchGreeks:!0,fetchIndexOHLCV:!0,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLedger:!0,fetchLeverage:!0,fetchLeverages:!0,fetchLeverageTiers:!0,fetchLiquidations:!0,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarketLeverageTiers:!0,fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMyLiquidations:!0,fetchMySettlementHistory:!0,fetchMyTrades:!0,fetchNetworkDepositAddress:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!0,fetchOpenOrders:!0,fetchOption:!0,fetchOptionChain:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrdersByStatus:!0,fetchOrderTrades:!0,fetchPosition:!0,fetchPositionHistory:"emulated",fetchPositionMode:!1,fetchPositions:!0,fetchPositionsHistory:!0,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTransactionFees:!0,fetchUnderlyingAssets:!0,fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!0,repayCrossMargin:!0,repayIsolatedMargin:!0,sandbox:!0,setLeverage:!0,setMarginMode:!1,setPositionMode:!0,signIn:!1,transfer:!0,withdraw:!0},api:{public:{wallet:{get:{currency_chains:{cost:1}}},unified:{get:{currencies:{cost:1},history_loan_rate:{cost:1}}},spot:{get:{currencies:{cost:1},"currencies/{currency}":{cost:1},currency_pairs:{cost:1},"currency_pairs/{currency_pair}":{cost:1},tickers:{cost:1},order_book:{cost:1},trades:{cost:1},candlesticks:{cost:1},time:{cost:1},insurance_history:{cost:1}}},margin:{get:{"uni/currency_pairs":{cost:1},"uni/currency_pairs/{currency_pair}":{cost:1},loan_margin_tiers:{cost:1},currency_pairs:{cost:1},"currency_pairs/{currency_pair}":{cost:1},funding_book:{cost:1},"cross/currencies":{cost:1},"cross/currencies/{currency}":{cost:1}}},flash_swap:{get:{currency_pairs:{cost:1},currencies:{cost:1}}},futures:{get:{"{settle}/contracts":{cost:1},"{settle}/contracts/{contract}":{cost:1},"{settle}/order_book":{cost:1},"{settle}/trades":{cost:1},"{settle}/candlesticks":{cost:1},"{settle}/premium_index":{cost:1},"{settle}/tickers":{cost:1},"{settle}/funding_rate":{cost:1},"{settle}/insurance":{cost:1},"{settle}/contract_stats":{cost:1},"{settle}/index_constituents/{index}":{cost:1},"{settle}/liq_orders":{cost:1},"{settle}/risk_limit_tiers":{cost:1},"{settle}/adl_risk_states":{cost:1}},post:{"{settle}/funding_rates":{cost:1}}},delivery:{get:{"{settle}/contracts":{cost:1},"{settle}/contracts/{contract}":{cost:1},"{settle}/order_book":{cost:1},"{settle}/trades":{cost:1},"{settle}/candlesticks":{cost:1},"{settle}/tickers":{cost:1},"{settle}/insurance":{cost:1},"{settle}/risk_limit_tiers":{cost:1}}},options:{get:{underlyings:{cost:1},expirations:{cost:1},contracts:{cost:1},"contracts/{contract}":{cost:1},settlements:{cost:1},"settlements/{contract}":{cost:1},order_book:{cost:1},tickers:{cost:1},"underlying/tickers/{underlying}":{cost:1},candlesticks:{cost:1},"underlying/candlesticks":{cost:1},trades:{cost:1}}},earn:{get:{"uni/currencies":{cost:1},"uni/currencies/{currency}":{cost:1},"dual/investment_plan":{cost:1},"structured/products":{cost:1},"dual/project-recommend":{cost:1},"fixed-term/product":{cost:1},"fixed-term/product/{asset}/list":{cost:1}}},loan:{get:{"collateral/currencies":{cost:1},"multi_collateral/currencies":{cost:1},"multi_collateral/ltv":{cost:1},"multi_collateral/fixed_rate":{cost:1},"multi_collateral/current_rate":{cost:1}}}},private:{withdrawals:{post:{withdrawals:{cost:20},push:{cost:1}},delete:{"withdrawals/{withdrawal_id}":{cost:1}}},wallet:{get:{deposit_address:{cost:1},withdrawals:{cost:1},deposits:{cost:1},sub_account_transfers:{cost:1},order_status:{cost:1},withdraw_status:{cost:1},sub_account_balances:{cost:2.5},sub_account_margin_balances:{cost:2.5},sub_account_futures_balances:{cost:2.5},sub_account_cross_margin_balances:{cost:2.5},saved_address:{cost:1},fee:{cost:1},total_balance:{cost:2.5},small_balance:{cost:1},small_balance_history:{cost:1},push:{cost:1},getLowCapExchangeList:{cost:1},transfers:{cost:1}},post:{transfers:{cost:2.5},sub_account_transfers:{cost:2.5},sub_account_to_sub_account:{cost:2.5},small_balance:{cost:1}}},subAccounts:{get:{sub_accounts:{cost:2.5},"sub_accounts/{user_id}":{cost:2.5},"sub_accounts/{user_id}/keys":{cost:2.5},"sub_accounts/{user_id}/keys/{key}":{cost:2.5}},post:{sub_accounts:{cost:2.5},"sub_accounts/{user_id}/keys":{cost:2.5},"sub_accounts/{user_id}/lock":{cost:2.5},"sub_accounts/{user_id}/unlock":{cost:2.5}},put:{"sub_accounts/{user_id}/keys/{key}":{cost:2.5}},delete:{"sub_accounts/{user_id}/keys/{key}":{cost:2.5}}},unified:{get:{accounts:{cost:20/15},borrowable:{cost:20/15},transferable:{cost:20/15},transferables:{cost:20/15},batch_borrowable:{cost:20/15},loans:{cost:20/15},loan_records:{cost:20/15},interest_records:{cost:20/15},risk_units:{cost:20/15},unified_mode:{cost:20/15},estimate_rate:{cost:20/15},currency_discount_tiers:{cost:20/15},loan_margin_tiers:{cost:20/15},"leverage/user_currency_config":{cost:20/15},"leverage/user_currency_setting":{cost:20/15},delta_neutral:{cost:20/15},estimated_quick_repayment:{cost:20/15},account_mode:{cost:20/15}},post:{loans:{cost:200/15},portfolio_calculator:{cost:20/15},"leverage/user_currency_setting":{cost:20/15},collateral_currencies:{cost:20/15},delta_neutral:{cost:20/15},"leverage/user_setting":{cost:20/15},quick_repayment:{cost:20/15},account_mode:{cost:20/15}},put:{unified_mode:{cost:20/15}}},spot:{get:{fee:{cost:1},batch_fee:{cost:1},accounts:{cost:1},account_book:{cost:1},open_orders:{cost:1},orders:{cost:1},"orders/{order_id}":{cost:1},my_trades:{cost:1},price_orders:{cost:1},"price_orders/{order_id}":{cost:1},pov_orders:{cost:1},"pov_orders/{order_id}":{cost:1}},post:{batch_orders:{cost:.4},cross_liquidate_orders:{cost:1},orders:{cost:.4},cancel_batch_orders:{cost:20/75},countdown_cancel_all:{cost:20/75},amend_batch_orders:{cost:.4},price_orders:{cost:.4},pov_orders:{cost:.4}},delete:{orders:{cost:20/75},"orders/{order_id}":{cost:20/75},price_orders:{cost:20/75},"price_orders/{order_id}":{cost:20/75},pov_orders:{cost:20/75},"pov_orders/{order_id}":{cost:20/75}},patch:{"orders/{order_id}":{cost:.4}}},margin:{get:{accounts:{cost:20/15},account_book:{cost:20/15},funding_accounts:{cost:20/15},auto_repay:{cost:20/15},transferable:{cost:20/15},"uni/estimate_rate":{cost:20/15},"uni/loans":{cost:20/15},"uni/loan_records":{cost:20/15},"uni/interest_records":{cost:20/15},"uni/borrowable":{cost:20/15},"user/loan_margin_tiers":{cost:20/15},"user/account":{cost:20/15},loans:{cost:20/15},"loans/{loan_id}":{cost:20/15},"loans/{loan_id}/repayment":{cost:20/15},loan_records:{cost:20/15},"loan_records/{loan_record_id}":{cost:20/15},borrowable:{cost:20/15},"cross/accounts":{cost:20/15},"cross/account_book":{cost:20/15},"cross/loans":{cost:20/15},"cross/loans/{loan_id}":{cost:20/15},"cross/repayments":{cost:20/15},"cross/interest_records":{cost:20/15},"cross/transferable":{cost:20/15},"cross/estimate_rate":{cost:20/15},"cross/borrowable":{cost:20/15}},post:{auto_repay:{cost:20/15},"uni/loans":{cost:20/15},"leverage/user_market_setting":{cost:20/15},loans:{cost:20/15},merged_loans:{cost:20/15},"loans/{loan_id}/repayment":{cost:20/15},"cross/loans":{cost:20/15},"cross/repayments":{cost:20/15}},patch:{"loans/{loan_id}":{cost:20/15},"loan_records/{loan_record_id}":{cost:20/15}},delete:{"loans/{loan_id}":{cost:20/15}}},flash_swap:{get:{orders:{cost:1},"orders/{order_id}":{cost:1}},post:{orders:{cost:1},"orders/preview":{cost:1}}},futures:{get:{"{settle}/accounts":{cost:1},"{settle}/account_book":{cost:1},"{settle}/positions":{cost:1},"{settle}/positions/{contract}":{cost:1},"{settle}/get_leverage/{contract}":{cost:1},"{settle}/dual_comp/positions/{contract}":{cost:1},"{settle}/orders":{cost:1},"{settle}/orders_timerange":{cost:1},"{settle}/orders/{order_id}":{cost:1},"{settle}/my_trades":{cost:1},"{settle}/my_trades_timerange":{cost:1},"{settle}/position_close":{cost:1},"{settle}/liquidates":{cost:1},"{settle}/auto_deleverages":{cost:1},"{settle}/fee":{cost:1},"{settle}/risk_limit_table":{cost:1},"{settle}/price_orders":{cost:1},"{settle}/price_orders/{order_id}":{cost:1},"{settle}/autoorder/v1/trail/list":{cost:1},"{settle}/autoorder/v1/trail/detail":{cost:1},"{settle}/autoorder/v1/trail/change_log":{cost:1},"{settle}/autoorder/v1/chase/list":{cost:1},"{settle}/autoorder/v1/chase/detail":{cost:1}},post:{"{settle}/positions/{contract}/margin":{cost:1},"{settle}/positions/{contract}/leverage":{cost:1},"{settle}/positions/{contract}/set_leverage":{cost:1},"{settle}/positions/{contract}/risk_limit":{cost:1},"{settle}/positions/cross_mode":{cost:1},"{settle}/dual_comp/positions/cross_mode":{cost:1},"{settle}/dual_mode":{cost:1},"{settle}/set_position_mode":{cost:1},"{settle}/dual_comp/positions/{contract}/margin":{cost:1},"{settle}/dual_comp/positions/{contract}/leverage":{cost:1},"{settle}/dual_comp/positions/{contract}/risk_limit":{cost:1},"{settle}/orders":{cost:.4},"{settle}/batch_orders":{cost:.4},"{settle}/countdown_cancel_all":{cost:.4},"{settle}/batch_cancel_orders":{cost:.4},"{settle}/batch_amend_orders":{cost:.4},"{settle}/bbo_orders":{cost:.4},"{settle}/price_orders":{cost:.4},"{settle}/autoorder/v1/trail/create":{cost:.4},"{settle}/autoorder/v1/trail/stop":{cost:.4},"{settle}/autoorder/v1/trail/stop_all":{cost:.4},"{settle}/autoorder/v1/trail/update":{cost:.4},"{settle}/autoorder/v1/chase/create":{cost:.4},"{settle}/autoorder/v1/chase/stop":{cost:.4},"{settle}/autoorder/v1/chase/stop_all":{cost:.4}},put:{"{settle}/orders/{order_id}":{cost:1},"{settle}/price_orders/{order_id}":{cost:1}},delete:{"{settle}/orders":{cost:20/75},"{settle}/orders/{order_id}":{cost:20/75},"{settle}/price_orders":{cost:20/75},"{settle}/price_orders/{order_id}":{cost:20/75}}},delivery:{get:{"{settle}/accounts":{cost:20/15},"{settle}/account_book":{cost:20/15},"{settle}/positions":{cost:20/15},"{settle}/positions/{contract}":{cost:20/15},"{settle}/orders":{cost:20/15},"{settle}/orders/{order_id}":{cost:20/15},"{settle}/my_trades":{cost:20/15},"{settle}/position_close":{cost:20/15},"{settle}/liquidates":{cost:20/15},"{settle}/settlements":{cost:20/15},"{settle}/price_orders":{cost:20/15},"{settle}/price_orders/{order_id}":{cost:20/15}},post:{"{settle}/positions/{contract}/margin":{cost:20/15},"{settle}/positions/{contract}/leverage":{cost:20/15},"{settle}/positions/{contract}/risk_limit":{cost:20/15},"{settle}/orders":{cost:20/15},"{settle}/price_orders":{cost:20/15}},delete:{"{settle}/orders":{cost:20/15},"{settle}/orders/{order_id}":{cost:20/15},"{settle}/price_orders":{cost:20/15},"{settle}/price_orders/{order_id}":{cost:20/15}}},options:{get:{my_settlements:{cost:20/15},accounts:{cost:20/15},account_book:{cost:20/15},positions:{cost:20/15},"positions/{contract}":{cost:20/15},position_close:{cost:20/15},orders:{cost:20/15},"orders/{order_id}":{cost:20/15},my_trades:{cost:20/15},mmp:{cost:20/15}},post:{orders:{cost:20/15},countdown_cancel_all:{cost:20/15},mmp:{cost:20/15},"mmp/reset":{cost:20/15}},put:{"orders/{order_id}":{cost:20/15}},delete:{orders:{cost:20/15},"orders/{order_id}":{cost:20/15}}},earn:{get:{"uni/lends":{cost:20/15},"uni/lend_records":{cost:20/15},"uni/interests/{currency}":{cost:20/15},"uni/interest_records":{cost:20/15},"uni/interest_status/{currency}":{cost:20/15},"uni/chart":{cost:20/15},"uni/rate":{cost:20/15},"staking/eth2/rate_records":{cost:20/15},"dual/orders":{cost:20/15},"dual/balance":{cost:20/15},"structured/orders":{cost:20/15},"staking/coins":{cost:20/15},"staking/order_list":{cost:20/15},"staking/award_list":{cost:20/15},"staking/assets":{cost:20/15},"dual/order-refund-preview":{cost:20/15},"fixed-term/user/lend":{cost:20/15},"fixed-term/user/history":{cost:20/15},"autoinvest/coins":{cost:20/15},"autoinvest/config":{cost:20/15},"autoinvest/orders":{cost:20/15},"autoinvest/plans/detail":{cost:20/15},"autoinvest/plans/list_info":{cost:20/15},"autoinvest/plans/records":{cost:20/15},"uni/currencies":{cost:20/15},"uni/currencies/{currency}":{cost:20/15}},post:{"uni/lends":{cost:20/15},"staking/eth2/swap":{cost:20/15},"dual/orders":{cost:20/15},"structured/orders":{cost:20/15},"staking/swap":{cost:20/15},"dual/order-refund":{cost:20/15},"dual/modify-order-reinvest":{cost:20/15},"fixed-term/user/lend":{cost:20/15},"fixed-term/user/pre-redeem":{cost:20/15},"autoinvest/min_invest_amount":{cost:20/15},"autoinvest/plans/add_position":{cost:20/15},"autoinvest/plans/create":{cost:20/15},"autoinvest/plans/stop":{cost:20/15},"autoinvest/plans/update":{cost:20/15}},put:{"uni/interest_reinvest":{cost:20/15}},patch:{"uni/lends":{cost:20/15}}},loan:{get:{"collateral/orders":{cost:20/15},"collateral/orders/{order_id}":{cost:20/15},"collateral/repay_records":{cost:20/15},"collateral/collaterals":{cost:20/15},"collateral/total_amount":{cost:20/15},"collateral/ltv":{cost:20/15},"multi_collateral/orders":{cost:20/15},"multi_collateral/orders/{order_id}":{cost:20/15},"multi_collateral/repay":{cost:20/15},"multi_collateral/mortgage":{cost:20/15},"multi_collateral/currency_quota":{cost:20/15},"collateral/currencies":{cost:20/15},"multi_collateral/currencies":{cost:20/15},"multi_collateral/ltv":{cost:20/15},"multi_collateral/fixed_rate":{cost:20/15},"multi_collateral/current_rate":{cost:20/15}},post:{"collateral/orders":{cost:20/15},"collateral/repay":{cost:20/15},"collateral/collaterals":{cost:20/15},"multi_collateral/orders":{cost:20/15},"multi_collateral/repay":{cost:20/15},"multi_collateral/mortgage":{cost:20/15}}},account:{get:{detail:{cost:20/15},main_keys:{cost:20/15},rate_limit:{cost:20/15},stp_groups:{cost:20/15},"stp_groups/{stp_id}/users":{cost:20/15},"stp_groups/debit_fee":{cost:20/15},debit_fee:{cost:20/15}},post:{stp_groups:{cost:20/15},"stp_groups/{stp_id}/users":{cost:20/15},debit_fee:{cost:20/15}},delete:{"stp_groups/{stp_id}/users":{cost:20/15}}},rebate:{get:{"agency/transaction_history":{cost:20/15},"agency/commission_history":{cost:20/15},"partner/transaction_history":{cost:20/15},"partner/commission_history":{cost:20/15},"partner/sub_list":{cost:20/15},"broker/commission_history":{cost:20/15},"broker/transaction_history":{cost:20/15},"user/info":{cost:20/15},"user/sub_relation":{cost:20/15},"partner/data/aggregated":{cost:20/15}}},otc:{get:{get_user_def_bank:{cost:1},"order/list":{cost:1},"stable_coin/order/list":{cost:1},"order/detail":{cost:1},"bank/list":{cost:1},"bank/bank_supplement_checklist":{cost:1}},post:{quote:{cost:1},"order/create":{cost:1},"stable_coin/order/create":{cost:1},"order/paid":{cost:1},"order/cancel":{cost:1},"bank/create":{cost:1},"bank/delete":{cost:1},"bank/set_default":{cost:1},"bank/personal/bank_supplement":{cost:1},"bank/enterprise/bank_supplement":{cost:1},"upload/pre_upload":{cost:1}}}}},timeframes:{"10s":"10s","1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","8h":"8h","1d":"1d","7d":"7d","1w":"7d"},commonCurrencies:{ORT:"XREATORS",ASS:"ASSF","88MPH":"MPH",AXIS:"AXISDEFI",BIFI:"BITCOINFILE",BOX:"DEFIBOX",BYN:"BEYONDFI",EGG:"GOOSEFINANCE",GTC:"GAMECOM",GTC_HT:"GAMECOM_HT",GTC_BSC:"GAMECOM_BSC",HIT:"HITCHAIN",MM:"MILLION",MPH:"MORPHER",POINT:"GATEPOINT",RAI:"RAIREFLEXINDEX",SBTC:"SUPERBITCOIN",TNC:"TRINITYNETWORKCREDIT",VAI:"VAIOT",TRAC:"TRACO"},requiredCredentials:{apiKey:!0,secret:!0},headers:{"X-Gate-Channel-Id":"ccxt"},options:{timeDifference:0,adjustForTimeDifference:!1,sandboxMode:!1,unifiedAccount:void 0,createOrder:{expiration:86400},fetchOrderBook:{maxSpotLimit:1e3},createMarketBuyOrderRequiresPrice:!0,networks:{BTC:"BTC",BRC20:"BTCBRC",ETH:"ETH",ERC20:"ETH",TRX:"TRX",TRC20:"TRX",HECO:"HT",HRC20:"HT",BSC:"BSC",BEP20:"BSC",SOL:"SOL",MATIC:"MATIC",OPTIMISM:"OPETH",ADA:"ADA",AVAXC:"AVAX_C",NEAR:"NEAR",ARBITRUM:"ARBEVM",ARBITRUM_NOVA:"ARBNOVA",BASE:"BASEEVM",SUI:"SUI",CRONOS:"CRO",CRO:"CRO",APT:"APT",SCROLL:"SCROLLETH",TAIKO:"TAIKOETH",HYPE:"HYPE",ALGO:"ALGO",LINEA:"LINEAETH",BLAST:"BLASTETH",XLM:"XLM",RSK:"RBTC",TON:"TON",MNT:"MNT",CELO:"CELO",HBAR:"HBAR",ZKSYNC:"ZKSERA",KLAY:"KLAY",EOS:"EOS",ACA:"ACA",XTZ:"XTZ",EGLD:"EGLD",GLMR:"GLMR",AURORA:"AURORAEVM",KON:"KONET",GATECHAIN:"GTEVM",KUSAMA:"KSMSM",OKC:"OKT",POLKADOT:"DOTSM",LUNA:"LUNC"},networksById:{OPETH:"OP",ETH:"ERC20",ERC20:"ERC20",TRX:"TRC20",TRC20:"TRC20",HT:"HRC20",HECO:"HRC20",BSC:"BEP20",BEP20:"BEP20",POLYGON:"MATIC",POL:"MATIC"},timeInForce:{GTC:"gtc",IOC:"ioc",PO:"poc",POC:"poc",FOK:"fok"},accountsByType:{funding:"spot",spot:"spot",margin:"margin",cross_margin:"cross_margin",cross:"cross_margin",isolated:"margin",swap:"futures",future:"delivery",futures:"futures",delivery:"delivery",option:"options",options:"options"},fetchMarkets:{types:["spot","swap","future","option"]},swap:{fetchMarkets:{settlementCurrencies:["usdt","btc"]}},future:{fetchMarkets:{settlementCurrencies:["usdt"]}}},features:{default:{sandbox:!0,createOrder:{marginMode:!0,triggerPrice:!0,triggerDirection:!0,triggerPriceType:void 0,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,iceberg:!0,selfTradePrevention:!0,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!0},createOrders:{max:40},fetchMyTrades:{marginMode:!0,limit:1e3,daysBack:void 0,untilDays:30,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!0,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!0,trigger:!0,trailing:!1,limit:100,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!0,trigger:!0,trailing:!1,limit:100,untilDays:30,daysBack:void 0,daysBackCanceled:void 0,symbolRequired:!1},fetchOHLCV:{limit:1e3}},spot:{extends:"default"},forDerivatives:{extends:"spot",createOrder:{marginMode:!1,triggerPriceType:{last:!0,mark:!0,index:!0}},createOrders:{max:10},fetchMyTrades:{marginMode:!1,untilDays:void 0},fetchOpenOrders:{marginMode:!1},fetchClosedOrders:{marginMode:!1,untilDays:void 0,limit:1e3},fetchOHLCV:{limit:1999}},swap:{linear:{extends:"forDerivatives"},inverse:{extends:"forDerivatives"}},future:{linear:{extends:"forDerivatives"},inverse:{extends:"forDerivatives"}}},precisionMode:4,fees:{trading:{tierBased:!0,feeSide:"get",percentage:!0,maker:this.parseNumber("0.002"),taker:this.parseNumber("0.002"),tiers:{maker:[[this.parseNumber("0"),this.parseNumber("0.002")],[this.parseNumber("1.5"),this.parseNumber("0.00185")],[this.parseNumber("3"),this.parseNumber("0.00175")],[this.parseNumber("6"),this.parseNumber("0.00165")],[this.parseNumber("12.5"),this.parseNumber("0.00155")],[this.parseNumber("25"),this.parseNumber("0.00145")],[this.parseNumber("75"),this.parseNumber("0.00135")],[this.parseNumber("200"),this.parseNumber("0.00125")],[this.parseNumber("500"),this.parseNumber("0.00115")],[this.parseNumber("1250"),this.parseNumber("0.00105")],[this.parseNumber("2500"),this.parseNumber("0.00095")],[this.parseNumber("3000"),this.parseNumber("0.00085")],[this.parseNumber("6000"),this.parseNumber("0.00075")],[this.parseNumber("11000"),this.parseNumber("0.00065")],[this.parseNumber("20000"),this.parseNumber("0.00055")],[this.parseNumber("40000"),this.parseNumber("0.00055")],[this.parseNumber("75000"),this.parseNumber("0.00055")]],taker:[[this.parseNumber("0"),this.parseNumber("0.002")],[this.parseNumber("1.5"),this.parseNumber("0.00195")],[this.parseNumber("3"),this.parseNumber("0.00185")],[this.parseNumber("6"),this.parseNumber("0.00175")],[this.parseNumber("12.5"),this.parseNumber("0.00165")],[this.parseNumber("25"),this.parseNumber("0.00155")],[this.parseNumber("75"),this.parseNumber("0.00145")],[this.parseNumber("200"),this.parseNumber("0.00135")],[this.parseNumber("500"),this.parseNumber("0.00125")],[this.parseNumber("1250"),this.parseNumber("0.00115")],[this.parseNumber("2500"),this.parseNumber("0.00105")],[this.parseNumber("3000"),this.parseNumber("0.00095")],[this.parseNumber("6000"),this.parseNumber("0.00085")],[this.parseNumber("11000"),this.parseNumber("0.00075")],[this.parseNumber("20000"),this.parseNumber("0.00065")],[this.parseNumber("40000"),this.parseNumber("0.00065")],[this.parseNumber("75000"),this.parseNumber("0.00065")]]}},swap:{tierBased:!0,feeSide:"base",percentage:!0,maker:this.parseNumber("0.0"),taker:this.parseNumber("0.0005"),tiers:{maker:[[this.parseNumber("0"),this.parseNumber("0.0000")],[this.parseNumber("1.5"),this.parseNumber("-0.00005")],[this.parseNumber("3"),this.parseNumber("-0.00005")],[this.parseNumber("6"),this.parseNumber("-0.00005")],[this.parseNumber("12.5"),this.parseNumber("-0.00005")],[this.parseNumber("25"),this.parseNumber("-0.00005")],[this.parseNumber("75"),this.parseNumber("-0.00005")],[this.parseNumber("200"),this.parseNumber("-0.00005")],[this.parseNumber("500"),this.parseNumber("-0.00005")],[this.parseNumber("1250"),this.parseNumber("-0.00005")],[this.parseNumber("2500"),this.parseNumber("-0.00005")],[this.parseNumber("3000"),this.parseNumber("-0.00008")],[this.parseNumber("6000"),this.parseNumber("-0.01000")],[this.parseNumber("11000"),this.parseNumber("-0.01002")],[this.parseNumber("20000"),this.parseNumber("-0.01005")],[this.parseNumber("40000"),this.parseNumber("-0.02000")],[this.parseNumber("75000"),this.parseNumber("-0.02005")]],taker:[[this.parseNumber("0"),this.parseNumber("0.00050")],[this.parseNumber("1.5"),this.parseNumber("0.00048")],[this.parseNumber("3"),this.parseNumber("0.00046")],[this.parseNumber("6"),this.parseNumber("0.00044")],[this.parseNumber("12.5"),this.parseNumber("0.00042")],[this.parseNumber("25"),this.parseNumber("0.00040")],[this.parseNumber("75"),this.parseNumber("0.00038")],[this.parseNumber("200"),this.parseNumber("0.00036")],[this.parseNumber("500"),this.parseNumber("0.00034")],[this.parseNumber("1250"),this.parseNumber("0.00032")],[this.parseNumber("2500"),this.parseNumber("0.00030")],[this.parseNumber("3000"),this.parseNumber("0.00030")],[this.parseNumber("6000"),this.parseNumber("0.00030")],[this.parseNumber("11000"),this.parseNumber("0.00030")],[this.parseNumber("20000"),this.parseNumber("0.00030")],[this.parseNumber("40000"),this.parseNumber("0.00030")],[this.parseNumber("75000"),this.parseNumber("0.00030")]]}}},exceptions:{exact:{INVALID_PARAM_VALUE:o.BadRequest,INVALID_PROTOCOL:o.BadRequest,INVALID_ARGUMENT:o.BadRequest,INVALID_REQUEST_BODY:o.BadRequest,MISSING_REQUIRED_PARAM:o.ArgumentsRequired,BAD_REQUEST:o.BadRequest,INVALID_CONTENT_TYPE:o.BadRequest,NOT_ACCEPTABLE:o.BadRequest,METHOD_NOT_ALLOWED:o.BadRequest,NOT_FOUND:o.ExchangeError,AUTHENTICATION_FAILED:o.AuthenticationError,INVALID_CREDENTIALS:o.AuthenticationError,INVALID_KEY:o.AuthenticationError,IP_FORBIDDEN:o.AuthenticationError,READ_ONLY:o.PermissionDenied,INVALID_SIGNATURE:o.AuthenticationError,MISSING_REQUIRED_HEADER:o.AuthenticationError,REQUEST_EXPIRED:o.AuthenticationError,ACCOUNT_LOCKED:o.AccountSuspended,FORBIDDEN:o.PermissionDenied,SUB_ACCOUNT_NOT_FOUND:o.ExchangeError,SUB_ACCOUNT_LOCKED:o.AccountSuspended,MARGIN_BALANCE_EXCEPTION:o.ExchangeError,MARGIN_TRANSFER_FAILED:o.ExchangeError,TOO_MUCH_FUTURES_AVAILABLE:o.ExchangeError,FUTURES_BALANCE_NOT_ENOUGH:o.InsufficientFunds,ACCOUNT_EXCEPTION:o.ExchangeError,SUB_ACCOUNT_TRANSFER_FAILED:o.ExchangeError,ADDRESS_NOT_USED:o.ExchangeError,TOO_FAST:o.RateLimitExceeded,WITHDRAWAL_OVER_LIMIT:o.ExchangeError,API_WITHDRAW_DISABLED:o.ExchangeNotAvailable,INVALID_WITHDRAW_ID:o.ExchangeError,INVALID_WITHDRAW_CANCEL_STATUS:o.ExchangeError,INVALID_PRECISION:o.InvalidOrder,INVALID_CURRENCY:o.BadSymbol,INVALID_CURRENCY_PAIR:o.BadSymbol,POC_FILL_IMMEDIATELY:o.OrderImmediatelyFillable,ORDER_NOT_FOUND:o.OrderNotFound,CLIENT_ID_NOT_FOUND:o.OrderNotFound,ORDER_CLOSED:o.InvalidOrder,ORDER_CANCELLED:o.InvalidOrder,QUANTITY_NOT_ENOUGH:o.InvalidOrder,BALANCE_NOT_ENOUGH:o.InsufficientFunds,MARGIN_NOT_SUPPORTED:o.InvalidOrder,MARGIN_BALANCE_NOT_ENOUGH:o.InsufficientFunds,AMOUNT_TOO_LITTLE:o.InvalidOrder,AMOUNT_TOO_MUCH:o.InvalidOrder,REPEATED_CREATION:o.InvalidOrder,LOAN_NOT_FOUND:o.OrderNotFound,LOAN_RECORD_NOT_FOUND:o.OrderNotFound,NO_MATCHED_LOAN:o.ExchangeError,NOT_MERGEABLE:o.ExchangeError,REPAY_TOO_MUCH:o.ExchangeError,TOO_MANY_CURRENCY_PAIRS:o.InvalidOrder,TOO_MANY_ORDERS:o.InvalidOrder,TOO_MANY_REQUESTS:o.RateLimitExceeded,MIXED_ACCOUNT_TYPE:o.InvalidOrder,AUTO_BORROW_TOO_MUCH:o.ExchangeError,TRADE_RESTRICTED:o.InsufficientFunds,USER_NOT_FOUND:o.AccountNotEnabled,CONTRACT_NO_COUNTER:o.ExchangeError,CONTRACT_NOT_FOUND:o.BadSymbol,RISK_LIMIT_EXCEEDED:o.ExchangeError,INSUFFICIENT_AVAILABLE:o.InsufficientFunds,LIQUIDATE_IMMEDIATELY:o.InvalidOrder,LEVERAGE_TOO_HIGH:o.InvalidOrder,LEVERAGE_TOO_LOW:o.InvalidOrder,ORDER_NOT_OWNED:o.ExchangeError,ORDER_FINISHED:o.ExchangeError,POSITION_CROSS_MARGIN:o.ExchangeError,POSITION_IN_LIQUIDATION:o.ExchangeError,POSITION_IN_CLOSE:o.ExchangeError,POSITION_EMPTY:o.InvalidOrder,REMOVE_TOO_MUCH:o.ExchangeError,RISK_LIMIT_NOT_MULTIPLE:o.ExchangeError,RISK_LIMIT_TOO_HIGH:o.ExchangeError,RISK_LIMIT_TOO_lOW:o.ExchangeError,PRICE_TOO_DEVIATED:o.InvalidOrder,SIZE_TOO_LARGE:o.InvalidOrder,SIZE_TOO_SMALL:o.InvalidOrder,PRICE_OVER_LIQUIDATION:o.InvalidOrder,PRICE_OVER_BANKRUPT:o.InvalidOrder,ORDER_POC_IMMEDIATE:o.OrderImmediatelyFillable,INCREASE_POSITION:o.InvalidOrder,CONTRACT_IN_DELISTING:o.ExchangeError,INTERNAL:o.ExchangeNotAvailable,SERVER_ERROR:o.ExchangeNotAvailable,TOO_BUSY:o.ExchangeNotAvailable,CROSS_ACCOUNT_NOT_FOUND:o.ExchangeError,RISK_LIMIT_TOO_LOW:o.BadRequest,AUTO_TRIGGER_PRICE_LESS_LAST:o.InvalidOrder,AUTO_TRIGGER_PRICE_GREATE_LAST:o.InvalidOrder,POSITION_HOLDING:o.BadRequest,USER_LOAN_EXCEEDED:o.BadRequest,NO_CHANGE:o.InvalidOrder,PRICE_THRESHOLD_EXCEEDED:o.InvalidOrder},broad:{"Your order size":o.InvalidOrder}},rollingWindowSize:5e3})}setSandboxMode(e){super.setSandboxMode(e),this.options.sandboxMode=e}async loadUnifiedStatus(e={}){if(void 0===this.safeBool(this.options,"unifiedAccount"))try{let t=await this.privateAccountGetDetail(e),i=this.safeDict(t,"key",{});this.options.unifiedAccount=2===this.safeInteger(i,"mode")}catch(e){this.options.unifiedAccount=!1}return this.options.unifiedAccount}async upgradeUnifiedTradeAccount(e={}){return await this.privateUnifiedPutUnifiedMode(e)}async fetchTime(e={}){let t=await this.publicSpotGetTime(e);return this.safeInteger(t,"server_time")}createExpiredOptionMarket(e){let t,i="USDT",s=e.split("-"),r=e.split("/"),a=e.split("_"),o=this.safeString(s,1);e.indexOf("/")>-1?t=this.safeString(r,0):(t=this.safeString(a,0),o=o.slice(2,8));let n=this.safeString(s,2),d=this.safeString(s,3),h=this.convertExpireDate(o),c=this.parse8601(h);return{id:t+"_"+i+"-20"+o+"-"+n+"-"+d,symbol:t+"/"+i+":"+i+"-"+o+"-"+n+"-"+d,base:t,quote:i,settle:i,baseId:t,quoteId:i,settleId:i,active:!1,type:"option",linear:void 0,inverse:void 0,spot:!1,swap:!1,future:!1,option:!0,margin:!1,contract:!0,contractSize:this.parseNumber("1"),expiry:c,expiryDatetime:h,optionType:"C"===d?"call":"put",strike:this.parseNumber(n),precision:{amount:this.parseNumber("1"),price:void 0},limits:{amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},info:void 0}}safeMarket(e,t,i,s){return void 0!==e&&(e.indexOf("-C")>-1||e.indexOf("-P")>-1)&&(void 0===this.markets_by_id||!(e in this.markets_by_id))?this.createExpiredOptionMarket(e):super.safeMarket(e,t,i,s)}async fetchMarkets(e={}){this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference(),this.checkRequiredCredentials(!1)&&await this.loadUnifiedStatus();let t=[],i=this.safeDict(this.options,"fetchMarkets"),s=this.safeList(i,"types",["spot","swap","future","option"]);for(let i=0;i<s.length;i++){let r=this.safeString(s,i);"spot"===r?t.push(this.fetchSpotMarkets(e)):"swap"===r?t.push(this.fetchSwapMarkets(e)):"future"===r?t.push(this.fetchFutureMarkets(e)):"option"===r&&t.push(this.fetchOptionMarkets(e))}let r=await Promise.all(t);return this.arraysConcat(r)}async fetchSpotMarkets(e={}){let t=this.publicMarginGetCurrencyPairs(e),i=this.publicSpotGetCurrencyPairs(e),[s,r]=await Promise.all([t,i]),o=this.indexBy(s,"id"),n=[];for(let e=0;e<r.length;e++){let t=this.safeDict(r,e,{}),i=this.safeString(t,"id"),s=this.safeDict(o,i),d=this.deepExtend(s,t),[h,c]=i.split("_"),l=this.safeCurrencyCode(h),u=this.safeCurrencyCode(c);if(void 0===l||void 0===u)continue;let f=this.safeString(d,"fee"),p=this.safeString(d,"maker_fee_rate",f),m=this.parseNumber(this.parsePrecision(this.safeString(d,"amount_precision"))),g=this.safeString(d,"trade_status"),v=this.safeInteger(d,"status",1),y=void 0!==this.safeNumber(d,"leverage"),b=this.safeIntegerProduct(t,"buy_start",1e3),w=0!==b?b:void 0,k="tradable"===g||y&&1===v;n.push({id:i,symbol:l+"/"+u,base:l,quote:u,settle:void 0,baseId:h,quoteId:c,settleId:void 0,type:"spot",spot:!0,margin:y,swap:!1,future:!1,option:!1,active:k,contract:!1,linear:void 0,inverse:void 0,taker:this.parseNumber(a.Y.stringDiv(f,"100")),maker:this.parseNumber(a.Y.stringDiv(p,"100")),contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:m,price:this.parseNumber(this.parsePrecision(this.safeString(d,"precision")))},limits:{leverage:{min:this.parseNumber("1"),max:this.safeNumber(d,"leverage",1)},amount:{min:this.safeNumber(t,"min_base_amount",m),max:void 0},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(d,"min_quote_amount"),max:y?this.safeNumber(d,"max_quote_amount"):void 0}},created:w,info:d})}return n}async fetchSwapMarkets(e={}){let t=[],i=this.getSettlementCurrencies("swap","fetchMarkets");this.safeBool(this.options,"sandboxMode",!1)&&(i=["usdt"]);for(let s=0;s<i.length;s++){let r=i[s],a={settle:r},o=await this.publicFuturesGetSettleContracts(this.extend(a,e));for(let e=0;e<o.length;e++){let i=this.safeDict(o,e,{}),s=this.parseContractMarket(i,r);void 0!==s&&t.push(s)}}return t}async fetchFutureMarkets(e={}){if(this.safeBool(this.options,"sandboxMode",!1))return[];let t=[],i=this.getSettlementCurrencies("future","fetchMarkets");for(let s=0;s<i.length;s++){let r=i[s],a={settle:r},o=await this.publicDeliveryGetSettleContracts(this.extend(a,e));for(let e=0;e<o.length;e++){let i=this.safeDict(o,e,{}),s=this.parseContractMarket(i,r);void 0!==s&&t.push(s)}}return t}parseContractMarket(e,t){let i=this.safeString(e,"name"),s=i.split("_"),r=this.safeString(s,0),o=this.safeString(s,1),n=this.safeString(s,2),d=this.safeCurrencyCode(r),h=this.safeCurrencyCode(o);if(void 0===d||void 0===h)return;let c=this.safeCurrencyCode(t),l=this.safeTimestamp(e,"expire_time"),u="",f="swap";void 0!==n?(u=d+"/"+h+":"+c+"-"+this.yymmdd(l,""),f="future"):u=d+"/"+h+":"+c;let p=this.safeString(e,"order_price_deviate"),m=this.safeString(e,"mark_price"),g=a.Y.stringSub("1",p),v=a.Y.stringAdd("1",p),y=a.Y.stringMul(g,m),b=a.Y.stringMul(v,m),w=h===c,k=this.safeString(e,"quanto_multiplier");return"0"===k&&(k="1"),{id:i,symbol:u,base:d,quote:h,settle:c,baseId:r,quoteId:o,settleId:t,type:f,spot:!1,margin:!1,swap:"swap"===f,future:"future"===f,option:!1,active:"trading"===this.safeString(e,"status","trading"),contract:!0,linear:w,inverse:!w,taker:this.parseNumber("0.0005"),maker:this.parseNumber("0.0002"),contractSize:this.parseNumber(k),expiry:l,expiryDatetime:this.iso8601(l),strike:void 0,optionType:void 0,precision:{amount:this.parseNumber("1"),price:this.safeNumber(e,"order_price_round")},limits:{leverage:{min:this.safeNumber(e,"leverage_min"),max:this.safeNumber(e,"leverage_max")},amount:{min:this.safeNumber(e,"order_size_min"),max:this.safeNumber(e,"order_size_max")},price:{min:this.parseNumber(y),max:this.parseNumber(b)},cost:{min:void 0,max:void 0}},created:this.safeIntegerProduct(e,"create_time",1e3),info:e}}async fetchOptionMarkets(e={}){let t=[],i=await this.fetchOptionUnderlyings();for(let s=0;s<i.length;s++){let r=i[s],o=this.extend({},e);o.underlying=r;let n=await this.publicOptionsGetContracts(o);for(let e=0;e<n.length;e++){let i=this.safeDict(n,e,{}),s=this.safeString(i,"name"),o=r.split("_"),d=this.safeString(o,0),h=this.safeString(o,1),c=this.safeCurrencyCode(d),l=this.safeCurrencyCode(h);if(void 0===c||void 0===l)continue;let u=c+"/"+l,f=this.safeTimestamp(i,"expiration_time"),p=this.safeString(i,"strike_price"),m=this.safeBool(i,"is_call"),g="P";!0===m&&(g="C");let v="put";!0===m&&(v="call"),u=u+":"+l+"-"+this.yymmdd(f)+"-"+p+"-"+g;let y=this.safeString(i,"order_price_deviate"),b=this.safeString(i,"mark_price"),w=a.Y.stringSub("1",y),k=a.Y.stringAdd("1",y),S=a.Y.stringMul(w,b),O=a.Y.stringMul(k,b),T=this.safeTimestamp(i,"create_time");0===T&&(T=void 0),t.push({id:s,symbol:u,base:c,quote:l,settle:l,baseId:d,quoteId:h,settleId:h,type:"option",spot:!1,margin:!1,swap:!1,future:!1,option:!0,active:!0,contract:!0,linear:!0,inverse:!1,taker:this.parseNumber("0.0003"),maker:this.parseNumber("0.0003"),contractSize:this.parseNumber("1"),expiry:f,expiryDatetime:this.iso8601(f),strike:this.parseNumber(p),optionType:v,precision:{amount:this.parseNumber("1"),price:this.safeNumber(i,"order_price_round")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(i,"order_size_min"),max:this.safeNumber(i,"order_size_max")},price:{min:this.parseNumber(S),max:this.parseNumber(O)},cost:{min:void 0,max:void 0}},created:T,info:i})}}return t}async fetchOptionUnderlyings(){let e=await this.publicOptionsGetUnderlyings(),t=[];for(let i=0;i<e.length;i++){let s=this.safeDict(e,i,{}),r=this.safeString(s,"name");void 0!==r&&t.push(r)}return t}prepareRequest(e,t,i={}){let s={};if(void 0!==e)!0===e.contract?(s.contract=e.id,!0!==e.option&&(s.settle=e.settleId)):s.currency_pair=e.id;else{let e="swap"===t;if(e||"future"===t){let t="btc";return e&&(t="usdt"),s.settle=this.safeStringLower(i,"settle",t),[s,this.omit(i,"settle")]}}return[s,i]}spotOrderPrepareRequest(e,t=!1,i={}){let[s,r]=this.getMarginMode(t,i),a={};if(!t){if(void 0===e)throw new o.ArgumentsRequired(this.id+" spotOrderPrepareRequest() requires a market argument for non-trigger orders");a.account=s,a.currency_pair=e.id}return[a,r]}multiOrderSpotPrepareRequest(e,t=!1,i={}){let[s,r]=this.getMarginMode(t,i),a={account:s};return void 0!==e&&(t?a.market=e.id:a.currency_pair=e.id),[a,r]}getMarginMode(e,t){let i=this.safeStringLower2(this.options,"defaultMarginMode","marginMode","spot"),s=this.safeStringLower2(t,"marginMode","account",i),r=this.omit(t,["marginMode","account"]);if("cross"===s?s="cross_margin":"isolated"===s?s="margin":""===s&&(s="spot"),!0===e&&("spot"===s&&(s="normal"),"cross_margin"===s))throw new o.BadRequest(this.id+" getMarginMode() does not support trigger orders for cross margin");let[a,n]=this.handleOptionBoolAndParams(r,"getMarginMode","unifiedAccount",!1);return a&&(s="unified"),[s,n]}getSettlementCurrencies(e,t){let i=this.safeDict(this.options,e,{}),s=this.safeDict(i,t,{});return this.safeList(s,"settlementCurrencies","swap"===e?["usdt"]:["btc"])}async fetchCurrencies(e={}){if(void 0!==this.safeDict(this.urls,"apiBackup"))return{};let t=await this.publicSpotGetCurrencies(e);return this.parseCurrencies(t)}parseCurrency(e){let t=this.safeString(e,"currency"),i=this.safeCurrencyCode(t),s="crypto";this.isLeveragedCurrency(t)&&(s="leveraged");let r=this.safeList(e,"chains",[]),a={};for(let e=0;e<r.length;e++){let t=r[e],s=this.safeString(t,"name"),o=this.networkIdToCode(s,i);void 0!==o&&(a[o]={info:t,id:s,network:o,active:void 0,deposit:!this.safeBool(t,"deposit_disabled",!1),withdraw:!this.safeBool(t,"withdraw_disabled",!1),fee:void 0,precision:this.parseNumber("0.0001"),limits:{deposit:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}}})}return this.safeCurrencyStructure({id:t,code:i,name:this.safeString(e,"name"),type:s,active:!this.safeBool(e,"delisted",!1),deposit:!this.safeBool(e,"deposit_disabled",!1),withdraw:!this.safeBool(e,"withdraw_disabled",!1),fee:void 0,networks:a,precision:this.parseNumber("0.0001"),info:e})}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new o.BadSymbol(this.id+" fetchFundingRate() supports swap contracts only");let[s,r]=this.prepareRequest(i,void 0,t),a=await this.publicFuturesGetSettleContractsContract(this.extend(s,r));return this.parseFundingRate(a)}async fetchFundingRates(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e);if(void 0!==s){let e=this.safeString(s,0);i=this.market(e)}let[r,a]=this.prepareRequest(i,"swap",t),o=await this.publicFuturesGetSettleContracts(this.extend(r,a));return this.parseFundingRates(o,s)}parseFundingRate(e,t){let i=this.safeString(e,"name"),s=this.safeSymbol(i,t,"_","swap"),r=this.safeNumber(e,"mark_price"),o=this.safeNumber(e,"index_price"),n=this.safeNumber(e,"interest_rate"),d=this.safeNumber(e,"funding_rate"),h=this.safeTimestamp(e,"funding_next_apply"),c=this.safeNumber(e,"funding_rate_indicative"),l=a.Y.stringMul("1000",this.safeString(e,"funding_interval"));return{info:e,symbol:s,markPrice:r,indexPrice:o,interestRate:n,estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:d,fundingTimestamp:h,fundingDatetime:this.iso8601(h),nextFundingRate:c,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:this.parseFundingInterval(l)}}parseFundingInterval(e){return this.safeString({36e5:"1h",144e5:"4h",288e5:"8h",576e5:"16h",864e5:"24h"},e,e)}async fetchNetworkDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={currency:this.currency(e).id},s=await this.privateWalletGetDepositAddress(this.extend(i,t)),r=this.safeValue(s,"multichain_addresses"),a=this.safeString(s,"currency"),o=this.safeCurrencyCode(a),n={};for(let e=0;e<r.length;e++){let t=r[e],i=this.safeInteger(t,"obtain_failed");if(void 0!==i&&0!==i)continue;let s=this.safeString(t,"chain"),a=this.safeString(t,"address"),d=this.safeString(t,"payment_id");n[s]={info:t,code:o,currency:o,address:a,tag:d}}return n}async fetchDepositAddressesByNetwork(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={currency:i.id},r=await this.privateWalletGetDepositAddress(this.extend(s,t)),a=this.safeList(r,"multichain_addresses",[]),o=this.safeString(r,"currency");i=this.safeCurrency(o,i);let n=this.parseDepositAddresses(a,void 0,!1);return this.indexBy(n,"network")}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleNetworkCodeAndParams(t),r=await this.fetchDepositAddressesByNetwork(e,s),a=this.selectNetworkCodeFromUnifiedNetworks(e,i,r);return r[a]}parseDepositAddress(e,t){let i=this.safeString(e,"address");this.checkAddress(i);let s=this.safeString(t,"code");return{info:e,currency:s,address:i,tag:this.safeString(e,"payment_id"),network:this.networkIdToCode(this.safeString(e,"chain"),s)}}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={currency_pair:i.id},r=await this.privateWalletGetFee(this.extend(s,t));return this.parseTradingFee(r,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateWalletGetFee(e);return this.parseTradingFees(t)}parseTradingFees(e){let t={},i=this.symbols;for(let s=0;s<i.length;s++){let r=i[s],a=this.market(r);t[r]=this.parseTradingFee(e,a)}return t}parseTradingFee(e,t){let i=this.safeBool(e,"gt_discount"),s="taker_fee";!0===i&&(s="gt_taker_fee");let r="maker_fee";!0===i&&(r="gt_maker_fee");let a=this.safeBool(t,"contract"),o=s;!0===a&&(o="futures_taker_fee");let n=r;return!0===a&&(n="futures_maker_fee"),{info:e,symbol:this.safeString(t,"symbol"),maker:this.safeNumber(e,n),taker:this.safeNumber(e,o),percentage:void 0,tierBased:void 0}}async fetchTransactionFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privateWalletGetWithdrawStatus(t),s={},r={};for(let t=0;t<i.length;t++){r={};let a=this.safeDict(i,t,{}),o=this.safeString(a,"currency"),n=this.safeCurrencyCode(o);if(void 0!==e&&!this.inArray(n,e))continue;let d=this.safeDict(a,"withdraw_fix_on_chains");if(void 0===d)r=this.safeNumber(a,"withdraw_fix");else{let e=Object.keys(d);for(let t=0;t<e.length;t++){let i=e[t],s=this.networkIdToCode(i,n);void 0!==s&&(r[s]=this.parseNumber(d[i]))}}s[n]={withdraw:r,deposit:void 0,info:a}}return s}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privateWalletGetWithdrawStatus(t);return this.parseDepositWithdrawFees(i,e,"currency")}parseDepositWithdrawFee(e,t){let i=this.safeDict(e,"withdraw_fix_on_chains"),s={info:e,withdraw:{fee:this.safeNumber(e,"withdraw_fix"),percentage:!1},deposit:{fee:this.safeNumber(e,"deposit"),percentage:!1},networks:{}};if(void 0!==i){let r=Object.keys(i);for(let a=0;a<r.length;a++){let o=r[a],n=this.safeString(e,"currency"),d=this.safeCurrencyCode(n,t),h=this.networkIdToCode(o,d);void 0!==h&&(s.networks[h]={withdraw:{fee:this.parseNumber(i[o]),percentage:!1},deposit:{fee:void 0,percentage:void 0}})}}return s}async fetchFundingHistory(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(a=this.market(e));let n=void 0!==a?a.symbol:void 0,[d,h]=this.handleMarketTypeAndParams("fetchFundingHistory",a,s),[c,l]=this.prepareRequest(a,d,h);if(c.type="fund",void 0!==t&&(c.from=this.parseToInt(t/1e3)),void 0!==i&&(c.limit=i),"swap"===d)r=await this.privateFuturesGetSettleAccountBook(this.extend(c,l));else if("future"===d)r=await this.privateDeliveryGetSettleAccountBook(this.extend(c,l));else throw new o.NotSupported(this.id+" fetchFundingHistory() only support swap & future market type");return this.parseFundingHistories(r,n,t,i)}parseFundingHistories(e,t,i,s){let r=[];for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s=this.parseFundingHistory(i);r.push(s)}let a=this.sortBy(r,"timestamp");return this.filterBySymbolSinceLimit(a,t,i,s)}parseFundingHistory(e,t){let i=this.safeTimestamp(e,"time"),s=this.safeString(e,"text"),r=this.safeMarket(s,t,"_","swap");return{info:e,symbol:this.safeString(r,"symbol"),code:this.safeString(r,"settle"),timestamp:i,datetime:this.iso8601(i),id:void 0,amount:this.safeNumber(e,"change")}}async fetchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),[a,n]=this.prepareRequest(r,this.safeString(r,"type"),i);if(void 0!==t&&(a.limit=Math.min(t,!0===r.spot?this.handleOption("fetchOrderBook","maxSpotLimit",1e3):300)),a.with_id=!0,!0===r.spot||!0===r.margin)s=await this.publicSpotGetOrderBook(this.extend(a,n));else if(!0===r.swap)s=await this.publicFuturesGetSettleOrderBook(this.extend(a,n));else if(!0===r.future)s=await this.publicDeliveryGetSettleOrderBook(this.extend(a,n));else if(!0===r.option)s=await this.publicOptionsGetOrderBook(this.extend(a,n));else throw new o.NotSupported(this.id+" fetchOrderBook() not support this market type");let d=this.safeInteger(s,"current");if(void 0===d)throw new o.ExchangeError(this.id+" method() missing timestamp");!0!==r.spot&&(d*=1e3);let h=!0===r.spot?0:"p",c=!0===r.spot?1:"s",l=this.safeInteger(s,"id"),u=this.parseOrderBook(s,e,d,"bids","asks",h,c);return u.nonce=l,u}async fetchTicker(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),[a,n]=this.prepareRequest(r,void 0,t);if(!0===r.spot||!0===r.margin)i=await this.publicSpotGetTickers(this.extend(a,n));else if(!0===r.swap)i=await this.publicFuturesGetSettleTickers(this.extend(a,n));else if(!0===r.future)i=await this.publicDeliveryGetSettleTickers(this.extend(a,n));else if(!0===r.option){let e=r.id.split("-");a.underlying=this.safeString(e,0),i=await this.publicOptionsGetTickers(this.extend(a,n))}else throw new o.NotSupported(this.id+" fetchTicker() not support this market type");if(!0===r.option)for(let e=0;e<i.length;e++){let t=i[e];if(this.safeString(t,"name")===r.id){s=t;break}}else s=this.safeDict(i,0);if(void 0===s)throw new o.NullResponse(this.id+" fetchTicker() returned empty response");return this.parseTicker(s,r)}parseTicker(e,t){let i=this.safeStringN(e,["currency_pair","contract","name"]),s="spot";"mark_price"in e&&(s="contract");let r=this.safeSymbol(i,t,"_",s),a=this.safeString2(e,"last","last_price"),o=this.safeStringN(e,["lowest_ask","a","ask1_price"]),n=this.safeStringN(e,["highest_bid","b","bid1_price"]),d=this.safeString(e,"high_24h"),h=this.safeString(e,"low_24h"),c=this.safeString2(e,"B","bid1_size"),l=this.safeString2(e,"A","ask1_size"),u=this.safeInteger(e,"t"),f=this.safeString2(e,"base_volume","volume_24h_base");"nan"===f&&(f="0");let p=this.safeString2(e,"quote_volume","volume_24h_quote");"nan"===p&&(p="0");let m=this.safeString(e,"change_percentage");return this.safeTicker({symbol:r,timestamp:u,datetime:this.iso8601(u),high:d,low:h,bid:n,bidVolume:c,ask:o,askVolume:l,vwap:void 0,open:void 0,close:a,last:a,previousClose:void 0,change:void 0,percentage:m,average:void 0,baseVolume:f,quoteVolume:p,markPrice:this.safeString(e,"mark_price"),indexPrice:this.safeString(e,"index_price"),info:e},t)}async fetchTickers(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e),a=this.safeString(r,0);void 0!==a&&(s=this.market(a));let[n,d]=this.handleMarketTypeAndParams("fetchTickers",s,t),[h,c]=this.prepareRequest(void 0,n,d);if(h.timezone="utc0","spot"===n||"margin"===n)i=await this.publicSpotGetTickers(this.extend(h,c));else if("swap"===n)i=await this.publicFuturesGetSettleTickers(this.extend(h,c));else if("future"===n)i=await this.publicDeliveryGetSettleTickers(this.extend(h,c));else if("option"===n){this.checkRequiredArgument("fetchTickers",r,"symbols");let e=this.safeString(s,"id").split("-");h.underlying=this.safeString(e,0),i=await this.publicOptionsGetTickers(this.extend(h,c))}else throw new o.NotSupported(this.id+' fetchTickers() not support this market type, provide symbols or set params["defaultType"] to one from spot/margin/swap/future/option');return this.parseTickers(i,r)}parseBalanceHelper(e){let t=this.account();return t.used=this.safeString2(e,"freeze","locked"),t.free=this.safeString(e,"available"),t.total=this.safeString(e,"total"),"borrowed"in e&&(t.debt=this.safeString(e,"borrowed")),t}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus();let i=this.safeString(e,"symbol"),s=this.omit(e,"symbol"),[r,a]=this.handleOptionBoolAndParams(s,"fetchBalance","unifiedAccount",!1),[n,d]=this.handleMarketTypeAndParams("fetchBalance",void 0,a),[h,c]=this.prepareRequest(void 0,n,d),[l,u]=this.getMarginMode(!1,c);if(void 0!==i&&(h.currency_pair=this.market(i).id),r)t=await this.privateUnifiedGetAccounts(this.extend(h,a));else if("spot"===n)if("spot"===l)t=await this.privateSpotGetAccounts(this.extend(h,u));else if("margin"===l)t=await this.privateMarginGetAccounts(this.extend(h,u));else if("cross_margin"===l)t=await this.privateMarginGetCrossAccounts(this.extend(h,u));else throw new o.NotSupported(this.id+" fetchBalance() not support this marginMode");else if("funding"===n)t=await this.privateMarginGetFundingAccounts(this.extend(h,u));else if("swap"===n)t=await this.privateFuturesGetSettleAccounts(this.extend(h,u));else if("future"===n)t=await this.privateDeliveryGetSettleAccounts(this.extend(h,u));else if("option"===n)t=await this.privateOptionsGetAccounts(this.extend(h,u));else throw new o.NotSupported(this.id+" fetchBalance() not support this market type");("swap"===n||"future"===n||"option"===n)&&(t=[t]);let f={info:t},p="margin"===l&&"spot"===n,m=t;if("balances"in m){let e=[],t=this.safeDict(m,"balances",{}),i=Object.keys(t);for(let s=0;s<i.length;s++){let r=i[s],a=t[r];a.currency=r,e.push(a)}m=e}for(let e=0;e<m.length;e++){let t=m[e];if(p){let e=this.safeDict(t,"base",{}),i=this.safeDict(t,"quote",{}),s=this.safeCurrencyCode(this.safeString(e,"currency")),r=this.safeCurrencyCode(this.safeString(i,"currency"));f=this.mergeBalanceAccount(f,s,this.parseBalanceHelper(e)),f=this.mergeBalanceAccount(f,r,this.parseBalanceHelper(i))}else f[this.safeCurrencyCode(this.safeString(t,"currency"))]=this.parseBalanceHelper(t)}return this.safeBalance(f)}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),[o,n]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(o)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,n,1e3);if(!0===a.option)return await this.fetchOptionOHLCV(e,t,i,s,n);let d=this.safeString(n,"price"),[h,c]=this.prepareRequest(a,void 0,n);h.interval=this.safeString(this.timeframes,t,t);let l=!0===a.contract?1999:1e3,u=void 0===s?l:Math.min(s,l),f=this.safeInteger(c,"until");void 0!==f&&(f=this.parseToInt(f/1e3));let p=this.omit(c,"until");if(void 0!==i){let e=this.parseTimeframe(t);h.from=this.parseToInt(i/1e3);let s=(u-1)*e,r=Math.min(this.sum(h.from,s),this.seconds());void 0!==f?h.to=Math.min(r,f):h.to=r}else void 0!==f&&(h.to=f),h.limit=u;let m=[];if(!0===a.contract){let e="mark"===d,t="index"===d;(e||t)&&(h.contract=d+"_"+a.id);let i=p;(e||t)&&(i=this.omit(p,"price")),!0===a.future?m=await this.publicDeliveryGetSettleCandlesticks(this.extend(h,i)):!0===a.swap&&(m=await this.publicFuturesGetSettleCandlesticks(this.extend(h,i)))}else m=await this.publicSpotGetCandlesticks(this.extend(h,p));return this.parseOHLCVs(this.toArray(m),a,t,i,u)}async fetchOptionOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),[o,n]=this.prepareRequest(a,void 0,r);o.interval=this.safeString(this.timeframes,t,t);let d=await this.publicOptionsGetCandlesticks(this.extend(o,n));return this.parseOHLCVs(this.toArray(d),a,t,i,s)}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(r)return await this.fetchPaginatedCallDeterministic("fetchFundingRateHistory",e,t,i,"8h",a);let n=this.market(e);if(!0!==n.swap)throw new o.BadSymbol(this.id+" fetchFundingRateHistory() supports swap contracts only");let[d,h]=this.prepareRequest(n,void 0,a);void 0!==i&&(d.limit=i),void 0!==t&&(d.from=this.parseToInt(t/1e3));let c=this.safeInteger(h,"until");void 0!==c&&(d.to=this.parseToInt(c/1e3));let l=await this.publicFuturesGetSettleFundingRate(this.extend(d,this.omit(h,"until"))),u=[];for(let t=0;t<l.length;t++){let i=this.safeDict(l,t,{}),s=this.safeTimestamp(i,"t");u.push({info:i,symbol:e,fundingRate:this.safeNumber(i,"r"),timestamp:s,datetime:this.iso8601(s)})}let f=this.sortBy(u,"timestamp");return this.filterBySymbolSinceLimit(f,this.safeString(n,"symbol"),t,i)}parseOHLCV(e,t){return Array.isArray(e)?[this.safeTimestamp(e,0),this.safeNumber(e,5),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,2),this.safeNumber(e,6)]:[this.safeTimestamp(e,"t"),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,n]=this.handleOptionBoolAndParams(s,"fetchTrades","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchTrades",e,t,i,n);let d=this.market(e),[h,c]=this.prepareRequest(d,void 0,n),l=this.safeInteger2(n,"to","until");if(void 0!==l&&(h.to=this.parseToInt(l/1e3)),void 0!==i&&(h.limit=Math.min(i,1e3)),void 0!==t&&!0===d.contract&&(h.from=this.parseToInt(t/1e3)),"spot"===d.type||"margin"===d.type)r=await this.publicSpotGetTrades(this.extend(h,c));else if(!0===d.swap)r=await this.publicFuturesGetSettleTrades(this.extend(h,c));else if(!0===d.future)r=await this.publicDeliveryGetSettleTrades(this.extend(h,c));else if("option"===d.type)r=await this.publicOptionsGetTrades(this.extend(h,c));else throw new o.NotSupported(this.id+" fetchTrades() not support this market type.");return this.parseTrades(r,d,t,i)}async fetchOrderTrades(e,t,i,s,r={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" fetchOrderTrades() requires a symbol argument");return void 0===this.markets&&await this.loadMarkets(),await this.fetchMyTrades(t,i,s,{order_id:e})}async fetchMyTrades(e,t,i,s={}){let r,a,n;void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus();let[d,h]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(d)return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,h);let c={},l=void 0!==e?this.market(e):void 0,u=this.safeInteger(h,"until"),f=this.omit(h,["until"]),[p,m]=this.handleMarketTypeAndParams("fetchMyTrades",l,f);if("swap"===p||"future"===p||"option"===p){let e;[c,e]=this.prepareRequest(l,p,m),n="option"===p?this.omit(e,"order_id"):e}else void 0!==l&&(c.currency_pair=l.id),[a,n]=this.getMarginMode(!1,m),c.account=a;if(void 0!==i&&(c.limit=i),void 0!==t&&(c.from=this.parseToInt(t/1e3)),void 0!==u&&(c.to=this.parseToInt(u/1e3)),"spot"===p||"margin"===p)r=await this.privateSpotGetMyTrades(this.extend(c,n));else if("swap"===p)r=await this.privateFuturesGetSettleMyTradesTimerange(this.extend(c,n));else if("future"===p)r=await this.privateDeliveryGetSettleMyTrades(this.extend(c,n));else if("option"===p)r=await this.privateOptionsGetMyTrades(this.extend(c,n));else throw new o.NotSupported(this.id+" fetchMyTrades() not support this market type.");return this.parseTrades(r,l,t,i)}parseTrade(e,t){let i,s=this.safeString2(e,"id","trade_id"),r=this.safeString(e,"create_time_ms");void 0!==r?(r=(r=a.Y.stringMul(r,"1000")).slice(0,13),i=this.parseToInt(r)):i=this.safeTimestamp2(e,"time","create_time");let o=this.safeString2(e,"currency_pair","contract"),n="spot";"contract"in e&&(n="contract");let d=this.safeMarket(o,t,"_",n),h=this.safeString2(e,"amount","size"),c=this.safeString(e,"price"),l="buy";a.Y.stringLt(h,"0")&&(l="sell"),h=a.Y.stringAbs(h);let u=this.safeString2(e,"side","type",l),f=this.safeString(e,"order_id"),p=this.safeString(e,"fee"),m=this.omitZero(this.safeString(e,"gt_fee")),g=this.omitZero(this.safeString(e,"point_fee")),v=[];if(void 0!==p){let t=this.safeString(e,"fee_currency"),i=this.safeCurrencyCode(t);void 0===i&&(i=this.safeString(d,"settle")),v.push({cost:p,currency:i})}void 0!==m&&v.push({cost:m,currency:"GT"}),void 0!==g&&v.push({cost:g,currency:"GATEPOINT"});let y=this.safeString(e,"role");return this.safeTrade({info:e,id:s,timestamp:i,datetime:this.iso8601(i),symbol:d.symbol,order:f,type:void 0,side:u,takerOrMaker:y,price:c,amount:h,cost:void 0,fee:void 0,fees:v},d)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchDeposits","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchDeposits",e,t,i,o);let n={};if(void 0!==e&&(n.currency=(r=this.currency(e)).id),void 0!==i&&(n.limit=i),void 0!==t){let e=this.parseToInt(t/1e3);n.from=e,n.to=this.sum(e,2592e3)}let[d,h]=this.handleUntilOption("to",n,o,.001),c=await this.privateWalletGetDeposits(this.extend(d,h));return this.parseTransactions(c,r)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchWithdrawals","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchWithdrawals",e,t,i,o);let n={};if(void 0!==e&&(n.currency=(r=this.currency(e)).id),void 0!==i&&(n.limit=i),void 0!==t){let e=this.parseToInt(t/1e3);n.from=e,n.to=this.sum(e,2592e3)}let[d,h]=this.handleUntilOption("to",n,o,.001),c=await this.privateWalletGetWithdrawals(this.extend(d,h));return this.parseTransactions(c,r)}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d={currency:n.id,address:i,amount:this.currencyToPrecision(e,t)};void 0!==a&&(d.memo=a);let[h,c]=this.handleNetworkCodeAndParams(o);void 0!==h&&(d.chain=this.networkCodeToId(h,e));let l=await this.privateWithdrawalsPostWithdrawals(this.extend(d,c));return this.parseTransaction(l,n)}parseTransactionStatus(e){return this.safeString({PEND:"pending",REQUEST:"pending",DMOVE:"pending",MANUAL:"pending",VERIFY:"pending",PROCES:"pending",EXTPEND:"pending",SPLITPEND:"pending",CANCEL:"canceled",FAIL:"failed",INVALID:"failed",DONE:"ok",BCODE:"ok"},e,e)}parseTransactionType(e){return this.safeString({d:"deposit",w:"withdrawal"},e,e)}parseTransaction(e,t){let i,s=this.safeString(e,"id"),r=this.safeString(e,"amount");void 0!==s&&("b"===s[0]?(i=a.Y.stringGt(r,"0")?"deposit":"withdrawal",r=a.Y.stringAbs(r)):i=this.parseTransactionType(s[0]));let o=this.safeString2(e,"fee","fee_amount");"withdrawal"===i&&(r=a.Y.stringSub(r,o));let n=this.safeStringUpper(e,"chain"),d=this.safeString(e,"currency"),h=this.safeCurrencyCode(d),c=this.safeString(e,"txid"),l=this.safeString(e,"status"),u=this.parseTransactionStatus(l),f=this.safeString(e,"address"),p=this.safeString(e,"memo"),m=this.safeTimestamp(e,"timestamp");return{info:e,id:s,txid:c,currency:h,amount:this.parseNumber(r),network:this.networkIdToCode(n,h),address:f,addressTo:void 0,addressFrom:void 0,tag:p,tagTo:void 0,tagFrom:void 0,status:u,type:i,timestamp:m,datetime:this.iso8601(m),updated:void 0,internal:void 0,comment:void 0,fee:{currency:h,cost:this.parseNumber(o)}}}async createOrder(e,t,i,s,r,a={}){let o;void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus();let n=this.market(e),d=this.safeValue(a,"trigger"),h=this.safeValue2(a,"triggerPrice","stopPrice"),c=this.safeValue(a,"stopLossPrice",h),l=this.safeString(a,"takeProfitPrice"),u=void 0===c&&void 0===l&&void 0===d,f=this.createOrderRequest(e,t,i,s,r,a);return o=!0===n.spot||!0===n.margin?u?await this.privateSpotPostOrders(f):await this.privateSpotPostPriceOrders(f):!0===n.swap?u?await this.privateFuturesPostSettleOrders(f):await this.privateFuturesPostSettlePriceOrders(f):!0===n.future?u?await this.privateDeliveryPostSettleOrders(f):await this.privateDeliveryPostSettlePriceOrders(f):await this.privateOptionsPostOrders(f),this.parseOrder(o,n)}createOrdersRequest(e,t={}){let i=[],s=[],r=e.length;if(0===r)throw new o.BadRequest(this.id+" createOrders() requires at least one order");if(r>10)throw new o.BadRequest(this.id+" createOrders() accepts a maximum of 10 orders at a time");for(let r=0;r<e.length;r++){let a=this.safeDict(e,r),n=this.safeString(a,"symbol");s.push(n);let d=this.safeString(a,"type"),h=this.safeString(a,"side"),c=this.safeValue(a,"amount"),l=this.safeValue(a,"price"),u=this.safeDict(a,"params",{}),f=this.extend(u,t);if(void 0!==this.safeValueN(u,["triggerPrice","stopPrice","takeProfitPrice","stopLossPrice"]))throw new o.NotSupported(this.id+" createOrders() does not support advanced order properties (stopPrice, takeProfitPrice, stopLossPrice)");f.textIsRequired=!0;let p=this.createOrderRequest(n,d,h,c,l,f);i.push(p)}let a=this.marketSymbols(s,void 0,!1,!0,!0),n=this.market(a[0]);if(!0===n.future||!0===n.option)throw new o.NotSupported(this.id+" createOrders() does not support futures or options markets");return i}async createOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus();let s=this.createOrdersRequest(e,t),r=e[0],a=this.market(r.symbol);return!0===a.spot?i=await this.privateSpotPostBatchOrders(s):!0===a.swap&&(i=await this.privateFuturesPostSettleBatchOrders(s)),this.parseOrders(i)}createOrderRequest(e,t,i,s,r,n={}){let d;if(void 0===t)throw new o.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new o.ArgumentsRequired(this.id+" requires a side argument");let h=this.market(e),c=h.contract,l=this.safeValue(n,"trigger"),u=this.safeValue2(n,"triggerPrice","stopPrice"),f=this.safeValue(n,"stopLossPrice",u),p=this.safeValue(n,"takeProfitPrice"),m=void 0!==f,g=void 0!==p;if(m&&g)throw new o.ExchangeError(this.id+" createOrder() stopLossPrice and takeProfitPrice cannot both be defined");let v=this.safeValue(n,"reduceOnly"),y=this.safeStringLowerN(n,["timeInForce","tif","time_in_force"]),[b,w]=this.handlePostOnly("market"===t,"poc"===y,n),k=this.handleTimeInForce(w);!0===b&&(k="poc");let S=this.safeString2(w,"text","clientOrderId"),O=this.omit(w,["stopPrice","triggerPrice","stopLossPrice","takeProfitPrice","reduceOnly","timeInForce","postOnly","clientOrderId"]),T="limit"===t,P="market"===t;if(T&&void 0===r)throw new o.ArgumentsRequired(this.id+" createOrder () requires a price argument for "+t+" orders");if(P){if("poc"===k||"gtc"===k)throw new o.ExchangeError(this.id+' createOrder () timeInForce for market order can only be "FOK" or "IOC"');else if(void 0===k){let e=this.safeString(this.options,"defaultTimeInForce","IOC");k=this.safeString(this.options.timeInForce,e,"ioc")}}let I=r;P&&!0===c&&(I=0);let A=0;if(!0===c&&!0!==this.safeBool(O,"close")){let t=this.amountToPrecision(e,s),r=t;"sell"===i&&(r=a.Y.stringNeg(t)),A=parseInt(r)}let x=!0===c?A:s;if(m||g||void 0!==l){if(!0===h.option)throw new o.NotSupported(this.id+" createOrder() conditional option orders are not supported");if(!0===c){if(d={initial:{contract:h.id,size:x},settle:h.settleId},"market"===t?d.initial.price="0":d.initial.price=0===I?"0":this.priceToPrecision(e,I),void 0===l){let t,s;m?(t="buy"===i?1:2,s=this.priceToPrecision(e,f)):g&&(t="buy"===i?2:1,s=this.priceToPrecision(e,p));let r=this.safeInteger(O,"price_type",0);if(r<0||r>2)throw new o.BadRequest(this.id+" createOrder () price_type should be 0 latest deal price, 1 mark price, 2 index price");O=this.omit(O,["price_type"]),d.trigger={price_type:r,price:this.priceToPrecision(e,s),rule:t}}void 0!==v&&(d.initial.reduce_only=v),void 0!==k&&(d.initial.tif=k),void 0!==S&&(d.initial.text=S)}else{let s,r=this.safeDict(this.options,"createOrder",{});if([s,O]=this.getMarginMode(!0,O),void 0===k&&(k="gtc"),d={put:{type:t,side:i,price:this.priceToPrecision(e,I),amount:this.amountToPrecision(e,x),account:s,time_in_force:k},market:h.id},void 0===l){let t,s,a=this.safeInteger(r,"expiration"),o=this.safeInteger(O,"expiration",a);m?(t="buy"===i?">=":"<=",s=this.priceToPrecision(e,f)):g&&(t="buy"===i?"<=":">=",s=this.priceToPrecision(e,p)),d.trigger={price:this.priceToPrecision(e,s),rule:t,expiration:o},void 0!==S&&(d.trigger.text=S)}}}else{if(!0===c)d={contract:h.id,size:x},!0!==h.option&&(d.settle=h.settleId),P?d.price="0":d.price=0===I?"0":this.priceToPrecision(e,I),void 0!==v&&(d.reduce_only=v),void 0!==k&&(d.tif=k);else{let s;if([s,O]=this.getMarginMode(!1,O),d={currency_pair:h.id,type:t,account:s,side:i},P&&"buy"===i){let t,i=!0;[i,O]=this.handleOptionBoolAndParams(O,"createOrder","createMarketBuyOrderRequiresPrice",!0);let s=this.safeNumber(O,"cost");if(O=this.omit(O,"cost"),void 0!==s)t=this.costToPrecision(e,s);else if(i)if(void 0===I)throw new o.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend (quote quantity) in the amount argument");else{let i=this.numberToString(x),s=this.numberToString(I),r=a.Y.stringMul(i,s);t=this.costToPrecision(e,r)}else t=this.costToPrecision(e,x);d.amount=t}else d.amount=this.amountToPrecision(e,x);T&&(d.price=this.priceToPrecision(e,I)),void 0!==k&&(d.time_in_force=k)}let s=this.safeBool(O,"textIsRequired",!1);if(void 0!==S){if(S.length>28)throw new o.BadRequest(this.id+" createOrder () clientOrderId or text param must be up to 28 characters");O=this.omit(O,"textIsRequired"),"t"!==S[0]&&(S="t-"+S),d.text=S}else!0===s&&(d.text="t-"+this.uuid16())}return this.extend(d,O)}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus(),!0!==this.market(e).spot)throw new o.NotSupported(this.id+" createMarketBuyOrderWithCost() supports spot orders only");let s=this.extend(i,{createMarketBuyOrderRequiresPrice:!1});return await this.createOrder(e,"market","buy",t,void 0,s)}editOrderRequest(e,t,i,s,r,n,d={}){let h=this.market(t),[c,l]=this.handleMarketTypeAndParams("editOrder",h,d),u=this.convertTypeToAccount(c),[f,p]=this.handleOptionBoolAndParams(l,"editOrder","unifiedAccount",!1);if(f&&(u="unified"),"spot"===u&&"limit"!==i)throw new o.InvalidOrder(this.id+" editOrder() does not support "+i+" orders for "+c+" markets");let m={order_id:e.toString(),currency_pair:h.id,account:u};return void 0!==r&&(!0===h.spot?m.amount=this.amountToPrecision(t,r):"sell"===s?m.size=this.parseToNumeric(a.Y.stringNeg(this.amountToPrecision(t,r))):m.size=this.parseToNumeric(this.amountToPrecision(t,r))),void 0!==n&&(m.price=this.priceToPrecision(t,n)),!0!==h.spot&&(m.settle=h.settleId),this.extend(m,p)}async editOrder(e,t,i,s,r,a,o={}){let n;void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus();let d=this.market(t),h=this.editOrderRequest(e,t,i,s,r,a,o);return n=!0===d.spot?await this.privateSpotPatchOrdersOrderId(h):await this.privateFuturesPutSettleOrdersOrderId(h),this.parseOrder(n,d)}parseOrderStatus(e){return this.safeString({open:"open",_new:"open",filled:"closed",cancelled:"canceled",liquidated:"closed",ioc:"canceled",failed:"canceled",expired:"canceled",finished:"closed",finish:"closed",succeeded:"closed"},e,e)}parseOrder(e,t){let i,s;if(!0!==this.safeBool(e,"succeeded",!0))return this.safeOrder({clientOrderId:this.safeString(e,"text"),info:e,status:"rejected",id:this.safeString(e,"id")});let r=this.safeDict2(e,"put","initial",{}),o=this.safeDict(e,"trigger",{}),n=this.safeString(r,"contract"),d=this.safeString(r,"type"),h=this.safeStringUpper2(r,"time_in_force","tif"),c=this.safeString2(r,"amount","size"),l=this.safeString(r,"side"),u=this.safeString(r,"price");n=this.safeString(e,"contract",n),d=this.safeString(e,"type",d),"POC"===(h=this.safeStringUpper2(e,"time_in_force","tif",h))&&(h="PO");let f="PO"===h;c=this.safeString2(e,"amount","size",c),l=this.safeString(e,"side",l),u=this.safeString(e,"price",u);let p=this.safeString(e,"left"),m=this.safeString(e,"filled_total"),g=this.safeNumber(o,"price"),v=this.safeNumber2(e,"avg_deal_price","fill_price");void 0!==g&&0!==g&&(p=c,m="0"),void 0!==n&&""!==n&&(d=a.Y.stringEquals(u,"0")&&"IOC"===h?"market":"limit",l=a.Y.stringGt(c,"0")?"buy":"sell");let y=this.safeStringN(e,["finish_as","status","open"]),b=this.safeString(e,"create_time_ms");void 0===b&&void 0!==(b=this.safeString2(e,"create_time","ctime"))&&(10===b.length||b.indexOf(".")>=0?b=a.Y.stringMul(b,"1000"):16===b.length&&(b=a.Y.stringDiv(b,"1000")));let w=this.safeString(e,"update_time_ms");void 0===w&&void 0!==(w=this.safeString2(e,"update_time","finish_time"))&&(10===w.length||w.indexOf(".")>=0?w=a.Y.stringMul(w,"1000"):16===w.length&&(w=a.Y.stringDiv(w,"1000")));let k="contract";("currency_pair"in e||"market"in e)&&(k="spot");let S=this.safeString2(e,"currency_pair","market",n),O=this.safeSymbol(S,t,"_",k),T=[],P=this.safeString(e,"gt_fee");void 0!==P&&T.push({currency:"GT",cost:P});let I=this.safeString(e,"fee");void 0!==I&&T.push({currency:this.safeCurrencyCode(this.safeString(e,"fee_currency")),cost:I});let A=this.safeString(e,"rebated_fee");void 0!==A&&T.push({currency:this.safeCurrencyCode(this.safeString(e,"rebated_fee_currency")),cost:a.Y.stringNeg(A)});let x=T.length>1,M=this.parseOrderStatus(y),_=a.Y.stringAbs(p),C=this.safeString(e,"account");if("spot"===C||"unified"===C){let t=this.safeString(e,"avg_deal_price");v=this.parseNumber(t),"market"===d&&"buy"===l&&(_=a.Y.stringDiv(p,t),u=void 0,m=c,c=a.Y.stringDiv(c,t))}void 0!==b&&(i=this.parseToInt(b)),void 0!==w&&(s=this.parseToInt(w));let B=this.safeDict(e,"initial",{}),E=this.safeBool(B,"is_reduce_only"),R=this.safeBool(e,"is_reduce_only",E),L=this.safeString(e,"text");return void 0===L&&("initial"in e?L=this.safeString(e.initial,"text"):"trigger"in e&&(L=this.safeString(e.trigger,"text"))),this.safeOrder({id:this.safeString(e,"id"),clientOrderId:L,timestamp:i,datetime:this.iso8601(i),lastTradeTimestamp:s,status:M,symbol:O,type:d,timeInForce:h,postOnly:f,reduceOnly:R,side:l,price:u,triggerPrice:g,average:v,amount:a.Y.stringAbs(c),cost:a.Y.stringAbs(m),filled:void 0,remaining:_,fee:x?void 0:this.safeDict(T,0),fees:x?T:[],trades:void 0,info:e},t)}fetchOrderRequest(e,t,i={}){let s=void 0===t?void 0:this.market(t),r=this.safeBoolN(i,["trigger","is_stop_order","stop"],!1),a=this.omit(i,["is_stop_order","stop","trigger"]),o=this.safeString2(a,"text","clientOrderId"),n=e;void 0!==o&&("t"!==o[0]&&(o="t-"+o),n=o);let d=void 0!==o?this.omit(a,["text","clientOrderId"]):a,[h,c]=this.handleMarketTypeAndParams("fetchOrder",s,d),[l,u]="swap"===h||"future"===h||"option"===h?this.prepareRequest(s,h,c):this.spotOrderPrepareRequest(s,r,c);return l.order_id=n.toString(),[l,u]}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus();let r=void 0===t?void 0:this.market(t),a=this.handleMarketTypeAndParams("fetchOrder",r,i)[0],n=this.safeBoolN(i,["trigger","is_stop_order","stop"],!1),[d,h]=this.fetchOrderRequest(e,t,i);if("spot"===a||"margin"===a)s=!0===n?await this.privateSpotGetPriceOrdersOrderId(this.extend(d,h)):await this.privateSpotGetOrdersOrderId(this.extend(d,h));else if("swap"===a)s=!0===n?await this.privateFuturesGetSettlePriceOrdersOrderId(this.extend(d,h)):await this.privateFuturesGetSettleOrdersOrderId(this.extend(d,h));else if("future"===a)s=!0===n?await this.privateDeliveryGetSettlePriceOrdersOrderId(this.extend(d,h)):await this.privateDeliveryGetSettleOrdersOrderId(this.extend(d,h));else if("option"===a)s=await this.privateOptionsGetOrdersOrderId(this.extend(d,h));else throw new o.NotSupported(this.id+" fetchOrder() not support this market type");return this.parseOrder(s,r)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrdersByStatus("open",e,t,i,s)}async fetchClosedOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus();let[a,o]=this.handleOptionBoolAndParams(s,"fetchClosedOrders","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchClosedOrders",e,t,i,o);let n=this.safeInteger(o,"until");void 0!==e&&(r=this.market(e));let d=void 0!==r?this.safeString(r,"symbol"):e,h=this.handleMarketTypeAndParams("fetchClosedOrders",r,o)[0],[c,l]=this.handleOptionBoolAndParams(o,"fetchClosedOrders","historical",!1);if(!c&&(void 0===t&&void 0===n||"swap"!==h))return await this.fetchOrdersByStatus("finished",d,t,i,l);let[u,f]=this.prepareRequest(r,h,this.omit(l,"type"));void 0!==t&&(u.from=this.parseToInt(t/1e3)),void 0!==n&&(u.to=this.parseToInt(n/1e3)),void 0!==i&&(u.limit=i);let p=await this.privateFuturesGetSettleOrdersTimerange(this.extend(u,this.omit(f,"until")));return this.parseOrders(p,r,t,i)}prepareOrdersByStatusRequest(e,t,i,s,r={}){let a;void 0!==t&&(a=this.market(t));let[o,n]=this.handleParamBool2(r,"trigger","stop"),[d,h]=this.handleMarketTypeAndParams("fetchOrdersByStatus",a,n),c="spot"===d||"margin"===d,l={},u={};if([l,u]=c?this.multiOrderSpotPrepareRequest(a,o,h):this.prepareRequest(a,d,h),c&&!0===o&&(l=this.omit(l,"account")),l.status="closed"===e?"finished":e,void 0!==s&&(l.limit=s),c){void 0!==i&&(l.from=this.parseToInt(i/1e3));let e=this.safeInteger(u,"until");void 0!==e&&(u=this.omit(u,"until"),l.to=this.parseToInt(e/1e3))}let[f,p]=this.handleParamString2(u,"lastId","last_id");return void 0!==f&&(l.last_id=f),[l,p]}async fetchOrdersByStatus(e,t,i,s,r={}){let a,n;void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus(),void 0!==t&&(n=this.market(t));let d=void 0!==n?this.safeString(n,"symbol"):t,h=this.safeBool2(r,"trigger","stop"),c=this.handleMarketTypeAndParams("fetchOrdersByStatus",n,r)[0],[l,u]=this.prepareOrdersByStatusRequest(e,d,i,s,r),f="spot"===c||"margin"===c,p="open"===e;if(f)a=!0!==h?p?await this.privateSpotGetOpenOrders(this.extend(l,u)):await this.privateSpotGetOrders(this.extend(l,u)):await this.privateSpotGetPriceOrders(this.extend(l,u));else if("swap"===c)a=!0===h?await this.privateFuturesGetSettlePriceOrders(this.extend(l,u)):await this.privateFuturesGetSettleOrders(this.extend(l,u));else if("future"===c)a=!0===h?await this.privateDeliveryGetSettlePriceOrders(this.extend(l,u)):await this.privateDeliveryGetSettleOrders(this.extend(l,u));else if("option"===c)a=await this.privateOptionsGetOrders(this.extend(l,u));else throw new o.NotSupported(this.id+" fetchOrders() not support this market type");let m=a;if(f&&p&&!0!==h){let e=[];for(let t=0;t<a.length;t++){let i=this.safeDict(a,t,{}),s=this.safeValue(i,"orders");e=this.arrayConcat(e,s)}m=e}let g=this.parseOrders(m,n,i,s);return this.filterBySymbolSinceLimit(g,d,i,s)}async cancelOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus();let r=void 0===t?void 0:this.market(t),a=this.safeBoolN(i,["is_stop_order","stop","trigger"],!1),n=this.omit(i,["is_stop_order","stop","trigger"]),[d,h]=this.handleMarketTypeAndParams("cancelOrder",r,n),[c,l]="spot"===d||"margin"===d?this.spotOrderPrepareRequest(r,a,h):this.prepareRequest(r,d,h);if(c.order_id=e,"spot"===d||"margin"===d)s=!0===a?await this.privateSpotDeletePriceOrdersOrderId(this.extend(c,l)):await this.privateSpotDeleteOrdersOrderId(this.extend(c,l));else if("swap"===d)s=!0===a?await this.privateFuturesDeleteSettlePriceOrdersOrderId(this.extend(c,l)):await this.privateFuturesDeleteSettleOrdersOrderId(this.extend(c,l));else if("future"===d)s=!0===a?await this.privateDeliveryDeleteSettlePriceOrdersOrderId(this.extend(c,l)):await this.privateDeliveryDeleteSettleOrdersOrderId(this.extend(c,l));else if("option"===d)s=await this.privateOptionsDeleteOrdersOrderId(this.extend(c,l));else throw new o.NotSupported(this.id+" cancelOrder() not support this market type");return this.parseOrder(s,r)}async cancelOrders(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus(),void 0!==t&&(s=this.market(t)),r=void 0===s?"usdt":s.settle;let a=this.safeStringLower(i,"settle",r),[n,d]=this.handleMarketTypeAndParams("cancelOrders",s,i),h="spot"===n;if(h&&void 0===t)throw new o.ArgumentsRequired(this.id+" cancelOrders requires a symbol argument for spot markets");if(h){let i=[];for(let s=0;s<e.length;s++){let r={id:e[s],symbol:t};i.push(r)}return await this.cancelOrdersForSymbols(i,d)}let c=[{settle:a}];for(let t=0;t<e.length;t++)c.push(e[t]);let l=await this.privateFuturesPostSettleBatchCancelOrders(c);return this.parseOrders(l)}async cancelOrdersForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus();let i=[];for(let t=0;t<e.length;t++){let s=this.safeDict(e,t),r=this.safeString(s,"symbol"),a=this.market(r);if(!0!==a.spot)throw new o.NotSupported(this.id+" cancelOrdersForSymbols() supports only spot markets");let n={id:this.safeString(s,"id"),currency_pair:a.id};i.push(n)}let s=await this.privateSpotPostCancelBatchOrders(i);return this.parseOrders(s)}async cancelAllOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus();let s=void 0===e?void 0:this.market(e),r=this.safeBool2(t,"stop","trigger"),a=this.omit(t,["stop","trigger"]),[n,d]=this.handleMarketTypeAndParams("cancelAllOrders",s,a),[h,c]="spot"===n?this.multiOrderSpotPrepareRequest(s,r,d):this.prepareRequest(s,n,d);if("spot"===n||"margin"===n)i=!0===r?await this.privateSpotDeletePriceOrders(this.extend(h,c)):await this.privateSpotDeleteOrders(this.extend(h,c));else if("swap"===n)i=!0===r?await this.privateFuturesDeleteSettlePriceOrders(this.extend(h,c)):await this.privateFuturesDeleteSettleOrders(this.extend(h,c));else if("future"===n)i=!0===r?await this.privateDeliveryDeleteSettlePriceOrders(this.extend(h,c)):await this.privateDeliveryDeleteSettleOrders(this.extend(h,c));else if("option"===n)i=await this.privateOptionsDeleteOrders(this.extend(h,c));else throw new o.NotSupported(this.id+" cancelAllOrders() not support this market type");return this.parseOrders(i,s)}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(e),n=this.convertTypeToAccount(i),d=this.convertTypeToAccount(s),h=this.currencyToPrecision(e,t),c={currency:a.id,amount:h};if(n in this.options.accountsByType?c.from=n:(c.from="margin",c.currency_pair=n),d in this.options.accountsByType?c.to=d:(c.to="margin",c.currency_pair=d),"margin"===n||"margin"===d){let e=this.safeString2(r,"symbol","currency_pair");if(void 0===e)throw new o.ArgumentsRequired(this.id+' transfer requires params["symbol"] for isolated margin transfers');c.currency_pair=this.market(e).id}("futures"===d||"delivery"===d||"futures"===n||"delivery"===n)&&(c.settle=a.id);let l=r;("margin"===n||"margin"===d)&&(l=this.omit(r,"symbol"));let u=await this.privateWalletPostTransfers(this.extend(c,l));return this.parseTransfer(u,a)}parseTransfer(e,t){return{id:this.safeString(e,"tx_id"),timestamp:void 0,datetime:void 0,currency:this.safeCurrencyCode(void 0,t),amount:void 0,fromAccount:void 0,toAccount:void 0,status:void 0,info:e}}async setLeverage(e,t,i={}){let s;if(void 0===t)throw new o.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");if(e<0||e>100)throw new o.BadRequest(this.id+" setLeverage() leverage should be between 1 and 100");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),[a,n]=this.prepareRequest(r,void 0,i),d=this.safeString2(this.options,"marginMode","defaultMarginMode"),h=this.safeString(n,"cross_leverage_limit"),c=this.safeString(n,"marginMode",d),l=this.numberToString(e);if(void 0!==h&&(c="cross",l=h),"cross"===c||"cross_margin"===c?(a.cross_leverage_limit=l,a.leverage="0"):a.leverage=l,!0===r.swap)s=await this.privateFuturesPostSettlePositionsContractLeverage(this.extend(a,n));else if(!0===r.future)s=await this.privateDeliveryPostSettlePositionsContractLeverage(this.extend(a,n));else throw new o.NotSupported(this.id+" setLeverage() not support this market type");return s}parsePosition(e,t){let i,s=this.safeString(e,"contract"),r=this.safeMarket(s,t,"_","contract"),o=this.safeString2(e,"size","accum_size"),n=this.safeString(e,"side");void 0===n&&(a.Y.stringGt(o,"0")?n="long":a.Y.stringLt(o,"0")&&(n="short"));let d=this.safeString(e,"value"),h=this.safeString(e,"leverage");void 0!==h&&(i="0"===h?"cross":"isolated");let c=this.safeString(e,"margin"),l=this.omitZero(this.safeString(e,"initial_margin")),u=this.omitZero(this.safeString(e,"maintenance_margin")),f=this.safeString(e,"unrealised_pnl"),p=c;void 0!==c&&void 0!==f&&(p=a.Y.stringAdd(c,f));let m=this.safeTimestamp2(e,"open_time","first_open_time");return 0===m&&(m=void 0),this.safePosition({info:e,id:void 0,symbol:this.safeString(r,"symbol"),timestamp:m,datetime:this.iso8601(m),lastUpdateTimestamp:this.safeTimestamp2(e,"update_time","time"),initialMargin:this.parseNumber(l),initialMarginPercentage:this.parseNumber(a.Y.stringDiv(l,d)),maintenanceMargin:this.parseNumber(u),maintenanceMarginPercentage:this.parseNumber(a.Y.stringDiv(u,d)),entryPrice:this.safeNumber(e,"entry_price"),notional:this.parseNumber(d),leverage:this.safeNumber(e,"leverage"),unrealizedPnl:this.parseNumber(f),realizedPnl:this.safeNumber2(e,"realised_pnl","pnl"),contracts:this.parseNumber(a.Y.stringAbs(o)),contractSize:this.safeNumber(r,"contractSize"),marginRatio:void 0,liquidationPrice:this.safeNumber(e,"liq_price"),markPrice:this.safeNumber(e,"mark_price"),lastPrice:void 0,collateral:this.parseNumber(p),marginMode:i,side:n,percentage:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}async fetchPosition(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e);if(!0!==s.contract)throw new o.BadRequest(this.id+" fetchPosition() supports contract markets only");let[r,a]=this.prepareRequest(s,this.safeString(s,"type"),t),n=this.extend(r,a);if(!0===s.swap?i=await this.privateFuturesGetSettlePositionsContract(n):!0===s.future?i=await this.privateDeliveryGetSettlePositionsContract(n):"option"===s.type&&(i=await this.privateOptionsGetPositionsContract(n)),void 0===i)throw new o.NullResponse(this.id+" fetchPosition() returned empty response");return this.parsePosition(i,s)}async fetchPositions(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!0,!0,!0);void 0!==r&&r.length>0&&(i=this.market(r[0]));let[a,o]=this.handleMarketTypeAndParams("fetchPositions",i,t),n=a;(void 0===a||"spot"===a)&&(n="swap");let[d,h]=this.prepareRequest(void 0,n,o);if("option"===n&&void 0!==r){let e=this.safeString(i,"id").split("-");d.underlying=this.safeString(e,0)}"swap"===n?s=await this.privateFuturesGetSettlePositions(this.extend(d,h)):"future"===n?s=await this.privateDeliveryGetSettlePositions(this.extend(d,h)):"option"===n&&(s=await this.privateOptionsGetPositions(this.extend(d,h)));let c=[];return void 0!==s&&(c=this.toArray(s)),this.parsePositions(c,r)}async fetchLeverageTiers(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleMarketTypeAndParams("fetchLeverageTiers",void 0,t),[a,n]=this.prepareRequest(void 0,s,r);if("future"!==s&&"swap"!==s)throw new o.BadRequest(this.id+" fetchLeverageTiers only supports swap and future");if("swap"===s)i=await this.publicFuturesGetSettleContracts(this.extend(a,n));else if("future"===s)i=await this.publicDeliveryGetSettleContracts(this.extend(a,n));else throw new o.NotSupported(this.id+" fetchLeverageTiers() not support this market type");return this.parseLeverageTiers(i,e,"name")}async fetchMarketLeverageTiers(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),[r,a]=this.handleMarketTypeAndParams("fetchMarketLeverageTiers",s,t),[n,d]=this.prepareRequest(s,r,a);if("future"!==r&&"swap"!==r)throw new o.BadRequest(this.id+" fetchMarketLeverageTiers only supports swap and future");return i="swap"===r?await this.publicFuturesGetSettleRiskLimitTiers(this.extend(n,d)):await this.publicDeliveryGetSettleRiskLimitTiers(this.extend(n,d)),this.parseMarketLeverageTiers(i,s)}parseEmulatedLeverageTiers(e,t){let i=this.safeString(e,"name"),s=this.safeString(e,"maintenance_rate"),r=this.safeString(e,"leverage_max"),o=this.safeString(e,"risk_limit_step"),n=this.safeString(e,"risk_limit_max"),d=a.Y.stringDiv("1",r),h=s,c=d,l="0",u=[];for(;a.Y.stringLt(l,n);){let r=a.Y.stringAdd(l,o);u.push({tier:this.parseNumber(a.Y.stringDiv(r,o)),symbol:this.safeSymbol(i,t,void 0,"contract"),currency:this.safeString(t,"settle"),minNotional:this.parseNumber(l),maxNotional:this.parseNumber(r),maintenanceMarginRate:this.parseNumber(h),maxLeverage:this.parseNumber(a.Y.stringDiv("1",c)),info:e}),h=a.Y.stringAdd(h,s),c=a.Y.stringAdd(c,d),l=r}return u}parseMarketLeverageTiers(e,t){if(!Array.isArray(e))return this.parseEmulatedLeverageTiers(e,t);let i=0,s=[];for(let r=0;r<e.length;r++){let a=this.safeDict(e,r),o=this.safeNumber(a,"risk_limit");s.push({tier:this.sum(r,1),symbol:this.safeString(t,"symbol"),currency:this.safeString(t,"base"),minNotional:i,maxNotional:o,maintenanceMarginRate:this.safeNumber(a,"maintenance_rate"),maxLeverage:this.safeNumber(a,"leverage_max"),info:a}),i=o}return s}async repayIsolatedMargin(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.currency(t),a={currency:r.id.toUpperCase(),amount:this.currencyToPrecision(t,i)};a.currency_pair=this.market(e).id,a.type="repay";let o=await this.privateMarginPostUniLoans(this.extend(a,s));return this.parseMarginLoan(o,r)}async repayCrossMargin(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus();let r=this.currency(e),a={currency:r.id.toUpperCase(),amount:this.currencyToPrecision(e,t)},[o,n]=this.handleOptionBoolAndParams(i,"repayCrossMargin","unifiedAccount",!1);return o?(a.type="repay",s=await this.privateUnifiedPostLoans(this.extend(a,n))):(s=await this.privateMarginPostCrossRepayments(this.extend(a,n)),s=this.safeDict(s,0)),this.parseMarginLoan(s,r)}async borrowIsolatedMargin(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.currency(t),a={currency:r.id.toUpperCase(),amount:this.currencyToPrecision(t,i)};a.currency_pair=this.market(e).id,a.type="borrow";let o=await this.privateMarginPostUniLoans(this.extend(a,s));return this.parseMarginLoan(o,r)}async borrowCrossMargin(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus();let r=this.currency(e),a={currency:r.id.toUpperCase(),amount:this.currencyToPrecision(e,t)},[o,n]=this.handleOptionBoolAndParams(i,"borrowCrossMargin","unifiedAccount",!1);return o?(a.type="borrow",s=await this.privateUnifiedPostLoans(this.extend(a,n))):s=await this.privateMarginPostCrossLoans(this.extend(a,n)),this.parseMarginLoan(s,r)}parseMarginLoan(e,t){let i=this.safeString2(this.options,"defaultMarginMode","marginMode","cross"),s=this.safeInteger(e,"create_time");"isolated"===i&&(s=this.safeTimestamp(e,"create_time"));let r=this.safeString(e,"currency"),a=this.safeString(e,"currency_pair");return{id:this.safeString(e,"id"),currency:this.safeCurrencyCode(r,t),amount:this.safeNumber(e,"amount"),symbol:this.safeSymbol(a,void 0,"_","margin"),timestamp:s,datetime:this.iso8601(s),info:e}}async fetchBorrowInterest(e,t,i,s,r={}){let a,o;void 0===this.markets&&await this.loadMarkets(),await this.loadUnifiedStatus();let[n,d]=this.handleOptionBoolAndParams(r,"fetchBorrowInterest","unifiedAccount",!1),[h,c]=this.handleUntilOption("to",{},d);void 0!==e&&(h.currency=this.currency(e).id),void 0!==t&&(a=this.market(t)),void 0!==i&&(h.from=i),void 0!==s&&(h.limit=s);let[l,u]=this.handleMarginModeAndParams("fetchBorrowInterest",c,"cross");n?o=await this.privateUnifiedGetInterestRecords(this.extend(h,u)):"isolated"===l?(void 0!==a&&(h.currency_pair=a.id),o=await this.privateMarginGetUniInterestRecords(this.extend(h,u))):"cross"===l&&(o=await this.privateMarginGetCrossInterestRecords(this.extend(h,u)));let f=this.parseBorrowInterests(o,a);return this.filterByCurrencySinceLimit(f,e,i,s)}parseBorrowInterest(e,t){let i=this.safeString(e,"currency_pair"),s=this.safeMarket(i,t),r="cross";void 0!==i&&(r="isolated");let a=this.safeInteger(e,"create_time");return{info:e,symbol:this.safeString(s,"symbol"),currency:this.safeCurrencyCode(this.safeString(e,"currency")),interest:this.safeNumber(e,"interest"),interestRate:this.safeNumber(e,"actual_rate"),amountBorrowed:void 0,marginMode:r,timestamp:a,datetime:this.iso8601(a)}}nonce(){let e=this.safeInteger(this.options,"timeDifference");if(void 0===e)throw new o.ExchangeError(this.id+' nonce() requires a numeric options["timeDifference"]');return this.milliseconds()-e}sign(e,t=[],i="GET",r={},a,n){let d,h,c,l,u=t[0],f=t[1],p=this.omit(r,this.extractParams(e));if(e.indexOf("settle")>-1&&!0===e.endsWith("batch_cancel_orders")){let t=this.safeDict(r,0);d=this.implodeParams(e,t);let i=[],s=this.toArray(r);for(let e=1;e<s.length;e++)i.push(r[e]);p=i}else if(Array.isArray(r)){let t=this.safeDict(r,0,{});d=this.implodeParams(e,t)}else d=this.implodeParams(e,r);let m="/"+f+(l=""===d?"":"/"+d);("subAccounts"===f||"withdrawals"===f)&&(m=l);let g=this.urls.api[u][f];if(void 0===g)throw new o.NotSupported(this.id+" does not have a testnet for the "+f+" market type.");if(g+=m,"public"===u)Object.keys(p).length>0&&(g+="?"+this.urlencode(p));else{this.checkRequiredCredentials();let e="",t="",r=!1;if(("futures"===f||"delivery"===f)&&"POST"===i){let e=d.split("/"),t=this.safeString(e,1,"");r=t.indexOf("dual")>=0||t.indexOf("positions")>=0}if("GET"===i||"DELETE"===i||r||"PATCH"===i)Object.keys(p).length>0&&(t=this.rawencode(p,!0),(e=this.urlencode(p,!0)).indexOf("currencies=")>=0&&e.indexOf("%2C")>=0&&(e=e.replaceAll("%2C",",")),g+="?"+e),"PATCH"===i&&(h=this.json(p));else{let t=this.safeDict(p,"query",{});Object.keys(t).length>0&&(g+="?"+(e=this.urlencode(t))),p=this.omit(p,"query"),h=this.json(p)}let a=void 0===h?n:h,o=this.hash(this.encode(void 0===a?"":a),s.Zf),l=this.nonce(),u=this.parseToInt(l/1e3).toString(),v="/api/"+this.version+m,y=[i.toUpperCase(),v,t,o,u].join("\n"),b=this.hmac(this.encode(y),this.encode(this.secret),s.Zf);c={KEY:this.apiKey,Timestamp:u,SIGN:b,"Content-Type":"application/json"}}return{url:g,method:i,body:void 0===h?n:h,headers:void 0===c?a:c}}async modifyMarginHelper(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),[a,n]=this.prepareRequest(r,void 0,i);if(a.change=this.numberToString(t),!0===r.swap)s=await this.privateFuturesPostSettlePositionsContractMargin(this.extend(a,n));else if(!0===r.future)s=await this.privateDeliveryPostSettlePositionsContractMargin(this.extend(a,n));else throw new o.NotSupported(this.id+" modifyMarginHelper() not support this market type");return this.parseMarginModification(s,r)}parseMarginModification(e,t){let i=this.safeString(e,"contract"),s=this.safeMarket(i,t,"_","contract"),r=this.safeNumber(e,"margin");return{info:e,symbol:s.symbol,type:void 0,marginMode:"isolated",amount:void 0,total:r,code:this.safeString(s,"quote"),status:"ok",timestamp:void 0,datetime:void 0}}async reduceMargin(e,t,i={}){return await this.modifyMarginHelper(e,-t,i)}async addMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,i)}async fetchOpenInterestHistory(e,t="5m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let[a,n]=this.handleOptionBoolAndParams(r,"fetchOpenInterestHistory","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchOpenInterestHistory",e,i,s,t,n,100);let d=this.market(e);if(!0!==d.swap)throw new o.BadRequest(this.id+" fetchOpenInterest() supports swap markets only");let h={contract:d.id,settle:d.settleId,interval:this.safeString(this.timeframes,t,t)};void 0!==s&&(h.limit=s),void 0!==i&&(h.from=this.parseToInt(i/1e3));let c=await this.publicFuturesGetSettleContractStats(this.extend(h,n));return this.parseOpenInterestsHistory(c,d,i,s)}parseOpenInterest(e,t){let i=this.safeTimestamp(e,"time");return{symbol:this.safeString(t,"symbol"),openInterestAmount:this.safeNumber(e,"open_interest"),openInterestValue:this.safeNumber(e,"open_interest_usd"),timestamp:i,datetime:this.iso8601(i),info:e}}async fetchSettlementHistory(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchSettlementHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),[a,n]=this.handleMarketTypeAndParams("fetchSettlementHistory",r,s);if("option"!==a)throw new o.NotSupported(this.id+" fetchSettlementHistory() supports option markets only");let d=r.id.split("-"),h={underlying:this.safeString(d,0)};void 0!==t&&(h.from=t),void 0!==i&&(h.limit=i);let c=await this.publicOptionsGetSettlements(this.extend(h,n)),l=this.parseSettlements(c,r),u=this.sortBy(l,"timestamp");return this.filterBySymbolSinceLimit(u,e,t,i)}async fetchMySettlementHistory(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(a=this.market(e));let n=void 0!==a?this.safeString(a,"symbol"):e,[d,h]=this.handleMarketTypeAndParams("fetchMySettlementHistory",a,s),c="option"===d,l="future"===d;if(!c&&!l)throw new o.NotSupported(this.id+" fetchMySettlementHistory() supports option and future markets only");let[u,f]=this.prepareRequest(a,d,h);if(void 0!==i&&(u.limit=i),l)r=await this.privateDeliveryGetSettleSettlements(this.extend(u,f));else{if(void 0!==t&&(u.from=t),void 0===a){if(void 0===this.safeString(h,"underlying"))throw new o.ArgumentsRequired(this.id+" fetchMySettlementHistory() requires a symbol argument or an underlying parameter in params")}else{let e=a.id.split("-");u.underlying=this.safeString(e,0)}r=await this.privateOptionsGetMySettlements(this.extend(u,h))}let p=this.safeDict(r,"result",{}),m=this.safeList(p,"list",[]),g=this.parseSettlements(m,a),v=this.sortBy(g,"timestamp");return this.filterBySymbolSinceLimit(v,n,t,i)}parseSettlement(e,t){let i=this.safeTimestamp(e,"time"),s=this.safeString(e,"contract");return{info:e,symbol:this.safeSymbol(s,t),price:this.safeNumber(e,"settle_price"),timestamp:i,datetime:this.iso8601(i)}}parseSettlements(e,t){let i=[];for(let s=0;s<e.length;s++)i.push(this.parseSettlement(e[s],t));return i}async fetchLedger(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(s,"fetchLedger","paginate",!1);if(o)return await this.fetchPaginatedCallDynamic("fetchLedger",e,t,i,n);let d={},[h,c]=this.handleMarketTypeAndParams("fetchLedger",void 0,n);if(("spot"===h||"margin"===h)&&void 0!==e&&(d.currency=(r=this.currency(e)).id),"swap"===h||"future"===h){let e="btc";"swap"===h&&(e="usdt"),d.settle=this.safeStringLower(c,"settle",e)}let l=c;("swap"===h||"future"===h)&&(l=this.omit(c,"settle")),void 0!==t&&(d.from=t),void 0!==i&&(d.limit=i);let[u,f]=this.handleUntilOption("to",d,l);return"spot"===h?a=await this.privateSpotGetAccountBook(this.extend(u,f)):"margin"===h?a=await this.privateMarginGetAccountBook(this.extend(u,f)):"swap"===h?a=await this.privateFuturesGetSettleAccountBook(this.extend(u,f)):"future"===h?a=await this.privateDeliveryGetSettleAccountBook(this.extend(u,f)):"option"===h&&(a=await this.privateOptionsGetAccountBook(this.extend(u,f))),this.parseLedger(a,r,t,i)}parseLedgerEntry(e,t){let i,s,r=this.safeString(e,"change");a.Y.stringLt(r,"0")?(i="out",r=a.Y.stringAbs(r)):i="in";let o=this.safeString(e,"currency"),n=this.safeCurrency(o,t),d=this.safeString(e,"type"),h=this.safeString(e,"time");s=h.length>10?parseInt(h):1e3*parseInt(h);let c=this.safeString(e,"balance"),l=this.safeString(e,"change"),u=this.parseNumber(a.Y.stringSub(c,l));return this.safeLedgerEntry({info:e,id:this.safeString(e,"id"),direction:i,account:void 0,referenceAccount:void 0,referenceId:void 0,type:this.parseLedgerEntryType(d),currency:this.safeCurrencyCode(o,n),amount:this.parseNumber(r),timestamp:s,datetime:this.iso8601(s),before:u,after:this.safeNumber(e,"balance"),status:void 0,fee:void 0},n)}parseLedgerEntryType(e){return this.safeString({deposit:"deposit",withdraw:"withdrawal",sub_account_transfer:"transfer",margin_in:"transfer",margin_out:"transfer",margin_funding_in:"transfer",margin_funding_out:"transfer",cross_margin_in:"transfer",cross_margin_out:"transfer",copy_trading_in:"transfer",copy_trading_out:"transfer",quant_in:"transfer",quant_out:"transfer",futures_in:"transfer",futures_out:"transfer",delivery_in:"transfer",delivery_out:"transfer",new_order:"trade",order_fill:"trade",referral_fee:"rebate",order_fee:"fee",interest:"interest",lend:"loan",redeem:"loan",profit:"interest",flash_swap_buy:"trade",flash_swap_sell:"trade",unknown:"unknown",set:"settlement",prem:"trade",point_refr:"rebate",point_fee:"fee",point_dnw:"deposit/withdraw",fund:"fee",refr:"rebate",fee:"fee",pnl:"trade",dnw:"deposit/withdraw"},e,e)}async setPositionMode(e,t,i={}){let s=void 0!==t?this.market(t):void 0,[r,a]=this.prepareRequest(s,"swap",i);return r.dual_mode=e,await this.privateFuturesPostSettleDualMode(this.extend(r,a))}async fetchUnderlyingAssets(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleMarketTypeAndParams("fetchUnderlyingAssets",void 0,e),s=t;if((void 0===t||"spot"===t)&&(s="option"),"option"!==s)throw new o.NotSupported(this.id+" fetchUnderlyingAssets() supports option markets only");let r=await this.publicOptionsGetUnderlyings(i),a=[];for(let e=0;e<r.length;e++){let t=this.safeDict(r,e,{}),i=this.safeString(t,"name");void 0!==i&&a.push(i)}return a}async fetchLiquidations(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e);if(!0!==r.swap)throw new o.NotSupported(this.id+" fetchLiquidations() supports swap markets only");let a={settle:r.settleId,contract:r.id};void 0!==t&&(a.from=t),void 0!==i&&(a.limit=i);let[n,d]=this.handleUntilOption("to",a,s),h=await this.publicFuturesGetSettleLiqOrders(this.extend(n,d));return this.parseLiquidations(this.toArray(h),r,t,i)}async fetchMyLiquidations(e,t,i,s={}){let r;if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchMyLiquidations() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let a=this.market(e),n={contract:a.id};if(!0===a.swap||!0===a.future)void 0!==i&&(n.limit=i),n.settle=a.settleId;else if(!0===a.option){let e=a.id.split("-");n.underlying=this.safeString(e,0)}if(!0===a.swap)r=await this.privateFuturesGetSettleLiquidates(this.extend(n,s));else if(!0===a.future)r=await this.privateDeliveryGetSettleLiquidates(this.extend(n,s));else if(!0===a.option)r=await this.privateOptionsGetPositionClose(this.extend(n,s));else throw new o.NotSupported(this.id+" fetchMyLiquidations() does not support "+a.type+" orders");return this.parseLiquidations(this.toArray(r),a,t,i)}parseLiquidation(e,t){let i,s=this.safeString(e,"contract"),r=this.safeTimestamp(e,"time"),o=this.safeString2(e,"size","settle_size"),n=this.safeString(e,"left","0"),d=a.Y.stringAbs(a.Y.stringSub(o,n)),h=this.safeString(t,"contractSize"),c=this.safeString2(e,"liq_price","fill_price"),l=a.Y.stringMul(d,h),u=this.safeString(e,"pnl");void 0===u&&(u=a.Y.stringMul(l,c));let f=this.safeStringLower(e,"side");return"long"===f?i="buy":"short"===f?i="sell":void 0!==o&&(a.Y.stringGt(o,"0")?i="buy":a.Y.stringLt(o,"0")&&(i="sell")),this.safeLiquidation({info:e,symbol:this.safeSymbol(s,t),contracts:this.parseNumber(d),contractSize:this.parseNumber(h),price:this.parseNumber(c),side:i,baseValue:this.parseNumber(l),quoteValue:this.parseNumber(a.Y.stringAbs(u)),timestamp:r,datetime:this.iso8601(r)})}async fetchGreeks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={underlying:i.info.underlying},r=await this.publicOptionsGetTickers(this.extend(s,t)),a=i.id;for(let e=0;e<r.length;e++){let t=this.safeDict(r,e,{});if(this.safeString(t,"name")===a)return this.parseGreeks(t,i)}throw new o.NullResponse(this.id+" fetchGreeks() could not find greeks for "+e)}parseGreeks(e,t){let i=this.safeString(e,"name"),s=this.safeSymbol(i,t);if(void 0===t)throw new o.ExchangeError(this.id+" parseGreeks() could not resolve market");return{symbol:s,timestamp:void 0,datetime:void 0,delta:this.parseNumber(this.safeNumber(e,"delta")),gamma:this.parseNumber(this.safeNumber(e,"gamma")),theta:this.parseNumber(this.safeNumber(e,"theta")),vega:this.parseNumber(this.safeNumber(e,"vega")),rho:void 0,bidSize:this.parseNumber(this.safeNumber(e,"bid1_size")),askSize:this.parseNumber(this.safeNumber(e,"ask1_size")),bidImpliedVolatility:this.parseNumber(this.safeNumber(e,"bid_iv")),askImpliedVolatility:this.parseNumber(this.safeNumber(e,"ask_iv")),markImpliedVolatility:this.parseNumber(this.safeNumber(e,"mark_iv")),bidPrice:this.parseNumber(this.safeNumber(e,"bid1_price")),askPrice:this.parseNumber(this.safeNumber(e,"ask1_price")),markPrice:this.parseNumber(this.safeNumber(e,"mark_price")),lastPrice:this.parseNumber(this.safeNumber(e,"last_price")),underlyingPrice:this.parseNumber(t.info.underlying_price),info:e}}async closePosition(e,t,i={}){let s=this.extend({close:!0},i);return await this.createOrder(e,"market",void 0===t?"":t,0,void 0,s)}async fetchLeverage(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(s=this.market(e));let r={},a=this.safeBool(t,"unified"),n=this.omit(t,"unified");if(this.safeBool(s,"spot",!1))r.currency_pair=this.safeString(s,"id"),i=!0===a?await this.publicMarginGetUniCurrencyPairsCurrencyPair(this.extend(r,n)):await this.publicMarginGetCurrencyPairsCurrencyPair(this.extend(r,n));else if(!0===a)i=await this.privateUnifiedGetAccounts(this.extend(r,n));else throw new o.NotSupported(this.id+" fetchLeverage() does not support "+this.safeString(s,"type")+" markets");return this.parseLeverage(i,s)}async fetchLeverages(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e),r=this.safeBool(t,"unified"),a=this.omit(t,"unified"),o="id";return!0===r?(o="currency_pair",i=await this.publicMarginGetUniCurrencyPairs(a)):i=await this.publicMarginGetCurrencyPairs(a),this.parseLeverages(this.toArray(i),s,o,"spot")}parseLeverage(e,t){let i=this.safeString2(e,"currency_pair","id"),s=this.safeInteger(e,"leverage");return{info:e,symbol:this.safeSymbol(i,t,"_","spot"),marginMode:void 0,longLeverage:s,shortLeverage:s}}async fetchOption(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={contract:i.id},r=await this.publicOptionsGetContractsContract(this.extend(s,t));return this.parseOption(r,void 0,i)}async fetchOptionChain(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={underlying:this.currency(e).code+"_USDT"},s=await this.publicOptionsGetContracts(this.extend(i,t));return this.parseOptionChain(this.toArray(s),void 0,"name")}parseOption(e,t,i){let s=this.safeString(e,"name"),r=this.safeMarket(s,i),a=this.safeTimestamp(e,"create_time");return{info:e,currency:void 0,symbol:r.symbol,timestamp:a,datetime:this.iso8601(a),impliedVolatility:void 0,openInterest:void 0,bidPrice:this.parseNumber(this.safeNumber(e,"bid1_price")),askPrice:this.parseNumber(this.safeNumber(e,"ask1_price")),midPrice:void 0,markPrice:this.parseNumber(this.safeNumber(e,"mark_price")),lastPrice:this.parseNumber(this.safeNumber(e,"last_price")),underlyingPrice:this.parseNumber(this.safeNumber(e,"underlying_price")),change:void 0,percentage:void 0,baseVolume:void 0,quoteVolume:void 0}}async fetchPositionsHistory(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&1===e.length&&(a=this.market(e[0]));let[n,d]=this.handleMarketTypeAndParams("fetchPositionsHistory",a,s,"swap"),h=this.safeInteger(d,"until"),c=this.omit(d,"until"),[l,u]=this.prepareRequest(a,n,c);if(void 0!==i&&(l.limit=i),void 0!==t&&(l.from=this.parseToInt(t/1e3)),void 0!==h&&(l.to=this.parseToInt(h/1e3)),"swap"===n)r=await this.privateFuturesGetSettlePositionClose(this.extend(l,u));else if("future"===n)r=await this.privateDeliveryGetSettlePositionClose(this.extend(l,u));else throw new o.NotSupported(this.id+" fetchPositionsHistory() does not support markets of type "+n);let f=[];return void 0!==r&&(f=this.toArray(r)),this.parsePositions(f,e,u)}handleErrors(e,t,i,s,r,a,n,d,h){if(void 0===n)return;let c=this.safeString(n,"label");if(void 0!==c){let e=this.id+" "+a;throw this.throwExactlyMatchedException(this.exceptions.exact,c,e),new o.ExchangeError(e)}}}i.d(t,{A:()=>n})},2943(e,t,i){"use strict";var s=i(1305);class r extends s.A{describe(){return this.deepExtend(super.describe(),{id:"gateeu",name:"Gate EU",countries:["EU"],version:"v4",rateLimit:20,pro:!0,certified:!1,urls:{api:{public:{wallet:"https://api.gateeu.com/api/v4",margin:"https://api.gateeu.com/api/v4",spot:"https://api.gateeu.com/api/v4",sub_accounts:"https://api.gateeu.com/api/v4",earn:"https://api.gateeu.com/api/v4"},private:{withdrawals:"https://api.gateeu.com/api/v4",wallet:"https://api.gateeu.com/api/v4",margin:"https://api.gateeu.com/api/v4",spot:"https://api.gateeu.com/api/v4",subAccounts:"https://api.gateeu.com/api/v4",unified:"https://api.gateeu.com/api/v4",rebate:"https://api.gateeu.com/api/v4",earn:"https://api.gateeu.com/api/v4",account:"https://api.gateeu.com/api/v4",loan:"https://api.gateeu.com/api/v4",otc:"https://api.gateeu.com/api/v4"}}},has:{CORS:!0,spot:!0,margin:!0,swap:!1,future:!1,option:void 0},options:{fetchMarkets:{types:["spot"]},fetchOrderBook:{maxSpotLimit:100},mica:!0}})}}i.d(t,{A:()=>r})},841(e,t,i){"use strict";var s=i(4721),r=i(2412),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"gemini",name:"Gemini",countries:["US"],rateLimit:100,version:"v1",pro:!0,has:{CORS:void 0,spot:!0,margin:void 0,swap:!0,future:!1,option:!1,addMargin:!1,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createDepositAddress:!0,createMarketOrder:!1,createOrder:!0,createReduceOnlyOrder:!1,fetchBalance:!0,fetchBidsAsks:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchClosedOrders:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!0,fetchDepositsWithdrawals:!0,fetchFundingHistory:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLeverage:!1,fetchLeverageTiers:!1,fetchMarginMode:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!1,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!1,fetchPosition:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchTransactions:"emulated",postOnly:!0,reduceMargin:!1,sandbox:!0,setLeverage:!1,setMarginMode:!1,setPositionMode:!1,withdraw:!0},urls:{logo:"https://user-images.githubusercontent.com/1294454/27816857-ce7be644-6096-11e7-82d6-3c257263229c.jpg",api:{public:"https://api.gemini.com",private:"https://api.gemini.com",web:"https://docs.gemini.com",webExchange:"https://exchange.gemini.com"},www:"https://gemini.com/",doc:["https://docs.gemini.com/rest-api","https://docs.sandbox.gemini.com"],test:{public:"https://api.sandbox.gemini.com",private:"https://api.sandbox.gemini.com",web:"https://docs.gemini.com",webExchange:"https://exchange.gemini.com"},fees:["https://gemini.com/api-fee-schedule","https://gemini.com/trading-fees","https://gemini.com/transfer-fees"]},api:{webExchange:{get:{"":{cost:1}}},web:{get:{"rest-api":{cost:1}}},public:{get:{"v1/symbols":{cost:5},"v1/symbols/details/{symbol}":{cost:5},"v1/network/{token}":{cost:5},"v1/staking/rates":{cost:5},"v1/pubticker/{symbol}":{cost:5},"v1/feepromos":{cost:5},"v2/ticker/{symbol}":{cost:5},"v2/candles/{symbol}/{timeframe}":{cost:5},"v1/trades/{symbol}":{cost:5},"v1/auction/{symbol}":{cost:5},"v1/auction/{symbol}/history":{cost:5},"v1/pricefeed":{cost:5},"v1/fundingamount/{symbol}":{cost:5},"v1/fundingamountreport/records.xlsx":{cost:5},"v1/book/{symbol}":{cost:5},"v1/earn/rates":{cost:5},"v2/derivatives/candles/{symbol}/{time_frame}":{cost:5},"v2/fxrate/{symbol}/{timestamp}":{cost:5},"v1/riskstats/{symbol}":{cost:5},"v1/prediction-markets/events":{cost:5},"v1/prediction-markets/events/{eventTicker}":{cost:5},"v1/prediction-markets/events/{eventTicker}/strike":{cost:5},"v1/prediction-markets/events/newly-listed":{cost:5},"v1/prediction-markets/events/recently-settled":{cost:5},"v1/prediction-markets/events/upcoming":{cost:5},"v1/prediction-markets/categories":{cost:5},"v1/prediction-markets/volume/{date}":{cost:5},"v1/prediction-markets/volume/{date}/hourly":{cost:5},"v1/prediction-markets/terms":{cost:5},"v1/prediction-markets/maker-rebate/rates":{cost:5},"v1/prediction-markets/liquidity-rewards/config":{cost:5},"v1/prediction-markets/liquidity-rewards/events":{cost:5}}},private:{get:{"v1/perpetuals/fundingpaymentreport/records.xlsx":{cost:1},"v1/prediction-markets/terms/status":{cost:1},"v1/prediction-markets/maker-rebate/summary/total":{cost:1},"v1/prediction-markets/liquidity-rewards/summary/daily":{cost:1},"v1/prediction-markets/liquidity-rewards/summary/total":{cost:1},"v2/network/{token}":{cost:1},"v2/networks/{network}/assets":{cost:1}},post:{"v1/staking/unstake":{cost:1},"v1/staking/stake":{cost:1},"v1/staking/rewards":{cost:1},"v1/staking/history":{cost:1},"v1/order/new":{cost:1},"v1/order/cancel":{cost:1},"v1/wrap/{symbol}":{cost:1},"v1/order/cancel/session":{cost:1},"v1/order/cancel/all":{cost:1},"v1/order/status":{cost:1},"v1/orders":{cost:1},"v1/mytrades":{cost:1},"v1/notionalvolume":{cost:1},"v1/tradevolume":{cost:1},"v1/clearing/new":{cost:1},"v1/clearing/status":{cost:1},"v1/clearing/cancel":{cost:1},"v1/clearing/confirm":{cost:1},"v1/balances":{cost:1},"v1/balances/staking":{cost:1},"v1/notionalbalances/{currency}":{cost:1},"v1/transfers":{cost:1},"v1/addresses/{network}":{cost:1},"v1/deposit/{network}/newAddress":{cost:1},"v1/deposit/{currency}/newAddress":{cost:1},"v1/withdraw/{currency}":{cost:1},"v1/account/transfer/{currency}":{cost:1},"v1/payments/addbank":{cost:1},"v1/payments/methods":{cost:1},"v1/payments/sen/withdraw":{cost:1},"v1/balances/earn":{cost:1},"v1/earn/interest":{cost:1},"v1/earn/history":{cost:1},"v1/approvedAddresses/{network}/request":{cost:1},"v1/approvedAddresses/account/{network}":{cost:1},"v1/approvedAddresses/{network}/remove":{cost:1},"v1/account":{cost:1},"v1/account/create":{cost:1},"v1/account/list":{cost:1},"v1/heartbeat":{cost:1},"v1/roles":{cost:1},"v1/custodyaccountfees":{cost:1},"v1/withdraw/{currencyCodeLowerCase}/feeEstimate":{cost:1},"v1/payments/addbank/cad":{cost:1},"v1/transactions":{cost:1},"v1/margin/account":{cost:1},"v1/margin/rates":{cost:1},"v1/margin/order/preview":{cost:1},"v1/clearing/list":{cost:1},"v1/clearing/broker/list":{cost:1},"v1/clearing/broker/new":{cost:1},"v1/clearing/trades":{cost:1},"v1/instant/quote":{cost:1},"v1/instant/execute":{cost:1},"v1/account/rename":{cost:1},"v1/oauth/revokeByToken":{cost:1},"v1/margin":{cost:1},"v1/perpetuals/fundingPayment":{cost:1},"v1/perpetuals/fundingpaymentreport/records.json":{cost:1},"v1/positions":{cost:1},"v1/prediction-markets/order":{cost:1},"v1/prediction-markets/order/batch":{cost:1},"v1/prediction-markets/order/cancel":{cost:1},"v1/prediction-markets/order/batch/cancel":{cost:1},"v1/prediction-markets/orders/active":{cost:1},"v1/prediction-markets/orders/history":{cost:1},"v1/prediction-markets/positions":{cost:1},"v1/prediction-markets/positions/settled":{cost:1},"v1/prediction-markets/metrics/volume":{cost:1},"v1/prediction-markets/terms/accept":{cost:1},"v1/prediction-markets/maker-rebate/payouts":{cost:1},"v2/transfers":{cost:1},"v2/withdraw/{network}/{ticker}":{cost:1},"v2/withdraw/{network}/{ticker}/feeEstimate":{cost:1}}}},precisionMode:4,fees:{trading:{taker:.004,maker:.002}},httpExceptions:{400:a.BadRequest,403:a.PermissionDenied,404:a.OrderNotFound,406:a.InsufficientFunds,429:a.RateLimitExceeded,500:a.ExchangeError,502:a.ExchangeNotAvailable,503:a.OnMaintenance},timeframes:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1hr","6h":"6hr","1d":"1day"},exceptions:{exact:{AuctionNotOpen:a.BadRequest,ClientOrderIdTooLong:a.BadRequest,ClientOrderIdMustBeString:a.BadRequest,ConflictingOptions:a.BadRequest,EndpointMismatch:a.BadRequest,EndpointNotFound:a.BadRequest,IneligibleTiming:a.BadRequest,InsufficientFunds:a.InsufficientFunds,InvalidJson:a.BadRequest,InvalidNonce:a.InvalidNonce,InvalidApiKey:a.AuthenticationError,InvalidOrderType:a.InvalidOrder,InvalidPrice:a.InvalidOrder,InvalidQuantity:a.InvalidOrder,InvalidSide:a.InvalidOrder,InvalidSignature:a.AuthenticationError,InvalidSymbol:a.BadRequest,InvalidTimestampInPayload:a.BadRequest,Maintenance:a.OnMaintenance,MarketNotOpen:a.InvalidOrder,MissingApikeyHeader:a.AuthenticationError,MissingOrderField:a.InvalidOrder,MissingRole:a.AuthenticationError,MissingPayloadHeader:a.AuthenticationError,MissingSignatureHeader:a.AuthenticationError,NoSSL:a.AuthenticationError,OptionsMustBeArray:a.BadRequest,OrderNotFound:a.OrderNotFound,RateLimit:a.RateLimitExceeded,System:a.ExchangeError,UnsupportedOption:a.BadRequest},broad:{"The Gemini Exchange is currently undergoing maintenance.":a.OnMaintenance,"We are investigating technical issues with the Gemini Exchange.":a.ExchangeNotAvailable,"Internal Server Error":a.ExchangeNotAvailable}},options:{fetchMarketsMethod:"fetch_markets_from_api",fetchMarketFromWebRetries:10,fetchMarketsFromAPI:{fetchDetailsForAllSymbols:!1,quoteCurrencies:["USDT","GUSD","USD","DAI","EUR","GBP","SGD","BTC","ETH","LTC","BCH","SOL","USDC"]},fetchMarkets:{webApiEnable:!0,webApiRetries:10},fetchUsdtMarkets:["btcusdt","ethusdt"],fetchCurrencies:{webApiEnable:!0,webApiRetries:5,webApiMuteFailure:!0},fetchTickerMethod:"fetchTickerV1",networks:{BTC:"bitcoin",ERC20:"ethereum",BCH:"bitcoincash",LTC:"litecoin",ZEC:"zcash",FIL:"filecoin",DOGE:"dogecoin",XTZ:"tezos",AVAXX:"avalanche",SOL:"solana",ATOM:"cosmos",DOT:"polkadot"},nonce:"milliseconds",conflictingMarkets:{paxgusd:{base:"PAXG",quote:"USD"}},brokenPairs:["efilusd","maticrlusd","maticusdc","eurusdc","maticgusd","maticusd","efilfil","eurusd"]},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:500,daysBack:void 0,untilDays:void 0,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:{limit:void 0}},spot:{extends:"default"},swap:{linear:{extends:"default"},inverse:void 0},future:{linear:void 0,inverse:void 0}}})}async fetchCurrencies(e={}){return await this.fetchCurrenciesFromWeb(e)}async fetchCurrenciesFromWeb(e={}){let t=await this.fetchWebEndpoint("fetchCurrencies","webExchangeGet",!0,'="currencyData">',"<\/script>");if(void 0===t)return{};this.options.tradingPairs=this.safeList(t,"tradingPairs");let i=this.safeList(t,"currencies",[]);return this.parseCurrencies(i)}parseCurrency(e){let t,i=this.safeString(e,0),s=this.safeCurrencyCode(i),r=this.safeString(e,7),a="crypto";void 0!==r&&""!==r&&(a="fiat");let o=this.parseNumber(this.parsePrecision(this.safeString(e,5))),n={},d=this.safeString(e,9);return void 0!==d&&void 0!==(t=this.networkIdToCode(d,s))&&(n[t]={info:e,id:d,network:t,active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,precision:o,limits:{deposit:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}}}),this.safeCurrencyStructure({info:e,id:i,code:s,name:this.safeString(e,1),active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,type:a,precision:o,limits:{deposit:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}},networks:n})}async fetchMarkets(e={}){if("fetch_markets_from_web"===this.safeString(this.options,"fetchMarketsMethod","fetch_markets_from_api")){let t=[];t.push(this.fetchMarketsFromWeb(e)),t.push(this.fetchUSDTMarkets(e));let i=await Promise.all(t);return this.arrayConcat(i[0],i[1])}return await this.fetchMarketsFromAPI(e)}async fetchMarketsFromWeb(e={}){let t=await this.fetchWebEndpoint("fetchMarkets","webGetRestApi",!1,'<h1 id="symbols-and-minimums">Symbols and minimums</h1>'),i=this.id+" fetchMarketsFromWeb() the API doc HTML markup has changed, breaking the parser of order limits and precision info for markets.",s=t.split("tbody>");if(s.length<2)throw new a.NotSupported(i);let r=s[1].split("\n<tr>\n"),o=r.length;if(o<2)throw new a.NotSupported(i);let n=[];for(let e=1;e<o;e++){let t=r[e],s=t.split("</td>\n");if(s.length<5)throw new a.NotSupported(i);let o=s[0].replace("<td>","");o=o.replace("*","");let d=s[1].replace("<td>","").split(" "),h=this.safeNumber(d,0),c=s[2].replace("<td>","").split(" "),l=o.length-0,u=l-3,f=s[3].replace("<td>","").split(" "),p=this.safeStringLower(f,1,o.slice(u,l)),m=this.safeStringLower(c,1,o.replace(p,"")),g=this.safeCurrencyCode(m),v=this.safeCurrencyCode(p);void 0!==g&&void 0!==v&&n.push({id:o,symbol:g+"/"+v,base:g,quote:v,settle:void 0,baseId:m,quoteId:p,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:void 0,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(c,0),price:this.safeNumber(f,0)},limits:{leverage:{min:void 0,max:void 0},amount:{min:h,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:t})}return n}parseMarketActive(e){return void 0===e||this.safeBool({open:!0,closed:!1,cancel_only:!0,post_only:!0,limit_only:!0},e,!0)}async fetchUSDTMarkets(e={}){if("test"in this.urls)return[];let t=this.safeList(this.options,"fetchUsdtMarkets",[]),i=[];for(let s=0;s<t.length;s++){let r={symbol:t[s]},a=await this.publicGetV1SymbolsDetailsSymbol(this.extend(r,e)),o=this.parseMarket(a);void 0!==o&&i.push(o)}return i}async fetchMarketsFromAPI(e={}){let t=await this.publicGetV1Symbols(e),i=[],s=this.safeDict(this.options,"fetchMarketsFromAPI",{}),r=this.safeList(this.options,"brokenPairs",[]),a=[],o=[];Array.isArray(t)&&(o=t);for(let e=0;e<o.length;e++)this.inArray(o[e],r)||a.push(o[e]);if(this.safeBool(s,"fetchDetailsForAllSymbols",!1)){let t=[];for(let i=0;i<a.length;i++){let s={symbol:a[i]};t.push(this.publicGetV1SymbolsDetailsSymbol(this.extend(s,e)))}let s=await Promise.all(t);for(let e=0;e<s.length;e++){let t=this.parseMarket(s[e]);void 0!==t&&i.push(t)}}else{let e=this.safeList(this.options,"tradingPairs");if(void 0!==e){let t=this.indexBy(e,0);for(let e=0;e<a.length;e++){let s=a[e],o=this.safeList(t,s.toUpperCase());if(void 0!==o&&!this.inArray(s,r)){let e=this.parseMarket(o);void 0!==e&&i.push(e)}}}else for(let e=0;e<a.length;e++)if(!this.inArray(a[e],r)){let t=this.parseMarket(a[e]);void 0!==t&&i.push(t)}}return i}parseMarket(e){let t,i,s,r,a,o,n,d,h,c,l,u=!1,f="string"==typeof e,p=Array.isArray(e);if(f||p){f?t=e:(t=this.safeStringLower(e,0),a=this.parseNumber(this.parsePrecision(this.safeString(e,1))),o=this.parseNumber(this.parsePrecision(this.safeString(e,2))),n=this.safeNumber(e,3));let d=t.toUpperCase(),h=d.indexOf("PERP")>=0,c=d.replace("PERP",""),l=this.safeDict(this.options,"conflictingMarkets",{}),u=c.toLowerCase();if(u in l){let e=l[u];i=e.base,s=e.quote,h&&(r=e.quote)}else{let e=this.handleOption("fetchMarketsFromAPI","quoteCurrencies",[]);for(let t=0;t<e.length;t++){let a=e[t];if(c.endsWith(a)){let e=this.parseToInt(-1*a.length);i=c.slice(0,e),s=a,h&&(r=a);break}}}}else t=this.safeStringLower(e,"symbol"),o=this.safeNumber(e,"tick_size"),a=this.safeNumber(e,"quote_increment"),n=this.safeNumber(e,"min_order_size"),d=this.parseMarketActive(this.safeString(e,"status")),i=this.safeString(e,"base_currency"),s=this.safeString(e,"quote_currency"),r=this.safeString(e,"contract_price_currency");let m=this.safeCurrencyCode(i),g=this.safeCurrencyCode(s);if(void 0===m||void 0===g)return;let v=this.safeCurrencyCode(r),y=m+"/"+g;void 0!==r&&(y=y+":"+v,u=!0,h=a,c=!0,l=!1);let b="spot";u&&(b="swap");let w=!u;return this.safeMarketStructure({id:t,symbol:y,base:m,quote:g,settle:v,baseId:i,quoteId:s,settleId:r,type:b,spot:w,margin:!1,swap:u,future:!1,option:!1,active:d,contract:u,linear:c,inverse:l,contractSize:h,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{price:a,amount:o},limits:{leverage:{min:void 0,max:void 0},amount:{min:n,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:e})}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};void 0!==t&&(r.limit_bids=t,r.limit_asks=t);let a=await this.publicGetV1BookSymbol(this.extend(r,i));return this.parseOrderBook(a,s.symbol,void 0,"bids","asks","price","amount")}async fetchTickerV1(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetV1PubtickerSymbol(this.extend(s,t));return this.parseTicker(r,i)}async fetchTickerV2(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetV2TickerSymbol(this.extend(s,t));return this.parseTicker(r,i)}async fetchTickerV1AndV2(e,t={}){let i=this.fetchTickerV1(e,t),s=this.fetchTickerV2(e,t),[r,a]=await Promise.all([i,s]);return this.deepExtend(r,{open:a.open,high:a.high,low:a.low,change:a.change,percentage:a.percentage,average:a.average,info:a.info})}async fetchTicker(e,t={}){let i=this.safeString(this.options,"fetchTickerMethod","fetchTickerV1");return"fetchTickerV1"===i?await this.fetchTickerV1(e,t):"fetchTickerV2"===i?await this.fetchTickerV2(e,t):await this.fetchTickerV1AndV2(e,t)}parseTicker(e,t){let i,s,r,a,o,n=this.safeDict(e,"volume",{}),d=this.safeInteger(n,"timestamp"),h=this.safeStringLower(e,"pair"),c=this.safeMarket(h,t);void 0!==h&&void 0===c&&(7==h.length-0?(s=h.slice(0,4),r=h.slice(4,7)):(s=h.slice(0,3),r=h.slice(3,6)),a=this.safeCurrencyCode(s),o=this.safeCurrencyCode(r),void 0!==a&&void 0!==o&&(i=a+"/"+o)),void 0===i&&void 0!==c&&(i=c.symbol,s=this.safeStringUpper(c,"baseId"),r=this.safeStringUpper(c,"quoteId"));let l=this.safeString(e,"price"),u=this.safeString2(e,"last","close",l),f=this.safeString(e,"percentChange24h"),p=this.safeString(e,"open"),m=this.safeString(n,s),g=this.safeString(n,r);return this.safeTicker({symbol:i,timestamp:d,datetime:this.iso8601(d),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"bid"),bidVolume:void 0,ask:this.safeString(e,"ask"),askVolume:void 0,vwap:void 0,open:p,close:u,last:u,previousClose:void 0,change:void 0,percentage:f,average:void 0,baseVolume:m,quoteVolume:g,info:e},c)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetV1Pricefeed(t),s=this.parseTickers(i,e),r=this.safeList(this.options,"brokenPairs",[]);return this.removeKeysFromDict(s,r)}parseTrade(e,t){let i=this.safeInteger(e,"timestampms"),s=this.safeString(e,"tid"),r=this.safeString(e,"order_id"),a=this.safeString(e,"fee_currency"),o=this.safeCurrencyCode(a),n={cost:this.safeString(e,"fee_amount"),currency:o},d=this.safeString(e,"price"),h=this.safeString(e,"amount"),c=this.safeStringLower(e,"type"),l=this.safeSymbol(void 0,t);return this.safeTrade({id:s,order:r,info:e,timestamp:i,datetime:this.iso8601(i),symbol:l,type:void 0,side:c,takerOrMaker:void 0,price:d,cost:void 0,amount:h,fee:n},t)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id};void 0!==i&&(a.limit_trades=Math.min(i,500)),void 0!==t&&(a.timestamp=t);let o=await this.publicGetV1TradesSymbol(this.extend(a,s));return this.parseTrades(o,r,t,i)}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"currency"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(s,"available"),o.total=this.safeString(s,"amount"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostV1Notionalvolume(e),i=this.safeString(t,"api_maker_fee_bps"),s=this.safeString(t,"api_taker_fee_bps"),r=o.Y.stringDiv(i,"10000"),a=o.Y.stringDiv(s,"10000"),n=this.parseNumber(r),d=this.parseNumber(a),h={},c=this.symbols;for(let e=0;e<c.length;e++){let i=c[e];h[i]={info:t,symbol:i,maker:n,taker:d,percentage:!0,tierBased:!0}}return h}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostV1Balances(e);return this.parseBalance(t)}parseOrder(e,t){let i=this.safeInteger(e,"timestampms"),s=this.safeString(e,"original_amount"),r=this.safeString(e,"remaining_amount"),a=this.safeString(e,"executed_amount"),o="closed";this.safeBool(e,"is_live",!1)&&(o="open"),this.safeBool(e,"is_cancelled",!1)&&(o="canceled");let n=this.safeString(e,"price"),d=this.safeString(e,"avg_execution_price"),h=this.safeString(e,"type");h="exchange limit"===h?"limit":"market buy"===h||"market sell"===h?"market":this.safeString(e,"type");let c=this.safeString(e,"symbol"),l=this.safeSymbol(c,t),u=this.safeString(e,"order_id"),f=this.safeStringLower(e,"side"),p=this.safeString(e,"client_order_id"),m=this.safeList(e,"options",[]),g=this.safeString(m,0),v="GTC",y=!1;return void 0!==g&&("immediate-or-cancel"===g?v="IOC":"fill-or-kill"===g?v="FOK":"maker-or-cancel"===g&&(v="PO",y=!0)),this.safeOrder({id:u,clientOrderId:p,info:e,timestamp:i,datetime:this.iso8601(i),lastTradeTimestamp:void 0,status:o,symbol:l,type:h,timeInForce:v,postOnly:y,side:f,price:n,triggerPrice:void 0,average:d,cost:void 0,amount:s,filled:a,remaining:r,fee:void 0,trades:void 0},t)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privatePostV1OrderStatus(this.extend({order_id:e},i));return this.parseOrder(s)}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=await this.privatePostV1Orders(s);return void 0!==e&&(r=this.market(e)),this.parseOrders(a,r,t,i)}async createOrder(e,t,i,s,r,o={}){if(void 0===this.markets&&await this.loadMarkets(),"limit"!==t)throw new a.ExchangeError(this.id+" createOrder() allows limit orders only");let n=this.safeString2(o,"clientOrderId","client_order_id");void 0===n&&(n=this.milliseconds().toString());let d=this.market(e),h=this.amountToPrecision(e,s),c=this.priceToPrecision(e,r),l={client_order_id:n,symbol:d.id,amount:h,price:c,side:i,type:"exchange limit"},u=this.safeString(o,"type",t),f=this.safeStringN(o,["triggerPrice","stop_price","stopPrice"]),p=void 0===f?["timeInForce","postOnly"]:[],m=this.omit(o,this.arrayConcat(["clientOrderId","client_order_id","type","triggerPrice","stop_price","stopPrice"],p));if("stopLimit"===u)throw new a.ArgumentsRequired(this.id+" createOrder() requires a triggerPrice parameter or a stop_price parameter for "+u+" orders");if(void 0!==f)l.stop_price=this.priceToPrecision(e,f),l.type="exchange stop limit";else{let e=this.safeString(o,"timeInForce");void 0!==e&&("IOC"===e||"immediate-or-cancel"===e?l.options=["immediate-or-cancel"]:"FOK"===e||"fill-or-kill"===e?l.options=["fill-or-kill"]:"PO"===e&&(l.options=["maker-or-cancel"])),!0===this.safeBool(o,"postOnly",!1)&&(l.options=["maker-or-cancel"]);let t=this.safeString(o,"options");void 0!==t&&(l.options=[t])}let g=await this.privatePostV1OrderNew(this.extend(l,m));return this.parseOrder(g)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privatePostV1OrderCancel(this.extend({order_id:e},i));return this.parseOrder(s)}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={symbol:r.id};void 0!==i&&(o.limit_trades=i),void 0!==t&&(o.timestamp=this.parseToInt(t/1e3));let n=await this.privatePostV1Mytrades(this.extend(o,s));return this.parseTrades(n,r,t,i)}async withdraw(e,t,i,s,r={}){let o=this.handleWithdrawTagAndParams(s,r)[1];this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d={currency:n.id,amount:t,address:i},h=await this.privatePostV1WithdrawCurrency(this.extend(d,o));if("error"===this.safeString(h,"result"))throw new a.ExchangeError(this.id+" withdraw() failed: "+this.json(h));return this.parseTransaction(h,n)}nonce(){return"milliseconds"===this.safeString(this.options,"nonce","milliseconds")?this.milliseconds():this.seconds()}async fetchDepositsWithdrawals(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={};void 0!==i&&(r.limit_transfers=i),void 0!==t&&(r.timestamp=t);let a=await this.privatePostV1Transfers(this.extend(r,s));return this.parseTransactions(a)}parseTransaction(e,t){let i,s=this.safeInteger(e,"timestampms"),r=this.safeString(e,"currency"),a=this.safeCurrencyCode(r,t),o=this.safeString(e,"destination"),n=this.safeStringLower(e,"type"),d=this.safeString(e,"status"),h=this.safeNumber(e,"feeAmount");return void 0!==h&&(i={cost:h,currency:a}),{info:e,id:this.safeString2(e,"eid","withdrawalId"),txid:this.safeString(e,"txHash"),timestamp:s,datetime:this.iso8601(s),network:void 0,address:o,addressTo:void 0,addressFrom:void 0,tag:void 0,tagTo:void 0,tagFrom:void 0,type:n,amount:this.safeNumber(e,"amount"),currency:a,status:this.parseTransactionStatus(d),updated:void 0,internal:void 0,comment:this.safeString(e,"message"),fee:i}}parseTransactionStatus(e){return this.safeString({Advanced:"ok",Complete:"ok"},e,e)}parseDepositAddress(e,t){let i=this.safeString(e,"address");return{currency:this.safeCurrencyCode(void 0,t),network:void 0,address:i,tag:void 0,info:e}}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.fetchDepositAddressesByNetwork(e,t),s=this.handleNetworkCodeAndParams(t)[0];return this.safeValue(i,s)}async fetchDepositAddressesByNetwork(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s=i.code,[r,o]=this.handleNetworkCodeAndParams(t);if(void 0===r)throw new a.ArgumentsRequired(this.id+" fetchDepositAddresses() requires a network parameter");let n=this.networkCodeToId(r,this.safeString(i,"code")),d=await this.privatePostV1AddressesNetwork(this.extend({network:n},o)),h=this.parseDepositAddresses(d,[s],!1,{network:r,currency:s});return this.indexBy(h,"network")}sign(e,t="public",i="GET",r={},o,n){let d,h="/"+this.implodeParams(e,r),c=this.omit(r,this.extractParams(e));if("private"===t){if(this.checkRequiredCredentials(),0>this.apiKey.indexOf("account"))throw new a.AuthenticationError(this.id+" sign() requires an account-key, master-keys are not-supported");let e=this.incrementingNonce().toString(),t=h,i=this.extend({request:t,nonce:e},c),r=this.json(i);r=this.stringToBase64(r);let o=this.hmac(this.encode(r),this.encode(this.secret),s.qt);d={"Content-Type":"text/plain","X-GEMINI-APIKEY":this.apiKey,"X-GEMINI-PAYLOAD":r,"X-GEMINI-SIGNATURE":o}}else Object.keys(c).length>0&&(h+="?"+this.urlencode(c));let l=this.safeString(this.urls.api,t);if(void 0===l)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let u=l+h,f="private"===t?d:o,p=n;return("POST"===i||"DELETE"===i)&&(p=this.json(c)),{url:u,method:i,body:p,headers:f}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n){if("string"==typeof o){let e=this.id+" "+o;this.throwBroadlyMatchedException(this.exceptions.broad,o,e)}return}if("error"===this.safeString(n,"result")){let e=this.safeString(n,"reason"),t=this.safeString(n,"message"),i=this.id+" "+t;throw this.throwExactlyMatchedException(this.exceptions.exact,e,i),this.throwExactlyMatchedException(this.exceptions.exact,t,i),this.throwBroadlyMatchedException(this.exceptions.broad,t,i),new a.ExchangeError(i)}}async createDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={currency:this.currency(e).id},s=await this.privatePostV1DepositCurrencyNewAddress(this.extend(i,t)),r=this.safeString(s,"address");return this.checkAddress(r),{currency:e,address:r,tag:void 0,network:void 0,info:s}}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={timeframe:this.safeString(this.timeframes,t,t),symbol:a.id},n=await this.publicGetV2CandlesSymbolTimeframe(this.extend(o,r)),d=[];return Array.isArray(n)&&(d=n),this.parseOHLCVs(d,a,t,i,s)}async fetchOpenInterest(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetV1RiskstatsSymbol(this.extend(s,t));return this.parseOpenInterest(r,i)}parseOpenInterest(e,t){return this.safeOpenInterest({info:e,symbol:this.safeString(t,"symbol"),openInterestAmount:this.safeString(e,"open_interest"),openInterestValue:this.safeString(e,"open_interest_notional"),timestamp:void 0,datetime:void 0},t)}}i.d(t,{A:()=>n})},5781(e,t,i){"use strict";var s=i(6834),r=i(6885),a=i(8512),o=i(1453),n=i(7749),d=i(1093);class h extends a.A{describe(){return this.deepExtend(super.describe(),{id:"grvt",name:"GRVT",countries:["SG"],rateLimit:10,certified:!1,version:"v1",dex:!0,pro:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!1,option:!1,cancelAllOrders:!0,cancelOrder:!0,createOrder:!0,fetchBalance:!0,fetchCurrencies:!0,fetchDeposits:!0,fetchFundingHistory:!0,fetchFundingRateHistory:!0,fetchLeverages:!0,fetchMarginModes:!0,fetchMarkets:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPositions:!0,fetchTicker:!0,fetchTrades:!0,fetchTransfers:!0,fetchWithdrawals:!0,setLeverage:!0,signIn:!0,transfer:!0,withdraw:!0},timeframes:{"1m":"CI_1_M","3m":"CI_3_M","5m":"CI_5_M","15m":"CI_15_M","30m":"CI_30_M","1h":"CI_1_H","2h":"CI_2_H","4h":"CI_4_H","6h":"CI_6_H","8h":"CI_8_H","12h":"CI_12_H","1d":"CI_1_D","3d":"CI_3_D","5d":"CI_5_D","1w":"CI_1_W","2w":"CI_2_W","3w":"CI_3_W","4w":"CI_4_W"},urls:{logo:"https://github.com/user-attachments/assets/cff0d37c-e594-40cb-88b3-90650ddadc18",api:{privateEdge:"https://edge.grvt.io/",privateTrading:"https://trades.grvt.io/",publicMarket:"https://market-data.grvt.io/"},test:{privateEdge:"https://edge.testnet.grvt.io/",privateTrading:"https://trades.testnet.grvt.io/",publicMarket:"https://market-data.testnet.grvt.io/"},www:"https://grvt.io",referral:"https://grvt.io/?ref=WBLS9D1",doc:["https://api-docs.grvt.io/"],fees:"https://help.grvt.io/en/articles/9614699-how-does-grvt-s-fee-model-work"},api:{privateEdge:{get:{"api/v1/deposit/addresses":{cost:40},"api/v1/bridge/withdrawal-info":{cost:40},"api/v1/bridge/withdrawal-status":{cost:40},"api/v1/referral/epochs":{cost:40},"api/v1/referral/points":{cost:40},"api/v1/referral/data":{cost:40},"api/v1/referral/indirect_data":{cost:40}},post:{"auth/api_key/login":{cost:100},"auth/wallet/login":{cost:100},"auth/builder/authorize":{cost:100},"api/v1/deposit/generate-address":{cost:100},"api/v1/bridge/withdrawal-quote":{cost:100},"api/v1/bridge/withdraw":{cost:100}}},publicMarket:{post:{"full/v1/instrument":{cost:4},"full/v1/all_instruments":{cost:4},"full/v1/instruments":{cost:4},"full/v1/currency":{cost:12},"full/v1/margin_rules":{cost:12},"full/v1/mini":{cost:4},"full/v1/ticker":{cost:4},"full/v1/book":{cost:12},"full/v1/trade":{cost:12},"full/v1/trade_history":{cost:12},"full/v1/kline":{cost:12},"full/v1/funding":{cost:12},"full/v1/supported_assets":{cost:12},"full/v1/get_all_collateral_asset_info":{cost:12}}},privateTrading:{post:{"full/v1/create_order":{cost:5},"full/v1/cancel_order":{cost:5},"full/v1/cancel_on_disconnect":{cost:100},"full/v1/cancel_all_orders":{cost:50},"full/v1/order":{cost:20},"full/v1/order_history":{cost:20},"full/v1/open_orders":{cost:20},"full/v1/fill_history":{cost:20},"full/v1/positions":{cost:20},"full/v1/funding_payment_history":{cost:40},"full/v1/get_sub_accounts":{cost:40},"full/v1/account_summary":{cost:40},"full/v1/account_history":{cost:40},"full/v1/aggregated_account_summary":{cost:40},"full/v1/funding_account_summary":{cost:40},"full/v1/transfer":{cost:100},"full/v1/deposit_history":{cost:100},"full/v1/transfer_history":{cost:100},"full/v1/withdrawal":{cost:100},"full/v1/withdrawal_history":{cost:100},"full/v1/add_position_margin":{cost:40},"full/v1/get_position_margin_limits":{cost:40},"full/v1/set_position_config":{cost:40},"full/v1/set_initial_leverage":{cost:40},"full/v1/get_all_initial_leverage":{cost:40},"full/v1/set_derisk_mm_ratio":{cost:40},"full/v1/vault_burn_tokens":{cost:40},"full/v1/vault_invest":{cost:40},"full/v1/vault_investor_summary":{cost:40},"full/v1/vault_redeem":{cost:40},"full/v1/vault_redeem_cancel":{cost:40},"full/v1/vault_view_redemption_queue":{cost:40},"full/v1/vault_manager_investor_history":{cost:40},"full/v1/authorize_builder":{cost:40},"full/v1/get_authorized_builders":{cost:40},"full/v1/builder_fill_history":{cost:40},"full/v1/create_rfq":{cost:5},"full/v1/cancel_rfq":{cost:5},"full/v1/ecn_from_broker":{cost:40},"full/v2/bulk_orders":{cost:50},"full/v1/position_history":{cost:20},"full/v1/interest_payment_history":{cost:40},"full/v1/get_collateral_preference":{cost:40},"full/v1/spot_account_summary":{cost:40},"full/v1/set_indicative_prices":{cost:40},"full/v1/withdrawal_fee":{cost:100}}}},options:{accountId:void 0,networks:{ARBITRUM:"42161",AVAXC:"43114",BASE:"8453",BSC:"56",ETH:"1",ERC20:"1",OP:"10",SOL:"900",TRX:"728126428",ZKSYNCERA:"324",KAIA:"8217"},networksById:{1:"ERC20"},builderFee:!0,builder:"0x21d2a053495994b1132a38cd1171acec40c6741e",builderRate:.01},precisionMode:4,features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:{last:!0,mark:!0,index:!0,median:!0},triggerDirection:!0,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,trailing:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:1e3,untilDays:1e3,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:1e3,daysBack:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:void 0,fetchOHLCV:{limit:1e3}},spot:void 0,swap:{linear:{extends:"default"},inverse:void 0},future:{linear:void 0,inverse:void 0}},requiredCredentials:{privateKey:!0,apiKey:!1,secret:!1},quoteJsonNumbers:!1,exceptions:{exact:{1e3:o.AuthenticationError,1001:o.PermissionDenied,1002:o.OperationFailed,1003:o.BadRequest,1004:o.OperationRejected,1005:o.OperationFailed,1006:o.RateLimitExceeded,1008:o.PermissionDenied,1009:o.OperationRejected,1012:o.BadRequest,1400:o.PermissionDenied,2e3:o.PermissionDenied,2001:o.InvalidNonce,2002:o.BadRequest,2003:o.PermissionDenied,2004:o.InvalidNonce,2005:o.BadRequest,2006:o.BadRequest,2007:o.BadRequest,2008:o.BadRequest,2010:o.InvalidOrder,2011:o.InvalidOrder,2012:o.InvalidOrder,2020:o.InvalidOrder,2021:o.InvalidOrder,2030:o.InvalidOrder,2031:o.InvalidOrder,2032:o.InvalidOrder,2040:o.InvalidOrder,2041:o.InvalidOrder,2042:o.InvalidOrder,2050:o.InvalidOrder,2051:o.InvalidOrder,2060:o.BadSymbol,2061:o.BadSymbol,2062:o.InvalidOrder,2063:o.InvalidOrder,2064:o.InvalidOrder,2065:o.InvalidOrder,2070:o.InvalidOrder,2080:o.InsufficientFunds,2081:o.OperationRejected,2082:o.InvalidOrder,2083:o.OperationRejected,2090:o.RateLimitExceeded,2100:o.BadRequest,2101:o.BadRequest,2102:o.OperationRejected,2103:o.OperationRejected,2104:o.BadRequest,2105:o.BadRequest,2107:o.BadRequest,2108:o.BadRequest,2110:o.InvalidOrder,2111:o.InvalidOrder,2112:o.InvalidOrder,2113:o.InvalidOrder,2114:o.InvalidOrder,2115:o.InvalidOrder,2116:o.InvalidOrder,2117:o.InvalidOrder,2300:o.OperationRejected,2301:o.OperationRejected,2400:o.OperationRejected,2401:o.OperationRejected,2402:o.OperationRejected,3e3:o.BadSymbol,3004:o.OperationRejected,3005:o.OperationRejected,3006:o.OperationRejected,3021:o.BadRequest,3031:o.BadRequest,4e3:o.InsufficientFunds,4002:o.OperationFailed,4010:o.OperationRejected,5e3:o.OperationRejected,5001:o.OperationRejected,5002:o.OperationRejected,5003:o.OperationRejected,5004:o.OperationRejected,5005:o.OperationRejected,6e3:o.OperationRejected,6100:o.OperationRejected,7e3:o.OperationRejected,7001:o.InsufficientFunds,7002:o.OperationFailed,7003:o.OperationRejected,7004:o.OperationRejected,7005:o.InsufficientFunds,7006:o.OperationFailed,7007:o.PermissionDenied,7100:o.OperationFailed,7101:o.OperationRejected,7102:o.OperationRejected,7103:o.OperationRejected,7201:o.OperationRejected,7450:o.OperationRejected,7451:o.OperationRejected,7452:o.OperationRejected,7453:o.OperationRejected,7454:o.OperationRejected,7455:o.OperationRejected,7500:o.OperationRejected,7501:o.BadRequest,7502:o.OperationRejected,7503:o.OperationRejected,7504:o.OperationRejected},broad:{}}})}eipDefinitions(){return{EIP712_ORDER_TYPE:{Order:[{name:"subAccountID",type:"uint64"},{name:"isMarket",type:"bool"},{name:"timeInForce",type:"uint8"},{name:"postOnly",type:"bool"},{name:"reduceOnly",type:"bool"},{name:"legs",type:"OrderLeg[]"},{name:"nonce",type:"uint32"},{name:"expiration",type:"int64"}],OrderLeg:[{name:"assetID",type:"uint256"},{name:"contractSize",type:"uint64"},{name:"limitPrice",type:"uint64"},{name:"isBuyingContract",type:"bool"}]},EIP712_ORDER_WITH_BUILDER_TYPE:{OrderWithBuilderFee:[{name:"subAccountID",type:"uint64"},{name:"isMarket",type:"bool"},{name:"timeInForce",type:"uint8"},{name:"postOnly",type:"bool"},{name:"reduceOnly",type:"bool"},{name:"legs",type:"OrderLeg[]"},{name:"builder",type:"address"},{name:"builderFee",type:"uint32"},{name:"nonce",type:"uint32"},{name:"expiration",type:"int64"}],OrderLeg:[{name:"assetID",type:"uint256"},{name:"contractSize",type:"uint64"},{name:"limitPrice",type:"uint64"},{name:"isBuyingContract",type:"bool"}]},EIP712_TRANSFER_TYPE:{Transfer:[{name:"fromAccount",type:"address"},{name:"fromSubAccount",type:"uint64"},{name:"toAccount",type:"address"},{name:"toSubAccount",type:"uint64"},{name:"tokenCurrency",type:"uint8"},{name:"numTokens",type:"uint64"},{name:"nonce",type:"uint32"},{name:"expiration",type:"int64"}]},EIP712_WITHDRAWAL_TYPE:{Withdrawal:[{name:"fromAccount",type:"address"},{name:"toEthAddress",type:"address"},{name:"tokenCurrency",type:"uint8"},{name:"numTokens",type:"uint64"},{name:"nonce",type:"uint32"},{name:"expiration",type:"int64"}]},EIP712_BUILDER_APPROVAL_TYPE:{AuthorizeBuilder:[{name:"mainAccountID",type:"address"},{name:"builderAccountID",type:"address"},{name:"maxFutureFeeRate",type:"uint32"},{name:"maxSpotFeeRate",type:"uint32"},{name:"nonce",type:"uint32"},{name:"expiration",type:"int64"}]},EIP712_WALLETLOGIN_TYPE:{WalletLogin:[{name:"signer",type:"address"},{name:"nonce",type:"uint32"},{name:"expiration",type:"int64"}]}}}usesPrivateKey(){let e=void 0!==this.privateKey&&""!==this.privateKey,t=void 0!==this.apiKey&&""!==this.apiKey;if(e&&t)throw new o.ExchangeError('You should provide either "privateKey" or "apikey & secret"');return e}async signIn(e={}){if(void 0===this.privateKey||""===this.privateKey)throw new o.PermissionDenied("Private key is required for this operation. If you used joined GRVT through email registration instead of Web3 wallet, then read: https://github.com/ccxt/ccxt/wiki/FAQ#how-to-use-the-grvt-exchange-in-ccxt");return await this.signInWithPrivateKey(e),await this.initializeClient(e),await this.loadAccountInfos(),!0}async signInWithApiKey(e={}){let t=this.milliseconds(),i=this.safeInteger(this.options,"signInExpiration",0);if(void 0!==i&&i>t+1e4)return{};let s={api_key:this.apiKey},r=await this.privateEdgePostAuthApiKeyLogin(this.extend(s,e));return this.options.signInExpiration=t+864e5,r}async signInWithPrivateKey(e={}){this.checkRequiredCredentials();let t=this.milliseconds(),i=this.safeInteger(this.options,"signInExpiration",0);if(void 0!==i&&i>t+1e4)return{};let s={address:this.ethGetAddressFromPrivateKey(this.privateKey),signature:this.defaultSignature()};s=this.createSignedRequest(s,"EIP712_WALLETLOGIN_TYPE");let r=await this.privateEdgePostAuthWalletLogin(this.extend(s,e));return this.options.signInExpiration=t+864e5,r}async initializeClient(e={}){if(!0!==this.safeBool(e,"builderFee",this.safeBool(this.options,"builderFee",!0)))return!1;if(!0===this.safeBool(this.options,"approvedBuilderFee",!1))return!0;let t=await Promise.all([this.privateTradingPostFullV1GetAuthorizedBuilders(),this.loadAccountInfos()]),i=this.safeDict(t,0),s=this.safeList(i,"results",[]),r=s.length,a=!1;for(let e=0;e<r;e++){let t=this.safeDict(s,e,{});if(this.safeString(t,"builder_account_id")===this.safeString(this.options,"builder")){a=!0;break}}if(a)this.options.approvedBuilderFee=!0;else try{let t={main_account_id:this.safeString(this.options,"userMainAccountId"),builder_account_id:this.safeString(this.options,"builder"),max_futures_fee_rate:this.safeString(this.options,"builderRate"),max_spot_fee_rate:this.safeString(this.options,"builderRate"),signature:this.defaultSignature()};t=this.createSignedRequest(t,"EIP712_BUILDER_APPROVAL_TYPE");let i=await this.privateTradingPostFullV1AuthorizeBuilder(this.extend(t,e)),s=this.safeDict(i,"result"),r=this.safeBool(s,"ack");if(!0!==r)throw new o.ExchangeError("Builder authorization failed, "+this.json(i));this.options.approvedBuilderFee=!0}catch(e){this.options.builderFee=!1}}async fetchMarkets(e={}){let t=[this.publicMarketPostFullV1AllInstruments(e)];this.isEmptyString(this.apiKey)&&this.isEmptyString(this.privateKey)||t.push(this.signIn());let i=await Promise.all(t),s=this.safeDict(i,0),r=this.safeList(s,"result",[]);return this.parseMarkets(r)}parseMarket(e){let t,i=this.safeString(e,"instrument"),s=this.safeString(e,"base"),r=this.safeString(e,"quote"),a=this.safeCurrencyCode(s),o=this.safeCurrencyCode(r);if(void 0===a||void 0===o)return;let n=this.safeCurrencyCode(r);"PERPETUAL"===this.safeString(e,"kind")&&(t="swap");let d="spot"===t,h="swap"===t,c="future"===t;return{id:i,symbol:a+"/"+o+":"+n,base:a,quote:o,settle:n,baseId:s,quoteId:r,settleId:r,type:t,spot:d,margin:!1,swap:h,future:c,option:!1,active:void 0,contract:h||c,linear:!!h||void 0,inverse:!h&&void 0,contractSize:this.parseNumber("1"),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(e,"min_size"),price:this.safeNumber(e,"tick_size"),base:this.parseNumber(this.parsePrecision(this.safeString(e,"base_decimals"))),quote:this.parseNumber(this.parsePrecision(this.safeString(e,"quote_decimals")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(e,"min_size"),max:this.safeNumber(e,"max_position_size")},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(e,"min_notional"),max:void 0}},created:this.safeIntegerProduct(e,"create_time",1e-6),info:e}}async fetchCurrencies(e={}){let t=await this.publicMarketPostFullV1Currency({"":""}),i=this.safeList(t,"result",[]);return this.parseCurrencies(i)}parseCurrency(e){let t=this.safeString(e,"symbol"),i=this.safeCurrencyCode(t);return this.safeCurrencyStructure({info:e,id:t,code:i,name:void 0,active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,precision:this.parseNumber(this.parsePrecision(this.safeString(e,"balance_decimals"))),limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},type:"crypto",networks:void 0,numericId:this.safeInteger(e,"id")})}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instrument:this.marketId(e)},r=await this.publicMarketPostFullV1Ticker(this.extend(s,t)),a=this.safeDict(r,"result",{});return this.parseTicker(a,i)}parseTicker(e,t){let i=this.safeString(e,"instrument"),s=this.safeIntegerProduct(e,"event_time",1e-6);return this.safeTicker({info:e,symbol:this.safeSymbol(i,t),timestamp:s,datetime:this.iso8601(s),open:this.safeString(e,"open_price"),high:this.safeString(e,"high_price"),low:this.safeString(e,"low_price"),last:this.safeString(e,"last_price"),bid:this.safeString(e,"best_bid_price"),bidVolume:this.safeString(e,"best_bid_size"),ask:this.safeString(e,"best_ask_price"),askVolume:this.safeString(e,"best_ask_size"),change:void 0,percentage:void 0,baseVolume:this.safeString(e,"buy_volume_24h_b"),quoteVolume:this.safeString(e,"buy_volume_24h_q"),markPrice:this.safeString(e,"mark_price"),indexPrice:this.safeString(e,"index_price"),vwap:void 0,average:void 0,previousClose:void 0})}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={instrument:this.marketId(e)},r=void 0===t?100:t;r<=500&&(s.depth=this.findNearestCeiling([10,50,100,500],r));let a=await this.publicMarketPostFullV1Book(this.extend(s,i)),o=this.safeDict(a,"result",{}),n=this.parse8601(this.safeString(o,"event_time")),d=this.safeString(o,"instrument");return this.parseOrderBook(o,this.safeSymbol(d),n,"bids","asks","price","size")}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={instrument:r.id};void 0!==i&&(a.limit=Math.min(i,1e3));let[o,n]=this.handleUntilOptionString("end_time",a,s,1e6);void 0!==t&&(o.start_time=this.numberToString(1e6*t));let d=await this.publicMarketPostFullV1TradeHistory(this.extend(o,n)),h=this.safeList(d,"result",[]);return this.parseTrades(h,r,t,i)}parseTrade(e,t){let i,s,r,a=this.safeString(e,"instrument"),o=this.safeMarket(a,t),n=this.safeIntegerProduct(e,"event_time",1e-6),d=this.safeBool(e,"is_taker_buyer");if(void 0!==d)s=d?"buy":"sell",i="taker";else{let t=this.safeBool(e,"is_taker",!1),r=this.safeBool(e,"is_buyer",!1);i=t?"taker":"maker",s=r?"buy":"sell"}let h=this.safeString(e,"fee");return void 0!==h&&(r={cost:this.parseNumber(h),currency:o.quote,rate:this.safeNumber(e,"fee_rate")}),this.safeTrade({info:e,id:this.safeString(e,"trade_id"),timestamp:n,datetime:this.iso8601(n),symbol:o.symbol,side:s,takerOrMaker:i,price:this.safeString(e,"price"),amount:this.safeString(e,"size"),cost:void 0,fee:r,order:this.safeString(e,"order_id")},o)}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,o,1e3);let n=this.market(e),d={instrument:n.id,interval:this.safeString(this.timeframes,t,t)},h=this.safeString(o,"priceType","last");d.type=this.safeString({last:"TRADE",mark:"MARK",index:"INDEX"},h),void 0!==s&&(d.limit=Math.min(s,1e3));let[c,l]=this.handleUntilOptionString("end_time",d,o,1e6);void 0!==i&&(c.start_time=this.numberToString(1e6*i));let u=await this.publicMarketPostFullV1Kline(this.extend(c,l)),f=this.safeList(u,"result",[]);return this.parseOHLCVs(f,n,t,i,s)}parseOHLCV(e,t){return[this.safeIntegerProduct(e,"open_time",1e-6),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume_b")]}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(r)return await this.fetchPaginatedCallDeterministic("fetchFundingRateHistory",e,t,i,"8h",a);let n=this.market(e),d={instrument:n.id};void 0!==i&&(d.limit=Math.min(i,1e3));let[h,c]=this.handleUntilOptionString("end_time",d,a,1e6);void 0!==t&&(h.start_time=this.numberToString(1e6*t));let l=await this.publicMarketPostFullV1Funding(this.extend(h,c)),u=this.safeList(l,"result",[]);return this.parseFundingRateHistories(u,n)}parseFundingRateHistory(e,t){let i=this.safeString(e,"instrument"),s=this.safeIntegerProduct(e,"funding_time",1e-6),r=this.safeString(e,"funding_rate");return{info:e,symbol:this.safeSymbol(i,t),fundingRate:this.parseNumber(n.Y.stringDiv(r,"100")),timestamp:s,datetime:this.iso8601(s)}}getSubAccountId(e){let t=this.handleOptionAndParams(e,"getSubAccountId","accountId")[0];if(void 0===t)throw new o.ArgumentsRequired(this.id+' you should set "accountId" in options or params, which can be found in the grvt dashboard, under Api-Keys page');return t.toString()}async fetchBalance(e={}){await this.loadMarketsAndSignIn();let t={sub_account_id:this.getSubAccountId(e)},i=await this.privateTradingPostFullV1AccountSummary(this.extend(t,e)),s=this.safeDict(i,"result",{});return this.parseBalance(s)}parseBalance(e){let t=this.safeIntegerProduct(e,"event_time",1e-6),i={info:e,timestamp:t,datetime:this.iso8601(t)},s=this.safeList(e,"spot_balances",[]),r=this.safeString(e,"available_balance");for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),a=this.safeString(t,"currency"),o=this.safeCurrencyCode(a),n=this.account();n.total=this.safeString(t,"balance"),n.free=r,void 0!==o&&(i[o]=n)}return this.safeBalance(i)}async fetchDeposits(e,t,i,s={}){let r;await this.loadMarketsAndSignIn();let a={};void 0!==e&&(a.currency=[(r=this.currency(e)).code]),void 0!==i&&(a.limit=Math.min(i,1e3));let[o,n]=this.handleUntilOptionString("end_time",a,s,1e6);if(void 0!==t&&(o.start_time=this.numberToString(1e6*t)),!0===this.safeBool(this.options,"useTransfersEndpointForDepositsWithdrawals",!0)){let e=await this.internalFetchTransfers(this.extend(o,n),r,t,i),s=this.filterTransfersByType(e,"deposit",!0),a=this.getListFromObjectValues(s[0],"info");return this.parseTransactions(a,r,t,i)}{let e=await this.privateTradingPostFullV1DepositHistory(this.extend(o,n)),s=this.safeList(e,"result",[]);return this.parseTransactions(s,r,t,i)}}async fetchWithdrawals(e,t,i,s={}){let r;await this.loadMarketsAndSignIn();let a={};void 0===e?a.currency=null:a.currency=[(r=this.currency(e)).code],void 0!==i&&(a.limit=Math.min(i,1e3));let[o,n]=this.handleUntilOptionString("end_time",a,s,1e6);if(void 0!==t&&(o.start_time=this.numberToString(1e6*t)),!0===this.safeBool(this.options,"useTransfersEndpointForDepositsWithdrawals",!0)){let e=await this.internalFetchTransfers(this.extend(o,n),r,t,i),s=this.filterTransfersByType(e,"withdrawal",!0),a=this.getListFromObjectValues(s[0],"info");return this.parseTransactions(a,r,t,i)}{let e=await this.privateTradingPostFullV1WithdrawalHistory(this.extend(o,n)),s=this.safeList(e,"result",[]);return this.parseTransactions(s,r,t,i)}}async internalFetchTransfers(e,t,i,s){let r=await this.privateTradingPostFullV1TransferHistory(e),a=this.safeList(r,"result",[]);return this.parseTransfers(a,t,i,s)}parseTransaction(e,t){let i,s,r,a=this.safeString(e,"from_account_id"),o=this.safeString(e,"to_account_id"),n=this.safeString(e,"currency"),d=this.safeCurrencyCode(n,t);if("transfer_metadata"in e){let t=this.omitZero(this.safeString(e,"transfer_metadata"));if(void 0!==t){let e=this.parseJson(t);i=this.safeStringLower(e,"direction"),s=this.safeString(e,"provider_tx_id"),r=this.networkIdToCode(this.safeString(e,"chainid"),d),"withdrawal"===i?o=this.safeString(e,"endpoint"):"deposit"===i&&(a=this.safeString(e,"endpoint"))}}let h=this.safeIntegerProduct2(e,"event_time","initiated_time",1e-6);return{info:e,id:void 0,txid:s,type:i,currency:d,network:r,amount:this.safeNumber(e,"num_tokens"),status:void 0,timestamp:h,datetime:this.iso8601(h),address:void 0,addressFrom:a,addressTo:o,tag:void 0,tagFrom:void 0,tagTo:void 0,updated:void 0,comment:void 0,fee:void 0}}async fetchTransfers(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchTransfers() requires a code argument");await this.loadMarketsAndSignIn();let r={},a=this.currency(e),[n,d]=this.handleOptionBoolAndParams(s,"fetchTransfers","paginate",!1);if(n)return await this.fetchPaginatedCallDynamic("fetchTransfers",void 0,t,i,d,1e3);void 0!==i&&(r.limit=Math.min(i,1e3));let[h,c]=this.handleUntilOptionString("end_time",r,d,1e6);void 0!==t&&(h.start_time=this.numberToString(1e6*t));let l=await this.privateTradingPostFullV1TransferHistory(this.extend(h,c)),u=this.safeList(l,"result",[]),f=this.parseTransfers(u,a,t,i);return this.filterTransfersByType(f,"internal",!1)[1]}filterTransfersByType(e,t,i=!0){let s=[],r=[];for(let a=0;a<e.length;a++){let o=e[a];if(i&&"0"===this.safeString(o,"fromAccount")&&"0"===this.safeString(o,"toAccount")||!i&&("0"!==this.safeString(o,"fromAccount")||"0"!==this.safeString(o,"toAccount"))){let e=this.safeString(o.info,"transfer_metadata"),i=this.parseJson(e);this.safeString(i,"direction")===t?s.push(o):r.push(o)}}return[s,r]}async transfer(e,t,i,s,r={}){let a;await this.loadMarketsAndSignIn();let n=this.currency(e),d=this.safeString(this.options,"userMainAccountId"),h=this.inArray(i,["trading","funding"])&&this.inArray(s,["trading","funding"]),c=i,l=s,u=r;if(h){let[e,t]=this.handleOptionStringAndParams(r,"transfer","tradingAccountId"),[a,n]=this.handleOptionStringAndParams(t,"transfer","fundingAccountId");if(void 0===e||void 0===a)throw new o.ArgumentsRequired(this.id+' transfer(): you should set (in the options or params) "tradingAccountId" and "fundingAccountId" (you can use "0" as a main funding account id)');c="trading"===i?e:a,l="trading"===s?e:a,u=n}let f={from_account_id:this.safeString(u,"from_account_id",d),from_sub_account_id:this.safeString(u,"from_sub_account_id",c),to_account_id:this.safeString(u,"to_account_id",d),to_sub_account_id:this.safeString(u,"to_sub_account_id",l),currency:n.id,num_tokens:this.currencyToPrecision(e,t),signature:this.defaultSignature(),transfer_type:"STANDARD",transfer_metadata:null};f=this.createSignedRequest(f,"EIP712_TRANSFER_TYPE",n);try{a=await this.privateTradingPostFullV1Transfer(this.extend(f,u))}catch(t){let e=this.exceptionMessage(t);if("funding"===c&&e.indexOf("You are not authorized")>=0)throw new o.PermissionDenied(this.id+" transfer() failed. Ensure you use funding api-keys when trying to transfer from Funding accounts: "+e);throw t}let p=this.safeDict(a,"result",{});return this.parseTransfer(p,n)}parseTransfer(e,t){let i=this.safeString(e,"currency"),s=this.safeCurrencyCode(i,t),r=this.safeIntegerProduct(e,"event_time",1e-6);return{info:e,id:this.safeString(e,"tx_id"),timestamp:r,datetime:this.iso8601(r),currency:s,amount:this.safeNumber(e,"amount"),fromAccount:this.safeString(e,"from_sub_account_id"),toAccount:this.safeString(e,"to_sub_account_id"),status:void 0}}async loadAccountInfos(){if(void 0!==this.safeString(this.options,"userMainAccountId"))return!1;let e=[];e.push(this.privateTradingPostFullV1AggregatedAccountSummary());let t=void 0===this.safeString(this.options,"accountId");t&&e.push(this.privateTradingPostFullV1GetSubAccounts());let i=await Promise.all(e),s=this.safeDict(i[0],"result",{}),r=this.safeString(s,"main_account_id");if(this.options.userMainAccountId=r,t){let e=this.safeList(i[1],"sub_account_ids",[]),t=e.length;if(t<1)throw new o.ArgumentsRequired(this.id+" loadAccountInfos(): no sub accounts found, you might need to create an api-key in GRVT website");if(t>1)throw new o.ArgumentsRequired(this.id+' loadAccountInfos(): multiple sub accounts found, please set the exchange.options["accountId"] to your preferred sub_account_id from this list: '+this.json(e));let s=this.safeString(e,0);this.options.accountId=s}return!0}async withdraw(e,t,i,s,r={}){this.checkAddress(i),await this.loadMarketsAndSignIn();let a=this.safeString(this.options,"userMainAccountId"),n=this.currency(e),d={to_eth_address:i,from_account_id:a,currency:n.id,num_tokens:this.currencyToPrecision(e,t),signature:this.defaultSignature()},[h,c]=this.handleNetworkCodeAndParams(r),l=this.networkCodeToId(h,e);if(void 0===l)throw new o.BadRequest(this.id+" withdraw() requires a network parameter");d.signature.chain_id=l,d=this.createSignedRequest(d,"EIP712_WITHDRAWAL_TYPE",n);let u=await this.privateTradingPostFullV1Withdrawal(this.extend(d,c)),f=this.safeDict(u,"result",{});return this.parseTransaction(f,n)}async createOrder(e,t,i,s,r,a={}){await this.loadMarketsAndSignIn();let n=this.market(e),d={instrument:n.id,size:this.amountToPrecision(e,s)};if(void 0!==r?d.limit_price=this.priceToPrecision(e,r):d.limit_price=null,"sell"===i)d.is_buying_asset=!1;else if("buy"===i)d.is_buying_asset=!0;else throw new o.InvalidOrder(this.id+' createOrder(): order side must be either "buy" or "sell"');let h=this.safeString(a,"clientOrderId");void 0===h&&(h=this.nonce().toString()+"000"+this.requestId().toString());let c=this.omit(a,["clientOrderId"]),l="market"===t,u=this.getSubAccountId(c),f=this.safeBool(c,"reduceOnly",!1),p={sub_account_id:u,time_in_force:void 0,legs:[d],signature:this.defaultSignature(),metadata:{client_order_id:h},is_market:l,post_only:!1,reduce_only:f},m=this.safeStringUpper(c,"timeInForce","GOOD_TILL_TIME"),g=this.isPostOnly(l,void 0,c);g&&(p.post_only=!0),p.time_in_force=m=void 0===m?"GOOD_TILL_TIME":this.safeString({GTC:"GOOD_TILL_TIME",FOK:"FILL_OR_KILL",IOC:"IMMEDIATE_OR_CANCEL"},m,m),l||(g?m="POST_ONLY":"ioc"===m&&(m="IMMEDIATE_OR_CANCEL"));let v=this.omit(c,["reduceOnly","postOnly","timeInForce"]),[y,b,w,k]=this.handleTriggerPricesAndParams(e,v),S=void 0!==y||void 0!==b||void 0!==w;if(S){let e,t;void 0!==y?e=y:void 0!==b?e=b:void 0!==w&&(e=w);let s="buy"===i;if(void 0!==b)t=s?"STOP_LOSS":"TAKE_PROFIT";else if(void 0!==w)t=s?"TAKE_PROFIT":"STOP_LOSS";else{let e=this.safeString(k,"triggerDirection");if(void 0===e)throw new o.ArgumentsRequired(this.id+' createOrder() requires a triggerDirection parameter when triggerPrice is specified, must be "ascending" or "descending"');void 0!==e&&("ascending"===e?t=s?"STOP_LOSS":"TAKE_PROFIT":"descending"===e&&(t=s?"TAKE_PROFIT":"STOP_LOSS"))}let r=this.safeStringUpper(k,"triggerPriceType","LAST");p.metadata.trigger={trigger_type:t,tpsl:{trigger_by:r,trigger_price:e,close_position:this.safeBool(k,"closePosition",!1)}}}let O=k;S&&(O=this.omit(k,["triggerDirection","triggerPriceType","closePosition"]));let T="EIP712_ORDER_TYPE";!0===this.safeBool(O,"builderFee",this.safeBool(this.options,"builderFee",!0))&&(T="EIP712_ORDER_WITH_BUILDER_TYPE",p.builder=this.safeString(this.options,"builder"),p.builder_fee=this.safeString(this.options,"builderRate"));let P=this.omit(O,["builderFee"]),I=this.createSignedRequest(p,T),A=await this.privateTradingPostFullV1CreateOrder(this.extend({order:I},P)),x=this.safeDict(A,"result",{});return this.parseOrder(x,n)}convertToBigIntCustom(e){return parseInt(e)}eipMessageForOrder(e,t){let i=this.safeList(e,"legs",[]),s=[];for(let e=0;e<i.length;e++){let t=i[e],r=this.market(t.instrument),a=this.convertToBigIntCustom("10"),o=this.precisionFromString(this.safeString(r.precision,"base")).toString(),n=Math.pow(a,this.convertToBigIntCustom(o)),d=t.size,h=d.split("."),c=(this.safeString(h,1,"").length+0).toString(),l=this.convertToBigIntCustom(d.replace(".",""))*n/Math.pow(a,this.convertToBigIntCustom(c)),u={assetID:r.info.instrument_hash,contractSize:this.parseToInt(l),isBuyingContract:t.is_buying_asset},f=this.safeString(t,"limit_price");if(void 0!==this.omitZero(f)){let e=t.limit_price,i=e.split("."),s=(this.safeString(i,1,"").length+0).toString(),r="0"===s?0:this.convertToBigIntCustom(s),o=this.convertToBigIntCustom(e.replace(".",""))*this.convertToBigIntCustom("1000000000")/Math.pow(a,r);u.limitPrice=this.parseToInt(o)}else u.limitPrice=0;s.push(u)}let r={subAccountID:e.sub_account_id,isMarket:e.is_market,timeInForce:this.timeInForceToInt(e.time_in_force),postOnly:e.post_only,reduceOnly:e.reduce_only,legs:s,nonce:e.signature.nonce,expiration:e.signature.expiration};return"EIP712_ORDER_WITH_BUILDER_TYPE"===t&&this.safeBool(this.options,"builderFee",!0)&&(r.builder=e.builder,r.builderFee=this.parseToInt(this.convertToBigIntCustom(this.feeAmountMultiplier())*parseFloat(e.builder_fee))),r}async fetchMyTrades(e,t,i,s={}){let r;await this.loadMarketsAndSignIn();let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,o);let n={sub_account_id:this.getSubAccountId(o)};void 0!==e&&(r=this.market(e),n.base=[],n.base.push(r.baseId),n.quote=[],n.quote.push(r.quoteId)),void 0!==i&&(n.limit=Math.min(i,1e3));let[d,h]=this.handleUntilOptionString("end_time",n,o,1e6);void 0!==t&&(d.start_time=this.numberToString(1e6*t));let c=await this.privateTradingPostFullV1FillHistory(this.extend(d,h)),l=this.safeList(c,"result",[]);return this.parseTrades(l,void 0,t,i)}async fetchPositions(e,t={}){await this.loadMarketsAndSignIn();let i={sub_account_id:this.getSubAccountId(t)},s=this.marketSymbols(e);if(void 0!==s){i.base=[],i.quote=[];for(let e=0;e<s.length;e++){let t=s[e],r=this.market(t);if(!0!==r.contract)throw new o.BadRequest(this.id+" fetchPositions() supports contract markets only");i.base.push(r.baseId),i.quote.push(r.quoteId)}}let r=await this.privateTradingPostFullV1Positions(this.extend(i,t)),a=this.safeList(r,"result",[]);return this.parsePositions(a,s)}parsePosition(e,t){let i=this.safeString(e,"instrument"),s=this.safeIntegerProduct(e,"event_time",1e-6),r=this.safeString(e,"size"),a=n.Y.stringGe(r,"0"),o="short";return a&&(o="long"),this.safePosition({info:e,id:void 0,symbol:this.safeSymbol(i,t),notional:this.parseNumber(n.Y.stringAbs(this.safeString(e,"notional"))),marginMode:void 0,liquidationPrice:this.safeNumber(e,"est_liquidation_price"),entryPrice:this.safeNumber(e,"entry_price"),unrealizedPnl:this.safeNumber(e,"unrealized_pnl"),realizedPnl:this.safeNumber(e,"realized_pnl"),percentage:void 0,contracts:this.parseNumber(n.Y.stringAbs(r)),markPrice:this.safeNumber(e,"mark_price"),lastPrice:void 0,side:o,hedged:void 0,timestamp:s,datetime:this.iso8601(s),lastUpdateTimestamp:this.safeInteger(e,"lastUpdateTime"),maintenanceMargin:this.safeNumber(e,"maintenanceMargin"),maintenanceMarginPercentage:void 0,collateral:void 0,initialMargin:this.safeNumber(e,"initialMargin"),initialMarginPercentage:void 0,leverage:this.safeNumber(e,"leverage"),marginRatio:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}async fetchLeverages(e,t={}){await this.loadMarketsAndSignIn();let i={sub_account_id:this.getSubAccountId(t)},s=await this.privateTradingPostFullV1GetAllInitialLeverage(this.extend(i,t)),r=this.safeList(s,"results",[]);return this.parseLeverages(r,e)}async setLeverage(e,t,i={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");await this.loadMarketsAndSignIn();let s=this.market(t),r={sub_account_id:this.getSubAccountId(i),instrument:s.id,leverage:this.numberToString(e)},a=await this.privateTradingPostFullV1SetInitialLeverage(this.extend(r,i));return this.parseLeverage(a,s)}parseLeverage(e,t){let i=this.safeString(e,"instrument"),s=this.safeNumber(e,"leverage"),r=this.safeStringLower(e,"margin_type");return{info:e,symbol:this.safeSymbol(i,t),marginMode:r,longLeverage:s,shortLeverage:s}}async fetchMarginModes(e,t={}){await this.loadMarketsAndSignIn();let i={sub_account_id:this.getSubAccountId(t)},s=await this.privateTradingPostFullV1GetAllInitialLeverage(this.extend(i,t)),r=this.safeList(s,"results",[]);return this.parseLeverages(r,e)}parseMarginMode(e,t){let i=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(i,t),marginMode:this.safeStringLower(e,"margin_type")}}async fetchFundingHistory(e,t,i,s={}){let r;await this.loadMarketsAndSignIn();let[a,o]=this.handleOptionBoolAndParams(s,"fetchFundingHistory","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchFundingHistory",e,t,i,o,1e3);let n={sub_account_id:this.getSubAccountId(o)};void 0!==e&&(r=this.market(e),n.base=[],n.base.push(r.baseId),n.quote=[],n.quote.push(r.quoteId)),void 0!==i&&(n.limit=Math.min(i,1e3));let[d,h]=this.handleUntilOptionString("end_time",n,o,1e6);void 0!==t&&(d.start_time=this.numberToString(1e6*t));let c=await this.privateTradingPostFullV1FundingPaymentHistory(this.extend(d,h)),l=this.safeList(c,"result",[]);return this.parseIncomes(l,r,t,i)}parseIncome(e,t){let i=this.safeString(e,"instrument"),s=this.safeString(e,"currency"),r=this.safeIntegerProduct(e,"event_time",1e-6);return{info:e,symbol:this.safeSymbol(i,t),code:this.safeCurrencyCode(s),timestamp:r,datetime:this.iso8601(r),id:this.safeString(e,"tx_id"),amount:this.safeNumber(e,"amount")}}async fetchOrders(e,t,i,s={}){let r;await this.loadMarketsAndSignIn();let a={sub_account_id:this.getSubAccountId(s)};void 0!==e&&(r=this.market(e),a.base=[],a.base.push(r.baseId),a.quote=[],a.quote.push(r.quoteId)),void 0!==i&&(a.limit=Math.min(i,1e3));let[o,n]=this.handleUntilOptionString("end_time",a,s,1e6);void 0!==t&&(o.start_time=this.numberToString(1e6*t));let d=await this.privateTradingPostFullV1OrderHistory(this.extend(o,n)),h=this.safeList(d,"result",[]);return this.parseOrders(h,r,t,i)}async fetchOpenOrders(e,t,i,s={}){await this.loadMarketsAndSignIn();let r={sub_account_id:this.getSubAccountId(s)},a=await this.privateTradingPostFullV1OpenOrders(this.extend(r,s)),o=this.safeList(a,"result",[]);return this.parseOrders(o,void 0,t,i)}async fetchOrder(e,t,i={}){await this.loadMarketsAndSignIn();let s={sub_account_id:this.getSubAccountId(i)},r=this.safeString2(i,"clientOrderId","client_order_id");void 0!==r?s.client_order_id=r:s.order_id=e;let a=void 0!==r?this.omit(i,"clientOrderId","client_order_id"):i,o=await this.privateTradingPostFullV1Order(this.extend(s,a)),n=this.safeDict(o,"result",{});return this.parseOrder(n)}parseOrder(e,t){let i,s,r,a,o;if("ack"in e)return this.safeOrder({info:e,id:void 0});let n=this.safeBool(e,"is_market"),d="limit";!0===n&&(d="market");let h=this.safeBool(e,"post_only"),c=this.safeBool(e,"reduce_only"),l=this.safeString(e,"time_in_force"),u=!0===h?"PO":this.parseTimeInForce(l),f=this.safeList(e,"legs",[]),p=this.safeDict(e,"metadata",{}),m=this.safeDict(e,"state",{}),g=this.safeList(m,"traded_size",[]),v=this.safeList(m,"avg_fill_price",[]),y=this.safeDict(f,0),b=this.safeString(y,"instrument"),w=void 0!==y?this.safeMarket(b,t):t;void 0!==y&&(i=this.safeString(y,"size"),s=this.safeBool(y,"is_buying_asset",!1)?"buy":"sell",r=this.safeString(y,"limit_price"),a=this.safeString(g,0),o=this.safeString(v,0));let k=this.safeIntegerProduct(p,"create_time",1e-6);return this.safeOrder({id:this.safeString(e,"order_id"),clientOrderId:this.safeString(p,"client_order_id"),timestamp:k,datetime:this.iso8601(k),lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeIntegerProduct(m,"update_time",1e-6),status:this.parseOrderStatus(this.safeString(m,"status")),symbol:this.safeString(w,"symbol"),type:d,timeInForce:u,postOnly:h,side:s,price:r,triggerPrice:void 0,cost:void 0,average:o,amount:i,filled:a,remaining:void 0,trades:void 0,fees:void 0,reduceOnly:c,info:e},w)}parseTimeInForce(e){return this.safeStringUpper({GOOD_TILL_TIME:"GTC",IMMEDIATE_OR_CANCEL:"IOC",FILL_OR_KILL:"FOK",ALL_OR_NONE:"ALL_OR_NONE",RETAIL_PRICE_IMPROVEMENT:"RETAIL_PRICE_IMPROVEMENT"},e,e)}timeInForceToInt(e){return this.safeInteger({GOOD_TILL_TIME:1,ALL_OR_NONE:2,IMMEDIATE_OR_CANCEL:3,FILL_OR_KILL:4,RETAIL_PRICE_IMPROVEMENT:5},e,0)}parseOrderStatus(e){return this.safeString({PENDING:"pending",OPEN:"open",FILLED:"closed",REJECTED:"rejected",CANCELLED:"canceled"},e,e)}async cancelAllOrders(e,t={}){await this.loadMarketsAndSignIn();let i={sub_account_id:this.getSubAccountId(t)};if(void 0!==e){let t=this.market(e);i.base=[],i.base.push(t.baseId),i.quote=[],i.quote.push(t.quoteId)}let s=await this.privateTradingPostFullV1CancelAllOrders(this.extend(i,t)),r=this.safeDict(s,"result",{});return this.parseOrders([r])}async cancelOrder(e,t,i={}){await this.loadMarketsAndSignIn();let s={sub_account_id:this.getSubAccountId(i)},r=this.safeString2(i,"clientOrderId","client_order_id");void 0!==r?s.client_order_id=r:s.order_id=e;let a=void 0!==r?this.omit(i,"clientOrderId"):i,o=await this.privateTradingPostFullV1CancelOrder(this.extend(s,a)),n=this.safeDict(o,"result",{});return this.parseOrder(n)}eipDomainData(){return{name:"GRVT Exchange",version:"0",chainId:this.isSandboxModeEnabled?326:325}}feeAmountMultiplier(){return this.convertToBigIntCustom("10000")}createSignedRequest(e,t,i,a){let n;if("EIP712_TRANSFER_TYPE"===t){let t=this.convertToBigIntCustom("1000000"),s=e.num_tokens*t;if(void 0===i)throw new o.ExchangeError(this.id+" createSignedRequest() missing currencyObj");n={fromAccount:e.from_account_id,fromSubAccount:e.from_sub_account_id,toAccount:e.to_account_id,toSubAccount:e.to_sub_account_id,tokenCurrency:i.numericId,numTokens:this.parseToInt(s),nonce:e.signature.nonce,expiration:e.signature.expiration}}else if("EIP712_WITHDRAWAL_TYPE"===t){let t=this.convertToBigIntCustom("1000000");if(void 0===i)throw new o.ExchangeError(this.id+" createSignedRequest() missing currencyObj");n={fromAccount:e.from_account_id,toEthAddress:e.to_eth_address,tokenCurrency:i.numericId,numTokens:this.parseToInt(e.num_tokens*t),nonce:e.signature.nonce,expiration:e.signature.expiration}}else if("EIP712_ORDER_TYPE"===t||"EIP712_ORDER_WITH_BUILDER_TYPE"===t)n=this.eipMessageForOrder(e,t);else if("EIP712_BUILDER_APPROVAL_TYPE"===t){let t=this.convertToBigIntCustom(this.feeAmountMultiplier());n={mainAccountID:e.main_account_id,builderAccountID:e.builder_account_id,maxFutureFeeRate:this.parseToInt(parseFloat(e.max_futures_fee_rate)*t),maxSpotFeeRate:this.parseToInt(parseFloat(e.max_spot_fee_rate)*t),nonce:e.signature.nonce,expiration:e.signature.expiration}}else"EIP712_WALLETLOGIN_TYPE"===t&&(n={signer:e.address,nonce:e.signature.nonce,expiration:e.signature.expiration});let h=this.eipDomainData(),c=this.eipDefinitions(),l=this.ethEncodeStructuredData(h,c[t],n),u="0x"+this.hash(l,s.lY,"hex"),f=this.usesPrivateKey()?this.privateKey:this.secret,p=this.remove0xPrefix(f),m=(0,d.h1)(this.remove0xPrefix(u),p,r.bI,void 0);return e.signature.r=this.formatSignatureRS(m.r),e.signature.s=this.formatSignatureRS(m.s),e.signature.v=this.sum(27,m.v),e.signature.signer=void 0===a?this.ethGetAddressFromPrivateKey("0x"+p):a,e}formatSignatureRS(e){let t=e.padStart(64,"0");return t.startsWith("0x")?t:"0x"+t}defaultSignature(){return{signer:"",r:"",s:"",v:0,expiration:(1e6*this.milliseconds()+1e6*this.safeInteger(this.options,"expirationSeconds",30)*1e3).toString(),nonce:this.nonce(),chain_id:this.isSandboxModeEnabled?"326":"325"}}handleUntilOptionString(e,t,i={},s=1){let r=this.safeInteger2(i,"until","till");return void 0!==r?(t[e]=this.numberToString(this.parseToInt(r*s)),[t,this.omit(i,["until","till"])]):[t,i]}requestId(){let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,e}sign(e,t="public",i="GET",s={},r,a){let n=r,d=a,h=e,c=this.omit(s,this.extractParams(h)),l=this.safeString(this.urls.api,t);if(void 0===l)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let u=l+h,f="";if("GET"===i?Object.keys(c).length>0&&(u+="?"+(f=this.urlencode(c))):"POST"===i&&(n={"Content-Type":"application/json"},d=0===Object.keys(s).length?"{}":this.json(s)),!0===t.startsWith("private"))if(this.checkRequiredCredentials(),""!==f&&(h=h+"?"+f),n={"Content-Type":"application/json"},!0===h.endsWith("auth/api_key/login")||!0===h.endsWith("auth/wallet/login"))n.Cookie="rm=true;";else{let e=this.safeString(this.options,"AuthAccountId"),t=this.safeString(this.options,"AuthCookieValue");if(void 0===t||void 0===e)throw new o.AuthenticationError(this.id+" : at first, you need to authenticate with exchange using signIn() method.");n.Cookie=t,n["X-Grvt-Account-Id"]=e}return{url:u,method:i,body:d,headers:n}}handleErrors(e,t,i,s,r,a,n,d,h){if(i.endsWith("auth/api_key/login")||i.endsWith("auth/wallet/login")){let e=this.safeString2(r,"X-Grvt-Account-Id","x-grvt-account-id");this.options.AuthAccountId=e;let t=this.safeString2(r,"Set-Cookie","set-cookie");if(void 0!==t){let e=t.split(";")[0];this.options.AuthCookieValue=e}if(void 0===this.safeString(this.options,"AuthCookieValue")||void 0===this.safeString(this.options,"AuthAccountId"))throw new o.AuthenticationError(this.id+" signIn() failed to receive auth-cookie or account-id")}else{let e=this.safeString(n,"code");if(void 0!==e){let t=this.id+" "+a;throw this.throwExactlyMatchedException(this.exceptions.exact,e,t),new o.ExchangeError(t)}{let e=this.safeString(n,"message");if(void 0!==e){let t=this.id+" "+a;throw this.throwBroadlyMatchedException(this.exceptions.broad,e,t),new o.ExchangeError(t)}{let e=this.safeString(n,"status");if(void 0!==e&&"success"!==e){let e=this.id+" "+a;throw new o.ExchangeError(e)}}}}}}i.d(t,{A:()=>h})},6671(e,t,i){"use strict";var s=i(4721),r=i(1264),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"hashkey",name:"HashKey Global",countries:["BM"],rateLimit:100,version:"v1",certified:!0,pro:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!0,future:!1,option:!1,addMargin:!0,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelAllOrdersAfter:!1,cancelOrder:!0,cancelOrders:!0,cancelWithdraw:!1,closeAllPositions:!1,closePosition:!1,createConvertTrade:!1,createDepositAddress:!1,createMarketBuyOrderWithCost:!0,createMarketOrder:!0,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!1,createReduceOnlyOrder:!0,createStopLimitOrder:!0,createStopLossOrder:!1,createStopMarketOrder:!0,createStopOrder:!0,createTakeProfitOrder:!1,createTrailingAmountOrder:!1,createTrailingPercentOrder:!1,createTriggerOrder:!0,fetchAccounts:!0,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCanceledAndClosedOrders:!0,fetchCanceledOrders:!0,fetchClosedOrder:!0,fetchClosedOrders:!1,fetchConvertCurrencies:!1,fetchConvertQuote:!1,fetchConvertTrade:!1,fetchConvertTradeHistory:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLastPrices:!0,fetchLedger:!0,fetchLeverage:!0,fetchLeverages:!1,fetchLeverageTiers:!0,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:"emulated",fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrice:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrder:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!1,fetchOrderTrades:!1,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsForSymbol:!0,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTransactions:!1,fetchTransfers:!1,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!0,repayCrossMargin:!1,repayIsolatedMargin:!1,sandbox:!1,setLeverage:!0,setMargin:!1,setMarginMode:!0,setPositionMode:!1,transfer:!0,withdraw:!0},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","8h":"8h","12h":"12h","1d":"1d","1w":"1w","1M":"1M"},urls:{logo:"https://github.com/user-attachments/assets/3dd65db2-5da9-4ecc-93ac-6d420f36261c",api:{public:"https://api-glb.hashkey.com",private:"https://api-glb.hashkey.com"},test:{public:"https://api-glb.sim.hashkeydev.com",private:"https://api-glb.sim.hashkeydev.com"},www:"https://global.hashkey.com/",doc:"https://hashkeyglobal-apidoc.readme.io/",fees:"https://support.global.hashkey.com/hc/en-us/articles/13199900083612-HashKey-Global-Fee-Structure",referral:"https://global.hashkey.com/en-US/register/invite?invite_code=82FQUN"},api:{public:{get:{"api/v1/exchangeInfo":{cost:5},"quote/v1/depth":{cost:1},"quote/v1/trades":{cost:1},"quote/v1/klines":{cost:1},"quote/v1/ticker/24hr":{cost:1},"quote/v1/ticker/price":{cost:1},"quote/v1/ticker/bookTicker":{cost:1},"quote/v1/depth/merged":{cost:1},"quote/v1/markPrice":{cost:1},"quote/v1/index":{cost:1},"api/v1/futures/fundingRate":{cost:1},"api/v1/futures/historyFundingRate":{cost:1},"api/v1/ping":{cost:1},"api/v1/time":{cost:1}}},private:{get:{"api/v1/spot/order":{cost:1},"api/v1/spot/openOrders":{cost:1},"api/v1/spot/tradeOrders":{cost:5},"api/v1/futures/leverage":{cost:1},"api/v1/futures/order":{cost:1},"api/v1/futures/openOrders":{cost:1},"api/v1/futures/userTrades":{cost:1},"api/v1/futures/positions":{cost:1},"api/v1/futures/historyOrders":{cost:1},"api/v1/futures/balance":{cost:1},"api/v1/futures/liquidationAssignStatus":{cost:1},"api/v1/futures/riskLimit":{cost:1},"api/v1/futures/commissionRate":{cost:1},"api/v1/futures/getBestOrder":{cost:1},"api/v1/coinInfo":{cost:1},"api/v1/account/vipInfo":{cost:1},"api/v1/account":{cost:1},"api/v1/account/trades":{cost:5},"api/v1/account/type":{cost:5},"api/v1/account/chainType":{cost:1},"api/v1/account/checkApiKey":{cost:1},"api/v1/account/balanceFlow":{cost:5},"api/v1/spot/subAccount/openOrders":{cost:1},"api/v1/spot/subAccount/tradeOrders":{cost:1},"api/v1/subAccount/trades":{cost:1},"api/v1/futures/subAccount/openOrders":{cost:1},"api/v1/futures/subAccount/historyOrders":{cost:1},"api/v1/futures/subAccount/userTrades":{cost:1},"api/v1/account/deposit/address":{cost:1},"api/v1/account/depositOrders":{cost:1},"api/v1/account/withdrawOrders":{cost:1},"api/v1/affiliate/inviteeInfo":{cost:1}},post:{"api/v1/userDataStream":{cost:1},"api/v1/spot/orderTest":{cost:1},"api/v1/spot/order":{cost:1},"api/v1.1/spot/order":{cost:1},"api/v1/spot/batchOrders":{cost:5},"api/v1/futures/leverage":{cost:1},"api/v1/futures/order":{cost:1},"api/v1/futures/marginType":{cost:1},"api/v1/futures/positionMargin":{cost:1},"api/v1/futures/position/trading-stop":{cost:3},"api/v1/futures/batchOrders":{cost:5},"api/v1/account/assetTransfer":{cost:1},"api/v1/account/authAddress":{cost:1},"api/v1/account/withdraw":{cost:1}},put:{"api/v1/userDataStream":{cost:1}},delete:{"api/v1/spot/order":{cost:1},"api/v1/spot/openOrders":{cost:5},"api/v1/spot/cancelOrderByIds":{cost:5},"api/v1/spot/cancelAllOpenOrders":{cost:5},"api/v1/futures/order":{cost:1},"api/v1/futures/batchOrders":{cost:1},"api/v1/futures/cancelOrderByIds":{cost:1},"api/v1/futures/cancelAllOpenOrders":{cost:1},"api/v1/userDataStream":{cost:1}}}},fees:{trading:{spot:{tierBased:!0,percentage:!0,feeSide:"get",maker:this.parseNumber("0.0012"),taker:this.parseNumber("0.0012"),tiers:{maker:[[this.parseNumber("0"),this.parseNumber("0.0012")],[this.parseNumber("1000000"),this.parseNumber("0.00080")],[this.parseNumber("5000000"),this.parseNumber("0.00070")],[this.parseNumber("10000000"),this.parseNumber("0.00060")],[this.parseNumber("50000000"),this.parseNumber("0.00040")],[this.parseNumber("200000000"),this.parseNumber("0.00030")],[this.parseNumber("400000000"),this.parseNumber("0.00010")],[this.parseNumber("800000000"),this.parseNumber("0.00")]],taker:[[this.parseNumber("0"),this.parseNumber("0.0012")],[this.parseNumber("1000000"),this.parseNumber("0.00090")],[this.parseNumber("5000000"),this.parseNumber("0.00085")],[this.parseNumber("10000000"),this.parseNumber("0.00075")],[this.parseNumber("50000000"),this.parseNumber("0.00065")],[this.parseNumber("200000000"),this.parseNumber("0.00045")],[this.parseNumber("400000000"),this.parseNumber("0.00040")],[this.parseNumber("800000000"),this.parseNumber("0.00035")]]}},swap:{tierBased:!0,percentage:!0,feeSide:"get",maker:this.parseNumber("0.00025"),taker:this.parseNumber("0.00060"),tiers:{maker:[[this.parseNumber("0"),this.parseNumber("0.00025")],[this.parseNumber("1000000"),this.parseNumber("0.00016")],[this.parseNumber("5000000"),this.parseNumber("0.00014")],[this.parseNumber("10000000"),this.parseNumber("0.00012")],[this.parseNumber("50000000"),this.parseNumber("0.000080")],[this.parseNumber("200000000"),this.parseNumber("0.000060")],[this.parseNumber("400000000"),this.parseNumber("0.000020")],[this.parseNumber("800000000"),this.parseNumber("0.00")]],taker:[[this.parseNumber("0"),this.parseNumber("0.00060")],[this.parseNumber("1000000"),this.parseNumber("0.00050")],[this.parseNumber("5000000"),this.parseNumber("0.00045")],[this.parseNumber("10000000"),this.parseNumber("0.00040")],[this.parseNumber("50000000"),this.parseNumber("0.00035")],[this.parseNumber("200000000"),this.parseNumber("0.00030")],[this.parseNumber("400000000"),this.parseNumber("0.00025")],[this.parseNumber("800000000"),this.parseNumber("0.00020")]]}}}},options:{broker:"10000700011",recvWindow:void 0,sandboxMode:!1,networks:{BTC:"BTC",ERC20:"ETH",AVAX:"AvalancheC",SOL:"Solana",MATIC:"Polygon",ATOM:"Cosmos",DOT:"Polkadot",LTC:"LTC",OPTIMISM:"Optimism",ARBITRUM:"Arbitrum",DOGE:"Dogecoin",TRC20:"Tron",ZKSYNC:"zkSync",TON:"TON",KLAYTN:"Klaytn",MERLINCHAIN:"Merlin Chain"},networksById:{BTC:"BTC",Bitcoin:"BTC",ETH:"ERC20",ERC20:"ERC20",AvalancheC:"AVAX","AVAX C-Chain":"AVAX",Solana:"SOL",Cosmos:"ATOM",Arbitrum:"ARBITRUM",Polygon:"MATIC",Optimism:"OPTIMISM",Polkadot:"DOT",LTC:"LTC",Litecoin:"LTC",Dogecoin:"DOGE","Merlin Chain":"MERLINCHAIN",zkSync:"ZKSYNC",TRC20:"TRC20",Tron:"TRC20",TON:"TON","BSC(BEP20)":"BSC",Klaytn:"KLAYTN"},defaultNetwork:"ERC20"},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!0,selfTradePrevention:!0,iceberg:!1},createOrders:{max:20},fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:30,untilDays:30,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:1e3,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:{limit:1e3}},spot:{extends:"default"},forDerivatives:{extends:"default",createOrder:{triggerPrice:!0,selfTradePrevention:!0},fetchOpenOrders:{trigger:!0,limit:500}},swap:{linear:{extends:"forDerivatives"},inverse:void 0},future:{linear:void 0,inverse:void 0}},commonCurrencies:{},exceptions:{exact:{"0001":a.BadRequest,"0002":a.AuthenticationError,"0003":a.RateLimitExceeded,"0102":a.AuthenticationError,"0103":a.AuthenticationError,"0104":a.PermissionDenied,"0201":a.ExchangeError,"0202":a.PermissionDenied,"0206":a.BadRequest,"0207":a.BadRequest,"0209":a.BadRequest,"0210":a.BadRequest,"0211":a.OrderNotFound,"0401":a.InsufficientFunds,"0402":a.BadRequest,"-1000":a.ExchangeError,"-1001":a.ExchangeError,"-100010":a.BadSymbol,"-100012":a.BadSymbol,"-1002":a.AuthenticationError,"-1004":a.BadRequest,"-1005":a.PermissionDenied,"-1006":a.ExchangeError,"-1007":a.RequestTimeout,"-1014":a.InvalidOrder,"-1015":a.InvalidOrder,"-1020":a.OperationRejected,"-1021":a.InvalidNonce,"-1024":a.BadRequest,"-1101":a.ExchangeNotAvailable,"-1115":a.InvalidOrder,"-1117":a.InvalidOrder,"-1123":a.InvalidOrder,"-1124":a.InvalidOrder,"-1126":a.InvalidOrder,"-1129":a.BadRequest,"-1130":a.BadRequest,"-1132":a.BadRequest,"-1133":a.BadRequest,"-1135":a.BadRequest,"-1136":a.BadRequest,"-1138":a.InvalidOrder,"-1137":a.InvalidOrder,"-1139":a.OrderImmediatelyFillable,"-1140":a.InvalidOrder,"-1141":a.DuplicateOrderId,"-1142":a.OrderNotFillable,"-1143":a.OrderNotFound,"-1144":a.OperationRejected,"-1145":a.NotSupported,"-1146":a.RequestTimeout,"-1147":a.RequestTimeout,"-1148":a.InvalidOrder,"-1149":a.OperationRejected,"-1150":a.OperationFailed,"-1151":a.OperationRejected,"-1152":a.AccountNotEnabled,"-1153":a.InvalidOrder,"-1154":a.InvalidOrder,"-1155":a.OperationRejected,"-1156":a.OperationFailed,"-1157":a.OperationFailed,"-1158":a.OperationFailed,"-1159":a.AccountNotEnabled,"-1160":a.AccountNotEnabled,"-1161":a.OperationFailed,"-1162":a.ContractUnavailable,"-1163":a.InvalidAddress,"-1164":a.OperationFailed,"-1165":a.ArgumentsRequired,"-1166":a.OperationRejected,"-1167":a.BadRequest,"-1168":a.BadRequest,"-1169":a.PermissionDenied,"-1170":a.PermissionDenied,"-1171":a.PermissionDenied,"-1172":a.BadRequest,"-1173":a.BadRequest,"-1174":a.PermissionDenied,"-1175":a.BadRequest,"-1176":a.BadRequest,"-1177":a.InvalidOrder,"-1178":a.AccountNotEnabled,"-1179":a.AccountSuspended,"-1181":a.ExchangeError,"-1193":a.OperationRejected,"-1194":a.OperationRejected,"-1195":a.BadRequest,"-1196":a.BadRequest,"-1200":a.BadRequest,"-1201":a.BadRequest,"-1202":a.BadRequest,"-1203":a.BadRequest,"-1204":a.BadRequest,"-1205":a.AccountNotEnabled,"-1206":a.BadRequest,"-1207":a.BadRequest,"-1208":a.BadRequest,"-1209":a.BadRequest,"-2001":a.ExchangeNotAvailable,"-2002":a.OperationFailed,"-2003":a.OperationFailed,"-2004":a.OperationFailed,"-2005":a.RequestTimeout,"-2010":a.OperationRejected,"-2011":a.OperationRejected,"-2016":a.OperationRejected,"-2017":a.OperationRejected,"-2018":a.OperationRejected,"-2019":a.PermissionDenied,"-2020":a.PermissionDenied,"-2021":a.PermissionDenied,"-2022":a.OperationRejected,"-2023":a.AuthenticationError,"-2024":a.AccountNotEnabled,"-2025":a.AccountNotEnabled,"-2026":a.BadRequest,"-2027":a.OperationRejected,"-2028":a.OperationRejected,"-2029":a.OperationRejected,"-2030":a.InsufficientFunds,"-2031":a.NotSupported,"-2032":a.OperationRejected,"-2033":a.OperationFailed,"-2034":a.InsufficientFunds,"-2035":a.OperationRejected,"-2036":a.NotSupported,"-2037":a.ExchangeError,"-2038":a.InsufficientFunds,"-2039":a.NotSupported,"-2040":a.ExchangeNotAvailable,"-2041":a.BadRequest,"-2042":a.OperationRejected,"-2043":a.OperationRejected,"-2044":a.BadRequest,"-2045":a.BadRequest,"-2046":a.BadRequest,"-2048":a.BadRequest,"-2049":a.BadRequest,"-2050":a.BadRequest,"-2051":a.OperationRejected,"-2052":a.OperationRejected,"-2053":a.OperationRejected,"-2054":a.BadRequest,"-2055":a.BadRequest,"-2056":a.BadRequest,"-2057":a.BadRequest,"-3117":a.PermissionDenied,"-3143":a.PermissionDenied,"-3144":a.PermissionDenied,"-3145":a.DDoSProtection,"-4001":a.BadRequest,"-4002":a.BadRequest,"-4003":a.InsufficientFunds,"-4004":a.BadRequest,"-4005":a.BadRequest,"-4006":a.AccountNotEnabled,"-4007":a.NotSupported,"-4008":a.AccountNotEnabled,"-4009":a.PermissionDenied,"-4010":a.PermissionDenied,"-4011":a.ExchangeError,"-4012":a.ExchangeError,"-4013":a.OperationFailed},broad:{}},precisionMode:4})}async fetchTime(e={}){let t=await this.publicGetApiV1Time(e);return this.safeInteger(t,"serverTime")}async fetchStatus(e={}){return{status:"ok",updated:void 0,eta:void 0,url:void 0,info:await this.publicGetApiV1Ping(e)}}async fetchMarkets(e={}){let t=await this.publicGetApiV1ExchangeInfo(this.extend({},e)),i=this.safeList(t,"symbols",[]),s=this.safeList(t,"contracts",[]),r=this.arrayConcat(i,s);return this.isEmpty(r)&&(r=[t]),this.parseMarkets(r)}parseMarket(e){let t,i,s,r,a,n=this.safeString(e,"symbol"),d=this.safeString(e,"quoteAsset"),h=this.safeCurrencyCode(d),c=this.safeString(e,"marginToken"),l=this.safeCurrencyCode(c),u=this.safeString(e,"baseAsset"),f="spot",p=!0,m=!1,g="",v=n.split("-");"PERPETUAL"===this.safeString(v,1)&&(f="swap",p=!1,m=!0,u=this.safeString(e,"underlying"),g+=":"+c);let y=this.safeCurrencyCode(u);if(void 0===y||void 0===h)return;let b=y+"/"+h+g,w=this.safeString(e,"status"),k=this.safeBool(e,"inverse");void 0!==k&&(k?(t=!1,i="inverse"):(t=!0,i="linear"));let S=this.safeList(e,"filters",[]),O=this.indexBy(S,"filterType"),T=this.safeDict(O,"PRICE_FILTER",{}),P=this.safeDict(O,"LOT_SIZE",{}),I=this.safeDict(O,"MIN_NOTIONAL",{}),A=this.omitZero(this.safeString(I,"min_notional")),x=this.safeString(e,"contractMultiplier"),M=this.safeString(P,"stepSize"),_=this.safeString(P,"minQty"),C=this.safeString(P,"maxQty");if(m){M=o.Y.stringDiv(M,x),_=o.Y.stringDiv(_,x),C=o.Y.stringDiv(C,x);let t=this.safeList(e,"riskLimits");if(void 0!==t){let e=this.safeDict(t,0),i=t.length,a=this.safeDict(t,i-1),n=this.safeString(e,"initialMargin"),d=this.safeString(a,"initialMargin");o.Y.stringGt(n,d)&&([n,d]=[d,n]),s=this.parseToInt(o.Y.stringDiv("1",d)),r=this.parseToInt(o.Y.stringDiv("1",n))}}let B=this.safeDict(this.fees,"trading");return a=p?this.safeDict(B,"spot"):this.safeDict(B,"swap"),this.safeMarketStructure({id:n,symbol:b,base:y,quote:h,baseId:u,quoteId:d,active:"TRADING"===w,type:f,subType:i,spot:p,margin:this.safeBool(e,"allowMargin"),swap:m,future:!1,option:!1,contract:m,settle:l,settleId:c,contractSize:this.parseNumber(x),linear:t,inverse:k,taker:this.safeNumber(a,"taker"),maker:this.safeNumber(a,"maker"),percentage:this.safeBool(a,"percentage"),tierBased:this.safeBool(a,"tierBased"),feeSide:this.safeString(a,"feeSide"),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(M),price:this.safeNumber(T,"tickSize")},limits:{amount:{min:this.parseNumber(_),max:this.parseNumber(C)},price:{min:this.safeNumber(T,"minPrice"),max:this.safeNumber(T,"maxPrice")},leverage:{min:s,max:r},cost:{min:this.parseNumber(A),max:void 0}},created:void 0,info:e})}async fetchCurrencies(e={}){let t=await this.publicGetApiV1ExchangeInfo(e),i=this.safeList(t,"coins");return this.parseCurrencies(i)}parseCurrency(e){let t=this.safeString(e,"coinId"),i=this.safeCurrencyCode(t),s=this.safeList(e,"chainTypes"),r={};for(let e=0;e<s.length;e++){let t=s[e],a=this.safeString(t,"chainType"),o=this.networkCodeToId(a,i);void 0!==o&&(r[o]={id:a,network:o,limits:{withdraw:{min:this.safeNumber(t,"minWithdrawQuantity"),max:this.parseNumber(this.omitZero(this.safeString(t,"maxWithdrawQuantity")))},deposit:{min:this.safeNumber(t,"minDepositQuantity"),max:void 0}},active:void 0,deposit:this.safeBool(t,"allowDeposit"),withdraw:this.safeBool(t,"allowWithdraw"),fee:this.safeNumber(t,"withdrawFee"),precision:void 0,info:t})}let a=this.safeString(e,"tokenType"),o="crypto";return"REAL_MONEY"===a&&(o="fiat"),this.safeCurrencyStructure({id:t,code:i,precision:void 0,type:o,name:this.safeString(e,"coinFullName"),active:void 0,deposit:this.safeBool(e,"allowDeposit"),withdraw:this.safeBool(e,"allowWithdraw"),fee:void 0,limits:{deposit:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}},networks:r,info:e})}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={symbol:this.market(e).id};void 0!==t&&(s.limit=t);let r=await this.publicGetQuoteV1Depth(this.extend(s,i)),a=this.safeInteger(r,"t");return this.parseOrderBook(r,e,a,"b","a")}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id};void 0!==i&&(a.limit=i);let o=await this.publicGetQuoteV1Trades(this.extend(a,s));return this.parseTrades(o,r,t,i)}async fetchMyTrades(e,t,i,s={}){let r,o,n="fetchMyTrades";void 0===this.markets&&await this.loadMarkets();let d={};void 0!==e&&(r=this.market(e));let[h,c]=this.handleMarketTypeAndParams(n,r,s);void 0!==t&&(d.startTime=t),void 0!==i&&(d.limit=i);let[l,u]=this.handleOptionAndParams(c,n,"until");void 0!==l&&(d.endTime=l);let[f,p]=this.handleOptionStringAndParams(u,n,"accountId");if("spot"===h)void 0!==r&&(d.symbol=r.id),void 0!==f&&(d.accountId=f),o=await this.privateGetApiV1AccountTrades(this.extend(d,p));else if("swap"===h){if(void 0===e)throw new a.ArgumentsRequired(this.id+" "+n+"() requires a symbol argument for swap markets");d.symbol=this.safeString(r,"id"),void 0!==f?(d.subAccountId=f,o=await this.privateGetApiV1FuturesSubAccountUserTrades(this.extend(d,p))):o=await this.privateGetApiV1FuturesUserTrades(this.extend(d,p))}else throw new a.NotSupported(this.id+" "+n+"() is not supported for "+h+" type of markets");return this.parseTrades(o,r,t,i)}parseTrade(e,t){let i,s,r=this.safeInteger2(e,"t","time"),a=this.safeString(e,"symbol"),o=this.safeMarket(a,t),n=this.safeStringLower(e,"side");void 0!==n&&(n=this.safeString(n.split("_"),0));let d=this.safeBool(e,"isBuyer");void 0!==d&&(n=d?"buy":"sell");let h=this.safeBool2(e,"isMaker","isMarker");void 0!==h&&(i=h?"maker":"taker");let c=this.safeBool(e,"ibm");void 0!==c&&(i="taker",n=c?"sell":"buy");let l=this.safeString(e,"commission"),u=this.safeString(e,"commissionAsset"),f=this.safeDict(e,"fee");return void 0!==f&&(l=this.safeString(f,"fee"),u=this.safeString(f,"feeCoinId")),void 0!==l&&(s={cost:this.parseNumber(l),currency:this.safeCurrencyCode(u)}),this.safeTrade({id:this.safeString2(e,"id","tradeId"),timestamp:r,datetime:this.iso8601(r),symbol:o.symbol,side:n,price:this.safeString2(e,"p","price"),amount:this.safeStringN(e,["q","qty","quantity"]),cost:void 0,takerOrMaker:i,type:void 0,order:this.safeString(e,"orderId"),fee:s,info:e},o)}async fetchOHLCV(e,t="1m",i,s,r={}){let a="fetchOHLCV";void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(r,a,"paginate",!1);if(o)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,n,1e3);let d=this.market(e),h=this.safeString(this.timeframes,t,t),c={symbol:d.id,interval:h};void 0!==i&&(c.startTime=i),void 0!==s&&(c.limit=s);let[l,u]=this.handleOptionAndParams(n,a,"until");void 0!==l&&(c.endTime=l);let f=await this.publicGetQuoteV1Klines(this.extend(c,u)),p=this.toArray(f);return this.parseOHLCVs(p,d,h,i,s)}parseOHLCV(e,t){return[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetQuoteV1Ticker24hr(this.extend(s,t)),a=this.safeDict(r,0,{});return this.parseTicker(a,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetQuoteV1Ticker24hr(t);return this.parseTickers(s,i)}parseTicker(e,t){let i=this.safeInteger(e,"t"),s=this.safeString(e,"s"),r=this.safeMarket(s,t),a=r.symbol,n=this.safeString(e,"c"),d=this.safeString(e,"v");return!0===r.contract&&void 0!==r.contractSize&&(d=o.Y.stringMul(d,this.numberToString(r.contractSize))),this.safeTicker({symbol:a,timestamp:i,datetime:this.iso8601(i),high:this.safeString(e,"h"),low:this.safeString(e,"l"),bid:this.safeString(e,"b"),bidVolume:void 0,ask:this.safeString(e,"a"),askVolume:void 0,vwap:void 0,open:this.safeString(e,"o"),close:n,last:n,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:d,quoteVolume:this.safeString(e,"qv"),info:e},r)}async fetchLastPrices(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetQuoteV1TickerPrice(this.extend({},t));return this.parseLastPrices(s,i)}parseLastPrice(e,t){let i=this.safeString(e,"s");return{symbol:this.safeMarket(i,t).symbol,timestamp:void 0,datetime:void 0,price:this.safeNumberOmitZero(e,"p"),side:void 0,info:e}}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t="fetchBalance",[i,s]=this.handleMarketTypeAndParams(t,void 0,e,"spot");if("swap"===i){let e=await this.privateGetApiV1FuturesBalance(s),t=this.safeDict(e,0,{});return this.parseSwapBalance(t)}if("spot"===i){let e=await this.privateGetApiV1Account(this.extend({},s));return this.parseBalance(e)}throw new a.NotSupported(this.id+" "+t+"() is not supported for "+i+" type of markets")}parseBalance(e){let t={info:e},i=this.safeList(e,"balances",[]);for(let e=0;e<i.length;e++){let s=this.safeDict(i,e),r=this.safeString(s,"asset"),a=this.safeCurrencyCode(r),o=this.account();o.total=this.safeString(s,"total"),o.free=this.safeString(s,"free"),o.used=this.safeString(s,"locked"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}parseSwapBalance(e){let t=this.safeString(e,"asset"),i=this.safeCurrencyCode(t),s=this.account();s.total=this.safeString(e,"balance");let r=this.safeString(e,"positionMargin"),a=this.safeString(e,"orderMargin");s.used=o.Y.stringAdd(r,a);let n={info:e};return void 0!==i&&(n[i]=s),this.safeBalance(n)}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={coin:i.id},[r,a]=this.handleNetworkCodeAndParams(t),o=void 0===r?this.defaultNetworkCode(e):r;s.chainType=this.networkCodeToId(o,e);let n=await this.privateGetApiV1AccountDepositAddress(this.extend(s,a)),d=this.parseDepositAddress(n,i);return d.network=o,d}parseDepositAddress(e,t){let i=this.safeString(e,"address");this.checkAddress(i);let s=this.safeString(e,"addressExt");return""===s&&(s=void 0),{info:e,currency:this.safeString(t,"code"),network:void 0,address:i,tag:s}}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.coin=(r=this.currency(e)).id),void 0!==t&&(a.startTime=t),void 0!==i&&(a.limit=i);let[o,n]=this.handleOptionAndParams(s,"fetchDeposits","until");void 0!==o&&(a.endTime=o);let d=await this.privateGetApiV1AccountDepositOrders(this.extend(a,n));return this.parseTransactions(d,r,t,i,{type:"deposit"})}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.coin=(r=this.currency(e)).id),void 0!==t&&(a.startTime=t),void 0!==i&&(a.limit=i);let[o,n]=this.handleOptionAndParams(s,"fetchWithdrawals","until");void 0!==o&&(a.endTime=o);let d=await this.privateGetApiV1AccountWithdrawOrders(this.extend(a,n));return this.parseTransactions(d,r,t,i,{type:"withdrawal"})}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d={coin:n.id,address:i,quantity:t};void 0!==a&&(d.addressExt=a);let[h,c]=this.handleNetworkCodeAndParams(o);void 0!==h&&(d.chainType=this.networkCodeToId(h,this.safeString(n,"code")));let l=await this.privatePostApiV1AccountWithdraw(this.extend(d,c));return this.parseTransaction(l,n)}parseTransaction(e,t){let i,s=this.safeString2(e,"id","orderId"),r=this.safeString(e,"address"),a=this.safeString(e,"status");void 0===a&&(!0===this.safeBool(e,"success",!1)?a="ok":void 0!==this.safeString(e,"addressUrl")&&(a="ok"));let o=this.safeString(e,"txId"),n=this.safeString(e,"coin"),d=this.safeCurrencyCode(n,t),h=this.safeInteger(e,"time"),c=this.safeNumber(e,"quantity"),l=this.safeNumber(e,"fee");return void 0!==l&&(i={cost:l,currency:d}),{info:e,id:s,txid:o,timestamp:h,datetime:this.iso8601(h),network:void 0,address:r,addressTo:void 0,addressFrom:void 0,tag:void 0,tagTo:void 0,tagFrom:void 0,type:void 0,amount:c,currency:d,status:this.parseTransactionStatus(a),updated:void 0,internal:void 0,comment:void 0,fee:i}}parseTransactionStatus(e){return this.safeString({1:"pending",2:"pending",3:"failed",4:"ok",5:"pending",6:"ok",7:"failed",8:"cancelled",9:"failed",10:"failed",successful:"ok",success:"ok"},e,e)}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(e),o={coin:a.id,quantity:this.currencyToPrecision(e,t),fromAccountId:i,toAccountId:s},n=await this.privatePostApiV1AccountAssetTransfer(this.extend(o,r));return this.parseTransfer(n,a)}parseTransfer(e,t){let i,s=this.safeInteger(e,"timestamp"),r=this.safeString(t,"id");return!0===this.safeBool(e,"success",!1)&&(i="ok"),{id:this.safeString(e,"orderId"),timestamp:s,datetime:this.iso8601(s),currency:this.safeCurrencyCode(r,t),amount:void 0,fromAccount:void 0,toAccount:void 0,status:i,info:e}}async fetchAccounts(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetApiV1AccountType(e);return this.parseAccounts(t,e)}parseAccount(e){let t=this.safeString(e,"accountLabel"),i="";"Main Trading Account"===t||"Main Future Account"===t?i="main":("Sub Main Trading Account"===t||"Sub Main Future Account"===t)&&(i="sub");let s=i+" "+this.parseAccountType(this.safeString(e,"accountType"));return{id:this.safeString(e,"accountId"),type:s,code:void 0,info:e}}parseAccountType(e){return this.safeString({1:"spot account",3:"swap account",5:"custody account",6:"fiat account"},e,e)}encodeAccountType(e){return this.safeInteger({spot:"1",swap:"3",custody:"5"},e,e)}encodeFlowType(e){return this.safeInteger({trade:"1",fee:"3",transfer:"51",deposit:"900",withdraw:"904"},e,e)}async fetchLedger(e,t,i,s={}){let r="fetchLedger";if(void 0===t)throw new a.ArgumentsRequired(this.id+" "+r+"() requires a since argument");let[o,n]=this.handleOptionAndParams(s,r,"until");if(void 0===o)throw new a.ArgumentsRequired(this.id+" "+r+"() requires an until argument");void 0===this.markets&&await this.loadMarkets();let d=this.currency(e),h={};h.startTime=t,void 0!==i&&(h.limit=i),h.endTime=o;let[c,l]=this.handleOptionStringAndParams(n,r,"flowType");void 0!==c&&(h.flowType=this.encodeFlowType(c));let[u,f]=this.handleOptionStringAndParams(l,r,"accountType");void 0!==u&&(h.accountType=this.encodeAccountType(u));let p=await this.privateGetApiV1AccountBalanceFlow(this.extend(h,f));return this.parseLedger(p,d,t,i)}parseLedgerEntryType(e){return this.safeString({1:"trade",2:"fee",51:"transfer",900:"deposit",904:"withdraw"},e,e)}parseLedgerEntry(e,t){let i=this.safeString(e,"id"),s=this.safeString(e,"accountId"),r=this.safeInteger(e,"created"),a=this.parseLedgerEntryType(this.safeString(e,"flowTypeValue")),o=this.safeString(e,"coin"),n=this.safeCurrencyCode(o,t),d=this.safeCurrency(o,t),h=this.safeString(e,"change"),c=this.parseNumber(h),l="in";h.indexOf("-")>=0&&(l="out");let u=this.safeString(e,"total"),f=this.parseNumber(u);return this.safeLedgerEntry({info:e,id:i,timestamp:r,datetime:this.iso8601(r),account:s,direction:l,referenceId:void 0,referenceAccount:void 0,type:a,currency:n,symbol:void 0,amount:c,before:void 0,after:f,status:"ok",fee:void 0},d)}async createOrder(e,t,i,s,r,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(e);if(!0===n.spot)return await this.createSpotOrder(e,t,i,s,r,o);if(!0===n.swap)return await this.createSwapOrder(e,t,i,s,r,o);throw new a.NotSupported(this.id+" createOrder() is not supported for "+n.type+" type of markets")}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new a.NotSupported(this.id+" createMarketBuyOrderWithCost() is supported for spot markets only");return await this.createOrder(e,"market","buy",t,void 0,this.extend({cost:t},i))}async createSpotOrder(e,t,i,s,r,o={}){if(void 0!==this.safeString2(o,"stopPrice","triggerPrice"))throw new a.NotSupported(this.id+" trigger orders are not supported for spot markets");void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d="market"===t&&"buy"===i,h=this.safeString(o,"cost");if(!d&&void 0!==h)throw new a.NotSupported(this.id+" createOrder() supports cost parameter for spot market buy orders only");let c=this.createSpotOrderRequest(e,t,i,s,r,o),l={};return l=!0===this.safeBool(o,"test")?await this.privatePostApiV1SpotOrderTest(c):d&&void 0===h?await this.privatePostApiV11SpotOrder(c):await this.privatePostApiV1SpotOrder(c),this.parseOrder(l,n)}createOrderRequest(e,t,i,s,r,o={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let n=this.market(e);if(!0===n.spot)return this.createSpotOrderRequest(e,t,i,s,r,o);if(!0===n.swap)return this.createSwapOrderRequest(e,t,i,s,r,o);throw new a.NotSupported(this.id+" createOrderRequest() is not supported for "+n.type+" type of markets")}createSpotOrderRequest(e,t,i,s,r,o={}){let n;if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let d=this.market(e),h=t.toUpperCase(),c={symbol:d.id,side:i.toUpperCase(),type:h};void 0!==s&&(c.quantity=this.amountToPrecision(e,s));let[l,u]=this.handleParamString(o,"cost");void 0!==l&&(c.quantity=this.costToPrecision(e,l)),void 0!==r&&(c.price=this.priceToPrecision(e,r));let f="MARKET"===h,[p,m]=this.handlePostOnly(f,"LIMIT_MAKER"===h,u);p&&"LIMIT"===h&&(c.type="LIMIT_MAKER");let g={};return[n,g]=this.handleParamString(m,"clientOrderId"),void 0!==n&&(g.newClientOrderId=n),this.extend(c,g)}createSwapOrderRequest(e,t,i,s,r,a={}){let o={symbol:this.market(e).id,type:"LIMIT",quantity:this.amountToPrecision(e,s)},n="market"===t;n&&(o.priceType="MARKET"),void 0!==r&&(o.price=this.priceToPrecision(e,r),o.priceType="INPUT");let[d,h]=this.handleParamBool(a,"reduceOnly",!1),c="_OPEN";!0===d&&(c="_CLOSE"),o.side=i.toUpperCase()+c;let[l,u]=this.handleParamString(h,"timeInForce"),[f,p]=this.handlePostOnly(n,"LIMIT_MAKER"===l,u),m=l;f&&(m="LIMIT_MAKER"),void 0!==m&&(o.timeInForce=m),void 0===this.safeString(p,"clientOrderId")&&(o.clientOrderId=this.uuid());let g=this.safeString(p,"triggerPrice"),v=void 0!==g?this.omit(p,"triggerPrice"):p;return void 0!==g&&(o.stopPrice=this.priceToPrecision(e,g),o.type="STOP"),this.extend(o,v)}async createSwapOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=this.createSwapOrderRequest(e,t,i,s,r,a),d=await this.privatePostApiV1FuturesOrder(this.extend(n,a));return this.parseOrder(d,o)}async createOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=[];for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),r=this.safeString(i,"symbol"),a=this.safeString(i,"type"),o=this.safeString(i,"side"),n=this.safeNumber(i,"amount"),d=this.safeNumber(i,"price"),h=this.safeDict(i,"params",{}),c=this.createOrderRequest(r,a,o,n,d,h);void 0===this.safeString(c,"clientOrderId")&&(c.clientOrderId=this.uuid()),s.push(c)}let r=this.safeDict(s,0),o=this.safeString(r,"symbol"),n=this.market(o),d={orders:s};if(!0===n.spot)i=await this.privatePostApiV1SpotBatchOrders(this.extend(d,t));else if(!0===n.swap)i=await this.privatePostApiV1FuturesBatchOrders(this.extend(d,t));else throw new a.NotSupported(this.id+" createOrderRequest() is not supported for "+n.type+" type of markets");let h=this.safeList(i,"result",[]),c=[];for(let e=0;e<h.length;e++){let t=this.safeDict(h,e,{}),i=this.safeDict(t,"order",{});c.push(i)}return this.parseOrders(c)}async cancelOrder(e,t,i={}){let s,r,o="cancelOrder";this.checkTypeParam(o,i),void 0===this.markets&&await this.loadMarkets();let n={};void 0===this.safeString(i,"clientOrderId")&&(n.orderId=e),void 0!==t&&(s=this.market(t));let[d,h]=this.handleMarketTypeAndParams(o,s,i,"spot");if("spot"===d)r=await this.privateDeleteApiV1SpotOrder(this.extend(n,h));else if("swap"===d){let[e,t]=this.handleTriggerOptionAndParams(h,o,!1);!0===e?n.type="STOP":n.type="LIMIT",void 0!==s&&(n.symbol=s.id),r=await this.privateDeleteApiV1FuturesOrder(this.extend(n,t))}else throw new a.NotSupported(this.id+" "+o+"() is not supported for "+d+" type of markets");return this.parseOrder(r)}async cancelAllOrders(e,t={}){let i,s="cancelAllOrders";if(void 0===e)throw new a.ArgumentsRequired(this.id+" "+s+"() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={symbol:r.id},n=this.safeString(t,"side");if(void 0!==n&&(o.side=n),!0===r.spot)i=await this.privateDeleteApiV1SpotOpenOrders(this.extend(o,t));else if(!0===r.swap)i=await this.privateDeleteApiV1FuturesBatchOrders(this.extend(o,t));else throw new a.NotSupported(this.id+" "+s+"() is not supported for "+r.type+" type of markets");let d=this.safeOrder(i);return d.info=i,[d]}async cancelOrders(e,t,i={}){let s,r,o="cancelOrders";void 0===this.markets&&await this.loadMarkets();let n={};n.ids=e.join(","),void 0!==t&&(r=this.market(t));let d=this.handleMarketTypeAndParams(o,r,i,"spot")[0];if("spot"===d)s=await this.privateDeleteApiV1SpotCancelOrderByIds(n);else if("swap"===d)s=await this.privateDeleteApiV1FuturesCancelOrderByIds(n);else throw new a.NotSupported(this.id+" "+o+"() is not supported for "+d+" type of markets");let h=this.safeOrder(s);return h.info=s,[h]}async fetchOrder(e,t,i={}){let s,r,o="fetchOrder";this.checkTypeParam(o,i),void 0===this.markets&&await this.loadMarkets();let n={},[d,h]=this.handleParamString(i,"clientOrderId");void 0===d&&(n.orderId=e),void 0!==t&&(s=this.market(t));let[c,l]=this.handleMarketTypeAndParams(o,s,h,"spot");if("spot"===c)void 0!==d&&(n.origClientOrderId=d),r=await this.privateGetApiV1SpotOrder(this.extend(n,l));else if("swap"===c){let[e,t]=this.handleTriggerOptionAndParams(l,o,!1);!0===e&&(n.type="STOP"),r=await this.privateGetApiV1FuturesOrder(this.extend(n,t))}else throw new a.NotSupported(this.id+" "+o+"() is not supported for "+c+" type of markets");return this.parseOrder(r)}async fetchOpenOrders(e,t,i,s={}){let r,o="fetchOpenOrders";this.checkTypeParam(o,s),void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let[n,d]=this.handleMarketTypeAndParams(o,r,s,"spot"),h=this.extend({methodName:o},d);if("spot"===n)return await this.fetchOpenSpotOrders(e,t,i,h);if("swap"===n)return await this.fetchOpenSwapOrders(e,t,i,h);throw new a.NotSupported(this.id+" "+o+"() is not supported for "+n+" type of markets")}async fetchOpenSpotOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleParamString(s,"methodName","fetchOpenSpotOrders"),d={},[h,c]=this.handleOptionStringAndParams(n,o,"accountId");return void 0!==h?(d.subAccountId=h,a=await this.privateGetApiV1SpotSubAccountOpenOrders(this.extend(d,c))):(void 0!==e&&(d.symbol=(r=this.market(e)).id),void 0!==i&&(d.limit=i),a=await this.privateGetApiV1SpotOpenOrders(this.extend(d,c))),this.parseOrders(a,r,t,i)}async fetchOpenSwapOrders(e,t,i,s={}){let r,[o,n]=this.handleParamString(s,"methodName","fetchOpenSwapOrders");if(void 0===e)throw new a.ArgumentsRequired(this.id+" "+o+"() requires a symbol argument for swap market orders");let d=this.market(e),h={symbol:d.id},[c,l]=this.handleTriggerOptionAndParams(n,o,!1);!0===c?h.type="STOP":h.type="LIMIT",void 0!==i&&(h.limit=i);let[u,f]=this.handleOptionStringAndParams(l,o,"accountId");return void 0!==u?(h.subAccountId=u,r=await this.privateGetApiV1FuturesSubAccountOpenOrders(this.extend(h,f))):r=await this.privateGetApiV1FuturesOpenOrders(this.extend(h,f)),this.parseOrders(r,d,t,i)}async fetchCanceledAndClosedOrders(e,t,i,s={}){let r,o,n="fetchCanceledAndClosedOrders";this.checkTypeParam(n,s),void 0===this.markets&&await this.loadMarkets();let d={};void 0!==i&&(d.limit=i),void 0!==t&&(d.startTime=t);let[h,c]=this.handleOptionAndParams(s,n,"until");void 0!==h&&(d.endTime=h);let[l,u]=this.handleOptionStringAndParams(c,n,"accountId");void 0!==e&&(r=this.market(e));let[f,p]=this.handleMarketTypeAndParams(n,r,u,"spot");if("spot"===f)void 0!==r&&(d.symbol=r.id),void 0!==l&&(d.accountId=l),o=await this.privateGetApiV1SpotTradeOrders(this.extend(d,p));else if("swap"===f){if(void 0===e)throw new a.ArgumentsRequired(this.id+" "+n+"() requires a symbol argument for swap markets");d.symbol=this.safeString(r,"id");let[t,i]=this.handleTriggerOptionAndParams(p,n,!1);!0===t?d.type="STOP":d.type="LIMIT",void 0!==l?(d.subAccountId=l,o=await this.privateGetApiV1FuturesSubAccountHistoryOrders(this.extend(d,i))):o=await this.privateGetApiV1FuturesHistoryOrders(this.extend(d,i))}else throw new a.NotSupported(this.id+" "+n+"() is not supported for "+f+" type of markets");return this.parseOrders(o,r,t,i)}checkTypeParam(e,t){let i=this.safeString(t,"type");if(void 0!==i&&"spot"!==i&&"swap"!==i)throw new a.BadRequest(this.id+" "+e+' () type parameter can not be "'+i+'". It should define the type of the market ("spot" or "swap"). To define the type of an order use the trigger parameter (true for trigger orders)')}handleTriggerOptionAndParams(e,t,i){let[s,r]=this.handleOptionBoolAndParams2(e,t,"stop","trigger",i);return[s,r]}parseOrder(e,t){let i,s,r=this.safeString(e,"symbol"),a=this.safeMarket(r,t),o=this.safeInteger2(e,"transactTime","time"),n=this.safeString(e,"status"),d=this.safeString(e,"type");"MARKET"===this.safeString(e,"priceType")&&(d="market");let h=this.omitZero(this.safeString(e,"price"));"STOP"===d&&(d=void 0===h?"market":"limit");let c=this.safeString(e,"timeInForce");[d,c,i]=this.parseOrderTypeTimeInForceAndPostOnly(d,c);let l=this.omitZero(this.safeString(e,"avgPrice"));void 0===h&&(h=l);let u=this.safeStringLower(e,"side");[u,s]=this.parseOrderSideAndReduceOnly(u);let f=this.safeString(e,"feeCoin");return""===f&&(f=void 0),this.safeOrder({id:this.safeString(e,"orderId"),clientOrderId:this.safeString(e,"clientOrderId"),datetime:this.iso8601(o),timestamp:o,lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeInteger(e,"updateTime"),status:this.parseOrderStatus(n),symbol:a.symbol,type:d,timeInForce:c,side:u,price:h,average:l,amount:this.omitZero(this.safeString(e,"origQty")),filled:this.safeString(e,"executedQty"),remaining:void 0,triggerPrice:this.omitZero(this.safeString(e,"stopPrice")),takeProfitPrice:void 0,stopLossPrice:void 0,cost:this.omitZero(this.safeString2(e,"cumulativeQuoteQty","cummulativeQuoteQty")),trades:void 0,fee:{currency:this.safeCurrencyCode(f),cost:this.omitZero(this.safeString(e,"feeAmount"))},reduceOnly:s,postOnly:i,info:e},a)}parseOrderSideAndReduceOnly(e){let t,i=e.split("_"),s=i[0],r=this.safeString(i,1);return void 0!==r&&("open"===r?t=!1:"close"===r&&(t=!0)),[s,t]}parseOrderStatus(e){return this.safeString({NEW:"open",PARTIALLY_FILLED:"open",PARTIALLY_CANCELED:"canceled",FILLED:"closed",CANCELED:"canceled",ORDER_CANCELED:"canceled",PENDING_CANCEL:"canceled",REJECTED:"rejected",ORDER_NEW:"open"},e,e)}parseOrderTypeTimeInForceAndPostOnly(e,t){let i,s="LIMIT_MAKER"===t||"MAKER"===t;("LIMIT_MAKER"===e||s)&&(i=!0);let r=t;return"LIMIT_MAKER"!==e&&s&&(r="PO"),[this.parseOrderType(e),r,i]}parseOrderType(e){return this.safeString({MARKET:"market",LIMIT:"limit",LIMIT_MAKER:"limit",MARKET_OF_BASE:"market"},e,e)}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id,timestamp:this.milliseconds()},r=await this.publicGetApiV1FuturesFundingRate(this.extend(s,t)),a=this.safeDict(r,0,{});return this.parseFundingRate(a,i)}async fetchFundingRates(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s={timestamp:this.milliseconds()},r=await this.publicGetApiV1FuturesFundingRate(this.extend(s,t));return this.parseFundingRates(r,i)}parseFundingRate(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t,void 0,"swap"),r=this.safeNumber(e,"rate"),a=this.safeInteger(e,"nextSettleTime");return{info:e,symbol:s.symbol,markPrice:void 0,indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:r,fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:void 0,nextFundingTimestamp:a,nextFundingDatetime:this.iso8601(a),previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:void 0}}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");let r=this.market(e),o={symbol:r.id};void 0!==i&&(o.limit=i);let n=await this.publicGetApiV1FuturesHistoryFundingRate(this.extend(o,s)),d=[],h=this.toArray(n);for(let e=0;e<h.length;e++){let t=h[e],i=this.safeInteger(t,"settleTime");d.push({info:t,symbol:this.safeSymbol(this.safeString(t,"symbol"),r,void 0,"swap"),fundingRate:this.safeNumber(t,"settleRate"),timestamp:i,datetime:this.iso8601(i)})}let c=this.sortBy(d,"timestamp");return this.filterBySinceLimit(c,t,i)}async fetchPositions(e,t={}){let i="fetchPositions";if(void 0===e)throw new a.ArgumentsRequired(this.id+" "+i+"() requires a symbol argument with one single market symbol");if(1!==e.length)throw new a.NotSupported(this.id+" "+i+"() is supported for a symbol argument with one single market symbol only");return void 0===this.markets&&await this.loadMarkets(),await this.fetchPositionsForSymbol(e[0],this.extend({methodName:"fetchPositions"},t))}async fetchPositionsForSymbol(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),[s,r]=this.handleParamString(t,"methodName","fetchPosition");if(!0!==i.swap)throw new a.NotSupported(this.id+" "+s+"() supports swap markets only");let o={symbol:i.id},n=await this.privateGetApiV1FuturesPositions(this.extend(o,r));return this.parsePositions(n,[e])}parsePosition(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t).symbol;return this.safePosition({symbol:s,id:void 0,timestamp:void 0,datetime:void 0,contracts:this.safeNumber(e,"position"),contractSize:void 0,side:this.safeStringLower(e,"side"),notional:this.safeNumber(e,"positionValue"),leverage:this.safeInteger(e,"leverage"),unrealizedPnl:this.safeNumber(e,"unrealizedPnL"),realizedPnl:this.safeNumber(e,"realizedPnL"),collateral:void 0,entryPrice:this.safeNumber(e,"avgPrice"),markPrice:void 0,liquidationPrice:this.safeNumber(e,"liquidationPrice"),marginMode:"cross",hedged:!0,maintenanceMargin:this.safeNumber(e,"minMargin"),maintenanceMarginPercentage:void 0,initialMargin:this.safeNumber(e,"margin"),initialMarginPercentage:void 0,marginRatio:void 0,lastUpdateTimestamp:void 0,lastPrice:this.safeNumber(e,"lastPrice"),stopLossPrice:void 0,takeProfitPrice:void 0,percentage:void 0,info:e})}async fetchLeverage(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.privateGetApiV1FuturesLeverage(this.extend(s,t)),a=this.safeDict(r,0,{});return this.parseLeverage(a,i)}parseLeverage(e,t){let i=this.safeStringLower(e,"marginType"),s=this.safeNumber(e,"leverage");return{info:e,symbol:this.safeString(t,"symbol"),marginMode:i,longLeverage:s,shortLeverage:s}}async setLeverage(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s={leverage:e},r=this.market(t);s.symbol=r.id;let o=await this.privatePostApiV1FuturesLeverage(this.extend(s,i));return this.parseLeverage(o,r)}async setMarginMode(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=e.toUpperCase(),r="CROSSED"===s?"CROSS":s;if("CROSS"!==r&&"ISOLATED"!==r)throw new a.ArgumentsRequired(this.id+" setMarginMode() marginMode must be either cross or isolated");let o=this.market(t);if(!0!==o.swap)throw new a.BadSymbol(this.id+" setMarginMode() supports swap markets only");let n={symbol:o.id,marginType:r};return await this.privatePostApiV1FuturesMarginType(this.extend(n,i))}async addMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,"add",i)}async reduceMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,"reduce",i)}async modifyMarginHelper(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e);if(!0!==r.swap)throw new a.BadSymbol(this.id+" modifyMarginHelper() supports swap markets only");let[n,d]=this.handleParamString(s,"side");if(void 0===n)throw new a.ArgumentsRequired(this.id+" "+i+'Margin() requires a params["side"] argument, either "long" or "short"');let h=n.toUpperCase();if("LONG"!==h&&"SHORT"!==h)throw new a.ArgumentsRequired(this.id+" "+i+'Margin() params["side"] must be either long or short');let c=this.numberToString(t);"reduce"===i&&(c=o.Y.stringMul(c,"-1"));let l={symbol:r.id,side:h,amount:c},u=await this.privatePostApiV1FuturesPositionMargin(this.extend(l,d));return this.extend(this.parseMarginModification(u,r),{type:i,amount:t})}parseMarginModification(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t,void 0,"swap"),r=this.safeInteger(e,"timestamp"),a=this.safeString(e,"code");return{info:e,symbol:s.symbol,type:void 0,marginMode:"isolated",amount:void 0,total:this.safeNumber(e,"margin"),code:s.settle,status:"0000"===a?"ok":"failed",timestamp:r,datetime:this.iso8601(r)}}async fetchLeverageTiers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetApiV1ExchangeInfo(t),s=this.safeList(i,"contracts",[]),r=this.marketSymbols(e);return this.parseLeverageTiers(s,r,"symbol")}parseMarketLeverageTiers(e,t){let i=this.safeList(e,"riskLimits",[]),s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=[];for(let e=0;e<i.length;e++){let t=i[e],n=this.safeString(t,"initialMargin");a.push({tier:this.sum(e,1),symbol:this.safeSymbol(s,r),currency:r.settle,minNotional:void 0,maxNotional:this.safeNumber(t,"quantity"),maintenanceMarginRate:this.safeNumber(t,"maintMargin"),maxLeverage:this.parseNumber(o.Y.stringDiv("1",n)),info:t})}return a}async fetchTradingFee(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e);if(!0===s.spot)return i=await this.fetchTradingFees(t),this.safeDict(i,e);if(!0===s.swap)return i=await this.privateGetApiV1FuturesCommissionRate(this.extend({symbol:s.id},t)),this.parseTradingFee(i,s);throw new a.NotSupported(this.id+" fetchTradingFee() is not supported for "+s.type+" type of markets")}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetApiV1AccountVipInfo(e),i=this.safeList(t,"data",[]),s={};for(let e=0;e<i.length;e++){let t=this.safeDict(i,e,{}),r=this.parseTradingFee(t);s[r.symbol]=r}return s}parseTradingFee(e,t){let i=this.safeString(e,"symbol");return{info:e,symbol:this.safeMarket(i,t).symbol,maker:this.safeNumber2(e,"openMakerFee","actualMakerRate"),taker:this.safeNumber2(e,"openTakerFee","actualTakerRate"),percentage:!0,tierBased:!0}}sign(e,t="public",i="GET",r={},o,n){let d,h=this.safeString(this.urls.api,t);if(void 0===h)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let c=h+"/"+e;if("private"===t){let t,a;this.checkRequiredCredentials();let o={timestamp:this.milliseconds()},h=this.safeInteger(this.options,"recvWindow");void 0!==h&&(o.recvWindow=h);let l={"X-HK-APIKEY":this.apiKey,"Content-Type":"application/x-www-form-urlencoded"};if("POST"===i&&("api/v1/spot/batchOrders"===e||"api/v1/futures/batchOrders"===e))l["Content-Type"]="application/json",a=this.json(this.safeList(r,"orders")),t=this.hmac(this.encode(this.customUrlencode(o)),this.encode(this.secret),s.sc),c+="?"+(d=this.customUrlencode(this.extend(o,{signature:t})));else{let e=this.extend(o,r);t=this.hmac(this.encode(this.customUrlencode(e)),this.encode(this.secret),s.sc),e.signature=t,d=this.customUrlencode(e),"GET"===i?c+="?"+d:a=d}l["INPUT-SOURCE"]=this.safeString(this.options,"broker","10000700011"),l.broker_sign=t;let u="GET"===i?n:a;return{url:c,method:i,body:u,headers:l}}return 0!==(d=this.urlencode(r)).length&&(c+="?"+d),{url:c,method:i,body:n,headers:o}}customUrlencode(e={}){let t=this.urlencode(e);return t.replace("%2C",",")}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=!1,l=this.safeString(n,"code");if(0===this.safeInteger(n,"code")){let e=this.safeList(n,"result",[]);for(let t=0;t<e.length;t++){let i=this.safeDict(e,t);0!==this.safeInteger(i,"code")&&(c=!0,l=this.safeString(i,"code"))}}if(200!==e||c){let e=this.id+" "+o;throw this.throwBroadlyMatchedException(this.exceptions.broad,l,e),this.throwExactlyMatchedException(this.exceptions.exact,l,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>n})},4440(e,t,i){"use strict";var s=i(4721),r=i(6885),a=i(2495),o=i(1093),n=i(7749),d=i(1453);class h extends a.A{describe(){return this.deepExtend(super.describe(),{id:"hibachi",name:"Hibachi",countries:["US"],rateLimit:100,userAgent:this.userAgents.chrome,certified:!1,pro:!1,dex:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!1,option:!1,addMargin:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,cancelWithdraw:!1,closeAllPositions:!1,closePosition:!1,createConvertTrade:!1,createDepositAddress:!1,createMarketBuyOrderWithCost:!1,createMarketOrder:!1,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!1,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopLossOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,createTakeProfitOrder:!1,createTrailingAmountOrder:!1,createTrailingPercentOrder:!1,createTriggerOrder:!1,editOrder:!0,editOrders:!0,fetchAccounts:!1,fetchBalance:!0,fetchCanceledOrders:!0,fetchClosedOrder:!1,fetchClosedOrders:!0,fetchConvertCurrencies:!1,fetchConvertQuote:!1,fetchCurrencies:!1,fetchDepositAddress:!0,fetchDeposits:!0,fetchDepositsWithdrawals:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchIndexOHLCV:!1,fetchLedger:!0,fetchLeverage:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarkets:!0,fetchMySettlementHistory:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!1,fetchOpenOrder:!1,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!1,fetchOrdersByStatus:!0,fetchOrderTrades:!1,fetchPosition:!1,fetchPositionMode:!1,fetchPositions:!0,fetchPremiumIndexOHLCV:!1,fetchStatus:!1,fetchTicker:!0,fetchTickers:!1,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchTradingLimits:!1,fetchTransactions:"emulated",fetchTransfers:!1,fetchWithdrawals:!0,reduceMargin:!1,setLeverage:!1,setMargin:!1,setPositionMode:!1,transfer:!1,withdraw:!0},timeframes:{"1m":"1min","5m":"5min","15m":"15min","1h":"1h","4h":"4h","1d":"1d","1w":"1w"},urls:{logo:"https://github.com/user-attachments/assets/f267bf5b-5c6c-45e2-9ce4-fb0af8a9d9ab",api:{public:"https://data-api.hibachi.xyz",private:"https://api.hibachi.xyz"},www:"https://www.hibachi.xyz/",referral:{url:"https://hibachi.xyz/r/ZBL2YFWIHU"}},api:{public:{get:{"market/exchange-info":{cost:1},"market/inventory":{cost:1},"market/data/prices":{cost:1},"market/data/stats":{cost:1},"market/data/trades":{cost:1},"market/data/klines":{cost:1},"market/data/open-interest":{cost:1},"market/data/orderbook":{cost:1},"market/data/funding-rates":{cost:1},"exchange/utc-timestamp":{cost:1}}},private:{get:{"capital/balance":{cost:1},"capital/history":{cost:1},"capital/deposit-info":{cost:1},"trade/account/info":{cost:1},"trade/account/trades":{cost:1},"trade/account/trading_history":{cost:1},"trade/account/settlements_history":{cost:1},"trade/orders":{cost:1},"trade/order":{cost:1},"trade/orders/history":{cost:1}},put:{"trade/order":{cost:1}},delete:{"trade/order":{cost:1},"trade/orders":{cost:1}},post:{"trade/order":{cost:1},"trade/orders":{cost:1},"capital/withdraw":{cost:1},"capital/transfer":{cost:1},"trade/account/leverage":{cost:1}}}},requiredCredentials:{apiKey:!0,secret:!1,accountId:!0,privateKey:!0},fees:{trading:{tierBased:!1,percentage:!0,maker:this.parseNumber("0.00015"),taker:this.parseNumber("0.00045")}},currencies:this.hardcodedCurrencies(),options:{},features:{default:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:void 0,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!1,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:void 0,daysBack:void 0,untilDays:void 0,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:{limit:void 0}},swap:{linear:{extends:"default"},inverse:void 0},future:{linear:{extends:"default"},inverse:void 0}},commonCurrencies:{},exceptions:{exact:{2:d.BadRequest,3:d.OrderNotFound,4:d.BadRequest},broad:{}},precisionMode:4})}getAccountId(){return this.checkRequiredCredentials(),this.parseToInt(this.accountId)}parseMarket(e){let t=this.safeString(e,"symbol"),i=this.safeNumber(e,"id"),s=this.safeString(e,"underlyingSymbol"),r=this.safeString(e,"settlementSymbol"),a=this.safeCurrencyCode(s),o=this.safeCurrencyCode(r);if(void 0===a||void 0===o)return;let n=this.safeString(e,"settlementSymbol"),d=this.safeCurrencyCode(n),h=this.safeIntegerProduct(e,"marketCreationTimestamp",1e3);return this.safeMarketStructure({id:t,numericId:i,symbol:a+"/"+o+":"+d,base:a,quote:o,settle:d,baseId:s,quoteId:r,settleId:n,type:"swap",spot:!1,margin:!1,swap:!0,future:!1,option:!1,active:"LIVE"===this.safeString(e,"status"),contract:!0,linear:!0,inverse:!1,contractSize:this.parseNumber("1"),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(e,"underlyingDecimals"))),price:this.parseNumber(this.safeValue(this.safeList(e,"orderbookGranularities",[]),0))/1e4},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(e,"minNotional"),max:void 0}},created:h,info:e})}async fetchMarkets(e={}){let t=await this.publicGetMarketExchangeInfo(e),i=this.safeList(t,"futureContracts");return this.parseMarkets(i)}hardcodedCurrencies(){let e={},t={},i="ARBITRUM";t[i]={id:i,network:i,limits:{withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},active:void 0,deposit:void 0,withdraw:void 0,info:{}};let s=this.safeCurrencyCode("USDT");return void 0!==s&&(e[s]=this.safeCurrencyStructure({id:"USDT",name:"USDT",type:"fiat",code:s,precision:this.parseNumber("0.000001"),active:!0,fee:void 0,networks:t,deposit:!0,withdraw:!0,limits:{deposit:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}},info:{}})),e}parseBalance(e){let t={info:e},i=this.safeCurrencyCode("USDT"),s=this.account();return s.total=this.safeString(e,"balance"),s.free=this.safeString(e,"maximalWithdraw"),void 0!==i&&(t[i]=s),this.safeBalance(t)}async fetchBalance(e={}){let t={accountId:this.getAccountId()},i=await this.privateGetTradeAccountInfo(this.extend(t,e));return this.parseBalance(i)}parseTicker(e,t){let i=this.safeDict(e,"prices"),s=this.safeDict(e,"stats"),r=this.safeNumber(i,"bidPrice"),a=this.safeNumber(i,"askPrice"),o=this.safeNumber(i,"tradePrice"),n=this.safeNumber(s,"high24h"),d=this.safeNumber(s,"low24h"),h=this.safeNumber(s,"volume24h");return this.safeTicker({symbol:this.safeSymbol(void 0,t),timestamp:void 0,datetime:void 0,bid:r,ask:a,last:o,high:n,low:d,bidVolume:void 0,askVolume:void 0,vwap:void 0,open:void 0,close:o,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:void 0,quoteVolume:h,info:e},t)}parseTrade(e,t){let i,s,r,a,o,d=this.safeString(e,"symbol"),h=this.safeMarket(d,t),c=h.symbol,l=this.safeString(e,"id"),u=this.safeString(e,"price"),f=this.safeString(e,"quantity"),p=this.safeIntegerProduct(e,"timestamp",1e3),m=n.Y.stringMul(u,f);return void 0===l?(i=this.safeStringLower(e,"takerSide"),o="taker"):(i=this.safeStringLower(e,"side"),s={cost:this.safeString(e,"fee"),currency:"USDT"},r=this.safeStringLower(e,"orderType"),a="buy"===i?this.safeString(e,"bidOrderId"):this.safeString(e,"askOrderId")),this.safeTrade({id:l,timestamp:p,datetime:this.iso8601(p),symbol:c,side:i,price:u,amount:f,cost:m,order:a,takerOrMaker:o,type:r,fee:s,info:e},h)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id},o=await this.publicGetMarketDataTrades(this.extend(a,s)),n=this.safeList(o,"trades",[]),d=[];return void 0!==n&&(d=n),this.parseTrades(d,r)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=[this.publicGetMarketDataPrices(this.extend(s,t)),this.publicGetMarketDataStats(this.extend(s,t))],a=await Promise.all(r),o=a[0],n=a[1];return this.parseTicker({prices:o,stats:n},i)}parseOrderStatus(e){let t=void 0===e?void 0:e.toUpperCase();return this.safeString({PENDING:"open",CHILD_PENDING:"open",SCHEDULED_TWAP:"open",PLACED:"open",PARTIALLY_FILLED:"open",FILLED:"closed",CANCELLED:"canceled",PARTIAL_CANCELLED:"canceled",REJECTED:"rejected"},t,e)}parseOrder(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=this.safeString(e,"status"),o=this.safeStringLower(e,"orderType"),d=this.safeString2(e,"price","avgFillPrice"),h=this.safeString(e,"side");"BID"===h?i="buy":"ASK"===h&&(i="sell");let c=this.safeString(e,"totalQuantity"),l=this.safeString(e,"availableQuantity"),u=this.safeString(e,"totalQuantity"),f=this.safeString(e,"availableQuantity"),p=this.safeString(e,"filledQuantity");void 0!==u&&void 0!==f&&(p=n.Y.stringSub(u,f));let m=l;void 0===m&&void 0!==u&&void 0!==p&&(m=n.Y.stringSub(u,p));let g="GTC",v=this.safeString(e,"orderFlags"),y=!1,b=!1;"POST_ONLY"===v?(g="PO",y=!0):"IOC"===v?g="IOC":"REDUCE_ONLY"===v&&(b=!0);let w=this.safeInteger(e,"createdAt");void 0===w&&(w=this.safeIntegerProduct(e,"creationTime",1e3));let k=this.safeInteger(e,"closedAt");return this.safeOrder({info:e,id:this.safeString(e,"orderId"),clientOrderId:void 0,datetime:this.iso8601(w),timestamp:w,lastTradeTimestamp:void 0,lastUpdateTimestamp:k,status:this.parseOrderStatus(a),symbol:r.symbol,type:o,timeInForce:g,side:i,price:d,average:this.safeString(e,"avgFillPrice"),amount:c,filled:p,remaining:m,cost:void 0,trades:void 0,fee:void 0,reduceOnly:b,postOnly:y,triggerPrice:this.safeNumber(e,"triggerPrice")},r)}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let r={orderId:e,accountId:this.getAccountId()},a=await this.privateGetTradeOrder(this.extend(r,i));return this.parseOrder(a,s)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t={accountId:this.getAccountId()},i=await this.privateGetTradeAccountInfo(this.extend(t,e)),s=this.safeNumber(i,"tradeMakerFeeRate"),r=this.safeNumber(i,"tradeTakerFeeRate"),a={},o=this.symbols;for(let e=0;e<o.length;e++){let t=o[e];a[t]={info:i,symbol:t,maker:s,taker:r,percentage:!0}}return a}orderMessage(e,t,i,s,r,a,o){if(void 0===s)throw new d.ArgumentsRequired(this.id+" requires a type argument");if(void 0===r)throw new d.ArgumentsRequired(this.id+" requires a side argument");let h=0;"sell"===r?h=0:"buy"===r&&(h=1);let c=this.amountToPrecision(this.safeString(e,"symbol"),a),l=this.numberToString(i),u=this.safeDict(e,"info"),f="1e"+this.safeString(u,"underlyingDecimals"),p="1e"+this.safeString(u,"settlementDecimals"),m=n.Y.stringDiv(n.Y.stringMul(c,f),"1",0),g=n.Y.stringDiv(n.Y.stringMul(l,"100000000"),"1",0),v=this.intToBase16(t).padStart(16,"0"),y=this.base16ToBinary(v),b=this.intToBase16(this.safeInteger(e,"numericId")).padStart(8,"0"),w=this.base16ToBinary(b),k=this.intToBase16(this.parseToInt(m)).padStart(16,"0"),S=this.base16ToBinary(k),O=this.intToBase16(h).padStart(8,"0"),T=this.base16ToBinary(O),P=this.intToBase16(this.parseToInt(g)).padStart(16,"0"),I=this.base16ToBinary(P),A=this.binaryConcat();if("limit"===s){let t=this.priceToPrecision(this.safeString(e,"symbol"),o),i=n.Y.stringDiv(n.Y.stringDiv(n.Y.stringMul(n.Y.stringMul(t,"4294967296"),p),f),"1",0),s=this.intToBase16(this.parseToInt(i)).padStart(16,"0");A=this.base16ToBinary(s)}return this.binaryConcat(y,w,S,T,A,I)}createOrderRequest(e,t,i,s,r,a,o={}){if(void 0===i)throw new d.ArgumentsRequired(this.id+" requires a type argument");if(void 0===s)throw new d.ArgumentsRequired(this.id+" requires a side argument");let n=this.market(t),h=this.safeNumber(n,"taker",this.safeNumber(this.options,"defaultTakerFee",45e-5)),c=this.safeNumber(n,"maker",this.safeNumber(this.options,"defaultMakerFee",15e-5)),l=Math.max(void 0===h?0:h,void 0===c?0:c),u="";"sell"===s?u="ASK":"buy"===s&&(u="BID");let f="";void 0!==a&&0!==a&&(f=this.priceToPrecision(t,a));let p=this.orderMessage(n,e,l,i,s,r,a),m=this.signMessage(p,this.privateKey),g={symbol:this.safeString(n,"id"),nonce:e,side:u,orderType:i.toUpperCase(),quantity:this.amountToPrecision(t,r),price:f,signature:m,maxFeesPercent:this.numberToString(l)},v=this.isPostOnly("MARKET"===i.toUpperCase(),void 0,o),y=this.safeBool2(o,"reduceOnly","reduce_only"),b=this.safeStringLower(o,"timeInForce"),w=this.safeString2(o,"triggerPrice","stopPrice");v?g.orderFlags="POST_ONLY":"ioc"===b?g.orderFlags="IOC":!0===y&&(g.orderFlags="REDUCE_ONLY"),void 0!==w&&(g.triggerPrice=w);let k=this.omit(o,["reduceOnly","reduce_only","postOnly","timeInForce","stopPrice","triggerPrice"]);return this.extend(g,k)}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.incrementingNonce(),n=this.createOrderRequest(o,e,t,i,s,r,a);n.accountId=this.getAccountId();let d=await this.privatePostTradeOrder(n);return this.safeOrder({id:this.safeString(d,"orderId"),status:"pending"})}async createOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.incrementingNonce(),s=[];for(let t=0;t<e.length;t++){let r=this.safeDict(e,t),a=this.safeString(r,"symbol"),o=this.safeString(r,"type"),n=this.safeString(r,"side"),d=this.safeNumber(r,"amount"),h=this.safeNumber(r,"price"),c=this.safeDict(r,"params",{}),l=this.createOrderRequest(i+t,a,o,n,d,h,c);l.action="place",s.push(l)}let r={accountId:this.getAccountId(),orders:s},a=await this.privatePostTradeOrders(this.extend(r,t)),o=[],n=this.safeList(a,"orders",[]);for(let e=0;e<n.length;e++){let t=n[e];o.push(this.safeOrder({info:t,id:this.safeString(t,"orderId"),status:"pending"}))}return o}editOrderRequest(e,t,i,s,r,a,o,n={}){if(void 0===s)throw new d.ArgumentsRequired(this.id+" requires a type argument");if(void 0===r)throw new d.ArgumentsRequired(this.id+" requires a side argument");let h=this.market(i),c=this.safeNumber(h,"taker",0),l=this.safeNumber(h,"maker",0),u=Math.max(void 0===c?0:c,void 0===l?0:l),f=this.orderMessage(h,e,u,s,r,a,o),p=this.signMessage(f,this.privateKey),m={orderId:t,nonce:e,updatedQuantity:this.amountToPrecision(i,a),updatedPrice:this.priceToPrecision(i,o),maxFeesPercent:this.numberToString(u),signature:p};return this.extend(m,n)}async editOrder(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.incrementingNonce(),d=this.editOrderRequest(n,e,t,i,s,r,a,o);return d.accountId=this.getAccountId(),await this.privatePutTradeOrder(d),this.safeOrder({id:e,status:"pending"})}async editOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.incrementingNonce(),s=[];for(let t=0;t<e.length;t++){let r=this.safeDict(e,t),a=this.safeString(r,"id"),o=this.safeString(r,"symbol"),n=this.safeString(r,"type"),d=this.safeString(r,"side"),h=this.safeNumber(r,"amount"),c=this.safeNumber(r,"price"),l=this.safeDict(r,"params",{}),u=this.editOrderRequest(i+t,a,o,n,d,h,c,l);u.action="modify",s.push(u)}let r={accountId:this.getAccountId(),orders:s},a=await this.privatePostTradeOrders(this.extend(r,t)),o=[],n=this.safeList(a,"orders",[]);for(let e=0;e<n.length;e++){let t=n[e];o.push(this.safeOrder({info:t,id:this.safeString(t,"orderId"),status:"pending"}))}return o}cancelOrderRequest(e){let t=this.convertToBigInt(e),i=this.intToBase16(t).padStart(16,"0"),s=this.base16ToBinary(i);return{orderId:e,signature:this.signMessage(s,this.privateKey)}}async cancelOrder(e,t,i={}){let s=this.cancelOrderRequest(e);s.accountId=this.getAccountId();let r=await this.privateDeleteTradeOrder(this.extend(s,i));return this.safeOrder({info:r,id:e,status:"canceled"})}async cancelOrders(e,t,i={}){let s=[];for(let t=0;t<e.length;t++){let i=this.cancelOrderRequest(e[t]);i.action="cancel",s.push(i)}let r={accountId:this.getAccountId(),orders:s},a=await this.privatePostTradeOrders(this.extend(r,i)),o=[],n=this.safeList(a,"orders",[]);for(let e=0;e<n.length;e++){let t=n[e];o.push(this.safeOrder({info:t,id:this.safeString(t,"orderId"),status:"canceled"}))}return o}async cancelAllOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.incrementingNonce(),s=this.intToBase16(i).padStart(16,"0"),r=this.base16ToBinary(s),a=this.signMessage(r,this.privateKey),o={accountId:this.getAccountId(),nonce:i,signature:a};if(void 0!==e){let t=this.market(e);o.contractId=this.safeInteger(t,"numericId")}let n=await this.privateDeleteTradeOrders(this.extend(o,t));return[this.safeOrder({info:n})]}encodeWithdrawMessage(e,t,i){let s="1000000",r=this.numberToString(e),a=this.numberToString(t),o=n.Y.stringDiv(n.Y.stringMul(r,s),"1",0),d=n.Y.stringDiv(n.Y.stringMul(a,s),"1",0),h=this.intToBase16(1).padStart(8,"0"),c=this.base16ToBinary(h),l=this.intToBase16(this.parseToInt(o)).padStart(16,"0"),u=this.base16ToBinary(l),f=this.intToBase16(this.parseToInt(d)).padStart(16,"0"),p=this.base16ToBinary(f),m=this.base16ToBinary(i);return this.binaryConcat(c,u,p,m)}async withdraw(e,t,i,s,r={}){let a=i.slice(-40),o=await this.publicGetMarketExchangeInfo(r),n=this.safeDict(o,"feeConfig"),d=this.safeNumber(n,"withdrawalFees"),h=this.encodeWithdrawMessage(t,d,a),c=this.signMessage(h,this.privateKey),l={accountId:this.getAccountId(),coin:"USDT",network:"ARBITRUM",withdrawAddress:a,selfWithdrawal:!1,quantity:this.numberToString(t),maxFees:this.numberToString(d),signature:c};return await this.privatePostCapitalWithdraw(this.extend(l,r)),{info:void 0,id:void 0,txid:void 0,timestamp:this.milliseconds(),datetime:void 0,address:void 0,addressFrom:void 0,addressTo:a,tag:void 0,tagFrom:void 0,tagTo:void 0,type:"withdrawal",amount:t,currency:e,status:"pending",fee:{currency:"USDT",cost:d},network:"ARBITRUM",updated:void 0,comment:void 0,internal:void 0}}nonce(){return this.milliseconds()}signMessage(e,t){if(44===t.length)return this.hmac(e,this.encode(t),s.sc,"hex");{let i=this.hash(e,s.sc,"hex"),a=(0,o.h1)(i.slice(-64),t.slice(-64),r.bI,void 0),n=a.r,d=a.s,h=this.intToBase16(a.v);return n.padStart(64,"0")+d.padStart(64,"0")+h.padStart(2,"0")}}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={symbol:this.market(e).id},r=await this.publicGetMarketDataOrderbook(this.extend(s,i)),a={};return a.ask=this.safeList(this.safeDict(r,"ask"),"levels"),a.bid=this.safeList(this.safeDict(r,"bid"),"levels"),this.parseOrderBook(a,e,this.milliseconds(),"bid","ask","price","quantity")}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a={accountId:this.getAccountId()},o=await this.privateGetTradeAccountTrades(this.extend(a,s)),n=this.safeList(o,"trades"),d=[];return void 0!==n&&(d=n),this.parseTrades(d,r,t,i,s)}parseOHLCV(e,t){return[this.safeIntegerProduct(e,"timestamp",1e3),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volumeNotional")]}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a={accountId:this.getAccountId()},o=await this.privateGetTradeOrders(this.extend(a,s));return this.parseOrders(o,r,t,i)}async fetchOrdersByStatus(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o={accountId:this.getAccountId()};void 0!==t&&(a=this.market(t)),void 0!==e&&(o.status=e),void 0!==i&&(o.startTime=i);let[n,d]=this.handleOptionIntegerAndParams(r,"fetchOrdersByStatus","until");void 0!==n&&(o.endTime=n);let h=await this.privateGetTradeOrdersHistory(this.extend(o,d)),c=this.safeList(h,"orders",[]),l=this.parseOrders(c,a);return this.filterBySymbolSinceLimit(l,t,i,s)}async fetchClosedOrders(e,t,i,s={}){let r=await this.fetchOrdersByStatus("filled",e,t,i,s),a=this.filterBy(r,"status","closed");return this.filterBySinceLimit(a,t,i)}async fetchCanceledOrders(e,t,i,s={}){let r=await this.fetchOrdersByStatus(void 0,e,t,i,s),a=this.filterBy(r,"status","canceled");return this.filterBySinceLimit(a,t,i)}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=this.safeString(this.timeframes,t,t),n={symbol:a.id,interval:o};void 0!==i&&(n.fromMs=i);let[d,h]=this.handleOptionIntegerAndParams(r,"fetchOHLCV","until");void 0!==d&&(n.toMs=d);let c=await this.publicGetMarketDataKlines(this.extend(n,h)),l=this.safeList(c,"klines",[]);return this.parseOHLCVs(l,a,o,i,s)}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s={accountId:this.getAccountId()},r=await this.privateGetTradeAccountInfo(this.extend(s,t)),a=this.safeList(r,"positions",[]);return this.parsePositions(a,i)}parsePosition(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t).symbol,r=this.safeStringLower(e,"direction"),a=this.safeString(e,"quantity"),o=this.safeString(e,"unrealizedFundingPnl","0"),d=this.safeString(e,"unrealizedTradingPnl","0"),h=n.Y.stringAdd(o,d);return this.safePosition({info:e,id:void 0,symbol:s,entryPrice:this.safeString(e,"average_entry_price"),markPrice:void 0,notional:this.safeString(e,"notionalValue"),collateral:void 0,unrealizedPnl:h,side:r,contracts:this.parseNumber(a),contractSize:void 0,timestamp:void 0,datetime:void 0,hedged:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,initialMargin:void 0,initialMarginPercentage:void 0,leverage:void 0,liquidationPrice:void 0,marginRatio:void 0,marginMode:void 0,percentage:void 0})}sign(e,t="public",i="GET",s={},r,a){let o="/"+this.implodeParams(e,s),n=this.safeString(this.urls.api,t);if(void 0===n)throw new d.ExchangeError(this.id+" sign() has no API URL for this endpoint");let h=n+o,c={"Hibachi-Client":"HibachiCCXT/unversioned"};if("GET"===i){let t=this.omit(s,this.extractParams(e)),i=this.urlencode(t);0!==i.length&&(h+="?"+i)}let l="POST"===i||"PUT"===i||"DELETE"===i;l&&(c["Content-Type"]="application/json");let u=a;return l&&(u=this.json(s)),"private"===t&&(this.checkRequiredCredentials(),c.Authorization=this.apiKey),{url:h,method:i,body:u,headers:c}}handleErrors(e,t,i,s,r,a,o,n,h){if(void 0!==o&&"status"in o&&"failed"===this.safeString(o,"status")){let e=this.safeString(o,"errorCode"),t=this.id+" "+a;this.throwBroadlyMatchedException(this.exceptions.broad,a,t),this.throwExactlyMatchedException(this.exceptions.exact,e,t);let i=this.safeString(o,"message");throw this.throwExactlyMatchedException(this.exceptions.exact,i,t),new d.ExchangeError(t)}}parseTransactionType(e){return this.safeString({deposit:"transaction",withdrawal:"transaction","transfer-in":"transfer","transfer-out":"transfer"},e,e)}parseTransactionStatus(e){return this.safeString({pending:"pending",claimable:"pending",completed:"ok",failed:"canceled"},e,e)}parseLedgerEntry(e,t){let i,s,r,a,o,d,h,c,l=this.safeString(e,"transactionType");if(void 0===l){i=this.safeIntegerProduct(e,"timestamp",1e3),s="trade";let t=this.safeString(e,"realizedPnl");n.Y.stringLt(t,"0")?(r="out",t=n.Y.stringNeg(t)):r="in",a=this.parseNumber(t),o={currency:"USDT",cost:this.safeNumber(e,"fee")},c="ok"}else i=this.safeIntegerProduct(e,"timestampSec",1e3),a=this.safeNumber(e,"quantity"),r="deposit"===l||"transfer-in"===l?"in":"out",s=this.parseTransactionType(l),c=this.parseTransactionStatus(this.safeString(e,"status")),"transfer-in"===l?h=this.safeString(e,"srcAccountId"):"transfer-out"===l&&(h=this.safeString(e,"receivingAccountId")),d=this.safeString(e,"transactionHash");return this.safeLedgerEntry({id:this.safeString(e,"id"),currency:this.currency("USDT"),account:this.numberToString(this.accountId),referenceAccount:h,referenceId:d,status:c,amount:a,before:void 0,after:void 0,fee:o,direction:r,timestamp:i,datetime:this.iso8601(i),type:s,info:e},t)}async fetchLedger(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.currency("USDT"),a={accountId:this.getAccountId()},o=[this.privateGetCapitalHistory(this.extend(a,s)),this.privateGetTradeAccountTradingHistory(this.extend(a,s))],n=await Promise.all(o),d=this.safeDict(n,0),h=this.safeList(d,"transactions",[]),c=this.safeDict(n,1),l=this.safeList(c,"tradingHistory",[]),u=this.arrayConcat(h,l);return this.parseLedger(u,r,t,i,s)}async fetchDepositAddress(e,t={}){let i={publicKey:this.safeString(t,"publicKey"),accountId:this.getAccountId()},s=await this.privateGetCapitalDepositInfo(this.extend(i,t));return{info:s,currency:"USDT",network:"ARBITRUM",address:this.safeString(s,"depositAddressEvm"),tag:void 0}}parseTransaction(e,t){let i=this.safeIntegerProduct(e,"timestampSec",1e3),s=this.safeString(e,"withdrawalAddress"),r=this.safeString(e,"transactionType");return"deposit"!==r&&"withdrawal"!==r&&(r=this.parseTransactionType(r)),{info:e,id:this.safeString(e,"id"),txid:this.safeString(e,"transactionHash"),timestamp:i,datetime:this.iso8601(i),network:"ARBITRUM",address:s,addressTo:s,addressFrom:void 0,tag:void 0,tagTo:void 0,tagFrom:void 0,type:r,amount:this.safeNumber(e,"quantity"),currency:"USDT",status:this.parseTransactionStatus(this.safeString(e,"status")),updated:void 0,internal:void 0,comment:void 0,fee:void 0}}async fetchDepositsWithdrawals(e,t,i,s={}){let r=this.safeCurrency(e),a={accountId:this.getAccountId()},o=await this.privateGetCapitalHistory(this.extend(a,s)),n=this.safeList(o,"transactions",[]);return this.parseTransactions(n,r,t,i,s)}async fetchDeposits(e,t,i,s={}){let r=await this.fetchDepositsWithdrawals(e,t,void 0,s),a=this.filterBy(r,"type","deposit");return this.filterBySinceLimit(a,t,i,"timestamp")}async fetchWithdrawals(e,t,i,s={}){let r=await this.fetchDepositsWithdrawals(e,t,void 0,s),a=this.filterBy(r,"type","withdrawal");return this.filterBySinceLimit(a,t,i,"timestamp")}parseSettlement(e,t){let i=this.safeTimestamp(e,"timestamp"),s=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(s,t),price:this.safeNumber(e,"indexPrice"),timestamp:i,datetime:this.iso8601(i)}}parseSettlements(e,t){let i=[];for(let s=0;s<e.length;s++)i.push(this.parseSettlement(e[s],t));return i}async fetchMySettlementHistory(e,t,i,s={}){let r,a;await this.loadMarkets();let o={accountId:this.getAccountId()};void 0!==e&&(o.contractId=(r=this.market(e)).numericId,a=this.safeString(r,"symbol")),void 0!==t&&(o.startTime=this.parseToInt(t/1e3)),void 0!==i&&(o.limit=i);let[n,d]=this.handleOptionIntegerAndParams(s,"fetchMySettlementHistory","until");void 0!==n&&(o.endTime=this.parseToInt(n/1e3));let h=await this.privateGetTradeAccountSettlementsHistory(this.extend(o,d)),c=this.safeList(h,"settlements",[]),l=this.parseSettlements(c,r),u=this.sortBy(l,"timestamp");return this.filterBySymbolSinceLimit(u,a,t,i)}async fetchTime(e={}){let t=await this.publicGetExchangeUtcTimestamp(e);return this.safeInteger(t,"timestampMs")}async fetchOpenInterest(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetMarketDataOpenInterest(this.extend(s,t)),a=this.milliseconds();return this.safeOpenInterest({symbol:e,openInterestAmount:this.safeString(r,"totalQuantity"),openInterestValue:void 0,timestamp:a,datetime:this.iso8601(a),info:r},i)}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetMarketDataPrices(this.extend(s,t)),a=this.safeDict(r,"fundingRateEstimation",{}),o=this.milliseconds(),n=this.safeIntegerProduct(a,"nextFundingTimestamp",1e3);return{info:a,symbol:i.symbol,markPrice:void 0,indexPrice:void 0,interestRate:this.parseNumber("0"),estimatedSettlePrice:void 0,timestamp:o,datetime:this.iso8601(o),fundingRate:this.safeNumber(a,"estimatedFundingRate"),fundingTimestamp:n,fundingDatetime:this.iso8601(n),nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:"8h"}}async fetchFundingRateHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={symbol:this.market(e).id},a=await this.publicGetMarketDataFundingRates(this.extend(r,s)),o=this.safeList(a,"data",[]),n=[];for(let t=0;t<o.length;t++){let i=o[t],s=this.safeIntegerProduct(i,"fundingTimestamp",1e3);n.push({info:i,symbol:e,fundingRate:this.safeNumber(i,"fundingRate"),timestamp:s,datetime:this.iso8601(s)})}let d=this.sortBy(n,"timestamp");return this.filterBySymbolSinceLimit(d,e,t,i)}}i.d(t,{A:()=>h})},3030(e,t,i){"use strict";var s=i(4721),r=i(9447),a=i(7749),o=i(1453);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"hitbtc",name:"HitBTC",countries:["HK"],rateLimit:3.333,version:"3",has:{CORS:!1,spot:!0,margin:!0,swap:!0,future:!1,option:!1,addMargin:!0,cancelAllOrders:!0,cancelOrder:!0,closePosition:!0,createDepositAddress:!0,createOrder:!0,createPostOnlyOrder:!0,createReduceOnlyOrder:!0,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,editOrder:!0,fetchAccounts:!1,fetchBalance:!0,fetchBorrowRateHistories:void 0,fetchBorrowRateHistory:void 0,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!0,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:void 0,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchGreeks:!1,fetchIndexOHLCV:!0,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLeverage:!0,fetchLeverageTiers:void 0,fetchLiquidations:!1,fetchMarginMode:"emulated",fetchMarginModes:!0,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!1,fetchOpenInterests:!0,fetchOpenOrder:!0,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:!0,fetchOrders:!1,fetchOrderTrades:!0,fetchPosition:!0,fetchPositions:!0,fetchPremiumIndexOHLCV:!0,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTransactions:"emulated",fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!0,sandbox:!0,setLeverage:!0,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!0,withdraw:!0},precisionMode:4,urls:{logo:"https://user-images.githubusercontent.com/1294454/27766555-8eaec20e-5edc-11e7-9c5b-6dc69fc42f5e.jpg",test:{public:"https://api.demo.hitbtc.com/api/3",private:"https://api.demo.hitbtc.com/api/3"},api:{public:"https://api.hitbtc.com/api/3",private:"https://api.hitbtc.com/api/3"},www:"https://hitbtc.com",referral:"https://hitbtc.com/?ref_id=5a5d39a65d466",doc:["https://api.hitbtc.com","https://github.com/hitbtc-com/hitbtc-api/blob/master/APIv2.md"],fees:["https://hitbtc.com/fees-and-limits","https://support.hitbtc.com/hc/en-us/articles/115005148605-Fees-and-limits"]},api:{public:{get:{"public/currency":{cost:10},"public/currency/{currency}":{cost:10},"public/symbol":{cost:10},"public/symbol/{symbol}":{cost:10},"public/ticker":{cost:10},"public/ticker/{symbol}":{cost:10},"public/price/rate":{cost:10},"public/price/history":{cost:10},"public/price/ticker":{cost:10},"public/price/ticker/{symbol}":{cost:10},"public/trades":{cost:10},"public/trades/{symbol}":{cost:10},"public/orderbook":{cost:10},"public/orderbook/{symbol}":{cost:10},"public/candles":{cost:10},"public/candles/{symbol}":{cost:10},"public/converted/candles":{cost:10},"public/converted/candles/{symbol}":{cost:10},"public/futures/info":{cost:10},"public/futures/info/{symbol}":{cost:10},"public/futures/history/funding":{cost:10},"public/futures/history/funding/{symbol}":{cost:10},"public/futures/candles/index_price":{cost:10},"public/futures/candles/index_price/{symbol}":{cost:10},"public/futures/candles/mark_price":{cost:10},"public/futures/candles/mark_price/{symbol}":{cost:10},"public/futures/candles/premium_index":{cost:10},"public/futures/candles/premium_index/{symbol}":{cost:10},"public/futures/candles/open_interest":{cost:10},"public/futures/candles/open_interest/{symbol}":{cost:10}}},private:{get:{"spot/balance":{cost:15},"spot/balance/{currency}":{cost:15},"spot/order":{cost:1},"spot/order/{client_order_id}":{cost:1},"spot/fee":{cost:15},"spot/fee/{symbol}":{cost:15},"spot/history/order":{cost:15},"spot/history/trade":{cost:15},"margin/account":{cost:1},"margin/account/isolated/{symbol}":{cost:1},"margin/account/cross/{currency}":{cost:1},"margin/order":{cost:1},"margin/order/{client_order_id}":{cost:1},"margin/config":{cost:15},"margin/history/order":{cost:15},"margin/history/trade":{cost:15},"margin/history/positions":{cost:15},"margin/history/clearing":{cost:15},"margin-settings":{cost:15},"futures/balance":{cost:15},"futures/balance/{currency}":{cost:15},"futures/account":{cost:1},"futures/account/isolated/{symbol}":{cost:1},"futures/order":{cost:1},"futures/order/{client_order_id}":{cost:1},"futures/config":{cost:15},"futures/fee":{cost:15},"futures/fee/{symbol}":{cost:15},"futures/history/order":{cost:15},"futures/history/trade":{cost:15},"futures/history/positions":{cost:15},"futures/history/clearing":{cost:15},"user/api-keys":{cost:15},"wallet/balance":{cost:30},"wallet/balance/{currency}":{cost:30},"wallet/crypto/address/white-list":{cost:30},"wallet/crypto/address":{cost:30},"wallet/crypto/address/recent-deposit":{cost:30},"wallet/crypto/address/recent-withdraw":{cost:30},"wallet/crypto/address/check-mine":{cost:30},"wallet/transactions":{cost:30},"wallet/transactions/{tx_id}":{cost:30},"wallet/crypto/fee/estimate":{cost:30},"wallet/crypto/fee/withdraw/hash":{cost:30},"wallet/airdrops":{cost:30},"wallet/amount-locks":{cost:30},"sub-account":{cost:15},"sub-account/acl":{cost:15},"sub-account/balance/{subAccID}":{cost:15},"sub-account/crypto/address/{subAccID}/{currency}":{cost:15}},post:{"spot/order":{cost:1},"spot/order/list":{cost:1},"margin/order":{cost:1},"margin/order/list":{cost:1},"futures/order":{cost:1},"futures/order/list":{cost:1},"wallet/crypto/address":{cost:30},"wallet/crypto/withdraw":{cost:30},"wallet/convert":{cost:30},"wallet/transfer":{cost:30},"wallet/internal/withdraw":{cost:30},"wallet/crypto/check-offchain-available":{cost:30},"wallet/crypto/fees/estimate":{cost:30},"wallet/crypto/fee/estimate/bulk":{cost:30},"wallet/airdrops/{id}/claim":{cost:30},"sub-account/freeze":{cost:15},"sub-account/activate":{cost:15},"sub-account/transfer":{cost:15},"sub-account/transfer/sub-to-super":{cost:15},"sub-account/transfer/sub-to-sub":{cost:15},"sub-account/acl":{cost:15}},patch:{"spot/order/{client_order_id}":{cost:1},"margin/order/{client_order_id}":{cost:1},"futures/order/{client_order_id}":{cost:1}},delete:{"spot/order":{cost:1},"spot/order/{client_order_id}":{cost:1},"margin/position":{cost:1},"margin/position/isolated/{symbol}":{cost:1},"margin/order":{cost:1},"margin/order/{client_order_id}":{cost:1},"futures/position":{cost:1},"futures/position/{margin_mode}/{symbol}":{cost:1},"futures/order":{cost:1},"futures/order/{client_order_id}":{cost:1},"wallet/crypto/withdraw/{id}":{cost:30}},put:{"margin/account/isolated/{symbol}":{cost:1},"margin-settings/amm":{cost:15},"margin/margin-settings/amr":{cost:15},"futures/account/isolated/{symbol}":{cost:1},"futures/margin-settings/amr":{cost:15},"wallet/crypto/withdraw/{id}":{cost:30}}}},fees:{trading:{tierBased:!0,percentage:!0,taker:this.parseNumber("0.0009"),maker:this.parseNumber("0.0009"),tiers:{maker:[[this.parseNumber("0"),this.parseNumber("0.0009")],[this.parseNumber("10"),this.parseNumber("0.0007")],[this.parseNumber("100"),this.parseNumber("0.0006")],[this.parseNumber("500"),this.parseNumber("0.0005")],[this.parseNumber("1000"),this.parseNumber("0.0003")],[this.parseNumber("5000"),this.parseNumber("0.0002")],[this.parseNumber("10000"),this.parseNumber("0.0001")],[this.parseNumber("20000"),this.parseNumber("0")],[this.parseNumber("50000"),this.parseNumber("-0.0001")],[this.parseNumber("100000"),this.parseNumber("-0.0001")]],taker:[[this.parseNumber("0"),this.parseNumber("0.0009")],[this.parseNumber("10"),this.parseNumber("0.0008")],[this.parseNumber("100"),this.parseNumber("0.0007")],[this.parseNumber("500"),this.parseNumber("0.0007")],[this.parseNumber("1000"),this.parseNumber("0.0006")],[this.parseNumber("5000"),this.parseNumber("0.0006")],[this.parseNumber("10000"),this.parseNumber("0.0005")],[this.parseNumber("20000"),this.parseNumber("0.0004")],[this.parseNumber("50000"),this.parseNumber("0.0003")],[this.parseNumber("100000"),this.parseNumber("0.0002")]]}}},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!0},hedged:!1,selfTradePrevention:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,iceberg:!0},createOrders:void 0,fetchMyTrades:{marginMode:!0,limit:1e3,daysBack:1e5,untilDays:1e5,symbolRequired:!1,marketType:!0},fetchOrder:{marginMode:!0,trigger:!1,trailing:!1,symbolRequired:!1,marketType:!0},fetchOpenOrders:{marginMode:!0,limit:1e3,trigger:!1,trailing:!1,symbolRequired:!1,marketType:!0},fetchOrders:void 0,fetchClosedOrders:{marginMode:!0,limit:1e3,daysBack:1e5,daysBackCanceled:1,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1,marketType:!0},fetchOHLCV:{limit:1e3}},spot:{extends:"default"},forDerivatives:{extends:"default",createOrder:{marginMode:!0},fetchOrder:{marginMode:!1},fetchMyTrades:{marginMode:!1},fetchOpenOrders:{marginMode:!1},fetchClosedOrders:{marginMode:!1}},swap:{linear:{extends:"forDerivatives"},inverse:{extends:"forDerivatives"}},future:{linear:{extends:"forDerivatives"},inverse:{extends:"forDerivatives"}}},timeframes:{"1m":"M1","3m":"M3","5m":"M5","15m":"M15","30m":"M30","1h":"H1","4h":"H4","1d":"D1","1w":"D7","1M":"1M"},exceptions:{exact:{429:o.RateLimitExceeded,500:o.ExchangeError,503:o.ExchangeNotAvailable,504:o.ExchangeNotAvailable,600:o.PermissionDenied,800:o.ExchangeError,1002:o.AuthenticationError,1003:o.PermissionDenied,1004:o.AuthenticationError,1005:o.AuthenticationError,2001:o.BadSymbol,2002:o.BadRequest,2003:o.BadRequest,2010:o.BadRequest,2011:o.BadRequest,2012:o.BadRequest,2020:o.BadRequest,2022:o.BadRequest,2024:o.InvalidOrder,10001:o.BadRequest,10021:o.AccountSuspended,10022:o.BadRequest,20001:o.InsufficientFunds,20002:o.OrderNotFound,20003:o.ExchangeError,20004:o.ExchangeError,20005:o.ExchangeError,20006:o.ExchangeError,20007:o.ExchangeError,20008:o.InvalidOrder,20009:o.InvalidOrder,20010:o.OnMaintenance,20011:o.ExchangeError,20012:o.ExchangeError,20014:o.ExchangeError,20016:o.ExchangeError,20018:o.ExchangeError,20031:o.ExchangeError,20032:o.ExchangeError,20033:o.ExchangeError,20034:o.ExchangeError,20040:o.ExchangeError,20041:o.ExchangeError,20042:o.ExchangeError,20043:o.ExchangeError,20044:o.PermissionDenied,20045:o.InvalidOrder,20047:o.InvalidOrder,20048:o.InvalidOrder,20049:o.InvalidOrder,20080:o.ExchangeError,21001:o.ExchangeError,21003:o.AccountSuspended,21004:o.AccountSuspended,22004:o.ExchangeError,22008:o.ExchangeError},broad:{}},options:{defaultNetwork:"ERC20",defaultNetworks:{ETH:"ETH",USDT:"TRC20"},networks:{BTC:"btc",OMNI:"BTC",ETH:"eth",ERC20:"ETH",ETC:"ETC",BEP20:"BSC",TRC20:"TRX",NEAR:"NEAR",DGB:"DGB",AE:"AE",AR:"AR",ADA:"ADA",CHZ:"CHZ",ABBC:"ABBC",ALGO:"ALGO",APT:"APT",ATOM:"ATOM",AVAXC:"AVAC",AVAXX:"AVAX",BSV:"BCHSV",BEP2:"BNB",CELO:"CELO",CKB:"CKB",CTXC:"CTXC",DASH:"DASH",DCR:"DCR",DOGE:"doge",EGLD:"EGLD",EOS:"EOS",ETHW:"ETHW",EVER:"EVER",FET:"FET",FIL:"FIL",FLOW:"FLOW",GLMR:"GLMR",GRIN:"GRIN",HBAR:"HBAR",HIVE:"HIVE",HYDRA:"HYDRA",ICP:"ICP",ICX:"ICX",IOST:"IOST",IOTA:"IOTA",IOTX:"IOTX",KAVA:"KAVA",KLAY:"KIM",KOMODO:"KMD",KSM:"KSM",LSK:"LSK",LTC:"ltc",MINA:"MINA",MOVR:"MOVR",NANO:"NANO",NEO:"NEO",ONE:"ONE",ONT:"ONT",OPTIMISM:"OP",PLCU:"PLCU",MATIC:"POLYGON",QTUM:"QTUM",REI:"REI",OASIS:"ROSE",RVN:"RVN",SC:"SC",SCRT:"SCRT",SOL:"SOL",STEEM:"STEEM",THETA:"Theta",TRUE:"TRUE",VET:"VET",VSYS:"VSYS",WAVES:"WAVES",WAX:"WAX",XCH:"XCH",XEC:"XEC",NEM:"XEM",XLM:"XLM",XMR:"xmr",XRD:"XRD",XRP:"XRP",XTZ:"XTZ",XVG:"XVG",XYM:"XYM",ZEC:"ZEC",ZEN:"ZEN",ZIL:"ZIL"},accountsByType:{spot:"spot",funding:"wallet",swap:"derivatives",future:"derivatives"},withdraw:{includeFee:!1}},commonCurrencies:{AUTO:"Cube",BCC:"BCC",BDP:"BidiPass",BET:"DAO.Casino",BIT:"BitRewards",BOX:"BOX Token",CPT:"Cryptaur",GET:"Themis",GMT:"GMT Token",HSR:"HC",IQ:"IQ.Cash",LNC:"LinkerCoin",PLA:"PlayChip",PNT:"Penta",SBTC:"Super Bitcoin",STEPN:"GMT",STX:"STOX",TV:"Tokenville",XMT:"MTL",XPNT:"PNT"},rollingWindowSize:1e3})}nonce(){return this.milliseconds()}async fetchMarkets(e={}){let t=await this.publicGetPublicSymbol(e),i=[],s=Object.keys(t);for(let e=0;e<s.length;e++){let r,o,n,d,h,c=s[e];if(c.endsWith("_BQX"))continue;let l=this.safeDict(t,c),u=this.safeString(l,"type"),f=this.safeInteger(l,"expiry"),p="futures"===u,m="spot"===u,g=this.safeBool(l,"margin_trading",!1),v=m&&g,y=void 0!==f,b=p&&!y,w=this.safeString2(l,"base_currency","underlying"),k=this.safeString(l,"quote_currency"),S=this.safeString(l,"fee_currency"),O=this.safeCurrencyCode(w),T=this.safeCurrencyCode(k);if(void 0===O||void 0===T)continue;let P=this.safeCurrencyCode(S),I=O+"/"+T,A="spot";p&&(n=this.parseNumber("1"),r=S,o=this.safeCurrencyCode(r),h=!(d=void 0!==T&&T===o),I=I+":"+o,y?(I=I+"-"+f,A="future"):A="swap");let x=this.safeString(l,"quantity_increment"),M=this.safeString(l,"tick_size"),_=this.parseNumber(x),C=this.parseNumber(M);i.push({id:c,symbol:I,base:O,quote:T,settle:o,baseId:w,quoteId:k,settleId:r,type:A,spot:m,margin:v,swap:b,future:y,option:!1,active:!0,contract:p,linear:d,inverse:h,taker:this.safeNumber(l,"take_rate"),maker:this.safeNumber(l,"make_rate"),contractSize:n,expiry:f,expiryDatetime:void 0,strike:void 0,optionType:void 0,feeCurrency:P,precision:{amount:_,price:C},limits:{leverage:{min:this.parseNumber("1"),max:this.safeNumber(l,"max_initial_leverage",1)},amount:{min:_,max:void 0},price:{min:C,max:void 0},cost:{min:this.parseNumber(a.Y.stringMul(x,M)),max:void 0}},created:void 0,info:l})}return i}async fetchCurrencies(e={}){let t=await this.publicGetPublicCurrency(e),i=this.addKeyInArrayItems(t,"_coin_id");return this.parseCurrencies(i)}parseCurrency(e){let t=e._coin_id,i=this.safeCurrencyCode(t),s=this.safeList(e,"networks",[]),r={};for(let e=0;e<s.length;e++){let t=s[e],a=this.safeString2(t,"protocol","network"),o=this.networkIdToCode(a,i);void 0!==(o=void 0!==o?o.toUpperCase():i)&&(r[o]={info:t,id:a,network:o,active:void 0,fee:this.safeNumber(t,"payout_fee"),deposit:this.safeBool(t,"payin_enabled"),withdraw:this.safeBool(t,"payout_enabled"),precision:this.safeNumber(t,"precision_payout"),limits:{withdraw:{min:void 0,max:void 0}}})}return this.safeCurrencyStructure({info:e,code:i,id:t,precision:this.safeNumber(e,"precision_transfer"),name:this.safeString(e,"full_name"),active:!this.safeBool(e,"delisted",!1),deposit:this.safeBool(e,"payin_enabled"),withdraw:this.safeBool(e,"payout_enabled"),networks:r,fee:void 0,limits:{amount:{min:void 0,max:void 0}},type:void 0})}async createDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={currency:this.currency(e).id},s=this.safeStringUpper(t,"network");if(void 0!==s&&"USDT"===e){let e=this.safeDict(this.options,"networks"),t=this.safeString(e,s);void 0!==t&&(i.currency=t)}let r=t;void 0!==s&&"USDT"===e&&(r=this.omit(t,"network"));let a=await this.privatePostWalletCryptoAddress(this.extend(i,r)),o=this.safeString(a,"currency");return{currency:this.safeCurrencyCode(o),address:this.safeString(a,"address"),tag:this.safeString(a,"payment_id"),network:void 0,info:a}}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={currency:this.currency(e).id},s=this.safeStringUpper(t,"network");if(void 0!==s&&"USDT"===e){let e=this.safeDict(this.options,"networks"),t=this.safeString(e,s);void 0!==t&&(i.currency=t)}let r=t;void 0!==s&&"USDT"===e&&(r=this.omit(t,"network"));let a=await this.privateGetWalletCryptoAddress(this.extend(i,r)),o=this.safeDict(a,0),n=this.safeString(o,"address"),d=this.safeString(o,"currency"),h=this.safeString(o,"payment_id");return{info:a,currency:this.safeCurrencyCode(d),network:void 0,address:n,tag:h}}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"currency"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(s,"available"),o.used=this.safeString(s,"reserved"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async fetchBalance(e={}){let t,i=this.safeStringLower(e,"type","spot"),s=this.omit(e,["type"]),r=this.safeDict(this.options,"accountsByType",{}),a=void 0===i?void 0:this.safeString(r,i,i);if("wallet"===a)t=await this.privateGetWalletBalance(s);else if("spot"===a)t=await this.privateGetSpotBalance(s);else if("derivatives"===a)t=await this.privateGetFuturesBalance(s);else{let e=Object.keys(r);throw new o.BadRequest(this.id+" fetchBalance() type parameter must be one of "+e.join(", "))}return this.parseBalance(t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetPublicTickerSymbol(this.extend(s,t));return this.parseTicker(r,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s={};void 0!==i&&(s.symbols=this.marketIds(i).join(","));let r=await this.publicGetPublicTicker(this.extend(s,t)),a={},o=Object.keys(r);for(let e=0;e<o.length;e++){let t=o[e],i=this.safeMarket(t),s=i.symbol,n=this.safeDict(r,t,{});a[s]=this.parseTicker(n,i)}return this.filterByArrayTickers(a,"symbol",i)}parseTicker(e,t){let i=this.parse8601(e.timestamp),s=this.safeSymbol(void 0,t),r=this.safeString(e,"volume"),a=this.safeString(e,"volume_quote"),o=this.safeString(e,"open"),n=this.safeString(e,"last");return this.safeTicker({symbol:s,timestamp:i,datetime:this.iso8601(i),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"bid"),bidVolume:void 0,ask:this.safeString(e,"ask"),askVolume:void 0,vwap:void 0,open:o,close:n,last:n,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:r,quoteVolume:a,info:e},t)}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};if(void 0!==i&&(a.limit=Math.min(i,1e3)),void 0!==t&&(a.from=t),void 0!==e){a.symbol=(r=this.market(e)).id;let t=await this.publicGetPublicTradesSymbol(this.extend(a,s));return this.parseTrades(t,r)}let o=await this.publicGetPublicTrades(this.extend(a,s)),n=[],d=Object.keys(o);for(let e=0;e<d.length;e++){let t=d[e],i=this.market(t),s=this.safeList(o,t,[]),r=this.parseTrades(s,i);n=this.arrayConcat(n,r)}return n}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id),void 0!==i&&(a.limit=i),void 0!==t&&(a.from=t);let n=[],[d,h]=this.handleMarketTypeAndParams("fetchMyTrades",r,s),[c,l]=this.handleMarginModeAndParams("fetchMyTrades",h),u=this.omit(l,["marginMode","margin"]);if(void 0!==c)n=await this.privateGetMarginHistoryTrade(this.extend(a,u));else if("spot"===d)n=await this.privateGetSpotHistoryTrade(this.extend(a,u));else if("swap"===d)n=await this.privateGetFuturesHistoryTrade(this.extend(a,u));else if("margin"===d)n=await this.privateGetMarginHistoryTrade(this.extend(a,u));else throw new o.NotSupported(this.id+" fetchMyTrades() not support this market type");return this.parseTrades(n,r,t,i)}parseTrade(e,t){let i,s,r=this.parse8601(e.timestamp),a=this.safeString(e,"symbol"),o=this.safeMarket(a,t),n=o.symbol,d=this.safeString(e,"fee"),h=this.safeBool(e,"taker");if(s=void 0!==h?!0===h?"taker":"maker":"taker",void 0!==d){let e=this.safeDict(o,"info",{}),t=this.safeString(e,"fee_currency");i={cost:d,currency:this.safeCurrencyCode(t)}}let c=this.safeString2(e,"clientOrderId","client_order_id"),l=this.safeString(e,"price"),u=this.safeString2(e,"quantity","qty"),f=this.safeString(e,"side"),p=this.safeString(e,"id");return this.safeTrade({info:e,id:p,order:c,timestamp:r,datetime:this.iso8601(r),symbol:n,type:void 0,side:f,takerOrMaker:s,price:l,amount:u,cost:void 0,fee:i},o)}async fetchTransactionsHelper(e,t,i,s,r){let a;void 0===this.markets&&await this.loadMarkets();let o={types:e};void 0!==t&&(o.currencies=(a=this.currency(t)).id),void 0!==i&&(o.from=this.iso8601(i)),void 0!==s&&(o.limit=s);let n=await this.privateGetWalletTransactions(this.extend(o,r));return this.parseTransactions(n,a,i,s,r)}parseTransactionStatus(e){if(void 0!==e)return this.safeString({CREATED:"pending",PENDING:"pending",FAILED:"failed",ROLLED_BACK:"failed",SUCCESS:"ok"},e,e)}parseTransactionType(e){return this.safeString({DEPOSIT:"deposit",WITHDRAW:"withdrawal"},e,e)}parseTransaction(e,t){let i=this.safeString2(e,"operation_id","id"),s=this.parse8601(this.safeString(e,"created_at")),r=this.parse8601(this.safeString(e,"updated_at")),a=this.parseTransactionType(this.safeString(e,"type")),o=this.parseTransactionStatus(this.safeString(e,"status")),n=this.safeDict(e,"native",{}),d=this.safeString(n,"currency"),h=this.safeCurrencyCode(d),c=this.safeString(n,"hash"),l=this.safeString(n,"address"),u=this.safeString(n,"payment_id"),f=this.safeList(n,"senders"),p=this.safeString(f,0),m=this.safeNumber(n,"amount"),g=this.safeString(e,"subtype"),v={currency:void 0,cost:void 0,rate:void 0},y=this.safeNumber(n,"fee");return void 0!==y&&(v.currency=h,v.cost=y),{info:e,id:i,txid:c,type:a,currency:h,network:void 0,amount:m,status:o,timestamp:s,datetime:this.iso8601(s),address:l,addressFrom:p,addressTo:l,tag:u,tagFrom:void 0,tagTo:u,updated:r,comment:void 0,internal:"OFFCHAIN"===g,fee:v}}async fetchDepositsWithdrawals(e,t,i,s={}){return await this.fetchTransactionsHelper("DEPOSIT,WITHDRAW",e,t,i,s)}async fetchDeposits(e,t,i,s={}){return await this.fetchTransactionsHelper("DEPOSIT",e,t,i,s)}async fetchWithdrawals(e,t,i,s={}){return await this.fetchTransactionsHelper("WITHDRAW",e,t,i,s)}async fetchOrderBooks(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={};void 0!==e&&(s.symbols=this.marketIds(e).join(",")),void 0!==t&&(s.depth=t);let r=await this.publicGetPublicOrderbook(this.extend(s,i)),a={},o=Object.keys(r);for(let e=0;e<o.length;e++){let t=o[e],i=this.safeDict(r,t,{}),s=this.safeSymbol(t),n=this.parse8601(this.safeString(i,"timestamp"));a[s]=this.parseOrderBook(i,s,n,"bid","ask")}return a}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={symbol:this.market(e).id};void 0!==t&&(s.depth=t);let r=await this.publicGetPublicOrderbookSymbol(this.extend(s,i)),a=this.parse8601(this.safeString(r,"timestamp"));return this.parseOrderBook(r,e,a,"bid","ask")}parseTradingFee(e,t){let i=this.safeNumber(e,"take_rate"),s=this.safeNumber(e,"make_rate"),r=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(r,t),taker:i,maker:s,percentage:void 0,tierBased:void 0}}async fetchTradingFee(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};if("spot"===s.type)i=await this.privateGetSpotFeeSymbol(this.extend(r,t));else if("swap"===s.type)i=await this.privateGetFuturesFeeSymbol(this.extend(r,t));else throw new o.NotSupported(this.id+" fetchTradingFee() not support this market type");return this.parseTradingFee(i,s)}async fetchTradingFees(e={}){let t;void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleMarketTypeAndParams("fetchTradingFees",void 0,e);if("spot"===i)t=await this.privateGetSpotFee(s);else if("swap"===i)t=await this.privateGetFuturesFee(s);else throw new o.NotSupported(this.id+" fetchTradingFees() not support this market type");let r={};for(let e=0;e<t.length;e++){let i=this.parseTradingFee(t[e]),s=i.symbol;void 0!==s&&(r[s]=i)}return r}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,o,1e3);let n=this.market(e),d={symbol:n.id,period:this.safeString(this.timeframes,t,t)};void 0!==i&&(d.from=this.iso8601(i));let[h,c]=this.handleUntilOption("until",d,o);void 0!==s&&(h.limit=Math.min(s,1e3));let l=this.safeString(c,"price"),u=this.omit(c,"price"),f=[];f="mark"===l?await this.publicGetPublicFuturesCandlesMarkPriceSymbol(this.extend(h,u)):"index"===l?await this.publicGetPublicFuturesCandlesIndexPriceSymbol(this.extend(h,u)):"premiumIndex"===l?await this.publicGetPublicFuturesCandlesPremiumIndexSymbol(this.extend(h,u)):await this.publicGetPublicCandlesSymbol(this.extend(h,u));let p=this.toArray(f);return this.parseOHLCVs(p,n,t,i,s)}parseOHLCV(e,t){return[this.parse8601(this.safeString(e,"timestamp")),this.safeNumber(e,"open"),this.safeNumber(e,"max"),this.safeNumber(e,"min"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchClosedOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let n={};void 0!==e&&(n.symbol=(a=this.market(e)).id),void 0!==t&&(n.from=this.iso8601(t)),void 0!==i&&(n.limit=i);let[d,h]=this.handleMarketTypeAndParams("fetchClosedOrders",a,s),[c,l]=this.handleMarginModeAndParams("fetchClosedOrders",h),u=this.omit(l,["marginMode","margin"]);if(void 0!==c)r=await this.privateGetMarginHistoryOrder(this.extend(n,u));else if("spot"===d)r=await this.privateGetSpotHistoryOrder(this.extend(n,u));else if("swap"===d)r=await this.privateGetFuturesHistoryOrder(this.extend(n,u));else if("margin"===d)r=await this.privateGetMarginHistoryOrder(this.extend(n,u));else throw new o.NotSupported(this.id+" fetchClosedOrders() not support this market type");let f=this.parseOrders(r,a,t,i);return this.filterByArray(f,"status",["closed","canceled"],!1)}async fetchOrder(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(r=this.market(t));let a={client_order_id:e},[n,d]=this.handleMarketTypeAndParams("fetchOrder",r,i),[h,c]=this.handleMarginModeAndParams("fetchOrder",d),l=this.omit(c,["marginMode","margin"]);if(void 0!==h)s=await this.privateGetMarginHistoryOrder(this.extend(a,l));else if("spot"===n)s=await this.privateGetSpotHistoryOrder(this.extend(a,l));else if("swap"===n)s=await this.privateGetFuturesHistoryOrder(this.extend(a,l));else if("margin"===n)s=await this.privateGetMarginHistoryOrder(this.extend(a,l));else throw new o.NotSupported(this.id+" fetchOrder() not support this market type");let u=this.safeDict(s,0,{});return this.parseOrder(u,r)}async fetchOrderTrades(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(a=this.market(t));let n={order_id:e},[d,h]=this.handleMarketTypeAndParams("fetchOrderTrades",a,r),[c,l]=this.handleMarginModeAndParams("fetchOrderTrades",h),u=this.omit(l,["marginMode","margin"]),f=[];if(void 0!==c)f=await this.privateGetMarginHistoryTrade(this.extend(n,u));else if("spot"===d)f=await this.privateGetSpotHistoryTrade(this.extend(n,u));else if("swap"===d)f=await this.privateGetFuturesHistoryTrade(this.extend(n,u));else if("margin"===d)f=await this.privateGetMarginHistoryTrade(this.extend(n,u));else throw new o.NotSupported(this.id+" fetchOrderTrades() not support this market type");return this.parseTrades(f,a,i,s)}async fetchOpenOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let n={};void 0!==e&&(n.symbol=(a=this.market(e)).id);let[d,h]=this.handleMarketTypeAndParams("fetchOpenOrders",a,s),[c,l]=this.handleMarginModeAndParams("fetchOpenOrders",h),u=this.omit(l,["marginMode","margin"]);if(void 0!==c)r=await this.privateGetMarginOrder(this.extend(n,u));else if("spot"===d)r=await this.privateGetSpotOrder(this.extend(n,u));else if("swap"===d)r=await this.privateGetFuturesOrder(this.extend(n,u));else if("margin"===d)r=await this.privateGetMarginOrder(this.extend(n,u));else throw new o.NotSupported(this.id+" fetchOpenOrders() not support this market type");return this.parseOrders(r,a,t,i)}async fetchOpenOrder(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(r=this.market(t));let a={client_order_id:e},[n,d]=this.handleMarketTypeAndParams("fetchOpenOrder",r,i),[h,c]=this.handleMarginModeAndParams("fetchOpenOrder",d),l=this.omit(c,["marginMode","margin"]);if(void 0!==h)s=await this.privateGetMarginOrderClientOrderId(this.extend(a,l));else if("spot"===n)s=await this.privateGetSpotOrderClientOrderId(this.extend(a,l));else if("swap"===n)s=await this.privateGetFuturesOrderClientOrderId(this.extend(a,l));else if("margin"===n)s=await this.privateGetMarginOrderClientOrderId(this.extend(a,l));else throw new o.NotSupported(this.id+" fetchOpenOrder() not support this market type");return this.parseOrder(s,r)}async cancelAllOrders(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r={};void 0!==e&&(r.symbol=(s=this.market(e)).id);let[a,n]=this.handleMarketTypeAndParams("cancelAllOrders",s,t),[d,h]=this.handleMarginModeAndParams("cancelAllOrders",n),c=this.omit(h,["marginMode","margin"]);if(void 0!==d)i=await this.privateDeleteMarginOrder(this.extend(r,c));else if("spot"===a)i=await this.privateDeleteSpotOrder(this.extend(r,c));else if("swap"===a)i=await this.privateDeleteFuturesOrder(this.extend(r,c));else if("margin"===a)i=await this.privateDeleteMarginOrder(this.extend(r,c));else throw new o.NotSupported(this.id+" cancelAllOrders() not support this market type");return this.parseOrders(i,s)}async cancelOrder(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets();let a={client_order_id:e};void 0!==t&&(r=this.market(t));let[n,d]=this.handleMarketTypeAndParams("cancelOrder",r,i),[h,c]=this.handleMarginModeAndParams("cancelOrder",d),l=this.omit(c,["marginMode","margin"]);if(void 0!==h)s=await this.privateDeleteMarginOrderClientOrderId(this.extend(a,l));else if("spot"===n)s=await this.privateDeleteSpotOrderClientOrderId(this.extend(a,l));else if("swap"===n)s=await this.privateDeleteFuturesOrderClientOrderId(this.extend(a,l));else if("margin"===n)s=await this.privateDeleteMarginOrderClientOrderId(this.extend(a,l));else throw new o.NotSupported(this.id+" cancelOrder() not support this market type");return this.parseOrder(s,r)}async editOrder(e,t,i,s,r,a,n={}){let d,h;void 0===this.markets&&await this.loadMarkets();let c={client_order_id:e,quantity:this.amountToPrecision(t,r)};if("limit"===i||"stopLimit"===i){if(void 0===a)throw new o.ExchangeError(this.id+" editOrder() limit order requires price");c.price=this.priceToPrecision(t,a)}void 0!==t&&(h=this.market(t));let[l,u]=this.handleMarketTypeAndParams("editOrder",h,n),[f,p]=this.handleMarginModeAndParams("editOrder",u),m=this.omit(p,["marginMode","margin"]);if(void 0!==f)d=await this.privatePatchMarginOrderClientOrderId(this.extend(c,m));else if("spot"===l)d=await this.privatePatchSpotOrderClientOrderId(this.extend(c,m));else if("swap"===l)d=await this.privatePatchFuturesOrderClientOrderId(this.extend(c,m));else if("margin"===l)d=await this.privatePatchMarginOrderClientOrderId(this.extend(c,m));else throw new o.NotSupported(this.id+" editOrder() not support this market type");return this.parseOrder(d,h)}async createOrder(e,t,i,s,r,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),[d,h]=this.handleMarketTypeAndParams("createOrder",n,a),[c,l]=this.handleMarginModeAndParams("createOrder",h),[u,f]=this.createOrderRequest(n,d,t,i,s,r,c,l);return o="swap"===d?await this.privatePostFuturesOrder(this.extend(u,f)):"margin"===d||void 0!==c?await this.privatePostMarginOrder(this.extend(u,f)):await this.privatePostSpotOrder(this.extend(u,f)),this.parseOrder(o,n)}createOrderRequest(e,t,i,s,r,a,n,d={}){let h="limit"===i,c=this.safeBool(d,"reduceOnly"),l=this.safeString(d,"timeInForce"),u=this.safeNumberN(d,["triggerPrice","stopPrice","stop_price"]),f=this.isPostOnly("market"===i,void 0,d),p={type:i,side:s,quantity:this.amountToPrecision(e.symbol,r),symbol:e.id};if(void 0!==c&&"swap"!==e.type&&"margin"!==e.type)throw new o.InvalidOrder(this.id+" createOrder() does not support reduce_only for "+e.type+" orders, reduce_only orders are supported for swap and margin markets only");if(!0===c&&(p.reduce_only=c),f&&(p.post_only=!0),void 0!==l&&(p.time_in_force=l),h||"stopLimit"===i||"takeProfitLimit"===i){if(void 0===a)throw new o.ExchangeError(this.id+" createOrder() requires a price argument for limit orders");p.price=this.priceToPrecision(e.symbol,a)}if("GTD"===l&&void 0===this.safeString(d,"expire_time"))throw new o.ExchangeError(this.id+" createOrder() requires an expire_time parameter for a GTD order");if(void 0!==u)p.stop_price=this.priceToPrecision(e.symbol,u),h?p.type="stopLimit":"market"===i&&(p.type="stopMarket");else if("stopLimit"===i||"stopMarket"===i||"takeProfitLimit"===i||"takeProfitMarket"===i)throw new o.ExchangeError(this.id+" createOrder() requires a triggerPrice parameter for stop-loss and take-profit orders");let m=this.omit(d,["triggerPrice","timeInForce","stopPrice","stop_price","reduceOnly","postOnly"]);return"swap"===t&&(p.margin_mode=void 0===n?"cross":n),[p,m]}parseOrderStatus(e){if(void 0!==e)return this.safeString({new:"open",suspended:"open",partiallyFilled:"open",filled:"closed",canceled:"canceled",expired:"failed"},e,e)}parseOrder(e,t){let i,s=this.safeString(e,"client_order_id"),r=this.safeString(e,"side"),a=this.safeString(e,"type"),o=this.safeString(e,"quantity"),n=this.safeString(e,"price"),d=this.safeString(e,"price_average"),h=this.safeString(e,"created_at"),c=this.parse8601(h),l=this.safeString(e,"updated_at");l!==h&&(i=this.parse8601(l));let u=this.safeString(e,"quantity_cumulative"),f=this.parseOrderStatus(this.safeString(e,"status")),p=this.safeString(e,"symbol"),m=this.safeMarket(p,t),g=m.symbol,v=this.safeBool(e,"post_only"),y=this.safeString(e,"time_in_force"),b=this.safeList(e,"trades");return this.safeOrder({info:e,id:s,clientOrderId:s,timestamp:c,datetime:this.iso8601(c),lastTradeTimestamp:i,lastUpdateTimestamp:i,symbol:g,price:n,amount:o,type:a,side:r,timeInForce:y,postOnly:v,reduceOnly:this.safeBool(e,"reduce_only"),filled:u,remaining:void 0,cost:void 0,status:f,average:d,trades:b,fee:void 0,triggerPrice:this.safeString(e,"stop_price"),takeProfitPrice:void 0,stopLossPrice:void 0},m)}async fetchMarginModes(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e);void 0!==r&&(s=this.market(r[0]));let[a,n]=this.handleMarketTypeAndParams("fetchMarginMode",s,t);if("margin"===a)i=await this.privateGetMarginConfig(n);else if("swap"===a)i=await this.privateGetFuturesConfig(n);else throw new o.BadSymbol(this.id+" fetchMarginModes () supports swap contracts and margin only");let d=this.safeList(i,"config",[]);return this.parseMarginModes(d,r,"symbol")}parseMarginMode(e,t){let i=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(i,t),marginMode:this.safeStringLower(e,"margin_mode")}}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(e),n=this.currencyToPrecision(e,t),d=this.safeDict(this.options,"accountsByType",{}),h=i.toLowerCase(),c=s.toLowerCase(),l=this.safeString(d,h,h),u=this.safeString(d,c,c);if(l===u)throw new o.BadRequest(this.id+" transfer() fromAccount and toAccount arguments cannot be the same account");let f={currency:a.id,amount:n,source:l,destination:u},p=await this.privatePostWalletTransfer(this.extend(f,r));return this.parseTransfer(p,a)}parseTransfer(e,t){return{id:this.safeString(e,0),timestamp:void 0,datetime:void 0,currency:this.safeCurrencyCode(void 0,t),amount:void 0,fromAccount:void 0,toAccount:void 0,status:void 0,info:e}}async convertCurrencyNetwork(e,t,i,s,r={}){if(void 0===this.markets&&await this.loadMarkets(),"USDT"!==e)throw new o.ExchangeError(this.id+" convertCurrencyNetwork() only supports USDT currently");let a=this.safeDict(this.options,"networks",{}),n=i.toUpperCase(),d=s.toUpperCase(),h=this.safeString(a,n),c=this.safeString(a,d);if(h===c)throw new o.BadRequest(this.id+" convertCurrencyNetwork() fromNetwork cannot be the same as toNetwork");if(void 0===h||void 0===c){let e=Object.keys(a);throw new o.ArgumentsRequired(this.id+" convertCurrencyNetwork() requires a fromNetwork parameter and a toNetwork parameter, supported networks are "+e.join(", "))}let l={from_currency:h,to_currency:c,amount:this.currencyToPrecision(e,t)};return{info:await this.privatePostWalletConvert(this.extend(l,r))}}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);void 0===this.markets&&await this.loadMarkets(),this.checkAddress(i);let n=this.currency(e),d={currency:n.id,amount:t,address:i};void 0!==a&&(d.payment_id=a);let h=this.safeDict(this.options,"networks",{}),c=this.safeStringUpper(o,"network");if(void 0!==c&&"USDT"===e){let e=this.safeString(h,c);void 0!==e&&(d.network_code=e)}let l=o;void 0!==c&&"USDT"===e&&(l=this.omit(o,"network"));let u=this.safeDict(this.options,"withdraw",{});!0===this.safeBool(u,"includeFee",!1)&&(d.include_fee=!0);let f=await this.privatePostWalletCryptoWithdraw(this.extend(d,l));return this.parseTransaction(f,n)}async fetchFundingRates(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={},r=this.marketSymbols(e);void 0!==r&&(i=this.market(r[0]),s.symbols=this.marketIds(r).join(","));let[a,n]=this.handleMarketTypeAndParams("fetchFundingRates",i,t);if("swap"!==a)throw new o.NotSupported(this.id+" fetchFundingRates() does not support "+a+" markets");let d=await this.publicGetPublicFuturesInfo(this.extend(s,n)),h=Object.keys(d),c={};for(let e=0;e<h.length;e++){let t=this.safeString(h,e);if(void 0===t)continue;let i=this.safeDict(d,t),s=this.market(t),r=s.symbol,a=this.parseFundingRate(i,s);c[r]=a}return this.filterByArray(c,"symbol",r)}async fetchFundingRateHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchFundingRateHistory",e,t,i,"8h",o,1e3);let[n,d]=this.handleUntilOption("until",{},o);void 0!==e&&(n.symbols=(r=this.market(e)).id),void 0!==t&&(n.from=t),void 0!==i&&(n.limit=i);let h=await this.publicGetPublicFuturesHistoryFunding(this.extend(n,d)),c=Object.keys(h),l=[];for(let e=0;e<c.length;e++){let t=c[e],i=this.safeMarket(t),s=this.safeList(h,t,[]);for(let e=0;e<s.length;e++){let t=s[e],r=this.safeSymbol(i.symbol),a=this.safeNumber(t,"funding_rate"),o=this.safeString(t,"timestamp");l.push({info:t,symbol:r,fundingRate:a,timestamp:this.parse8601(o),datetime:o})}}let u=this.sortBy(l,"timestamp"),f=void 0===r?e:this.safeString(r,"symbol");return this.filterBySymbolSinceLimit(u,f,t,i)}async fetchPositions(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={},[r,a]=this.handleMarketTypeAndParams("fetchPositions",void 0,t),n=r;"spot"===r&&(n="swap");let[d,h]=this.handleMarginModeAndParams("fetchPositions",a),c=this.omit(h,["marginMode","margin"]);if(void 0!==d)i=await this.privateGetMarginAccount(this.extend(s,c));else if("swap"===n)i=await this.privateGetFuturesAccount(this.extend(s,c));else if("margin"===n)i=await this.privateGetMarginAccount(this.extend(s,c));else throw new o.NotSupported(this.id+" fetchPositions() not support this market type");let l=[];for(let e=0;e<i.length;e++)l.push(this.parsePosition(i[e]));return l}async fetchPosition(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id},[a,n]=this.handleMarketTypeAndParams("fetchPosition",void 0,t),[d,h]=this.handleMarginModeAndParams("fetchPosition",n),c=this.omit(h,["marginMode","margin"]);if(void 0!==d)i=await this.privateGetMarginAccountIsolatedSymbol(this.extend(r,c));else if("swap"===a)i=await this.privateGetFuturesAccountIsolatedSymbol(this.extend(r,c));else if("margin"===a)i=await this.privateGetMarginAccountIsolatedSymbol(this.extend(r,c));else throw new o.NotSupported(this.id+" fetchPosition() not support this market type");return this.parsePosition(i,s)}parsePosition(e,t){let i,s,r,a,o=this.safeString(e,"type"),n=this.safeNumber(e,"leverage"),d=this.safeString(e,"updated_at"),h=this.safeList(e,"positions",[]);for(let e=0;e<h.length;e++){let t=this.safeDict(h,e);i=this.safeNumber(t,"price_liquidation"),s=this.safeNumber(t,"price_entry"),r=this.safeNumber(t,"quantity")}let c=this.safeList(e,"currencies",[]);for(let e=0;e<c.length;e++){let t=this.safeDict(c,e);a=this.safeNumber(t,"margin_balance")}let l=this.safeString(e,"symbol"),u=this.safeMarket(l,t).symbol;return this.safePosition({info:e,id:void 0,symbol:u,notional:void 0,marginMode:o,liquidationPrice:i,entryPrice:s,unrealizedPnl:void 0,percentage:void 0,contracts:r,contractSize:void 0,markPrice:void 0,lastPrice:void 0,side:void 0,hedged:void 0,timestamp:this.parse8601(d),datetime:d,lastUpdateTimestamp:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,collateral:a,initialMargin:void 0,initialMarginPercentage:void 0,leverage:n,marginRatio:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}parseOpenInterest(e,t){let i=this.safeString(e,"timestamp"),s=this.safeNumber(e,"open_interest");return this.safeOpenInterest({symbol:this.safeSymbol(void 0,t),openInterestAmount:void 0,openInterestValue:s,timestamp:this.parse8601(i),datetime:i,info:e},t)}async fetchOpenInterests(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={},s=this.marketSymbols(e);void 0!==s&&(i.symbols=this.marketIds(s).join(","));let r=await this.publicGetPublicFuturesInfo(this.extend(i,t)),a=[],o=Object.keys(r);for(let e=0;e<o.length;e++){let t=o[e],i=this.safeMarket(t),s=this.safeDict(r,t,{});a.push(this.parseOpenInterest(s,i))}return this.filterByArray(a,"symbol",s)}async fetchOpenInterest(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new o.BadSymbol(this.id+" fetchOpenInterest() supports swap contracts only");let s={symbol:i.id},r=await this.publicGetPublicFuturesInfoSymbol(this.extend(s,t));return this.parseOpenInterest(r,i)}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new o.BadSymbol(this.id+" fetchFundingRate() supports swap contracts only");let s={symbol:i.id},r=await this.publicGetPublicFuturesInfoSymbol(this.extend(s,t));return this.parseFundingRate(r,i)}parseFundingRate(e,t){let i=this.safeString(e,"next_funding_time"),s=this.safeString(e,"timestamp");return{info:e,symbol:this.safeSymbol(void 0,t),markPrice:this.safeNumber(e,"mark_price"),indexPrice:this.safeNumber(e,"index_price"),interestRate:this.safeNumber(e,"interest_rate"),estimatedSettlePrice:void 0,timestamp:this.parse8601(s),datetime:s,fundingRate:this.safeNumber(e,"funding_rate"),fundingTimestamp:this.parse8601(i),fundingDatetime:i,nextFundingRate:this.safeNumber(e,"indicative_funding_rate"),nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:void 0}}async modifyMarginHelper(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.market(e),n=this.safeString(s,"leverage");if(!0===a.swap&&void 0===n)throw new o.ArgumentsRequired(this.id+" modifyMarginHelper() requires a leverage parameter for swap markets");let d=this.numberToString(t),h="0"!==d?this.amountToPrecision(e,d):"0",c={symbol:a.id,margin_balance:h};void 0!==n&&(c.leverage=n);let[l,u]=this.handleMarketTypeAndParams("modifyMarginHelper",a,s),[f,p]=this.handleMarginModeAndParams("modifyMarginHelper",u);if("swap"===l)r=await this.privatePutFuturesAccountIsolatedSymbol(this.extend(c,p));else if("margin"===l||"spot"===l||"isolated"===f)r=await this.privatePutMarginAccountIsolatedSymbol(this.extend(c,p));else throw new o.NotSupported(this.id+" modifyMarginHelper() not support this market type");let m=this.parseNumber(h);return this.extend(this.parseMarginModification(r,a),{amount:m,type:i})}parseMarginModification(e,t){let i=this.safeList(e,"currencies",[]),s=this.safeDict(i,0),r=this.safeString(e,"updated_at");return{info:e,symbol:this.safeString(t,"symbol"),type:void 0,marginMode:"isolated",amount:void 0,total:void 0,code:this.safeString(s,"code"),status:void 0,timestamp:this.parse8601(r),datetime:r}}async reduceMargin(e,t,i={}){if("0"!==this.numberToString(t))throw new o.BadRequest(this.id+" reduceMargin() on hitbtc requires the amount to be 0 and that will remove the entire margin amount");return await this.modifyMarginHelper(e,t,"reduce",i)}async addMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,"add",i)}async fetchLeverage(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id},[a,n]=this.handleMarginModeAndParams("fetchLeverage",t),d=this.omit(n,["marginMode","margin"]);if(void 0!==a)i=await this.privateGetMarginAccountIsolatedSymbol(this.extend(r,d));else if("spot"===s.type)i=await this.privateGetMarginAccountIsolatedSymbol(this.extend(r,d));else if("swap"===s.type)i=await this.privateGetFuturesAccountIsolatedSymbol(this.extend(r,d));else if("margin"===s.type)i=await this.privateGetMarginAccountIsolatedSymbol(this.extend(r,d));else throw new o.NotSupported(this.id+" fetchLeverage() not support this market type");return this.parseLeverage(i,s)}parseLeverage(e,t){let i=this.safeString(e,"symbol"),s=this.safeInteger(e,"leverage");return{info:e,symbol:this.safeSymbol(i,t),marginMode:this.safeStringLower(e,"type"),longLeverage:s,shortLeverage:s}}async setLeverage(e,t,i={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");if(void 0===this.markets&&await this.loadMarkets(),void 0===i.margin_balance)throw new o.ArgumentsRequired(this.id+" setLeverage() requires a margin_balance parameter that will transfer margin to the specified trading pair");let s=this.market(t),r=this.safeNumber(i,"margin_balance"),a=this.safeInteger(s.limits.leverage,"max",50);if("swap"!==s.type)throw new o.BadSymbol(this.id+" setLeverage() supports swap contracts only");if(e<1||e>a)throw new o.BadRequest(this.id+" setLeverage() leverage should be between 1 and "+a.toString()+" for "+t);let n={symbol:s.id,leverage:e.toString(),margin_balance:this.amountToPrecision(t,r)};return await this.privatePutFuturesAccountIsolatedSymbol(this.extend(n,i))}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetPublicCurrency(t);return this.parseDepositWithdrawFees(i,e)}parseDepositWithdrawFee(e,t){let i=this.safeList(e,"networks",[]),s=this.depositWithdrawFee(e);for(let e=0;e<i.length;e++){let r=this.safeDict(i,e),a=this.safeString(r,"network"),o=this.safeString(t,"code"),n=this.networkIdToCode(a,o);n=void 0!==n?n.toUpperCase():void 0;let d=this.safeNumber(r,"payout_fee"),h=this.safeBool(r,"default"),c={fee:d,percentage:void 0===d&&void 0};!0===h&&(s.withdraw=c),void 0!==n&&(s.networks[n]={withdraw:c,deposit:{fee:void 0,percentage:void 0}})}return s}async closePosition(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleMarginModeAndParams("closePosition",i,"cross"),a=this.market(e),o={symbol:a.id,margin_mode:s},n=await this.privateDeleteFuturesPositionMarginModeSymbol(this.extend(o,r));return this.parseOrder(n,a)}handleMarginModeAndParams(e,t={},i){let s=this.safeString(this.options,"defaultType"),r=this.safeBool(t,"margin",!1),[a,o]=super.handleMarginModeAndParams(e,t,i);return void 0===a&&("margin"===s||!0===r)?["isolated",o]:[a,o]}handleErrors(e,t,i,s,r,a,n,d,h){let c=this.safeDict(n,"error"),l=this.safeString(c,"code");if(void 0!==l){let e=this.id+" "+a,t=this.safeString2(c,"message","description");throw this.throwExactlyMatchedException(this.exceptions.exact,l,e),this.throwBroadlyMatchedException(this.exceptions.broad,t,e),new o.ExchangeError(e)}}sign(e,t="public",i="GET",r={},a,n){let d,h=this.omit(r,this.extractParams(e)),c=this.implodeParams(e,r),l=this.safeString(this.urls.api,t);if(void 0===l)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let u=l+"/"+c,f=Object.keys(h).length,p={"Content-Type":"application/json"};"GET"===i&&0!==f&&(u+=d="?"+this.urlencode(h));let m="GET"===i?n:this.json(r);if("private"===t){this.checkRequiredCredentials();let e=this.nonce().toString(),t=[i,"/api/3/"+c];"GET"===i?void 0!==d&&t.push(d):void 0!==m&&t.push(m),t.push(e);let r=t.join(""),a=this.hmac(this.encode(r),this.encode(this.secret),s.sc,"hex"),o=this.apiKey+":"+a+":"+e;p.Authorization="HS256 "+this.stringToBase64(o)}return{url:u,method:i,body:m,headers:p}}}i.d(t,{A:()=>n})},33(e,t,i){"use strict";var s=i(4721),r=i(526),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"hollaex",name:"HollaEx",countries:["KR"],rateLimit:250,version:"v2",pro:!0,has:{CORS:void 0,spot:!0,margin:void 0,swap:!1,future:!1,option:!1,addMargin:!1,cancelAllOrders:!0,cancelOrder:!0,createLimitBuyOrder:!0,createLimitSellOrder:!0,createMarketBuyOrder:!0,createMarketSellOrder:!0,createOrder:!0,createPostOnlyOrder:!0,createReduceOnlyOrder:!1,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,fetchBalance:!0,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:"emulated",fetchDepositAddresses:!0,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositWithdrawFees:!0,fetchFundingHistory:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLeverage:!1,fetchMarginMode:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterestHistory:!1,fetchOpenOrder:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:!0,fetchOrders:!0,fetchPosition:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchTransactions:!1,fetchTransfer:!1,fetchTransfers:!1,fetchWithdrawal:!0,fetchWithdrawals:!0,reduceMargin:!1,sandbox:!0,setLeverage:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,withdraw:!0},timeframes:{"1m":"1m","5m":"5m","15m":"15m","1h":"1h","4h":"4h","1d":"1d","1w":"1w"},urls:{logo:"https://user-images.githubusercontent.com/1294454/75841031-ca375180-5ddd-11ea-8417-b975674c23cb.jpg",test:{rest:"https://api.sandbox.hollaex.com"},api:{rest:"https://api.hollaex.com"},www:"https://hollaex.com",doc:"https://apidocs.hollaex.com",referral:"https://pro.hollaex.com/signup?affiliation_code=QSWA6G"},precisionMode:4,requiredCredentials:{apiKey:!0,secret:!0},api:{public:{get:{health:{cost:1},constants:{cost:1},kit:{cost:1},tiers:{cost:1},ticker:{cost:1},tickers:{cost:1},orderbook:{cost:1},orderbooks:{cost:1},trades:{cost:1},chart:{cost:1},charts:{cost:1},minicharts:{cost:1},"oracle/prices":{cost:1},"quick-trade":{cost:1},"udf/config":{cost:1},"udf/history":{cost:1},"udf/symbols":{cost:1}}},private:{get:{user:{cost:1},"user/balance":{cost:1},"user/deposits":{cost:1},"user/withdrawals":{cost:1},"user/withdrawal/fee":{cost:1},subaccounts:{cost:1},"user/trades":{cost:1},orders:{cost:1},order:{cost:1}},post:{"user/withdrawal":{cost:1},"subaccount/transfer":{cost:1},order:{cost:1}},delete:{"order/all":{cost:1},order:{cost:1}}}},features:{spot:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!0,GTD:!1},hedged:!1,selfTradePrevention:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:100,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:100,daysBack:1e5,daysBackCanceled:1,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:1e3}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},fees:{trading:{tierBased:!0,percentage:!0,taker:.001,maker:.001}},exceptions:{broad:{"API request is expired":a.InvalidNonce,"Invalid token":a.AuthenticationError,"Order not found":a.OrderNotFound,"Insufficient balance":a.InsufficientFunds,"Error 1001 - Order rejected. Order could not be submitted as this order was set to a post only order.":a.OrderImmediatelyFillable},exact:{400:a.BadRequest,403:a.AuthenticationError,404:a.BadRequest,405:a.BadRequest,410:a.BadRequest,429:a.BadRequest,500:a.NetworkError,503:a.NetworkError}},options:{"api-expires":this.parseToInt(this.timeout/1e3),networks:{BTC:"btc",ETH:"eth",ERC20:"eth",TRX:"trx",TRC20:"trx",XRP:"xrp",XLM:"xlm",BNB:"bnb",MATIC:"matic"},networksById:{eth:"ERC20",ETH:"ERC20",ERC20:"ERC20",trx:"TRC20",TRX:"TRC20",TRC20:"TRC20"}}})}async fetchMarkets(e={}){let t=await this.publicGetConstants(e),i=this.safeDict(t,"pairs",{}),s=Object.keys(i),r=[];for(let e=0;e<s.length;e++){let t=s[e],a=this.safeDict(i,t),o=this.safeString(a,"pair_base"),n=this.safeString(a,"pair_2"),d=this.commonCurrencyCode(o.toUpperCase()),h=this.commonCurrencyCode(n.toUpperCase());r.push({id:this.safeString(a,"name"),symbol:d+"/"+h,base:d,quote:h,settle:void 0,baseId:o,quoteId:n,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:this.safeBool(a,"active"),contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(a,"increment_size"),price:this.safeNumber(a,"increment_price")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(a,"min_size"),max:this.safeNumber(a,"max_size")},price:{min:this.safeNumber(a,"min_price"),max:this.safeNumber(a,"max_price")},cost:{min:void 0,max:void 0}},created:this.parse8601(this.safeString(a,"created_at")),info:a})}return r}async fetchCurrencies(e={}){let t=await this.publicGetConstants(e),i=Object.values(this.safeDict(t,"coins",{}));return this.parseCurrencies(i)}parseCurrency(e){let t=this.safeString(e,"symbol"),i=this.safeCurrencyCode(t),s=this.safeList(e,"withdrawal_limits",[]),r=this.safeString(e,"type"),a="other";"blockchain"===r&&(a="crypto");let o=this.safeDict(e,"withdrawal_fees",{}),n={},d=Object.keys(o);for(let e=0;e<d.length;e++){let t=d[e],s=this.safeDict(o,t),r=this.networkIdToCode(t,i);void 0!==r&&(n[r]={id:t,network:r,active:this.safeBool(s,"active"),deposit:void 0,withdraw:void 0,fee:this.safeNumber(s,"value"),precision:void 0,limits:{withdraw:{min:void 0,max:void 0}},info:s})}return this.safeCurrencyStructure({id:t,numericId:this.safeInteger(e,"id"),code:i,info:e,name:this.safeString(e,"fullname"),active:this.safeBool(e,"active"),deposit:this.safeBool(e,"allow_deposit"),withdraw:this.safeBool(e,"allow_withdrawal"),fee:this.safeNumber(e,"withdrawal_fee"),precision:this.safeNumber(e,"increment_unit"),limits:{amount:{min:this.safeNumber(e,"min"),max:this.safeNumber(e,"max")},withdraw:{min:void 0,max:this.safeNumber(s,0)}},networks:n,type:a})}async fetchOrderBooks(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.publicGetOrderbooks(i),r={},a=Object.keys(s);for(let e=0;e<a.length;e++){let t=a[e],i=this.safeDict(s,t,{}),o=this.safeSymbol(t,void 0,"-"),n=this.parse8601(this.safeString(i,"timestamp"));r[o]=this.parseOrderBook(i,o,n)}return r}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id},a=await this.publicGetOrderbook(this.extend(r,i)),o=this.safeDict(a,s.id),n=this.parse8601(this.safeString(o,"timestamp"));return this.parseOrderBook(o,s.symbol,n)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetTicker(this.extend(s,t));return this.parseTicker(r,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetTickers(t);return this.parseTickers(s,i)}parseTickers(e,t,i={}){let s={},r=Object.keys(e);for(let t=0;t<r.length;t++){let a=r[t],o=e[a],n=this.safeString(o,"symbol",a),d=this.safeMarket(n,void 0,"-");s[d.symbol]=this.extend(this.parseTicker(o,d),i)}return this.filterByArrayTickers(s,"symbol",t)}parseTicker(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t,"-"),r=s.symbol,a=this.parse8601(this.safeString2(e,"time","timestamp")),o=this.safeString(e,"close");return this.safeTicker({symbol:r,info:e,timestamp:a,datetime:this.iso8601(a),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:this.safeString(e,"open"),close:o,last:this.safeString(e,"last",o),previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"volume"),quoteVolume:void 0},s)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id},o=await this.publicGetTrades(this.extend(a,s)),n=this.safeList(o,r.id,[]);return this.parseTrades(n,r,t,i)}parseTrade(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t,"-"),a=r.symbol,o=this.safeString(e,"timestamp"),n=this.parse8601(o),d=this.safeString(e,"side"),h=this.safeString(e,"order_id"),c=this.safeString(e,"price"),l=this.safeString(e,"size"),u=this.safeString(e,"fee"),f=this.safeString(e,"fee_coin");return void 0!==u&&(i={cost:u,currency:this.safeCurrencyCode(f)}),this.safeTrade({info:e,id:void 0,timestamp:n,datetime:o,symbol:a,order:h,type:void 0,side:d,takerOrMaker:void 0,price:c,amount:l,cost:void 0,fee:i},r)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.publicGetTiers(e),i=this.safeDict(t,"1",{}),s=this.safeDict(i,"fees",{}),r=this.safeDict(s,"maker",{}),a=this.safeDict(s,"taker",{}),n={};for(let e=0;e<this.symbols.length;e++){let t=this.symbols[e],i=this.market(t),d=this.safeString(r,i.id),h=this.safeString(a,i.id);n[t]={info:s,symbol:t,maker:this.parseNumber(o.Y.stringDiv(d,"100")),taker:this.parseNumber(o.Y.stringDiv(h,"100")),percentage:!0,tierBased:!0}}return n}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={symbol:a.id,resolution:this.safeString(this.timeframes,t,t)},[n,d]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(n)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,d,500);let h=this.safeInteger(d,"until"),c=500*this.parseTimeframe(t)*1e3,l=i,u=this.milliseconds();void 0===h&&(h=u),void 0===l&&(l=h-c),o.from=this.parseToInt(l/1e3),o.to=this.parseToInt(h/1e3);let f=this.omit(d,"until"),p=await this.publicGetChart(this.extend(o,f));return this.parseOHLCVs(this.toArray(p),a,t,i,s)}parseOHLCV(e,t){return[this.parse8601(this.safeString(e,"time")),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}parseBalance(e){let t=this.parse8601(this.safeString(e,"updated_at")),i={info:e,timestamp:t,datetime:this.iso8601(t)},s=this.currencies_by_id;if(void 0===s)throw new a.ExchangeError(this.id+" currencies not loaded");let r=Object.keys(s);for(let t=0;t<r.length;t++){let s=r[t],a=this.safeCurrencyCode(s),o=this.account();o.free=this.safeString(e,s+"_available"),o.total=this.safeString(e,s+"_balance"),void 0!==a&&(i[a]=o)}return this.safeBalance(i)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetUserBalance(e);return this.parseBalance(t)}async fetchOpenOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateGetOrder(this.extend({order_id:e},i));return this.parseOrder(s)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({open:!0},s))}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({open:!1},s))}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateGetOrder(this.extend({order_id:e},i));if(void 0===s)throw new a.OrderNotFound(this.id+" fetchOrder() could not find order id "+e);return this.parseOrder(s)}async fetchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id),void 0!==t&&(a.start_date=this.iso8601(t)),void 0!==i&&(a.limit=i);let o=await this.privateGetOrders(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseOrders(n,r,t,i)}parseOrderStatus(e){return this.safeString({new:"open",pfilled:"open",filled:"closed",canceled:"canceled"},e,e)}parseOrder(e,t){let i=this.safeString(e,"symbol"),s=this.safeSymbol(i,t,"-"),r=this.safeString(e,"id"),a=this.parse8601(this.safeString(e,"created_at")),o=this.safeString(e,"type"),n=this.safeString(e,"side"),d=this.safeString(e,"price"),h=this.safeString(e,"size"),c=this.safeString(e,"filled"),l=this.parseOrderStatus(this.safeString(e,"status")),u=this.safeDict(e,"meta",{}),f=this.safeBool(u,"post_only",!1);return this.safeOrder({id:r,clientOrderId:void 0,timestamp:a,datetime:this.iso8601(a),lastTradeTimestamp:void 0,status:l,symbol:s,type:o,timeInForce:void 0,postOnly:f,side:n,price:d,triggerPrice:this.safeString(e,"stop"),amount:h,filled:c,remaining:void 0,cost:void 0,trades:void 0,fee:void 0,info:e,average:void 0},t)}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={symbol:o.id,side:i,size:this.amountToPrecision(e,s),type:t},d=this.safeNumberN(a,["triggerPrice","stopPrice","stop"]),h=this.safeDict(a,"meta",{}),c=this.safeBool(h,"post_only",!1),l="market"===t,u=this.isPostOnly(l,c,a);l||(n.price=this.priceToPrecision(e,r)),void 0!==d&&(n.stop=this.priceToPrecision(e,d)),u&&(n.meta={post_only:!0});let f=this.omit(a,["postOnly","timeInForce","stopPrice","triggerPrice","stop"]),p=await this.privatePostOrder(this.extend(n,f));return this.parseOrder(p,o)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateDeleteOrder(this.extend({order_id:e},i));return this.parseOrder(s)}async cancelAllOrders(e,t={}){let i;if(void 0===e)throw new a.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s={};s.symbol=(i=this.market(e)).id;let r=await this.privateDeleteOrderAll(this.extend(s,t));return this.parseOrders(r,i)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id),void 0!==i&&(a.limit=i),void 0!==t&&(a.start_date=this.iso8601(t));let o=await this.privateGetUserTrades(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTrades(n,r,t,i)}parseDepositAddress(e,t){let i,s=this.safeString(e,"address");if(void 0!==s){let e=s.split(":");s=this.safeString(e,0),i=this.safeString(e,1)}this.checkAddress(s);let r=this.safeString(e,"currency"),a=this.safeCurrency(r,t),o=this.safeString(e,"network");return{info:e,currency:a.code,network:o,address:s,tag:i}}async fetchDepositAddresses(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.safeString(t,"network"),r=this.omit(t,"network"),a=await this.privateGetUser(r),o=this.safeList(a,"wallet",[]);return i=void 0===s?o:this.filterBy(o,"network",s),this.parseDepositAddresses(i,e,!1)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.currency=(r=this.currency(e)).id),void 0!==i&&(a.limit=i),void 0!==t&&(a.start_date=this.iso8601(t));let o=await this.privateGetUserDeposits(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTransactions(n,r,t,i)}async fetchWithdrawal(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r={transaction_id:e};void 0!==t&&(r.currency=(s=this.currency(t)).id);let a=await this.privateGetUserWithdrawals(this.extend(r,i)),o=this.safeList(a,"data",[]),n=this.safeDict(o,0,{});return this.parseTransaction(n,s)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.currency=(r=this.currency(e)).id),void 0!==i&&(a.limit=i),void 0!==t&&(a.start_date=this.iso8601(t));let o=await this.privateGetUserWithdrawals(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTransactions(n,r,t,i)}parseTransaction(e,t){let i,s,r,a,o=this.safeString(e,"id"),n=this.safeString(e,"transaction_id"),d=this.parse8601(this.safeString(e,"created_at")),h=this.parse8601(this.safeString(e,"updated_at")),c=this.safeString(e,"type"),l=this.safeNumber(e,"amount"),u=this.safeString(e,"address");if(void 0!==u){let e=u.split(":");u=this.safeString(e,0),s=this.safeString(e,1),i=u,r=s}let f=this.safeString(e,"currency"),p=this.safeCurrency(f,t),m=this.safeValue(e,"status"),g=this.safeBool(e,"dismissed"),v=this.safeBool(e,"rejected");m=!0===m?"ok":!0===g?"canceled":!0===v?"failed":"pending";let y=this.safeString(e,"fee_coin"),b=this.safeCurrencyCode(y,p),w=this.safeNumber(e,"fee");return void 0!==w&&(a={currency:b,cost:w}),{info:e,id:o,txid:n,timestamp:d,datetime:this.iso8601(d),network:void 0,addressFrom:void 0,address:u,addressTo:i,tagFrom:void 0,tag:s,tagTo:r,type:c,amount:l,currency:p.code,status:m,updated:h,comment:this.safeString(e,"message"),internal:void 0,fee:a}}async withdraw(e,t,i,s,r={}){let[o,n]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let d=this.currency(e),h=i;void 0!==o&&(h=i+":"+o);let c=this.safeString(n,"network");if(void 0===c)throw new a.ArgumentsRequired(this.id+" withdraw() requires a network parameter");let l=this.omit(n,"network"),u={currency:d.id,amount:t,address:h,network:this.networkCodeToId(c,e)},f=await this.privatePostUserWithdrawal(this.extend(u,l));return this.parseTransaction(f,d)}parseDepositWithdrawFee(e,t){let i={info:e,withdraw:{fee:void 0,percentage:void 0},deposit:{fee:void 0,percentage:void 0},networks:{}};!0===this.safeBool(e,"allow_withdrawal")&&(i.withdraw={fee:this.safeNumber(e,"withdrawal_fee"),percentage:!1});let s=this.safeDict(e,"withdrawal_fees");if(void 0!==s){let e=Object.keys(s),t=e.length;for(let r=0;r<t;r++){let t=e[r],o=this.safeDict(s,t),n=this.safeString(o,"symbol"),d=this.safeCurrencyCode(n),h=this.networkIdToCode(t,d);if(void 0===h)throw new a.ArgumentsRequired(this.id+" requires a networkCode argument");let c=h.toUpperCase(),l=this.safeNumber(o,"value");i.networks[c]={deposit:void 0,withdraw:l}}}return i}async fetchDepositWithdrawFees(e,t={}){let i=await this.publicGetConstants(t),s=this.safeDict(i,"coins",{});return this.parseDepositWithdrawFees(s,e,"symbol")}sign(e,t="public",i="GET",r={},o,n){let d,h,c=this.omit(r,this.extractParams(e)),l="/"+this.version+"/"+this.implodeParams(e,r);("GET"===i||"DELETE"===i)&&Object.keys(c).length>0&&(l+="?"+this.urlencode(c));let u=this.safeString(this.urls.api,"rest");if(void 0===u)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let f=u+l;if("private"===t){this.checkRequiredCredentials();let e=this.safeInteger2(this.options,"api-expires","expires",this.parseToInt(this.timeout/1e3)),t=this.sum(this.seconds(),e).toString(),r=i+l+t;h={"api-key":this.apiKey,"api-expires":t},"POST"===i&&(h["Content-type"]="application/json",Object.keys(c).length>0&&(r+=d=this.json(c)));let a=this.hmac(this.encode(r),this.encode(this.secret),s.sc);h["api-signature"]=a}return{url:f,method:i,body:void 0===d?n:d,headers:void 0===h?o:h}}handleErrors(e,t,i,s,r,a,o,n,d){if(void 0!==o&&e>=400&&e<=503){let t=this.id+" "+a,i=this.safeString(o,"message");this.throwBroadlyMatchedException(this.exceptions.broad,i,t);let s=e.toString();this.throwExactlyMatchedException(this.exceptions.exact,s,t)}}}i.d(t,{A:()=>n})},8552(e,t,i){"use strict";var s=i(4721),r=i(4135),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"htx",name:"HTX",countries:["CN"],rateLimit:100,userAgent:this.userAgents.chrome100,certified:!0,version:"v1",hostname:"api.huobi.pro",pro:!0,has:{CORS:void 0,spot:!0,margin:!0,swap:!0,future:!0,option:void 0,addMargin:void 0,borrowCrossMargin:!0,borrowIsolatedMargin:!0,cancelAllOrders:!0,cancelAllOrdersAfter:!0,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!1,closePosition:!0,createDepositAddress:void 0,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createReduceOnlyOrder:!1,createStopLimitOrder:!0,createStopLossOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,createTakeProfitOrder:!0,createTrailingPercentOrder:!0,createTriggerOrder:!0,fetchAccounts:!0,fetchBalance:!0,fetchBidsAsks:void 0,fetchBorrowInterest:!0,fetchBorrowRateHistories:void 0,fetchBorrowRateHistory:void 0,fetchCanceledOrders:!0,fetchClosedOrder:void 0,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:void 0,fetchDepositAddress:!0,fetchDepositAddresses:void 0,fetchDepositAddressesByNetwork:!0,fetchDeposits:!0,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!0,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchIndexOHLCV:!0,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!0,fetchL3OrderBook:void 0,fetchLastPrices:!0,fetchLedger:!0,fetchLedgerEntry:void 0,fetchLeverage:!1,fetchLeverageTiers:!0,fetchLiquidations:!0,fetchMarginAdjustmentHistory:!1,fetchMarketLeverageTiers:"emulated",fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMyLiquidations:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!0,fetchOpenInterests:!0,fetchOpenOrder:void 0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:void 0,fetchOrders:!0,fetchOrderTrades:!0,fetchPosition:!0,fetchPositionADLRank:!0,fetchPositionHistory:"emulated",fetchPositions:!0,fetchPositionsADLRank:!0,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!0,fetchSettlementHistory:!0,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!1,fetchTradingLimits:!0,fetchTransactionFee:void 0,fetchTransactionFees:void 0,fetchTransactions:void 0,fetchTransfers:!0,fetchWithdrawAddresses:!0,fetchWithdrawal:void 0,fetchWithdrawals:!0,fetchWithdrawalWhitelist:void 0,reduceMargin:void 0,repayCrossMargin:!0,repayIsolatedMargin:!0,setLeverage:!0,setMarginMode:!1,setPositionMode:!0,signIn:void 0,transfer:!0,withdraw:!0},timeframes:{"1m":"1min","5m":"5min","15m":"15min","30m":"30min","1h":"60min","4h":"4hour","1d":"1day","1w":"1week","1M":"1mon","1y":"1year"},urls:{logo:"https://user-images.githubusercontent.com/1294454/76137448-22748a80-604e-11ea-8069-6e389271911d.jpg",hostnames:{contract:"api.hbdm.vn",spot:"api.huobi.pro"},api:{status:"https://{hostname}",contract:"https://{hostname}",spot:"https://{hostname}",public:"https://{hostname}",private:"https://{hostname}",v2Public:"https://{hostname}",v2Private:"https://{hostname}"},www:"https://www.huobi.com",referral:{url:"https://www.htx.com/invite/en-us/1h?invite_code=6rmm2223",discount:.15},doc:["https://huobiapi.github.io/docs/spot/v1/en/","https://huobiapi.github.io/docs/dm/v1/en/","https://huobiapi.github.io/docs/coin_margined_swap/v1/en/","https://huobiapi.github.io/docs/usdt_swap/v1/en/","https://www.huobi.com/en-us/opend/newApiPages/"],fees:"https://www.huobi.com/about/fee/"},api:{v2Public:{get:{"reference/currencies":{cost:1},"market-status":{cost:1}}},v2Private:{get:{"account/ledger":{cost:1},"account/withdraw/quota":{cost:1},"account/withdraw/address":{cost:1},"account/deposit/address":{cost:1},"account/repayment":{cost:5},"reference/transact-fee-rate":{cost:1},"account/asset-valuation":{cost:.2},"point/account":{cost:5},"sub-user/user-list":{cost:1},"sub-user/user-state":{cost:1},"sub-user/account-list":{cost:1},"sub-user/deposit-address":{cost:1},"sub-user/query-deposit":{cost:1},"user/api-key":{cost:1},"user/uid":{cost:1},"algo-orders/opening":{cost:1},"algo-orders/history":{cost:1},"algo-orders/specific":{cost:1},"c2c/offers":{cost:1},"c2c/offer":{cost:1},"c2c/transactions":{cost:1},"c2c/repayment":{cost:1},"c2c/account":{cost:1},"etp/reference":{cost:1},"etp/transactions":{cost:5},"etp/transaction":{cost:5},"etp/rebalance":{cost:1},"etp/limit":{cost:1}},post:{"account/transfer":{cost:1},"account/repayment":{cost:5},"point/transfer":{cost:5},"sub-user/management":{cost:1},"sub-user/creation":{cost:1},"sub-user/tradable-market":{cost:1},"sub-user/transferability":{cost:1},"sub-user/api-key-generation":{cost:1},"sub-user/api-key-modification":{cost:1},"sub-user/api-key-deletion":{cost:1},"sub-user/deduct-mode":{cost:1},"algo-orders":{cost:1},"algo-orders/cancel-all-after":{cost:1},"algo-orders/cancellation":{cost:1},"c2c/offer":{cost:1},"c2c/cancellation":{cost:1},"c2c/cancel-all":{cost:1},"c2c/repayment":{cost:1},"c2c/transfer":{cost:1},"etp/creation":{cost:5},"etp/redemption":{cost:5},"etp/{transactId}/cancel":{cost:10},"etp/batch-cancel":{cost:50}}},public:{get:{"common/symbols":{cost:1},"common/currencys":{cost:1},"common/timestamp":{cost:1},"common/exchange":{cost:1},"settings/currencys":{cost:1}}},private:{get:{"account/accounts":{cost:.2},"account/accounts/{id}/balance":{cost:.2},"account/accounts/{sub-uid}":{cost:1},"account/history":{cost:4},"cross-margin/loan-info":{cost:1},"margin/loan-info":{cost:1},"fee/fee-rate/get":{cost:1},"order/openOrders":{cost:.4},"order/orders":{cost:.4},"order/orders/{id}":{cost:.4},"order/orders/{id}/matchresults":{cost:.4},"order/orders/getClientOrder":{cost:.4},"order/history":{cost:1},"order/matchresults":{cost:1},"query/deposit-withdraw":{cost:1},"margin/loan-orders":{cost:.2},"margin/accounts/balance":{cost:.2},"cross-margin/loan-orders":{cost:1},"cross-margin/accounts/balance":{cost:1},"points/actions":{cost:1},"points/orders":{cost:1},"subuser/aggregate-balance":{cost:10},"stable-coin/exchange_rate":{cost:1},"stable-coin/quote":{cost:1}},post:{"account/transfer":{cost:1},"futures/transfer":{cost:1},"order/batch-orders":{cost:.4},"order/orders/place":{cost:.2},"order/orders/submitCancelClientOrder":{cost:.2},"order/orders/batchCancelOpenOrders":{cost:.4},"order/orders/{id}/submitcancel":{cost:.2},"order/orders/batchcancel":{cost:.4},"dw/withdraw/api/create":{cost:1},"dw/withdraw-virtual/{id}/cancel":{cost:1},"dw/transfer-in/margin":{cost:10},"dw/transfer-out/margin":{cost:10},"margin/orders":{cost:10},"margin/orders/{id}/repay":{cost:10},"cross-margin/transfer-in":{cost:1},"cross-margin/transfer-out":{cost:1},"cross-margin/orders":{cost:1},"cross-margin/orders/{id}/repay":{cost:1},"stable-coin/exchange":{cost:1},"subuser/transfer":{cost:10}}},spot:{public:{get:{"v2/market-status":{cost:1},"v1/common/symbols":{cost:1},"v1/common/currencys":{cost:1},"v2/settings/common/currencies":{cost:1},"v2/reference/currencies":{cost:1},"v1/common/timestamp":{cost:1},"v1/common/exchange":{cost:1},"v1/settings/common/chains":{cost:1},"v1/settings/common/currencys":{cost:1},"v1/settings/common/symbols":{cost:1},"v2/settings/common/symbols":{cost:1},"v1/settings/common/market-symbols":{cost:1},"market/history/candles":{cost:1},"market/history/kline":{cost:1},"market/detail/merged":{cost:1},"market/tickers":{cost:1},"market/detail":{cost:1},"market/depth":{cost:1},"market/trade":{cost:1},"market/history/trade":{cost:1},"market/etp":{cost:1},"v2/etp/reference":{cost:1},"v2/etp/rebalance":{cost:1}}},private:{get:{"v1/account/accounts":{cost:.2},"v1/account/accounts/{account-id}/balance":{cost:.2},"v2/account/valuation":{cost:1},"v2/account/asset-valuation":{cost:.2},"v1/account/history":{cost:4},"v2/account/ledger":{cost:1},"v2/point/account":{cost:5},"v2/account/deposit/address":{cost:1},"v2/account/withdraw/quota":{cost:1},"v2/account/withdraw/address":{cost:1},"v2/reference/currencies":{cost:1},"v1/query/deposit-withdraw":{cost:1},"v1/query/withdraw/client-order-id":{cost:1},"v2/user/api-key":{cost:1},"v2/user/uid":{cost:1},"v2/sub-user/user-list":{cost:1},"v2/sub-user/user-state":{cost:1},"v2/sub-user/account-list":{cost:1},"v2/sub-user/deposit-address":{cost:1},"v2/sub-user/query-deposit":{cost:1},"v1/subuser/aggregate-balance":{cost:10},"v1/account/accounts/{sub-uid}":{cost:1},"v1/order/openOrders":{cost:.4},"v1/order/orders/{order-id}":{cost:.4},"v1/order/orders/getClientOrder":{cost:.4},"v1/order/orders/{order-id}/matchresult":{cost:.4},"v1/order/orders/{order-id}/matchresults":{cost:.4},"v1/order/orders":{cost:.4},"v1/order/history":{cost:1},"v1/order/matchresults":{cost:1},"v2/reference/transact-fee-rate":{cost:1},"v2/algo-orders/opening":{cost:1},"v2/algo-orders/history":{cost:1},"v2/algo-orders/specific":{cost:1},"v1/margin/loan-info":{cost:1},"v1/margin/loan-orders":{cost:.2},"v1/margin/accounts/balance":{cost:.2},"v1/cross-margin/loan-info":{cost:1},"v1/cross-margin/loan-orders":{cost:1},"v1/cross-margin/accounts/balance":{cost:1},"v2/account/repayment":{cost:5},"v5/account/universal_transfer_records":{cost:4},"v1/stable-coin/quote":{cost:1},"v1/stable_coin/exchange_rate":{cost:1},"v2/etp/transactions":{cost:5},"v2/etp/transaction":{cost:5},"v2/etp/limit":{cost:1},"v2/invitee/rebate/referrals":{cost:10},"v2/invitee/rebate/detail":{cost:1},"v2/invitee/rebate/history":{cost:1},"v2/invitee/rebate/all_rebate/detail":{cost:1},"v2/invitee/rebate/batcher_rebate/detail":{cost:1}},post:{"v1/account/transfer":{cost:1},"v1/futures/transfer":{cost:1},"v2/point/transfer":{cost:5},"v2/account/transfer":{cost:1},"v1/dw/withdraw/api/create":{cost:1},"v1/dw/withdraw-virtual/{withdraw-id}/cancel":{cost:1},"v2/sub-user/deduct-mode":{cost:1},"v2/sub-user/creation":{cost:1},"v2/sub-user/management":{cost:1},"v2/sub-user/tradable-market":{cost:1},"v2/sub-user/transferability":{cost:1},"v2/sub-user/api-key-generation":{cost:1},"v2/sub-user/api-key-modification":{cost:1},"v2/sub-user/api-key-deletion":{cost:1},"v1/subuser/transfer":{cost:10},"v1/trust/user/active/credit":{cost:10},"v1/order/orders/place":{cost:.2},"v1/order/batch-orders":{cost:.4},"v1/order/auto/place":{cost:.2},"v1/order/orders/{order-id}/submitcancel":{cost:.2},"v1/order/orders/submitCancelClientOrder":{cost:.2},"v1/order/orders/batchCancelOpenOrders":{cost:.4},"v1/order/orders/batchcancel":{cost:.4},"v2/algo-orders/cancel-all-after":{cost:1},"v2/algo-orders":{cost:1},"v2/algo-orders/cancellation":{cost:1},"v2/account/repayment":{cost:5},"v1/dw/transfer-in/margin":{cost:10},"v1/dw/transfer-out/margin":{cost:10},"v1/margin/orders":{cost:10},"v1/margin/orders/{order-id}/repay":{cost:10},"v1/cross-margin/transfer-in":{cost:1},"v1/cross-margin/transfer-out":{cost:1},"v1/cross-margin/orders":{cost:1},"v1/cross-margin/orders/{order-id}/repay":{cost:1},"v1/stable-coin/exchange":{cost:1},"v2/etp/creation":{cost:5},"v2/etp/redemption":{cost:5},"v2/etp/{transactId}/cancel":{cost:10},"v2/etp/batch-cancel":{cost:50},"v5/account/universal_transfer":{cost:4}}}},contract:{public:{get:{"api/v1/timestamp":{cost:1},"heartbeat/":{cost:1},"api/v1/contract_contract_info":{cost:1},"api/v1/contract_index":{cost:1},"api/v1/contract_query_elements":{cost:1},"api/v1/contract_price_limit":{cost:1},"api/v1/contract_open_interest":{cost:1},"api/v1/contract_delivery_price":{cost:1},"market/depth":{cost:1},"market/bbo":{cost:1},"market/history/kline":{cost:1},"index/market/history/mark_price_kline":{cost:1},"market/detail/merged":{cost:1},"market/detail/batch_merged":{cost:1},"v2/market/detail/batch_merged":{cost:1},"market/trade":{cost:1},"market/history/trade":{cost:1},"api/v1/contract_risk_info":{cost:1},"api/v1/contract_insurance_fund":{cost:1},"api/v1/contract_adjustfactor":{cost:1},"api/v1/contract_his_open_interest":{cost:1},"api/v1/contract_ladder_margin":{cost:1},"api/v1/contract_api_state":{cost:1},"api/v1/contract_elite_account_ratio":{cost:1},"api/v1/contract_elite_position_ratio":{cost:1},"api/v1/contract_liquidation_orders":{cost:1},"api/v1/contract_settlement_records":{cost:1},"index/market/history/index":{cost:1},"index/market/history/basis":{cost:1},"api/v1/contract_estimated_settlement_price":{cost:1},"api/v3/contract_liquidation_orders":{cost:1},"swap-api/v1/swap_contract_info":{cost:1},"swap-api/v1/swap_index":{cost:1},"swap-api/v1/swap_query_elements":{cost:1},"swap-api/v1/swap_price_limit":{cost:1},"swap-api/v1/swap_open_interest":{cost:1},"swap-ex/market/depth":{cost:1},"swap-ex/market/bbo":{cost:1},"swap-ex/market/history/kline":{cost:1},"index/market/history/swap_mark_price_kline":{cost:1},"swap-ex/market/detail/merged":{cost:1},"v2/swap-ex/market/detail/batch_merged":{cost:1},"index/market/history/swap_premium_index_kline":{cost:1},"swap-ex/market/detail/batch_merged":{cost:1},"swap-ex/market/trade":{cost:1},"swap-ex/market/history/trade":{cost:1},"swap-api/v1/swap_risk_info":{cost:1},"swap-api/v1/swap_insurance_fund":{cost:1},"swap-api/v1/swap_adjustfactor":{cost:1},"swap-api/v1/swap_his_open_interest":{cost:1},"swap-api/v1/swap_ladder_margin":{cost:1},"swap-api/v1/swap_api_state":{cost:1},"swap-api/v1/swap_elite_account_ratio":{cost:1},"swap-api/v1/swap_elite_position_ratio":{cost:1},"swap-api/v1/swap_estimated_settlement_price":{cost:1},"swap-api/v1/swap_liquidation_orders":{cost:1},"swap-api/v1/swap_settlement_records":{cost:1},"swap-api/v1/swap_funding_rate":{cost:1},"swap-api/v1/swap_batch_funding_rate":{cost:1},"swap-api/v1/swap_historical_funding_rate":{cost:1},"swap-api/v3/swap_liquidation_orders":{cost:1},"index/market/history/swap_estimated_rate_kline":{cost:1},"index/market/history/swap_basis":{cost:1},"linear-swap-api/v1/swap_contract_info":{cost:1},"linear-swap-api/v1/swap_index":{cost:1},"linear-swap-api/v1/swap_query_elements":{cost:1},"linear-swap-api/v1/swap_price_limit":{cost:1},"linear-swap-ex/market/depth":{cost:1},"linear-swap-ex/market/bbo":{cost:1},"linear-swap-ex/market/history/kline":{cost:1},"index/market/history/linear_swap_mark_price_kline":{cost:1},"linear-swap-ex/market/detail/merged":{cost:1},"linear-swap-ex/market/detail/batch_merged":{cost:1},"v2/linear-swap-ex/market/detail/batch_merged":{cost:1},"linear-swap-ex/market/trade":{cost:1},"linear-swap-ex/market/history/trade":{cost:1},"swap-api/v1/linear-swap-api/v1/swap_insurance_fund":{cost:1},"linear-swap-api/v1/swap_adjustfactor":{cost:1},"linear-swap-api/v1/swap_cross_adjustfactor":{cost:1},"linear-swap-api/v1/swap_his_open_interest":{cost:1},"linear-swap-api/v1/swap_ladder_margin":{cost:1},"linear-swap-api/v1/swap_cross_ladder_margin":{cost:1},"linear-swap-api/v1/swap_api_state":{cost:1},"linear-swap-api/v1/swap_elite_account_ratio":{cost:1},"linear-swap-api/v1/swap_elite_position_ratio":{cost:1},"linear-swap-api/v1/swap_settlement_records":{cost:1},"linear-swap-api/v3/swap_liquidation_orders":{cost:1},"index/market/history/linear_swap_premium_index_kline":{cost:1},"index/market/history/linear_swap_estimated_rate_kline":{cost:1},"index/market/history/linear_swap_basis":{cost:1},"linear-swap-api/v1/swap_estimated_settlement_price":{cost:1},"v5/market/funding_rate":{cost:.125},"v5/market/funding_rate_history":{cost:.125},"v5/market/open_interest":{cost:.125},"v5/market/liquidation_orders":{cost:.125},"v5/market/settlement_history":{cost:.125},"v5/market/elite_account_ratio":{cost:.125},"v5/market/elite_position_ratio":{cost:.125},"v5/market/estimated_settlement_price":{cost:.125},"v5/market/price_limit":{cost:.125}}},private:{get:{"api/v1/contract_sub_auth_list":{cost:1},"api/v1/contract_api_trading_status":{cost:1},"swap-api/v1/swap_sub_auth_list":{cost:1},"swap-api/v1/swap_api_trading_status":{cost:1},"v5/account/asset_mode":{cost:.20834},"v5/account/balance":{cost:.20834},"v5/account/bills":{cost:.20834},"v5/account/fee_deduction_currency":{cost:.20834},"v5/trade/position/opens":{cost:.41679},"v5/trade/order/opens":{cost:.41679},"v5/trade/order/details":{cost:.41679},"v5/trade/order/history":{cost:.41679},"v5/trade/order":{cost:.41679},"v5/position/lever":{cost:.20834},"v5/position/mode":{cost:.20834},"v5/position/risk/limit":{cost:.20834},"v5/position/risk/limit_tier":{cost:.20834},"v5/market/risk/limit":{cost:.125},"v5/market/assets_deduction_currency":{cost:.125},"v5/market/multi_assets_margin":{cost:.125},"v5/algo/order/opens":{cost:.41679},"v5/algo/order":{cost:.41679},"v5/algo/order/history":{cost:.41679},"api/v6/copyTrading/trader/instruments":{cost:2},"api/v6/copyTrading/trader/statistics":{cost:2},"api/v6/copyTrading/trader/profit-sharing-history":{cost:2},"api/v6/copyTrading/trader/profit-sharing-history-summary":{cost:2},"api/v6/copyTrading/trader/unrealized-profit-sharing-summary":{cost:2},"api/v6/copyTrading/trader/followers":{cost:2}},post:{"api/v1/contract_balance_valuation":{cost:1},"api/v1/contract_account_info":{cost:1},"api/v1/contract_position_info":{cost:1},"api/v1/contract_sub_auth":{cost:1},"api/v1/contract_sub_account_list":{cost:1},"api/v1/contract_sub_account_info_list":{cost:1},"api/v1/contract_sub_account_info":{cost:1},"api/v1/contract_sub_position_info":{cost:1},"api/v1/contract_financial_record":{cost:1},"api/v1/contract_financial_record_exact":{cost:1},"api/v1/contract_user_settlement_records":{cost:1},"api/v1/contract_order_limit":{cost:1},"api/v1/contract_fee":{cost:1},"api/v1/contract_transfer_limit":{cost:1},"api/v1/contract_position_limit":{cost:1},"api/v1/contract_account_position_info":{cost:1},"api/v1/contract_master_sub_transfer":{cost:1},"api/v1/contract_master_sub_transfer_record":{cost:1},"api/v1/contract_available_level_rate":{cost:1},"api/v3/contract_financial_record":{cost:1},"api/v3/contract_financial_record_exact":{cost:1},"api/v1/contract-cancel-after":{cost:1},"api/v1/contract_order":{cost:1},"api/v1/contract_batchorder":{cost:1},"api/v1/contract_cancel":{cost:1},"api/v1/contract_cancelall":{cost:1},"api/v1/contract_switch_lever_rate":{cost:30},"api/v1/lightning_close_position":{cost:1},"api/v1/contract_order_info":{cost:1},"api/v1/contract_order_detail":{cost:1},"api/v1/contract_openorders":{cost:1},"api/v1/contract_hisorders":{cost:1},"api/v1/contract_hisorders_exact":{cost:1},"api/v1/contract_matchresults":{cost:1},"api/v1/contract_matchresults_exact":{cost:1},"api/v3/contract_hisorders":{cost:1},"api/v3/contract_hisorders_exact":{cost:1},"api/v3/contract_matchresults":{cost:1},"api/v3/contract_matchresults_exact":{cost:1},"api/v1/contract_trigger_order":{cost:1},"api/v1/contract_trigger_cancel":{cost:1},"api/v1/contract_trigger_cancelall":{cost:1},"api/v1/contract_trigger_openorders":{cost:1},"api/v1/contract_trigger_hisorders":{cost:1},"api/v1/contract_tpsl_order":{cost:1},"api/v1/contract_tpsl_cancel":{cost:1},"api/v1/contract_tpsl_cancelall":{cost:1},"api/v1/contract_tpsl_openorders":{cost:1},"api/v1/contract_tpsl_hisorders":{cost:1},"api/v1/contract_relation_tpsl_order":{cost:1},"api/v1/contract_track_order":{cost:1},"api/v1/contract_track_cancel":{cost:1},"api/v1/contract_track_cancelall":{cost:1},"api/v1/contract_track_openorders":{cost:1},"api/v1/contract_track_hisorders":{cost:1},"swap-api/v1/swap_balance_valuation":{cost:1},"swap-api/v1/swap_account_info":{cost:1},"swap-api/v1/swap_position_info":{cost:1},"swap-api/v1/swap_account_position_info":{cost:1},"swap-api/v1/swap_sub_auth":{cost:1},"swap-api/v1/swap_sub_account_list":{cost:1},"swap-api/v1/swap_sub_account_info_list":{cost:1},"swap-api/v1/swap_sub_account_info":{cost:1},"swap-api/v1/swap_sub_position_info":{cost:1},"swap-api/v1/swap_financial_record":{cost:1},"swap-api/v1/swap_financial_record_exact":{cost:1},"swap-api/v1/swap_user_settlement_records":{cost:1},"swap-api/v1/swap_available_level_rate":{cost:1},"swap-api/v1/swap_order_limit":{cost:1},"swap-api/v1/swap_fee":{cost:1},"swap-api/v1/swap_transfer_limit":{cost:1},"swap-api/v1/swap_position_limit":{cost:1},"swap-api/v1/swap_master_sub_transfer":{cost:1},"swap-api/v1/swap_master_sub_transfer_record":{cost:1},"swap-api/v3/swap_financial_record":{cost:1},"swap-api/v3/swap_financial_record_exact":{cost:1},"swap-api/v1/swap-cancel-after":{cost:1},"swap-api/v1/swap_order":{cost:1},"swap-api/v1/swap_batchorder":{cost:1},"swap-api/v1/swap_cancel":{cost:1},"swap-api/v1/swap_cancelall":{cost:1},"swap-api/v1/swap_lightning_close_position":{cost:1},"swap-api/v1/swap_switch_lever_rate":{cost:30},"swap-api/v1/swap_order_info":{cost:1},"swap-api/v1/swap_order_detail":{cost:1},"swap-api/v1/swap_openorders":{cost:1},"swap-api/v1/swap_hisorders":{cost:1},"swap-api/v1/swap_hisorders_exact":{cost:1},"swap-api/v1/swap_matchresults":{cost:1},"swap-api/v1/swap_matchresults_exact":{cost:1},"swap-api/v3/swap_matchresults":{cost:1},"swap-api/v3/swap_matchresults_exact":{cost:1},"swap-api/v3/swap_hisorders":{cost:1},"swap-api/v3/swap_hisorders_exact":{cost:1},"swap-api/v1/swap_trigger_order":{cost:1},"swap-api/v1/swap_trigger_cancel":{cost:1},"swap-api/v1/swap_trigger_cancelall":{cost:1},"swap-api/v1/swap_trigger_openorders":{cost:1},"swap-api/v1/swap_trigger_hisorders":{cost:1},"swap-api/v1/swap_tpsl_order":{cost:1},"swap-api/v1/swap_tpsl_cancel":{cost:1},"swap-api/v1/swap_tpsl_cancelall":{cost:1},"swap-api/v1/swap_tpsl_openorders":{cost:1},"swap-api/v1/swap_tpsl_hisorders":{cost:1},"swap-api/v1/swap_relation_tpsl_order":{cost:1},"swap-api/v1/swap_track_order":{cost:1},"swap-api/v1/swap_track_cancel":{cost:1},"swap-api/v1/swap_track_cancelall":{cost:1},"swap-api/v1/swap_track_openorders":{cost:1},"swap-api/v1/swap_track_hisorders":{cost:1},"v5/account/asset_mode":{cost:100},"v5/trade/order":{cost:.41679},"v5/trade/batch_orders":{cost:.41679},"v5/trade/cancel_order":{cost:.41679},"v5/trade/cancel_batch_orders":{cost:.41679},"v5/trade/cancel_all_orders":{cost:.41679},"v5/trade/cancel-after":{cost:.41679},"v5/trade/position":{cost:.41679},"v5/trade/position_all":{cost:.41679},"v5/position/lever":{cost:.20834},"v5/position/mode":{cost:.20834},"v5/position/margin":{cost:.20834},"v5/account/fee_deduction_currency":{cost:.20834},"v5/algo/order":{cost:.41679},"v5/algo/cancel_orders":{cost:.41679},"api/v6/copyTrading/trader/follower":{cost:2},"api/v6/copyTrading/trader/transfer":{cost:2},"api/v6/copyTrading/trader/follower-settings":{cost:2},"api/v6/copyTrading/trader/config":{cost:2},"api/v6/copyTrading/trader/apikey":{cost:2}}}}},fees:{trading:{feeSide:"get",tierBased:!1,percentage:!0,maker:this.parseNumber("0.002"),taker:this.parseNumber("0.002")}},exceptions:{broad:{"contract is restricted of closing positions on API.  Please contact customer service":a.OnMaintenance,maintain:a.OnMaintenance,"API key has no permission":a.PermissionDenied},exact:{403:a.AuthenticationError,1010:a.AccountNotEnabled,1003:a.AuthenticationError,1013:a.BadSymbol,1017:a.OrderNotFound,1034:a.InvalidOrder,1036:a.InvalidOrder,1039:a.InvalidOrder,1041:a.InvalidOrder,1047:a.InsufficientFunds,1048:a.InsufficientFunds,1061:a.OrderNotFound,1051:a.InvalidOrder,1066:a.BadSymbol,1067:a.InvalidOrder,1094:a.InvalidOrder,1220:a.AccountNotEnabled,1303:a.BadRequest,1461:a.InvalidOrder,4007:a.BadRequest,"bad-request":a.BadRequest,"validation-format-error":a.BadRequest,"validation-constraints-required":a.BadRequest,"base-date-limit-error":a.BadRequest,"api-not-support-temp-addr":a.PermissionDenied,timeout:a.RequestTimeout,"gateway-internal-error":a.ExchangeNotAvailable,"account-frozen-balance-insufficient-error":a.InsufficientFunds,"invalid-amount":a.InvalidOrder,"order-limitorder-amount-min-error":a.InvalidOrder,"order-limitorder-amount-max-error":a.InvalidOrder,"order-marketorder-amount-min-error":a.InvalidOrder,"order-limitorder-price-min-error":a.InvalidOrder,"order-limitorder-price-max-error":a.InvalidOrder,"order-limitorder-price-buy-min-error":a.InvalidOrder,"order-limitorder-price-buy-max-error":a.InvalidOrder,"order-limitorder-price-sell-min-error":a.InvalidOrder,"order-limitorder-price-sell-max-error":a.InvalidOrder,"order-stop-order-hit-trigger":a.InvalidOrder,"order-value-min-error":a.InvalidOrder,"order-invalid-price":a.InvalidOrder,"order-holding-limit-failed":a.InvalidOrder,"order-orderprice-precision-error":a.InvalidOrder,"order-etp-nav-price-max-error":a.InvalidOrder,"order-orderstate-error":a.OrderNotFound,"order-queryorder-invalid":a.OrderNotFound,"order-update-error":a.ExchangeNotAvailable,"api-signature-check-failed":a.AuthenticationError,"api-signature-not-valid":a.AuthenticationError,"base-record-invalid":a.OrderNotFound,"base-symbol-trade-disabled":a.BadSymbol,"base-symbol-error":a.BadSymbol,"system-maintenance":a.OnMaintenance,"base-request-exceed-frequency-limit":a.RateLimitExceeded,"rate-too-many-requests":a.RateLimitExceeded,"invalid symbol":a.BadSymbol,"symbol trade not open now":a.BadSymbol,"require-symbol":a.BadSymbol,"invalid-address":a.BadRequest,"base-currency-chain-error":a.BadRequest,"dw-insufficient-balance":a.InsufficientFunds,"base-withdraw-fee-error":a.BadRequest,"dw-withdraw-min-limit":a.BadRequest,"request limit":a.RateLimitExceeded}},precisionMode:4,options:{include_OS_certificates:!1,fetchMarkets:{types:{spot:!0,linear:!0,inverse:!0}},timeDifference:0,adjustForTimeDifference:!1,fetchOHLCV:{useHistoricalEndpointForSpot:!0},withdraw:{includeFee:!1},defaultType:"spot",defaultSubType:"linear",defaultNetwork:"ERC20",defaultNetworks:{ETH:"ERC20",BTC:"BTC",USDT:"TRC20"},networks:{TRC20:"TRX",BTC:"BTC",ERC20:"ETH",SOL:"SOLANA",HRC20:"HECO",BEP20:"BSC",XMR:"XMR",LTC:"LTC",XRP:"XRP",XLM:"XLM",CRONOS:"CRO",CRO:"CRO",GLMR:"GLMR",POLYGON:"MATIC",MATIC:"MATIC",BTT:"BTT",CUBE:"CUBE",IOST:"IOST",NEO:"NEO",KLAY:"KLAY",EOS:"EOS",THETA:"THETA",NAS:"NAS",NULS:"NULS",QTUM:"QTUM",FTM:"FTM",CELO:"CELO",DOGE:"DOGE",DOGECHAIN:"DOGECHAIN",NEAR:"NEAR",STEP:"STEP",BITCI:"BITCI",CARDANO:"ADA",ADA:"ADA",ETC:"ETC",LUK:"LUK",MINEPLEX:"MINEPLEX",DASH:"DASH",ZEC:"ZEC",IOTA:"IOTA",NEON3:"NEON3",XEM:"XEM",HC:"HC",LSK:"LSK",DCR:"DCR",BTG:"BTG",STEEM:"STEEM",BTS:"BTS",ICX:"ICX",WAVES:"WAVES",CMT:"CMT",BTM:"BTM",VET:"VET",XZC:"XZC",ACT:"ACT",SMT:"SMT",BCD:"BCD",WAX:"WAX1",WICC:"WICC",ELF:"ELF",ZIL:"ZIL",ELA:"ELA",BCX:"BCX",SBTC:"SBTC",BIFI:"BIFI",CTXC:"CTXC",WAN:"WAN",POLYX:"POLYX",PAI:"PAI",WTC:"WTC",DGB:"DGB",XVG:"XVG",AAC:"AAC",AE:"AE",SEELE:"SEELE",BCV:"BCV",GRS:"GRS",ARDR:"ARDR",NANO:"NANO",ZEN:"ZEN",RBTC:"RBTC",BSV:"BSV",GAS:"GAS",XTZ:"XTZ",LAMB:"LAMB",CVNT1:"CVNT1",DOCK:"DOCK",SC:"SC",KMD:"KMD",ETN:"ETN",TOP:"TOP",IRIS:"IRIS",UGAS:"UGAS",TT:"TT",NEWTON:"NEWTON",VSYS:"VSYS",FSN:"FSN",BHD:"BHD",ONE:"ONE",EM:"EM",CKB:"CKB",EOSS:"EOSS",HIVE:"HIVE",RVN:"RVN",DOT:"DOT",KSM:"KSM",BAND:"BAND",OEP4:"OEP4",NBS:"NBS",FIS:"FIS",AR:"AR",HBAR:"HBAR",FIL:"FIL",MASS:"MASS",KAVA:"KAVA",XYM:"XYM",ENJ:"ENJ",CRUST:"CRUST",ICP:"ICP",CSPR:"CSPR",FLOW:"FLOW",IOTX:"IOTX",LAT:"LAT",APT:"APT",XCH:"XCH",MINA:"MINA",XEC:"ECASH",XPRT:"XPRT",CCA:"ACA",AOTI:"COTI",AKT:"AKT",ARS:"ARS",ASTR:"ASTR",AZERO:"AZERO",BLD:"BLD",BRISE:"BRISE",CORE:"CORE",DESO:"DESO",DFI:"DFI",EGLD:"EGLD",ERG:"ERG",ETHF:"ETHFAIR",ETHW:"ETHW",EVMOS:"EVMOS",FIO:"FIO",FLR:"FLR",FINSCHIA:"FINSCHIA",KMA:"KMA",KYVE:"KYVE",MEV:"MEV",MOVR:"MOVR",NODL:"NODL",OAS:"OAS",OSMO:"OSMO",PAYCOIN:"PAYCOIN",POKT:"POKT",PYG:"PYG",REI:"REI",SCRT:"SCRT",SDN:"SDN",SEI:"SEI",SGB:"SGB",SUI:"SUI",SXP:"SOLAR",SYS:"SYS",TENET:"TENET",TON:"TON",UNQ:"UNQ",UYU:"UYU",WEMIX:"WEMIX",XDC:"XDC",XPLA:"XPLA"},networksById:{MATIC:"MATIC"},fetchOrdersByStatesMethod:"spot_private_get_v1_order_orders",createMarketBuyOrderRequiresPrice:!0,language:"en-US",broker:{id:"AA03022abc"},accountsByType:{spot:"pro",funding:"pro",future:"futures"},accountsById:{spot:"spot",margin:"margin",otc:"otc",point:"point","super-margin":"super-margin",investment:"investment",borrow:"borrow","grid-trading":"grid-trading","deposit-earning":"deposit-earning","otc-options":"otc-options","linear-swap":"swap",swap:"swap",futures:"future"},typesByAccount:{pro:"spot",futures:"future"},spot:{stopOrderTypes:{"stop-limit":!0,"buy-stop-limit":!0,"sell-stop-limit":!0,"stop-limit-fok":!0,"buy-stop-limit-fok":!0,"sell-stop-limit-fok":!0},limitOrderTypes:{limit:!0,"buy-limit":!0,"sell-limit":!0,ioc:!0,"buy-ioc":!0,"sell-ioc":!0,"limit-maker":!0,"buy-limit-maker":!0,"sell-limit-maker":!0,"stop-limit":!0,"buy-stop-limit":!0,"sell-stop-limit":!0,"limit-fok":!0,"buy-limit-fok":!0,"sell-limit-fok":!0,"stop-limit-fok":!0,"buy-stop-limit-fok":!0,"sell-stop-limit-fok":!0}}},commonCurrencies:{NGL:"GFNGL",GET:"THEMIS",GTC:"GAMECOM",HIT:"HITCHAIN",PNT:"PENTA",SBTC:"SUPERBITCOIN",SOUL:"SOULSAVER",BIFI:"BITCOINFILE",FUD:"FTX Users Debt"},features:{spot:{sandbox:!0,createOrder:{marginMode:!0,triggerPrice:!0,triggerDirection:!0,triggerPriceType:void 0,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,iceberg:!1,selfTradePrevention:!0,leverage:!0,marketBuyByCost:!0,marketBuyRequiresPrice:!0},createOrders:{max:10},fetchMyTrades:{marginMode:!1,limit:500,daysBack:120,untilDays:2,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,trigger:!0,trailing:!1,limit:500,symbolRequired:!1},fetchOrders:{marginMode:!1,trigger:!0,trailing:!1,limit:500,untilDays:2,daysBack:180,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,trigger:!0,trailing:!1,untilDays:2,limit:500,daysBack:180,daysBackCanceled:1/12,symbolRequired:!1},fetchOHLCV:{limit:1e3}},forDerivatives:{extends:"spot",createOrder:{stopLossPrice:!0,takeProfitPrice:!0,trailing:!0,hedged:!0},createOrders:{max:25},fetchOrder:{marginMode:!0},fetchOpenOrders:{marginMode:!0,trigger:!0,trailing:!0,limit:50},fetchOrders:{marginMode:!0,trigger:!0,trailing:!0,limit:50,daysBack:90},fetchClosedOrders:{marginMode:!0,trigger:!0,trailing:!0,untilDays:2,limit:50,daysBack:90,daysBackCanceled:1/12},fetchOHLCV:{limit:2e3}},swap:{linear:{extends:"forDerivatives"},inverse:{extends:"forDerivatives"}},future:{linear:{extends:"forDerivatives"},inverse:{extends:"forDerivatives"}}},rollingWindowSize:2e3})}async fetchStatus(e={}){let t,i,s,[r,a]=this.handleMarketTypeAndParams("fetchStatus",void 0,e);if("spot"===r){s=await this.spotPublicGetV2MarketStatus(a);let e=this.safeDict(s,"data",{});t=1===this.safeInteger(e,"marketStatus")?"ok":"maintenance",i=this.safeInteger(e,"haltEndTime")}else{let[e,o]=this.handleSubTypeAndParams("fetchStatus",void 0,a);s=await this.contractPublicGetHeartbeat(o);let n=this.safeDict(s,"data",{}),d="heartbeat",h="estimated_recovery_time";"linear"===e?(d="linear_swap_heartbeat",h="linear_swap_estimated_recovery_time"):"swap"===r&&(d="swap_heartbeat",h="swap_estimated_recovery_time"),t=1===this.safeInteger(n,d)?"ok":"maintenance",i=this.safeInteger(n,h)}return{status:t,updated:void 0,eta:i,url:void 0,info:s}}async fetchTime(e={}){let t,i=this.safeDict(this.options,"fetchTime",{}),s=this.safeString(this.options,"defaultType","spot"),r=this.safeString(i,"type",s);return t="future"===(r=this.safeString(e,"type",r))||"swap"===r?await this.contractPublicGetApiV1Timestamp(e):await this.spotPublicGetV1CommonTimestamp(e),this.safeInteger2(t,"data","ts")}parseTradingFee(e,t){let i=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(i,t),maker:this.safeNumber(e,"actualMakerRate"),taker:this.safeNumber(e,"actualTakerRate"),percentage:void 0,tierBased:void 0}}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbols:i.id},r=await this.spotPrivateGetV2ReferenceTransactFeeRate(this.extend(s,t)),a=this.safeList(r,"data",[]),o=this.safeDict(a,0,{});return this.parseTradingFee(o,i)}async fetchTradingLimits(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=e;if(void 0===e&&(i=this.symbols),void 0===i)throw new a.ExchangeError(this.id+" markets not loaded");let s={};for(let e=0;e<i.length;e++){let r=i[e];s[r]=await this.fetchTradingLimitsById(this.marketId(r),t)}return s}async fetchTradingLimitsById(e,t={}){let i=await this.spotPublicGetV1CommonExchange(this.extend({symbol:e},t));return this.parseTradingLimits(this.safeDict(i,"data",{}))}parseTradingLimits(e,t,i={}){return{info:e,limits:{amount:{min:this.safeNumber(e,"limit-order-must-greater-than"),max:this.safeNumber(e,"limit-order-must-less-than")}}}}costToPrecision(e,t){return this.decimalToPrecision(t,0,this.market(e).precision.cost,this.precisionMode)}async fetchMarkets(e={}){this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference();let t={},i={};[t,i]=this.handleOptionAndParams(e,"fetchMarkets","types",{});let s=[],r=[],a=Object.keys(t);for(let e=0;e<a.length;e++){let s=a[e];this.safeBool(t,s,!1)&&("spot"===s?r.push(this.fetchMarketsByTypeAndSubType("spot",void 0,i)):"linear"===s?r.push(this.fetchMarketsByTypeAndSubType(void 0,"linear",i)):"inverse"===s&&(r.push(this.fetchMarketsByTypeAndSubType("swap","inverse",i)),r.push(this.fetchMarketsByTypeAndSubType("future","inverse",i))))}r=await Promise.all(r);for(let e=0;e<r.length;e++)s=this.arrayConcat(s,r[e]);return s}async fetchMarketsByTypeAndSubType(e,t,i={}){let s,r={};"spot"===e?s=await this.spotPublicGetV1CommonSymbols(this.extend(r,i)):"linear"===t?(r.business_type="all",s=await this.contractPublicGetLinearSwapApiV1SwapContractInfo(this.extend(r,i))):"inverse"===t&&("future"===e?s=await this.contractPublicGetApiV1ContractContractInfo(this.extend(r,i)):"swap"===e&&(s=await this.contractPublicGetSwapApiV1SwapContractInfo(this.extend(r,i))));let n=this.safeList(s,"data",[]);if(n.length<1)throw new a.OperationFailed(this.id+" fetchMarkets() returned an empty response: "+this.json(s));let d=[];for(let e=0;e<n.length;e++){let t,i,s,r,h,c,l,u,f,p,m,g,v,y,b,w,k=n[e],S="contract_code"in k,O=!S,T=!1,P=!1;if(S){if(void 0===(h=this.safeString(k,"contract_code")))throw new a.ExchangeError(this.id+" method() missing id");c=h.toLowerCase();let e=this.safeString(k,"delivery_date"),o=this.safeString(k,"business_type");if(T=!(P=void 0!==e),u=!(l=void 0!==o),T){if(t="swap",void 0===h)throw new a.ExchangeError(this.id+" method() missing id");let e=h.split("-");i=this.safeStringLower(k,"symbol"),s=this.safeStringLower(e,1),r=u?i:s}else if(P)if(t="future",i=this.safeStringLower(k,"symbol"),u)s="USD",r=i;else{let e=this.safeString(k,"pair");if(void 0===e)throw new a.ExchangeError(this.id+" method() missing pair");let t=e.split("-");r=s=this.safeStringLower(t,1)}}else{if(t="spot",i=this.safeString(k,"base-currency"),void 0===(s=this.safeString(k,"quote-currency")))throw new a.ExchangeError(this.id+" method() missing quoteId");if(void 0===i)throw new a.ExchangeError(this.id+" method() missing baseId");c=(h=i+s).toLowerCase()}let I=this.safeCurrencyCode(i),A=this.safeCurrencyCode(s);if(void 0===I||void 0===A)continue;let x=this.safeCurrencyCode(r),M=I+"/"+A;S&&(!0===u?M+=":"+I:!0===l&&(M+=":"+A),P&&(f=this.safeInteger(k,"delivery_time"),M+="-"+this.yymmdd(f)));let _=this.safeNumber(k,"contract_size"),C=this.safeNumber(k,"min-order-value"),B=this.safeNumber(k,"max-order-amt"),E=this.safeNumber(k,"min-order-amt");S&&(!0===l?E=_:!0===u&&(C=_)),O?(p=this.parseNumber(this.parsePrecision(this.safeString(k,"price-precision"))),m=this.parseNumber(this.parsePrecision(this.safeString(k,"amount-precision"))),g=this.parseNumber(this.parsePrecision(this.safeString(k,"value-precision"))),v=this.parseNumber("0.002"),y=this.parseNumber("0.002"),b="online"===this.safeString(k,"state")):(p=this.safeNumber(k,"price_tick"),m=this.parseNumber("1"),v=this.parseNumber("0.0002"),y=this.parseNumber("0.0005"),b=1===this.safeInteger(k,"contract_status"));let R=this.safeString(k,"leverage-ratio","1"),L=this.safeString(k,"super-margin-leverage-ratio","1"),N=o.Y.stringGt(R,"1")||o.Y.stringGt(L,"1"),D=this.safeString(k,"create_date");if(void 0!==D){let e=this.stringToCharsArray(D);D=e[0]+e[1]+e[2]+e[3]+"-"+e[4]+e[5]+"-"+e[6]+e[7]+" 00:00:00",w=this.parse8601(D)}d.push({id:h,lowercaseId:c,symbol:M,base:I,quote:A,settle:x,baseId:i,quoteId:s,settleId:r,type:t,spot:O,margin:O&&N,swap:T,future:P,option:!1,active:b,contract:S,linear:l,inverse:u,taker:y,maker:v,contractSize:_,expiry:f,expiryDatetime:this.iso8601(f),strike:void 0,optionType:void 0,precision:{amount:m,price:p,cost:g},limits:{leverage:{min:this.parseNumber("1"),max:this.parseNumber(R),superMax:this.parseNumber(L)},amount:{min:E,max:B},price:{min:void 0,max:void 0},cost:{min:C,max:void 0}},created:w,info:k})}return d}tryGetSymbolFromFutureMarkets(e){if(void 0!==this.markets&&e in this.markets)return e;"futureMarketIdsForSymbols"in this.options||(this.options.futureMarketIdsForSymbols={});let t=this.safeDict(this.options,"futureMarketIdsForSymbols",{});if(e in t)return t[e];let i=this.filterBy(this.markets,"future",!0),s={this_week:"CW",next_week:"NW",quarter:"CQ",next_quarter:"NQ"};for(let t=0;t<i.length;t++){let r=i[t],a=this.safeDict(r,"info",{}),o=this.safeString(a,"contract_type"),n=this.safeString(s,o);if(void 0!==n&&(!0===r.linear?r.base+"-"+r.quote+"-"+n:r.base+"_"+n)===e){let t=r.symbol;return this.options.futureMarketIdsForSymbols[e]=t,t}}return this.options.futureMarketIdsForSymbols[e]=e,e}parseTicker(e,t){let i,s,r,a,o=this.safeString2(e,"symbol","contract_code"),n=this.safeSymbol(o,t);n=this.tryGetSymbolFromFutureMarkets(n);let d=this.safeInteger2(e,"ts","quoteTime");"bid"in e&&(void 0!==e.bid&&Array.isArray(e.bid)?(i=this.safeString(e.bid,0),s=this.safeString(e.bid,1)):(i=this.safeString(e,"bid"),s=this.safeString(e,"bidSize"))),"ask"in e&&(void 0!==e.ask&&Array.isArray(e.ask)?(r=this.safeString(e.ask,0),a=this.safeString(e.ask,1)):(r=this.safeString(e,"ask"),a=this.safeString(e,"askSize")));let h=this.safeString(e,"open"),c=this.safeString(e,"close"),l=this.safeString(e,"amount"),u=this.safeString(e,"vol");return this.safeTicker({symbol:n,timestamp:d,datetime:this.iso8601(d),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:i,bidVolume:s,ask:r,askVolume:a,vwap:void 0,open:h,close:c,last:c,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:l,quoteVolume:u,info:e},t)}async fetchTicker(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={};!0===s.linear?(r.contract_code=s.id,i=await this.contractPublicGetLinearSwapExMarketDetailMerged(this.extend(r,t))):!0===s.inverse?!0===s.future?(r.symbol=s.id,i=await this.contractPublicGetMarketDetailMerged(this.extend(r,t))):!0===s.swap&&(r.contract_code=s.id,i=await this.contractPublicGetSwapExMarketDetailMerged(this.extend(r,t))):(r.symbol=s.id,i=await this.spotPublicGetMarketDetailMerged(this.extend(r,t)));let a=this.safeDict(i,"tick",{}),o=this.parseTicker(a,s),n=this.safeInteger(i,"ts");return o.timestamp=n,o.datetime=this.iso8601(n),o}async fetchTickers(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e),o=this.safeString(r,0);void 0!==o&&(i=this.market(o));let n="subType"in t||"business_type"in t,[d,h]=this.handleMarketTypeAndParams("fetchTickers",i,t),[c,l]=this.handleSubTypeAndParams("fetchTickers",i,h),u={},f="future"===d,p="swap"===d;if("spot"!==d||n)if("linear"===c)f?u.business_type="futures":p?u.business_type="swap":u.business_type="all",s=await this.contractPublicGetLinearSwapExMarketDetailBatchMerged(this.extend(u,l));else if("inverse"===c)if(f)s=await this.contractPublicGetMarketDetailBatchMerged(this.extend(u,l));else if(p)s=await this.contractPublicGetSwapExMarketDetailBatchMerged(this.extend(u,l));else throw new a.NotSupported(this.id+' fetchTickers() you have to set params["type"] to either "swap" or "future" for inverse contracts');else throw new a.NotSupported(this.id+' fetchTickers() you have to set params["subType"] to either "linear" or "inverse" for contracts');else s=await this.spotPublicGetMarketTickers(this.extend(u,l));let m=this.safeList2(s,"data","ticks",[]),g=this.parseTickers(m,r,l);return this.filterByArrayTickers(g,"symbol",r)}async fetchLastPrices(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e),r=this.getMarketFromSymbols(s),[o,n]=this.handleSubTypeAndParams("fetchLastPrices",r,t),[d,h]=this.handleMarketTypeAndParams("fetchLastPrices",r,n);if(("swap"===d||"future"===d)&&"linear"===o)i=await this.contractPublicGetLinearSwapExMarketTrade(h);else if("swap"===d&&"inverse"===o)i=await this.contractPublicGetSwapExMarketTrade(h);else if("future"===d&&"inverse"===o)i=await this.contractPublicGetMarketTrade(h);else throw new a.NotSupported(this.id+" fetchLastPrices() does not support "+d+" markets yet");let c=this.safeDict(i,"tick",{}),l=this.safeList(c,"data",[]);return this.parseLastPrices(l,s)}parseLastPrice(e,t){let i=this.safeString2(e,"symbol","contract_code"),s=this.safeMarket(i,t),r=this.safeNumber(e,"price"),a=this.safeString(e,"direction");return{symbol:s.symbol,timestamp:void 0,datetime:void 0,price:r,side:a,info:e}}async fetchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={type:"step0"};if(!0===r.linear)o.contract_code=r.id,s=await this.contractPublicGetLinearSwapExMarketDepth(this.extend(o,i));else if(!0===r.inverse)!0===r.future?(o.symbol=r.id,s=await this.contractPublicGetMarketDepth(this.extend(o,i))):!0===r.swap&&(o.contract_code=r.id,s=await this.contractPublicGetSwapExMarketDepth(this.extend(o,i)));else{if(void 0!==t){if(5!==t&&10!==t&&20!==t&&150!==t)throw new a.BadRequest(this.id+" fetchOrderBook() limit argument must be undefined, 5, 10, 20, or 150, default is 150");150!==t&&(o.depth=t)}o.symbol=r.id,s=await this.spotPublicGetMarketDepth(this.extend(o,i))}if(void 0===s)throw new a.NullResponse(this.id+" fetchOrderBook() returned empty response");if("tick"in s){if(void 0===s.tick||null===s.tick)throw new a.BadSymbol(this.id+" fetchOrderBook() returned empty response: "+this.json(s));let t=this.safeDict(s,"tick"),i=this.safeInteger(t,"ts",this.safeInteger(s,"ts")),r=this.parseOrderBook(t,e,i);return r.nonce=this.safeInteger(t,"version"),r}throw new a.ExchangeError(this.id+" fetchOrderBook() returned unrecognized response: "+this.json(s))}parseTrade(e,t){let i,s,r=this.safeString2(e,"contract_code","symbol"),a=this.safeMarket(r,t),n=a.symbol,d=this.safeIntegerN(e,["ts","created-at","created_at","create_date","created_time"]),h=this.safeString2(e,"order-id","order_id"),c=this.safeString2(e,"direction","side"),l=this.safeString(e,"type");if(void 0!==l&&l.indexOf("-")>=0){let e=l.split("-");c=e[0],l=e[1]}let u=this.safeStringLower(e,"role"),f=this.safeString2(e,"price","trade_price"),p=this.safeString2(e,"filled-amount","amount");p=this.safeString(e,"trade_volume",p);let m=this.safeString(e,"trade_turnover"),g=this.safeString(e,"filled-fees");void 0===g&&(g=o.Y.stringNeg(this.safeString(e,"trade_fee")));let v=this.safeStringN(e,["fee-currency","fee_asset","fee_currency"]),y=this.safeCurrencyCode(v),b=this.safeString(e,"filled-points");if(void 0!==b&&(void 0===g||o.Y.stringEquals(g,"0"))){let t=this.safeString(e,"fee-deduct-currency");void 0!==t&&(g=b,y=this.safeCurrencyCode(t))}void 0!==g&&(i={cost:g,currency:y});let w=this.safeString(e,"id");return s=void 0!==w&&w.indexOf("-")>=0?w:this.safeStringN(e,["trade_id","trade-id","id"]),this.safeTrade({id:s,info:e,order:h,timestamp:d,datetime:this.iso8601(d),symbol:n,type:l,side:c,takerOrMaker:u,price:f,amount:p,cost:m,fee:i},a)}async fetchOrderTrades(e,t,i,s,r={}){let o;void 0!==t&&(o=this.market(t));let[n,d]=this.handleMarketTypeAndParams("fetchOrderTrades",o,r);if("spot"!==n)throw new a.NotSupported(this.id+" fetchOrderTrades() is only supported for spot markets");return await this.fetchSpotOrderTrades(e,t,i,s,d)}async fetchSpotOrderTrades(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=await this.spotPrivateGetV1OrderOrdersOrderIdMatchresults(this.extend({"order-id":e},r)),o=this.safeList(a,"data",[]);return this.parseTrades(o,void 0,i,s)}async fetchMyTrades(e,t,i,s={}){let r,o,n;void 0===this.markets&&await this.loadMarkets();let[d,h]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(d)return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,h);void 0!==e&&(r=this.market(e));let[c,l]=this.handleMarketTypeAndParams("fetchMyTrades",r,h),u={};if("spot"===c)void 0!==e&&(r=this.market(e),u.symbol=r.id),void 0!==i&&(u.size=i),void 0!==t&&(u["start-time"]=t),[u,o]=this.handleUntilOption("end-time",u,l),n=await this.spotPrivateGetV1OrderMatchresults(this.extend(u,o));else{if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");if(void 0!==t&&(u.start_time=t),[u,o]=this.handleUntilOption("end_time",u,l),this.safeBool(r,"linear",!1))u.contract_code=this.safeString(r,"id"),void 0!==i&&(u.limit=i),n=await this.contractPrivateGetV5TradeOrderDetails(this.extend(u,o));else if(this.safeBool(r,"inverse",!1))if(void 0!==i&&(u.page_size=i),u.contract=this.safeString(r,"id"),u.trade_type=0,"future"===c)u.symbol=this.safeString(r,"settleId"),n=await this.contractPrivatePostApiV3ContractMatchresultsExact(this.extend(u,o));else if("swap"===c)n=await this.contractPrivatePostSwapApiV3SwapMatchresultsExact(this.extend(u,o));else throw new a.NotSupported(this.id+" fetchMyTrades() does not support "+c+" markets")}let f=this.safeValue(n,"data");return Array.isArray(f)||(f=this.safeList(f,"trades")),this.parseTrades(f,r,t,i)}async fetchTrades(e,t,i=1e3,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={};void 0!==i&&(o.size=Math.min(i,2e3)),!0===a.future?!0===a.inverse?(o.symbol=a.id,r=await this.contractPublicGetMarketHistoryTrade(this.extend(o,s))):!0===a.linear&&(o.contract_code=a.id,r=await this.contractPublicGetLinearSwapExMarketHistoryTrade(this.extend(o,s))):!0===a.swap?(o.contract_code=a.id,!0===a.inverse?r=await this.contractPublicGetSwapExMarketHistoryTrade(this.extend(o,s)):!0===a.linear&&(r=await this.contractPublicGetLinearSwapExMarketHistoryTrade(this.extend(o,s)))):(o.symbol=a.id,r=await this.spotPublicGetMarketHistoryTrade(this.extend(o,s)));let n=this.safeList(r,"data",[]),d=[];for(let e=0;e<n.length;e++){let t=this.safeList(n[e],"data",[]);for(let e=0;e<t.length;e++){let i=this.parseTrade(t[e],a);d.push(i)}}return d=this.sortBy(d,"timestamp"),this.filterBySymbolSinceLimit(d,this.safeString(a,"symbol"),t,i)}parseOHLCV(e,t){return[this.safeTimestamp(e,"id"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"amount")]}async fetchOHLCV(e,t="1m",i,s,r={}){let o;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(n)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,d,1e3);let h=this.market(e),c={period:this.safeString(this.timeframes,t,t)},l=this.safeString2(d,"priceType","price"),u=this.omit(d,["priceType","price"]),[f,p]=this.handleParamInteger(u,"until"),m=void 0!==f?this.parseToInt(f/1e3):void 0,g=!0===h.contract,v=void 0!==s?s:2e3,y=s;if(g&&(y=v),g&&(void 0!==s&&(c.size=Math.min(s,2e3)),void 0===l)){let e,s=this.parseTimeframe(t);if(void 0===i){let t=this.seconds();c.from=t-s*(v-1),e=t}else{let t=this.parseToInt(i/1e3);c.from=t,e=this.sum(t,s*(v-1))}c.to=void 0!==m?m:e}if(!0===h.future){if(!0===h.inverse)if(c.symbol=h.id,"mark"===l)o=await this.contractPublicGetIndexMarketHistoryMarkPriceKline(this.extend(c,p));else if("index"===l)o=await this.contractPublicGetIndexMarketHistoryIndex(this.extend(c,p));else if("premiumIndex"===l)throw new a.BadRequest(this.id+" "+h.type+" has no api endpoint for "+l+" kline data");else o=await this.contractPublicGetMarketHistoryKline(this.extend(c,p));else if(!0===h.linear)if(c.contract_code=h.id,"mark"===l)o=await this.contractPublicGetIndexMarketHistoryLinearSwapMarkPriceKline(this.extend(c,p));else if("index"===l)throw new a.BadRequest(this.id+" "+h.type+" has no api endpoint for "+l+" kline data");else o="premiumIndex"===l?await this.contractPublicGetIndexMarketHistoryLinearSwapPremiumIndexKline(this.extend(c,p)):await this.contractPublicGetLinearSwapExMarketHistoryKline(this.extend(c,p))}else if(!0===h.swap){if(c.contract_code=h.id,!0===h.inverse)if("mark"===l)o=await this.contractPublicGetIndexMarketHistorySwapMarkPriceKline(this.extend(c,p));else if("index"===l)throw new a.BadRequest(this.id+" "+h.type+" has no api endpoint for "+l+" kline data");else o="premiumIndex"===l?await this.contractPublicGetIndexMarketHistorySwapPremiumIndexKline(this.extend(c,p)):await this.contractPublicGetSwapExMarketHistoryKline(this.extend(c,p));else if(!0===h.linear)if("mark"===l)o=await this.contractPublicGetIndexMarketHistoryLinearSwapMarkPriceKline(this.extend(c,p));else if("index"===l)throw new a.BadRequest(this.id+" "+h.type+" has no api endpoint for "+l+" kline data");else o="premiumIndex"===l?await this.contractPublicGetIndexMarketHistoryLinearSwapPremiumIndexKline(this.extend(c,p)):await this.contractPublicGetLinearSwapExMarketHistoryKline(this.extend(c,p))}else{c.symbol=h.id;let[e,t]=this.handleOptionBoolAndParams(p,"fetchOHLCV","useHistoricalEndpointForSpot",!0);e?(void 0!==i&&(c.from=this.parseToInt(i/1e3)),void 0!==m&&(c.to=m),void 0!==s&&(c.size=Math.min(1e3,s)),o=await this.spotPublicGetMarketHistoryCandles(this.extend(c,t))):(void 0!==s&&(c.size=Math.min(s,2e3)),o=await this.spotPublicGetMarketHistoryKline(this.extend(c,t)))}let b=this.safeList(o,"data",[]);return this.parseOHLCVs(b,h,t,i,y)}async fetchAccounts(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.spotPrivateGetV1AccountAccounts(e),i=this.safeList(t,"data");return this.parseAccounts(i)}parseAccount(e){let t=this.safeString(e,"type"),i=this.safeDict(this.options,"accountsById",{}),s=this.safeString(i,t,t);return{info:e,id:this.safeString(e,"id"),type:s,code:void 0}}async fetchAccountIdByType(e,t,i,s={}){let r,a=await this.loadAccounts(),o=this.safeString2(s,"accountId","account-id");if(void 0!==o)return o;let n=e;"spot"===e&&("cross"===t?n="super-margin":"isolated"===t&&(n="margin")),void 0!==i&&(r=this.marketId(i));for(let e=0;e<a.length;e++){let t=this.safeDict(a,e),i=this.safeDict(t,"info"),s=this.safeString(i,"subtype"),o=this.safeString(t,"type");if("margin"===n){if(s===r)return this.safeString(t,"id")}else if(n===o)return this.safeString(t,"id")}let d=this.safeDict(a,0,{});return this.safeString(d,"id")}async fetchCurrencies(e={}){let t=await this.spotPublicGetV2ReferenceCurrencies(e),i=this.safeList(t,"data",[]);return this.options.networkNamesByChainIds={},this.options.networkChainIdsByNames={},this.parseCurrencies(i)}parseCurrency(e){"networkNamesByChainIds"in this.options||(this.options.networkNamesByChainIds={}),"networkChainIdsByNames"in this.options||(this.options.networkChainIdsByNames={});let t=this.safeString(e,"currency"),i=this.safeCurrencyCode(t),s=this.safeString(e,"assetType"),r="fiat";"1"===s&&(r="crypto"),void 0!==i&&(this.options.networkChainIdsByNames[i]={});let a=this.safeList(e,"chains",[]),o={};for(let e=0;e<a.length;e++){let t=a[e],s=this.safeString(t,"chain"),r=this.safeString2(t,"baseChain","displayName");void 0!==i&&void 0!==r&&(this.options.networkChainIdsByNames[i][r]=s),void 0!==s&&(this.options.networkNamesByChainIds[s]=r);let n=this.networkIdToCode(s,i);void 0!==n&&(o[n]={info:t,id:s,network:n,limits:{deposit:{min:this.safeNumber(t,"minDepositAmt"),max:void 0},withdraw:{min:this.safeNumber(t,"minWithdrawAmt"),max:this.safeNumber(t,"maxWithdrawAmt")}},active:void 0,deposit:"allowed"===this.safeString(t,"depositStatus"),withdraw:"allowed"===this.safeString(t,"withdrawStatus"),fee:this.safeNumber(t,"transactFeeWithdraw"),precision:this.parseNumber(this.parsePrecision(this.safeString(t,"withdrawPrecision")))})}return this.safeCurrencyStructure({info:e,code:i,id:t,active:"normal"===this.safeString(e,"instStatus"),deposit:void 0,withdraw:void 0,fee:void 0,name:void 0,type:r,limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},precision:void 0,networks:o})}networkIdToCode(e,t){if(void 0===e)return;if(0===Object.keys(this.options.networkNamesByChainIds).length)throw new a.ExchangeError(this.id+" networkIdToCode() - markets need to be loaded at first");let i=this.safeString(this.options.networkNamesByChainIds,e,e);return super.networkIdToCode(i,t)}networkCodeToId(e,t){if(void 0===e)return;if(void 0===t)return super.networkCodeToId(e);if(0===Object.keys(this.options.networkChainIdsByNames).length)throw new a.ExchangeError(this.id+" networkCodeToId() - markets need to be loaded at first");let i=this.safeDict(this.options.networkChainIdsByNames,t,{});if(e in i)return i[e];{let s=super.networkCodeToId(e,t);return this.safeString(i,s,s)}}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionBoolAndParams2(e,"fetchBalance","unified","uta",!1);if(i)throw new a.NotSupported(this.id+" fetchBalance() unified account has been deprecated on htx");let[r,o]=this.handleMarketTypeAndParams("fetchBalance",void 0,s),[n,d]=this.handleOptionStringAndParams2(o,"fetchBalance","defaultSubType","subType"),h=void 0===n?"linear":n,[c,l]=this.handleOptionBoolAndParams(d,"fetchBalance","multiAssetMode",!1),u={},f="spot"===r,p="future"===r,m="swap"===r,g="inverse"===h,v="linear"===h,[y,b]=this.handleMarginModeAndParams("fetchBalance",l),w="isolated"===y,k="margin"===r||f&&("cross"===y||w);if(c||v&&(m||p))t=await this.contractPrivateGetV5AccountBalance(this.extend(u,b));else if(f||k)if(k)t=w?await this.spotPrivateGetV1MarginAccountsBalance(this.extend(u,b)):await this.spotPrivateGetV1CrossMarginAccountsBalance(this.extend(u,b));else{await this.loadAccounts();let e=await this.fetchAccountIdByType(r,void 0,void 0,b);u["account-id"]=e,t=await this.spotPrivateGetV1AccountAccountsAccountIdBalance(this.extend(u,b))}else g&&(t=p?await this.contractPrivatePostApiV1ContractAccountInfo(this.extend(u,b)):await this.contractPrivatePostSwapApiV1SwapAccountInfo(this.extend(u,b)));let S={info:t},O=this.safeValue(t,"data");if(c||v&&(m||p)){let e=this.safeList(O,"details",[]);for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s=this.safeString(i,"currency"),r=this.safeCurrencyCode(s),a=this.account();a.free=this.safeString(i,"available_margin"),a.total=this.safeString(i,"equity"),void 0!==r&&(S[r]=a)}S=this.safeBalance(S)}else if(f||k)if(w){for(let e=0;e<O.length;e++){let t=this.safeDict(O,e),i=this.safeValue(t,"list"),s={};for(let e=0;e<i.length;e++){let t=i[e],r=this.safeString(t,"currency"),a=this.safeCurrencyCode(r);void 0!==a&&(s[a]=this.parseMarginBalanceHelper(t,a,s))}let r=Object.keys(s);for(let e=0;e<r.length;e++){let t=r[e];S=this.mergeBalanceAccount(S,t,s[t])}}S=this.safeBalance(S)}else{let e=this.safeList(O,"list",[]);for(let t=0;t<e.length;t++){let i=e[t],s=this.safeString(i,"currency"),r=this.safeCurrencyCode(s);void 0!==r&&(S[r]=this.parseMarginBalanceHelper(i,r,S))}S=this.safeBalance(S)}else if(g){for(let e=0;e<O.length;e++){let t=this.safeDict(O,e),i=this.safeString(t,"symbol"),s=this.safeCurrencyCode(i),r=this.account();r.free=this.safeString(t,"margin_available"),r.used=this.safeString(t,"margin_frozen"),void 0!==s&&(S[s]=r)}S=this.safeBalance(S)}return S}async fetchOrder(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let[o,n]=this.handleMarketTypeAndParams("fetchOrder",s,i),d={};if("spot"===o)void 0!==this.safeString(n,"clientOrderId")?r=await this.spotPrivateGetV1OrderOrdersGetClientOrder(this.extend(d,n)):(d["order-id"]=e,r=await this.spotPrivateGetV1OrderOrdersOrderId(this.extend(d,n)));else{let i=this.safeBool2(n,"stop","trigger"),h=this.safeBool(n,"stopLossTakeProfit"),c=this.safeBool(n,"stopLoss"),l=this.safeBool(n,"takeProfit"),u=this.safeBool(n,"trailing"),f=!0===i||!0===c||!0===l||!0===h||!0===u,p=this.omit(n,["stop","stopLossTakeProfit","trailing","trigger","stopLoss","takeProfit"]),m=this.safeStringN(p,["client_order_id","clientOrderId","algo_client_order_id"]),g=void 0!==m?this.omit(p,["client_order_id","clientOrderId","algo_client_order_id"]):p;if(void 0===m?!0===f?d.algo_id=e:d.order_id=e:!0===f?d.algo_client_order_id=m:d.client_order_id=m,this.safeBool(s,"linear",!1))if(!0===f)!0===i?d.type="trigger":!0===u?d.type="trailing_stop":!0===h?d.type="tpsl":!0===c?d.type="sl":!0===l&&(d.type="tp"),r=await this.contractPrivateGetV5AlgoOrder(this.extend(d,g));else{if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");d.contract_code=this.safeString(s,"id");let[e,i]=this.handleMarginModeAndParams("fetchOrder",g);d.margin_mode=void 0===e?"cross":e,r=await this.contractPrivateGetV5TradeOrder(this.extend(d,i))}else if(this.safeBool(s,"inverse",!1))if("future"===o)d.symbol=this.safeString(s,"settleId"),r=await this.contractPrivatePostApiV1ContractOrderInfo(this.extend(d,g));else if("swap"===o)d.contract_code=this.safeString(s,"id"),r=await this.contractPrivatePostSwapApiV1SwapOrderInfo(this.extend(d,g));else throw new a.NotSupported(this.id+" fetchOrder() does not support "+o+" markets")}let h=this.safeValue(r,"data");return Array.isArray(h)&&(h=this.safeDict(h,0)),this.parseOrder(h,s)}parseMarginBalanceHelper(e,t,i){let s;if(void 0===(s=t in i?i[t]:this.account())||("trade"===this.safeString(e,"type")&&(s.free=this.safeString(e,"balance")),void 0===s))throw new a.ExchangeError(this.id+" parseMarginBalanceHelper() could not resolve account");return"frozen"===this.safeString(e,"type")&&(s.used=this.safeString(e,"balance")),s}async fetchSpotOrdersByStates(e,t,i,s,r={}){let o,n,d=this.safeString(this.options,"fetchOrdersByStatesMethod","spot_private_get_v1_order_orders");if("spot_private_get_v1_order_orders"===d&&void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let h={states:e};void 0!==t&&(h.symbol=(o=this.market(t)).id),void 0!==i&&(h["start-time"]=i,h["end-time"]=this.sum(i,1728e5));let[c,l]=this.handleUntilOption("end-time",h,r);void 0!==s&&(c.size=s),n="spot_private_get_v1_order_orders"===d?await this.spotPrivateGetV1OrderOrders(this.extend(c,l)):await this.spotPrivateGetV1OrderHistory(this.extend(c,l));let u=this.safeList(n,"data",[]);return this.parseOrders(u,o,i,s)}async fetchSpotOrders(e,t,i,s={}){return await this.fetchSpotOrdersByStates("pre-submitted,submitted,partial-filled,filled,partial-canceled,canceled",e,t,i,s)}async fetchClosedSpotOrders(e,t,i,s={}){return await this.fetchSpotOrdersByStates("filled",e,t,i,s)}async fetchContractOrders(e,t,i,s={}){let r,o;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchContractOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d={},h=this.safeBool2(s,"stop","trigger"),c=this.safeBool(s,"stopLossTakeProfit"),l=this.safeBool(s,"stopLoss"),u=this.safeBool(s,"takeProfit"),f=this.safeBool(s,"trailing",!1),p=!0===h||!0===l||!0===u||!0===c||!0===f,m=this.omit(s,["stop","stopLossTakeProfit","trailing","trigger","stopLoss","takeProfit"]);if(void 0!==t&&(d.start_time=t),[d,r]=this.handleUntilOption("end_time",d,m),!0===n.linear){void 0!==i&&(d.limit=i);let[e,t]=this.handleMarginModeAndParams("fetchContractOrders",r);d.margin_mode=void 0===e?"cross":e,d.contract_code=n.id,!0===p?(!0===h?d.type="trigger":!0===f?d.type="trailing_stop":!0===c?d.type="tpsl":!0===l?d.type="sl":!0===u&&(d.type="tp"),o=await this.contractPrivateGetV5AlgoOrderHistory(this.extend(d,t))):o=await this.contractPrivateGetV5TradeOrderHistory(this.extend(d,t))}else!0===n.inverse&&(d.contract=n.id,d.type=1,d.trade_type=0,d.status="0",!0===n.swap?o=!0===h?await this.contractPrivatePostSwapApiV1SwapTriggerHisorders(this.extend(d,r)):!0===c?await this.contractPrivatePostSwapApiV1SwapTpslHisorders(this.extend(d,r)):!0===f?await this.contractPrivatePostSwapApiV1SwapTrackHisorders(this.extend(d,r)):await this.contractPrivatePostSwapApiV3SwapHisorders(this.extend(d,r)):!0===n.future&&(d.symbol=n.settleId,o=!0===h?await this.contractPrivatePostApiV1ContractTriggerHisorders(this.extend(d,r)):!0===c?await this.contractPrivatePostApiV1ContractTpslHisorders(this.extend(d,r)):!0===f?await this.contractPrivatePostApiV1ContractTrackHisorders(this.extend(d,r)):await this.contractPrivatePostApiV3ContractHisorders(this.extend(d,r))));let g=this.safeValue(o,"data");return Array.isArray(g)||(g=this.safeList(g,"orders",[])),this.parseOrders(g,n,t,i)}async fetchClosedContractOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchClosedContractOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r={};if(!0===this.market(e).linear){let e=this.safeBool2(s,"stop","trigger"),t=this.safeBool(s,"stopLossTakeProfit"),i=this.safeBool(s,"stopLoss"),a=this.safeBool(s,"takeProfit"),o=this.safeBool(s,"trailing",!1);!0==(!0===e||!0===i||!0===a||!0===t||!0===o)?r.states="effective":r.states="filled"}else r.status="6";return await this.fetchContractOrders(e,t,i,this.extend(r,s))}async fetchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let[o,n]=this.handleMarketTypeAndParams("fetchOrders",r,s),d="swap"===o||"future"===o;if(d&&void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrders() requires a symbol argument for "+o+" orders");return d?await this.fetchContractOrders(e,t,i,n):await this.fetchSpotOrders(e,t,i,n)}async fetchCanceledOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(s,"fetchCanceledOrders","paginate",!1);if(o)return await this.fetchPaginatedCallDynamic("fetchCanceledOrders",e,t,i,n,100);void 0!==e&&(r=this.market(e));let[d,h]=this.handleMarketTypeAndParams("fetchCanceledOrders",r,n);if("spot"===d)return await this.fetchSpotOrdersByStates("partial-canceled,canceled",e,t,i,h);{if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchCanceledOrders() requires a symbol argument for "+d+" orders");let s={};if(this.safeBool(r,"linear",!1)){let e=this.safeBool2(h,"stop","trigger"),t=this.safeBool(h,"stopLossTakeProfit"),i=this.safeBool(h,"stopLoss"),r=this.safeBool(h,"takeProfit"),a=this.safeBool(h,"trailing",!1);!0==(!0===e||!0===i||!0===r||!0===t||!0===a)?s.states="canceled":s.states="partially_canceled,canceled"}else s.status="5,7";return await this.fetchContractOrders(e,t,i,this.extend(s,h))}}async fetchClosedOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchClosedOrders","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchClosedOrders",e,t,i,o,100);void 0!==e&&(r=this.market(e));let[n,d]=this.handleMarketTypeAndParams("fetchClosedOrders",r,o);return"spot"===n?await this.fetchClosedSpotOrders(e,t,i,d):await this.fetchClosedContractOrders(e,t,i,d)}async fetchOpenOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let o={},[n,d]=this.handleMarketTypeAndParams("fetchOpenOrders",r,s),[h,c]=this.handleSubTypeAndParams("fetchOpenOrders",r,d,"linear"),l="linear"===h;if("spot"===n){void 0!==e&&(o.symbol=this.safeString(r,"id"));let t=this.safeString(c,"account-id");if(void 0===t){await this.loadAccounts();for(let e=0;e<this.accounts.length;e++){let i=this.accounts[e];if("spot"===this.safeString(i,"type")&&void 0!==(t=this.safeString(i,"id")))break}}o["account-id"]=t,void 0!==i&&(o.size=i);let s=this.omit(c,"account-id");a=await this.spotPrivateGetV1OrderOpenOrders(this.extend(o,s))}else{void 0!==e&&(o.contract_code=this.safeString(r,"id")),void 0!==i&&(l?o.limit=i:o.page_size=i);let t=this.safeBool2(c,"stop","trigger"),s=this.safeBool(c,"stopLossTakeProfit"),d=this.safeBool(c,"stopLoss"),u=this.safeBool(c,"takeProfit"),f=this.safeBool(c,"trailing",!1),p=this.omit(c,["stop","stopLossTakeProfit","trailing","trigger","stopLoss","takeProfit"]);l?!0===t||!0===f||!0===s||!0===d||!0===u?(!0===t?o.type="trigger":!0===f?o.type="trailing_stop":!0===s?o.type="tpsl":!0===d?o.type="sl":!0===u&&(o.type="tp"),a=await this.contractPrivateGetV5AlgoOrderOpens(this.extend(o,p))):a=await this.contractPrivateGetV5TradeOrderOpens(this.extend(o,p)):"inverse"===h&&("swap"===n?a=!0===t?await this.contractPrivatePostSwapApiV1SwapTriggerOpenorders(this.extend(o,p)):!0===s?await this.contractPrivatePostSwapApiV1SwapTpslOpenorders(this.extend(o,p)):!0===f?await this.contractPrivatePostSwapApiV1SwapTrackOpenorders(this.extend(o,p)):await this.contractPrivatePostSwapApiV1SwapOpenorders(this.extend(o,p)):"future"===n&&(o.symbol=this.safeString(r,"settleId","usdt"),a=!0===t?await this.contractPrivatePostApiV1ContractTriggerOpenorders(this.extend(o,p)):!0===s?await this.contractPrivatePostApiV1ContractTpslOpenorders(this.extend(o,p)):!0===f?await this.contractPrivatePostApiV1ContractTrackOpenorders(this.extend(o,p)):await this.contractPrivatePostApiV1ContractOpenorders(this.extend(o,p))))}let u=this.safeValue(a,"data");return Array.isArray(u)||(u=this.safeList(u,"orders",[])),this.parseOrders(u,r,t,i)}parseOrderStatus(e){return this.safeString({"partial-filled":"open","partial-canceled":"canceled",filled:"closed",canceled:"canceled",submitted:"open",created:"open",1:"open",2:"open",3:"open",4:"open",5:"canceled",6:"closed",7:"canceled",11:"canceling",active:"open",new:"open",partially_filled:"open",partially_canceled:"canceled"},e,e)}parseOrder(e,t){let i,s,r,a,o,n=this.safeString2(e,"contract_code","symbol"),d=this.safeMarket(n,t),h=this.safeString2(e,"err_code","err-code"),c=this.parseOrderStatus(this.safeString2(e,"state","status"));void 0!==h&&(c="rejected");let l=this.safeStringN(e,["algo_id","id","order_id_str","order-id","order_id"]),u=this.safeString2(e,"direction","side"),f=void 0!==this.safeString(e,"contract_code")&&void 0!==d&&!0===d.linear&&!0!==d.spot;if(!0===f)(void 0===(i=this.safeString(e,"type"))||"tp"===i||"sl"===i||"tpsl"===i)&&(i=this.safeString2(e,"tp_type","sl_type")),"0"===i&&(i=void 0);else{i=this.safeString(e,"order_price_type");let t=this.safeString(e,"type");if(void 0!==t)if(t.indexOf("-")>=0){let e=t.split("-");u=e[0],i=e[1]}else void 0===i&&(i=t)}let p=this.safeIntegerN(e,["created_at","created-at","create_date","created_time"]),m=this.safeStringN(e,["client_order_id","client-order-id","algo_client_order_id"]);void 0!==i&&i.indexOf("market")>=0&&!0!==f?s=this.safeString(e,"field-cash-amount"):(r=this.safeString2(e,"volume","amount"),s=this.safeStringN(e,["filled-cash-amount","field-cash-amount","trade_turnover"]));let g=this.safeStringN(e,["filled-amount","field-amount","trade_volume"]),v=this.safeString2(e,"price","order_price"),y=this.safeString2(e,"filled-fees","field-fees");if(void 0!==(y=this.safeString(e,"fee",y))&&"0"!==y&&"0.0"!==y){let t=this.safeString2(e,"fee_asset","fee_currency");a={cost:y,currency:void 0!==t?this.safeCurrencyCode(t):"sell"===u?d.quote:d.base}}let b=this.safeString(e,"trade_avg_price"),w=this.safeValue(e,"trades");if(!0===f)o=this.safeBool(e,"reduce_only");else{let t=this.safeInteger(e,"reduce_only");void 0!==t&&(o=0!==t)}return this.safeOrder({info:e,id:l,clientOrderId:m,timestamp:p,datetime:this.iso8601(p),lastTradeTimestamp:void 0,symbol:d.symbol,type:i,timeInForce:this.safeStringUpper(e,"time_in_force"),postOnly:void 0,side:u,price:v,triggerPrice:this.safeString2(e,"stop-price","trigger_price"),stopLossPrice:this.safeString2(e,"sl_trigger_price","sl_order_price"),takeProfitPrice:this.safeString2(e,"tp_trigger_price","tp_order_price"),average:b,cost:s,amount:r,filled:g,remaining:void 0,status:c,reduceOnly:o,fee:a,trades:w},d)}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new a.NotSupported(this.id+" createMarketBuyOrderWithCost() supports spot orders only");return i.createMarketBuyOrderRequiresPrice=!1,await this.createOrder(e,"market","buy",t,void 0,i)}async createTrailingPercentOrder(e,t,i,s,r,o,n,d={}){if(void 0===o)throw new a.ArgumentsRequired(this.id+" createTrailingPercentOrder() requires a trailingPercent argument");if(void 0===n)throw new a.ArgumentsRequired(this.id+" createTrailingPercentOrder() requires a trailingTriggerPrice argument");return d.trailingPercent=o,d.trailingTriggerPrice=n,await this.createOrder(e,t,i,s,r,d)}async createSpotOrderRequest(e,t,i,s,r,n={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let d=this.market(e),[h,c]=this.handleMarginModeAndParams("createOrder",n),l={"account-id":await this.fetchAccountIdByType(d.type,h,e),symbol:d.id},u=t.replace("buy-","");u=u.replace("sell-","");let f=this.safeDict(this.options,d.type,{}),p=this.safeStringN(c,["triggerPrice","stopPrice","stop-price"]);if(void 0===p){if(u in this.safeDict(f,"stopOrderTypes",{}))throw new a.ArgumentsRequired(this.id+" createOrder() requires a triggerPrice for a trigger order")}else{let s="gte";"sell"===i&&(s="lte");let r=this.safeString(c,"operator",s);if(l["stop-price"]=this.priceToPrecision(e,p),l.operator=r,"limit"===u||"limit-fok"===u)u="stop-"+u;else if("stop-limit"!==u&&"stop-limit-fok"!==u)throw new a.NotSupported(this.id+" createOrder() does not support "+t+" orders")}let[m,g]=this.handlePostOnly("market"===u,"limit-maker"===u,c);!0===m&&(u="limit-maker");let v=this.safeString(g,"timeInForce","GTC");"FOK"===v?u+="-fok":"IOC"===v&&(u="ioc"),l.type=i+"-"+u;let y=this.safeString2(g,"clientOrderId","client-order-id");if(void 0===y){let e=this.safeDict(this.options,"broker",{}),t=this.safeString(e,"id");l["client-order-id"]=t+this.uuid()}else l["client-order-id"]=y;"cross"===h?l.source="super-margin-api":"isolated"===h?l.source="margin-api":"c2c"===h&&(l.source="c2c-margin-api");let b="market"===u&&"buy"===i,w=this.handleOptionBoolAndParams(g,"createOrder","createMarketBuyOrderRequiresPrice",!0),k=this.safeNumber(w[1],"cost"),S=g;if(b&&(S=this.omit(w[1],"cost")),b){let t,i=w[0];if(void 0!==k)t=this.amountToPrecision(e,k);else if(i)if(void 0===r)throw new a.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument");else{let i=this.numberToString(s),a=this.numberToString(r);t=this.amountToPrecision(e,o.Y.stringMul(i,a))}else t=this.amountToPrecision(e,s);l.amount=t}else l.amount=this.amountToPrecision(e,s);u in this.safeDict(f,"limitOrderTypes",{})&&(l.price=this.priceToPrecision(e,r));let O=this.omit(S,["triggerPrice","stopPrice","stop-price","clientOrderId","client-order-id","operator","timeInForce"]);return this.extend(l,O)}createContractOrderRequest(e,t,i,s,r,n={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let d=this.market(e),h={contract_code:d.id,volume:this.amountToPrecision(e,s)},[c,l]=this.handlePostOnly("market"===t,"post_only"===t,n),u=!0===c?"post_only":t,[f,p]=this.handleSubTypeAndParams("createOrder",d,l),m=p,g="linear"===f,v=this.safeBool2(m,"reduceOnly","reduce_only",!1),y=this.safeBool(m,"hedged",!1),b=this.safeStringLower2(m,"timeInForce","time_in_force","gtc");if(g){let[t,s]=this.handleMarginModeAndParams("createOrder",m,"cross");m=s,h.margin_mode=t,h.side=i,void 0!==b&&(h.time_in_force=b.toLowerCase());let r=this.safeDict(m,"stopLoss"),a=this.safeDict(m,"takeProfit"),o=this.safeNumber(r,"triggerPrice"),n=this.safeNumber(r,"price"),d=this.safeString(r,"type"),c=this.safeNumber(a,"triggerPrice"),l=this.safeNumber(a,"price"),u=this.safeString(a,"type");void 0!==r&&(void 0!==o&&(h.sl_trigger_price=this.priceToPrecision(e,o)),void 0!==n&&(h.sl_order_price=this.priceToPrecision(e,n)),void 0!==d&&(h.sl_type=d),m=this.omit(m,"stopLoss")),void 0!==a&&(void 0!==c&&(h.tp_trigger_price=this.priceToPrecision(e,c)),void 0!==l&&(h.tp_order_price=this.priceToPrecision(e,l)),void 0!==u&&(h.tp_type=u),m=this.omit(m,"takeProfit"))}else!0===y&&(!0===v?h.offset="close":h.offset="open"),"fok"===b?u="fok":"ioc"===b&&(u="ioc"),h.direction=i;let w=this.safeNumberN(m,["triggerPrice","stopPrice","trigger_price"]),k=this.safeNumber2(m,"stopLossPrice","sl_trigger_price"),S=this.safeNumber2(m,"takeProfitPrice","tp_trigger_price"),O=this.safeString2(m,"trailingPercent","callback_rate"),T=this.safeNumber(m,"trailingTriggerPrice",r),P=void 0!==O,I=void 0!==w,A=void 0!==k,x=void 0!==S,M=this.safeIntegerN(m,["client_order_id","clientOrderId","algo_client_order_id"]);if(g&&(P||I||A||x)&&void 0!==M&&(h.algo_client_order_id=M,m=this.omit(m,["clientOrderId","client_order_id"])),I)h.trigger_price=this.priceToPrecision(e,w),g?(h.type="trigger",void 0!==r&&(h.price=this.priceToPrecision(e,r))):(h.trigger_type=this.safeString2(m,"triggerType","trigger_type","le"),void 0!==r&&(h.order_price=this.priceToPrecision(e,r)));else if(A||x)A?(g?h.type="sl":h.sl_order_price_type=u,h.sl_trigger_price=this.priceToPrecision(e,k),void 0!==r&&(h.sl_order_price=this.priceToPrecision(e,r))):(g?h.type="tp":h.tp_order_price_type=u,h.tp_trigger_price=this.priceToPrecision(e,S),void 0!==r&&(h.tp_order_price=this.priceToPrecision(e,r)));else if(P){let e=o.Y.stringDiv(O,"100");h.callback_rate=this.parseToNumeric(e),h.order_price_type=this.safeString(m,"order_price_type","formula_price"),h.active_price=T,g&&(h.type="trailing_stop")}else void 0!==M&&(h.client_order_id=M,m=this.omit(m,["clientOrderId"])),("limit"===u||"ioc"===u||"fok"===u||"post_only"===u)&&void 0!==r&&(h.price=this.priceToPrecision(e,r));A||x||(!0===v&&(h.reduce_only=1),g?P||(h.type=u):(P||(h.order_price_type=u),h.lever_rate=this.safeIntegerN(m,["leverRate","lever_rate","leverage"],1)));let _=this.safeDict(this.options,"broker",{});h.channel_code=this.safeString(_,"id");let C=this.omit(m,["reduceOnly","triggerPrice","stopPrice","stopLossPrice","takeProfitPrice","triggerType","leverRate","timeInForce","leverage","trailingPercent","trailingTriggerPrice","hedged"]);return this.extend(h,C)}async createOrder(e,t,i,s,r,o={}){let n,d,h;void 0===this.markets&&await this.loadMarkets();let c=this.market(e),l=this.safeNumberN(o,["triggerPrice","stopPrice","trigger_price"]),u=this.safeNumber2(o,"stopLossPrice","sl_trigger_price"),f=this.safeNumber2(o,"takeProfitPrice","tp_trigger_price"),p=void 0!==this.safeNumber(o,"trailingPercent"),m=void 0!==l,g=void 0!==u,v=void 0!==f;if(!0===c.spot){if(p)throw new a.NotSupported(this.id+" createOrder() does not support trailing orders for spot markets");let d=await this.createSpotOrderRequest(e,t,i,s,r,o);n=await this.spotPrivatePostV1OrderOrdersPlace(d)}else{let d=this.createContractOrderRequest(e,t,i,s,r,o);if(!0===c.linear)n=m||g||v||p?await this.contractPrivatePostV5AlgoOrder(d):await this.contractPrivatePostV5TradeOrder(d);else if(!0===c.inverse){if(void 0===this.safeString(o,"offset"))throw new a.ArgumentsRequired(this.id+' createOrder () requires an extra parameter params["offset"] to be set to "open" or "close" when placing orders in inverse markets');!0===c.swap?n=m?await this.contractPrivatePostSwapApiV1SwapTriggerOrder(d):g||v?await this.contractPrivatePostSwapApiV1SwapTpslOrder(d):p?await this.contractPrivatePostSwapApiV1SwapTrackOrder(d):await this.contractPrivatePostSwapApiV1SwapOrder(d):!0===c.future&&(n=m?await this.contractPrivatePostApiV1ContractTriggerOrder(d):g||v?await this.contractPrivatePostApiV1ContractTpslOrder(d):p?await this.contractPrivatePostApiV1ContractTrackOrder(d):await this.contractPrivatePostApiV1ContractOrder(d))}}if(!0===c.spot)return this.safeOrder({info:n,id:this.safeString(n,"data"),timestamp:void 0,datetime:void 0,lastTradeTimestamp:void 0,status:void 0,symbol:void 0,type:t,side:i,price:r,amount:s,filled:void 0,remaining:void 0,cost:void 0,trades:void 0,fee:void 0,clientOrderId:void 0,average:void 0},c);if(!0===c.linear){if(m||p||g||v?(d=this.safeList(n,"data",[]),h=this.safeDict(d,0,{})):h=this.safeDict(n,"data",{}),void 0===h)throw new a.NullResponse(this.id+" parseOrder() returned empty response");return this.extend(this.parseOrder(h,c),{type:t,side:i,price:r,amount:s})}if(g?(d=this.safeDict(n,"data",{}),h=this.safeDict(d,"sl_order",{})):v?(d=this.safeDict(n,"data",{}),h=this.safeDict(d,"tp_order",{})):h=this.safeDict(n,"data",{}),void 0===h)throw new a.NullResponse(this.id+" parseOrder() returned empty response");return this.parseOrder(h,c)}async createOrders(e,t={}){let i,s,r,o,n;void 0===this.markets&&await this.loadMarkets();let d=[];for(let t=0;t<e.length;t++){let o,n=this.safeDict(e,t),h=this.safeString(n,"symbol");if(void 0===i)i=h;else if(i!==h)throw new a.BadRequest(this.id+" createOrders() requires all orders to have the same symbol");let c=this.safeString(n,"type"),l=this.safeString(n,"side"),u=this.safeValue(n,"amount"),f=this.safeValue(n,"price"),p=this.safeDict(n,"params",{}),m=this.handleMarginModeAndParams("createOrders",p)[0];if(void 0!==m){if(void 0===r)r=m;else if(r!==m)throw new a.BadRequest(this.id+" createOrders() requires all orders to have the same margin mode (isolated or cross)")}o=!0===(s=this.market(i)).spot?await this.createSpotOrderRequest(h,c,l,u,f,p):this.createContractOrderRequest(h,c,l,u,f,p),o=this.omit(o,"marginMode"),d.push(o)}let h={};if(this.safeBool(s,"spot",!1)?o=await this.privatePostOrderBatchOrders(d):this.safeBool(s,"linear",!1)?o=await this.contractPrivatePostV5TradeBatchOrders(d):this.safeBool(s,"inverse",!1)&&(h.orders_data=d,this.safeBool(s,"swap",!1)?o=await this.contractPrivatePostSwapApiV1SwapBatchorder(h):this.safeBool(s,"future",!1)&&(o=await this.contractPrivatePostApiV1ContractBatchorder(h))),this.safeBool(s,"spot",!1))n=this.safeList(o,"data",[]);else{let e=this.safeValue(o,"data");if(Array.isArray(e))n=e;else{let e=this.safeDict(o,"data",{}),t=this.safeList(e,"success",[]),i=this.safeList(e,"errors",[]);n=this.arrayConcat(t,i)}}return this.parseOrders(n,s)}async cancelOrder(e,t,i={}){let s,r,o;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let[n,d]=this.handleMarketTypeAndParams("cancelOrder",s,i),[h,c]=this.handleSubTypeAndParams("cancelOrder",s,d),l="linear"===h,u={},f=this.safeBool2(c,"stop","trigger"),p=this.safeBoolN(c,["stopLossTakeProfit","stopLoss","takeProfit"]),m=this.safeBool(c,"trailing",!1),g=this.omit(c,["stop","stopLossTakeProfit","trailing","trigger","stopLoss","takeProfit"]);if("spot"===n){let t=this.safeString2(g,"client-order-id","clientOrderId");void 0===t?(u["order-id"]=e,r=await this.spotPrivatePostV1OrderOrdersOrderIdSubmitcancel(this.extend(u,g))):(u["client-order-id"]=t,g=this.omit(g,["client-order-id","clientOrderId"]),r=await this.spotPrivatePostV1OrderOrdersSubmitCancelClientOrder(this.extend(u,g)))}else{if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");let i=this.safeStringN(g,["client_order_id","clientOrderId","algo_client_order_id"]);if(l&&(!0===f||!0===p||!0===m)||(void 0===i?u.order_id=e:(u.client_order_id=i,g=this.omit(g,["client_order_id","clientOrderId"]))),this.safeBool(s,"future",!1)?u.symbol=this.safeString(s,"settleId"):u.contract_code=this.safeString(s,"id"),l)if(!0===f||!0===p||!0===m){let t={contract_code:this.safeString(s,"id")};void 0===i?(t.algo_id=e,g=this.omit(g,"algo_id")):(t.algo_client_order_id=i,g=this.omit(g,["client_order_id","clientOrderId","algo_client_order_id"]));let a=[this.extend(t,g)];r=await this.contractPrivatePostV5AlgoCancelOrders(a)}else r=await this.contractPrivatePostV5TradeCancelOrder(this.extend(u,g));else if(this.safeBool(s,"inverse",!1))this.safeBool(s,"swap",!1)?r=!0===f?await this.contractPrivatePostSwapApiV1SwapTriggerCancel(this.extend(u,g)):!0===p?await this.contractPrivatePostSwapApiV1SwapTpslCancel(this.extend(u,g)):!0===m?await this.contractPrivatePostSwapApiV1SwapTrackCancel(this.extend(u,g)):await this.contractPrivatePostSwapApiV1SwapCancel(this.extend(u,g)):this.safeBool(s,"future",!1)&&(r=!0===f?await this.contractPrivatePostApiV1ContractTriggerCancel(this.extend(u,g)):!0===p?await this.contractPrivatePostApiV1ContractTpslCancel(this.extend(u,g)):!0===m?await this.contractPrivatePostApiV1ContractTrackCancel(this.extend(u,g)):await this.contractPrivatePostApiV1ContractCancel(this.extend(u,g)));else throw new a.NotSupported(this.id+" cancelOrder() does not support "+n+" markets")}if(l)if(!0===f||!0===p||!0===m){let e=this.safeList(r,"data",[]);o=this.safeDict(e,0,{})}else o=this.safeDict(r,"data",{});else o=r;if(void 0===o)throw new a.NullResponse(this.id+" parseOrder() returned empty response");return this.extend(this.parseOrder(o,s),{id:e,status:"canceled"})}async cancelOrders(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let[o,n]=this.handleMarketTypeAndParams("cancelOrders",s,i),d={},h=this.safeBool2(n,"stop","trigger"),c=this.safeBool(n,"stopLossTakeProfit"),l=this.omit(n,["stop","stopLossTakeProfit","trigger"]);if("spot"===o){let t=this.safeValue2(l,"client-order-id","clientOrderId");void 0===(t=this.safeValue2(l,"client-order-ids","clientOrderIds",t))?"string"==typeof t?d["order-ids"]=[e]:d["order-ids"]=e:("string"==typeof t?d["client-order-ids"]=[t]:d["client-order-ids"]=t,l=this.omit(l,["client-order-id","client-order-ids","clientOrderId","clientOrderIds"])),r=await this.spotPrivatePostV1OrderOrdersBatchcancel(this.extend(d,l))}else{if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument");let i=this.safeValue2(l,"client_order_id","clientOrderId");if(i=this.safeValue2(l,"client_order_ids","clientOrderIds",i),l=this.omit(l,["client_order_id","client_order_ids","clientOrderId","clientOrderIds"]),this.safeBool(s,"linear",!1)||(void 0===i?d.order_id=e.join(","):d.client_order_id=i),this.safeBool(s,"future",!1)?d.symbol=this.safeString(s,"settleId"):d.contract_code=this.safeString(s,"id"),this.safeBool(s,"linear",!1))void 0===i?d.order_id=e:"string"==typeof i?d.client_order_id=i.split(","):d.client_order_id=i,r=await this.contractPrivatePostV5TradeCancelBatchOrders(this.extend(d,l));else if(this.safeBool(s,"inverse",!1))this.safeBool(s,"swap",!1)?r=!0===h?await this.contractPrivatePostSwapApiV1SwapTriggerCancel(this.extend(d,l)):!0===c?await this.contractPrivatePostSwapApiV1SwapTpslCancel(this.extend(d,l)):await this.contractPrivatePostSwapApiV1SwapCancel(this.extend(d,l)):this.safeBool(s,"future",!1)&&(r=!0===h?await this.contractPrivatePostApiV1ContractTriggerCancel(this.extend(d,l)):!0===c?await this.contractPrivatePostApiV1ContractTpslCancel(this.extend(d,l)):await this.contractPrivatePostApiV1ContractCancel(this.extend(d,l)));else throw new a.NotSupported(this.id+" cancelOrders() does not support "+o+" markets")}if(this.safeBool(s,"linear",!1)&&!0!==h&&!0!==c)return this.parseCancelOrders(r);let u=this.safeDict(r,"data");return this.parseCancelOrders(u)}parseCancelOrders(e){let t,i=this.safeString(e,"successes");t=void 0!==i?i.split(","):this.safeList(e,"success",[]);let s=this.safeList2(e,"errors","failed",[]),r=this.safeList(e,"data",[]),a=[];for(let e=0;e<r.length;e++){let t=r[e];a.push(this.safeOrder({info:t,id:this.safeString(t,"order_id"),status:"canceled",clientOrderId:this.safeString(t,"client_order_id")}))}for(let e=0;e<t.length;e++){let i=t[e];a.push(this.safeOrder({info:i,id:i,status:"canceled"}))}for(let e=0;e<s.length;e++){let t=s[e];a.push(this.safeOrder({info:t,id:this.safeString2(t,"order-id","order_id"),status:"failed",clientOrderId:this.safeString(t,"client-order-id")}))}return a}async cancelAllOrders(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(i=this.market(e));let[r,o]=this.handleMarketTypeAndParams("cancelAllOrders",i,t),n={};if("spot"===r){void 0!==e&&(n.symbol=this.safeString(i,"id")),s=await this.spotPrivatePostV1OrderOrdersBatchCancelOpenOrders(this.extend(n,o));let t=this.safeDict(s,"data");return[this.safeOrder({info:t})]}{if(void 0===e)throw new a.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument");this.safeBool(i,"future",!1)&&(n.symbol=this.safeString(i,"settleId")),n.contract_code=this.safeString(i,"id");let t=this.safeBool2(o,"stop","trigger"),d=this.safeBool(o,"stopLossTakeProfit"),h=this.safeBool(o,"trailing",!1),c=this.omit(o,["stop","stopLossTakeProfit","trailing","trigger"]);if(this.safeBool(i,"linear",!1))s=await this.contractPrivatePostV5TradeCancelAllOrders(this.extend(n,c));else if(this.safeBool(i,"inverse",!1))this.safeBool(i,"swap",!1)?s=!0===t?await this.contractPrivatePostSwapApiV1SwapTriggerCancelall(this.extend(n,c)):!0===d?await this.contractPrivatePostSwapApiV1SwapTpslCancelall(this.extend(n,c)):!0===h?await this.contractPrivatePostSwapApiV1SwapTrackCancelall(this.extend(n,c)):await this.contractPrivatePostSwapApiV1SwapCancelall(this.extend(n,c)):this.safeBool(i,"future",!1)&&(s=!0===t?await this.contractPrivatePostApiV1ContractTriggerCancelall(this.extend(n,c)):!0===d?await this.contractPrivatePostApiV1ContractTpslCancelall(this.extend(n,c)):!0===h?await this.contractPrivatePostApiV1ContractTrackCancelall(this.extend(n,c)):await this.contractPrivatePostApiV1ContractCancelall(this.extend(n,c)));else throw new a.NotSupported(this.id+" cancelAllOrders() does not support "+r+" markets");if(this.safeBool(i,"linear",!1)&&!0!==t&&!0!==h&&!0!==d)return this.parseCancelOrders(s);let l=this.safeDict(s,"data");return this.parseCancelOrders(l)}}async cancelAllOrdersAfter(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ExchangeError(this.id+" cancelAllOrdersAfter() missing timeout");let i={timeout:e>0?this.parseToInt(e/1e3):0};return await this.v2PrivatePostAlgoOrdersCancelAllAfter(this.extend(i,t))}parseDepositAddress(e,t){let i=this.safeString(e,"address"),s=this.safeString(e,"addressTag"),r=this.safeString(e,"currency"),a=this.safeCurrency(r,t),o=this.safeCurrencyCode(r,a),n=this.safeString(e,"note"),d=this.safeString(e,"chain");return this.checkAddress(i),{currency:o,address:i,tag:s,network:this.networkIdToCode(d,o),note:n,info:e}}async fetchDepositAddressesByNetwork(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={currency:i.id},r=await this.spotPrivateGetV2AccountDepositAddress(this.extend(s,t)),a=this.safeList(r,"data",[]),o=this.parseDepositAddresses(a,[i.code],!1);return this.indexBy(o,"network")}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),[s,r]=this.handleNetworkCodeAndParams(t),a=await this.fetchDepositAddressesByNetwork(e,r),o=this.selectNetworkCodeFromUnifiedNetworks(i.code,s,a);return this.safeValue(a,o)}async fetchWithdrawAddresses(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),a={currency:r.id},o=await this.spotPrivateGetV2AccountWithdrawAddress(this.extend(a,s)),n=this.safeList(o,"data",[]),d=this.parseDepositAddresses(n,[r.code],!1),h=[];for(let e=0;e<d.length;e++){let s=d[e],r=void 0===t||this.safeString(s,"note")===t,a=void 0===i||this.safeString(s,"network")===i;r&&a&&h.push(s)}return h}async fetchDeposits(e,t,i,s={}){let r,a=i;(void 0===i||i>100)&&(a=100),void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.currency(e));let o={type:"deposit",direct:"next",from:0};void 0!==r&&(o.currency=r.id),void 0!==a&&(o.size=a);let n=await this.spotPrivateGetV1QueryDepositWithdraw(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTransactions(d,r,t,a)}async fetchWithdrawals(e,t,i,s={}){let r,a=i;(void 0===i||i>100)&&(a=100),void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.currency(e));let o={type:"withdraw",direct:"next",from:0};void 0!==r&&(o.currency=r.id),void 0!==a&&(o.size=a);let n=await this.spotPrivateGetV1QueryDepositWithdraw(this.extend(o,s)),d=this.safeList(n,"data",[]);return this.parseTransactions(d,r,t,a)}parseTransaction(e,t){let i=this.safeInteger(e,"created-at"),s=this.safeCurrencyCode(this.safeString(e,"currency"),t),r=this.safeString(e,"type");"withdraw"===r&&(r="withdrawal");let a=this.safeString(e,"fee");void 0!==a&&(a=o.Y.stringAbs(a));let n=this.safeString(e,"chain"),d=this.safeString(e,"tx-hash");void 0!==d&&"ETH"===n&&0>d.indexOf("0x")&&(d="0x"+d);let h=this.safeString(e,"sub-type");return{info:e,id:this.safeString2(e,"id","data"),txid:d,timestamp:i,datetime:this.iso8601(i),network:this.networkIdToCode(n,s),address:this.safeString(e,"address"),addressTo:void 0,addressFrom:void 0,tag:this.safeString(e,"address-tag"),tagTo:void 0,tagFrom:void 0,type:r,amount:this.safeNumber(e,"amount"),currency:s,status:this.parseTransactionStatus(this.safeString(e,"state")),updated:this.safeInteger(e,"updated-at"),comment:void 0,internal:"FAST"===h,fee:{currency:s,cost:this.parseNumber(a),rate:void 0}}}parseTransactionStatus(e){return this.safeString({unknown:"failed",confirming:"pending",confirmed:"ok",safe:"ok",orphan:"failed",submitted:"pending",canceled:"canceled",reexamine:"pending",reject:"failed",pass:"pending","wallet-reject":"failed","confirm-error":"failed",repealed:"failed","wallet-transfer":"pending","pre-transfer":"pending",verifying:"pending"},e,e)}async withdraw(e,t,i,s,r={}){let[n,d]=this.handleWithdrawTagAndParams(s,r);void 0===this.markets&&await this.loadMarkets(),this.checkAddress(i);let h=this.currency(e),c={address:i,currency:h.id.toLowerCase()};void 0!==n&&(c["addr-tag"]=n);let[l,u]=this.handleNetworkCodeAndParams(d);void 0!==l&&(c.chain=this.networkCodeToId(l,e));let f=this.currencyToPrecision(e,t,l);void 0===f&&(f="0");let p=parseFloat(f),m=this.safeDict(this.options,"withdraw",{}),g=this.safeBool(m,"includeFee",!1),v=u;if(g&&(v=this.omit(u,"fee")),g){let t=this.safeNumber(u,"fee");if(void 0===t){let e=await this.fetchCurrencies();this.currencies=this.mapToSafeMap(this.deepExtend(this.currencies,e));let i=this.safeDict(h.networks,l,{});if(void 0===(t=this.safeNumber(i,"fee")))throw new a.ArgumentsRequired(this.id+' withdraw() function can not find withdraw fee for chosen network. You need to re-load markets with "exchange.loadMarkets(true)", or provide the "fee" parameter')}let i=this.currencyToPrecision(e,t,l),s=this.numberToString(p),r=o.Y.stringSub(s,i);void 0===r&&(r="0");let n=parseFloat(r),d=i;void 0===d&&(d="0"),c.fee=parseFloat(d);let f=this.currencyToPrecision(e,n,l);void 0===f&&(f="0"),p=parseFloat(f)}c.amount=p;let y=await this.spotPrivatePostV1DwWithdrawApiCreate(this.extend(c,v));return this.parseTransaction(y,h)}parseTransfer(e,t){let i,s=this.safeDict(this.options,"accountsById",{}),r=this.safeString2(e,"transfer_id","data"),a=this.safeString(e,"currency"),o=this.safeCurrencyCode(a,t),n=this.safeNumber(e,"amount"),d=this.safeInteger(e,"transfer_time"),h=this.safeString(e,"from_account_type"),c=this.safeString(e,"to_account_type"),l=this.safeString(s,h,h),u=this.safeString(s,c,c),f=this.safeString(e,"status");return"success"===f?i="ok":"pending"===f?i="pending":"failed"===f&&(i="failed"),{info:e,id:r,timestamp:d,datetime:this.iso8601(d),currency:o,amount:n,fromAccount:l,toAccount:u,status:i}}async transfer(e,t,i,s,r={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d=this.currencyToPrecision(e,t);void 0===d&&(d="0");let h={currency:n.id,amount:parseFloat(d)},[c,l]=this.handleSubTypeAndParams("transfer",void 0,r),u=this.convertTypeToAccount(i),f=this.convertTypeToAccount(s),p="cross"===f,m="cross"===u,g=void 0!==this.ids&&this.inArray(f,this.ids),v=void 0!==this.ids&&this.inArray(u,this.ids),y="pro"===u,b="pro"===f;if(y&&b)throw new a.BadRequest(this.id+" transfer () cannot make a transfer between "+i+" and "+s);if("futures"===u||"futures"===f){let e=u+"-to-"+f;h.type=e=this.safeString(l,"type",e),o=await this.spotPrivatePostV1FuturesTransfer(this.extend(h,l))}else if(y&&p)o=await this.privatePostCrossMarginTransferIn(this.extend(h,l));else if(m&&b)o=await this.privatePostCrossMarginTransferOut(this.extend(h,l));else if(y&&g)h.symbol=f,o=await this.privatePostDwTransferInMargin(this.extend(h,l));else if(v&&b)h.symbol=u,o=await this.privatePostDwTransferOutMargin(this.extend(h,l));else{let e=l;if("linear"===c){"swap"===u||"linear-swap"===i?u="linear-swap":f="linear-swap";let t=this.safeString(l,"symbol");e=this.omit(l,"symbol"),void 0!==t?(t=this.marketId(t),h["margin-account"]=t):h["margin-account"]="USDT"}h.from=y?"spot":u,h.to=b?"spot":f,o=await this.v2PrivatePostAccountTransfer(this.extend(h,e))}if(void 0===o)throw new a.NullResponse(this.id+" parseTransfer() returned empty response");return this.parseTransfer(o,n)}async fetchTransfers(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.currency=(r=this.currency(e)).id),void 0!==t&&(a.start_time=t);let o=this.safeInteger(s,"until"),n=void 0!==o?this.omit(s,"until"):s;void 0!==o&&(a.end_time=o),void 0!==i&&(a.limit=i);let d=await this.spotPrivateGetV5AccountUniversalTransferRecords(this.extend(a,n)),h=this.safeList(d,"data",[]);return this.parseTransfers(h,r,t,i)}async fetchIsolatedBorrowRates(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.spotPrivateGetV1MarginLoanInfo(e),i=this.safeList(t,"data",[]);return this.parseIsolatedBorrowRates(i)}parseIsolatedBorrowRate(e,t){let i=this.safeString(e,"symbol"),s=this.safeSymbol(i,t),r=this.safeList(e,"currencies",[]),a=this.safeDict(r,0),o=this.safeDict(r,1),n=this.safeString(a,"currency"),d=this.safeString(o,"currency");return{symbol:s,base:this.safeCurrencyCode(n),baseRate:this.safeNumber(a,"actual-rate"),quote:this.safeCurrencyCode(d),quoteRate:this.safeNumber(o,"actual-rate"),period:864e5,timestamp:void 0,datetime:void 0,info:e}}async fetchFundingRateHistory(e,t,i,s={}){let r;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");let[o,n]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(o)return await this.fetchPaginatedCallCursor("fetchFundingRateHistory",e,t,i,n,"current_page","page_index",1,50);void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h={contract_code:d.id};if(!0===d.linear?(void 0!==i&&(h.limit=Math.min(i,100)),void 0!==t&&(h.start_time=t)):void 0!==i?h.page_size=i:h.page_size=50,!0===d.inverse)r=await this.contractPublicGetSwapApiV1SwapHistoricalFundingRate(this.extend(h,n));else if(!0===d.linear)r=await this.contractPublicGetV5MarketFundingRateHistory(this.extend(h,n));else throw new a.NotSupported(this.id+" fetchFundingRateHistory() supports inverse and linear swaps only");let c=this.safeValue(r,"data"),l=[];if(!0===d.linear)for(let e=0;e<c.length;e++){let t=c[e],i=this.safeString(t,"contract_code"),s=this.safeSymbol(i,d),r=this.safeInteger(t,"funding_time");l.push({info:t,symbol:s,fundingRate:this.safeNumber(t,"funding_rate"),timestamp:r,datetime:this.iso8601(r)})}else{let e=this.safeValue(c,"current_page"),t=this.safeList(c,"data",[]);for(let i=0;i<t.length;i++){let s=t[i];s.current_page=e;let r=this.safeString(s,"contract_code"),a=this.safeSymbol(r),o=this.safeInteger(s,"funding_time");l.push({info:s,symbol:a,fundingRate:this.safeNumber(s,"funding_rate"),timestamp:o,datetime:this.iso8601(o)})}}let u=this.sortBy(l,"timestamp");return this.filterBySymbolSinceLimit(u,this.safeString(d,"symbol"),t,i)}parseFundingRate(e,t){let i=this.safeNumber(e,"estimated_rate"),s=this.safeInteger(e,"funding_time"),r=this.safeInteger(e,"next_funding_time"),a=this.safeString(e,"funding_time"),n=this.safeString(e,"next_funding_time"),d=o.Y.stringSub(n,a),h=this.safeString(e,"contract_code");return{info:e,symbol:this.safeSymbol(h,t),markPrice:void 0,indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:this.safeNumber(e,"funding_rate"),fundingTimestamp:s,fundingDatetime:this.iso8601(s),nextFundingRate:i,nextFundingTimestamp:r,nextFundingDatetime:this.iso8601(r),previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:this.parseFundingInterval(d)}}parseFundingInterval(e){return this.safeString({36e5:"1h",144e5:"4h",288e5:"8h",576e5:"16h",864e5:"24h"},e,e)}async fetchFundingRate(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={contract_code:r.id};if(!0===r.inverse)i=await this.contractPublicGetSwapApiV1SwapFundingRate(this.extend(o,t));else if(!0===r.linear)i=await this.contractPublicGetV5MarketFundingRate(this.extend(o,t));else throw new a.NotSupported(this.id+" fetchFundingRate() supports inverse and linear swaps only");if(!0===r.linear){let e=this.safeList(i,"data",[]);s=this.safeDict(e,0,{})}else s=this.safeDict(i,"data",{});return this.parseFundingRate(s,r)}async fetchFundingRates(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e),[r,o]=this.handleOptionStringAndParams(t,"fetchFundingRates","subType","linear"),n=r;if(void 0!==s){let e=this.safeString(s,0);n=!0===this.market(e).linear?"linear":"inverse"}if("linear"===n)throw new a.NotSupported(this.id+" fetchFundingRates() not support this market type");if("inverse"===n)i=await this.contractPublicGetSwapApiV1SwapBatchFundingRate(this.extend({},o));else throw new a.NotSupported(this.id+" fetchFundingRates() not support this market type");let d=this.safeList(i,"data",[]);return this.parseFundingRates(d,s)}async fetchBorrowInterest(e,t,i,s,r={}){let a,o;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleMarginModeAndParams("fetchBorrowInterest",r),h={};void 0!==i&&(h["start-date"]=this.yyyymmdd(i)),void 0!==s&&(h.size=s),"isolated"===(void 0===n?"cross":n)?(void 0!==t&&(h.symbol=(a=this.market(t)).id),o=await this.privateGetMarginLoanOrders(this.extend(h,d))):(void 0!==e&&(h.currency=this.currency(e).id),o=await this.privateGetCrossMarginLoanOrders(this.extend(h,d)));let c=this.safeList(o,"data"),l=this.parseBorrowInterests(c,a);return this.filterByCurrencySinceLimit(l,e,i,s)}parseBorrowInterest(e,t){let i=this.safeString(e,"symbol"),s="isolated";void 0===i&&(s="cross");let r=this.safeMarket(i),a=this.safeString(r,"symbol"),o=this.safeInteger(e,"accrued-at");return{info:e,symbol:a,currency:this.safeCurrencyCode(this.safeString(e,"currency")),interest:this.safeNumber(e,"interest-amount"),interestRate:this.safeNumber(e,"interest-rate"),amountBorrowed:this.safeNumber(e,"loan-amount"),marginMode:s,timestamp:o,datetime:this.iso8601(o)}}nonce(){return this.milliseconds()-this.safeInteger(this.options,"timeDifference",0)}sign(e,t="public",i="GET",r={},o,n){let d,h,c,l="/",u=Array.isArray(r);if(c=u?{}:this.omit(r,this.extractParams(e)),"string"==typeof t){if("public"===t||"private"===t?l+=this.version:("v2Public"===t||"v2Private"===t)&&(l+="v2"),l+="/"+this.implodeParams(e,r),"private"===t||"v2Private"===t){this.checkRequiredCredentials();let e=this.ymdhms(this.nonce(),"T"),t={SignatureMethod:"HmacSHA256",SignatureVersion:"2",AccessKeyId:this.apiKey,Timestamp:e};"POST"!==i&&(t=this.extend(t,c));let a=this.keysort(t),o=this.urlencode(a,!0),n=[i,this.hostname,l,o].join("\n"),f=this.hmac(this.encode(n),this.encode(this.secret),s.sc,"base64");if(o+="&"+this.urlencode({Signature:f}),l+="?"+o,"POST"===i){let e;e=u?r:c,h=this.json(e),d={"Content-Type":"application/json"}}else d={"Content-Type":"application/x-www-form-urlencoded"}}else void 0!==c&&Object.keys(c).length>0&&(l+="?"+this.urlencode(c));let o=this.safeString(this.urls.api,t);if(void 0===o)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");l=this.implodeParams(o,{hostname:this.hostname})+l}else{let o,n=this.safeString(t,0),f=this.safeString(t,1),p=this.safeString(t,2),m=this.safeString(t,3),g=this.safeValue(this.urls.hostnames,n);if("string"!=typeof g&&"string"!=typeof(g=this.safeValue(g,p))&&void 0!==m&&(g=this.safeValue(g,m)),o=g,l+=this.implodeParams(e,r),"public"===f)void 0!==c&&Object.keys(c).length>0&&(l+="?"+this.urlencode(c));else if("private"===f){if(this.checkRequiredCredentials(),"POST"===i){let t=this.safeDict(this.options,"broker",{}),i=this.safeString(t,"id","AA03022abc");!u&&(-1===e.indexOf("cancel")&&e.endsWith("order")?void 0===this.safeString(r,"channel_code")&&(r.channel_code=i):e.endsWith("orders/place")&&void 0===this.safeString(r,"client-order-id")&&(r["client-order-id"]=i+this.uuid()))}let t=this.ymdhms(this.nonce(),"T"),a={SignatureMethod:"HmacSHA256",SignatureVersion:"2",AccessKeyId:this.apiKey,Timestamp:t};if(a=this.keysort(a),"POST"!==i){let e=this.keysort(c);a=this.extend(a,e)}let n=this.urlencode(a,!0).replace("%2c","%2C"),f=[i,o,l,n].join("\n"),p=this.hmac(this.encode(f),this.encode(this.secret),s.sc,"base64");if(n+="&"+this.urlencode({Signature:p}),l+="?"+n,"POST"===i){let e;e=u?r:c,h=this.json(e),u||2!==h.length||(h="{}"),d={"Content-Type":"application/json"}}else d={"Content-Type":"application/x-www-form-urlencoded"}}let v=this.safeString(this.urls.api,n);if(void 0===v)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");l=this.implodeParams(v,{hostname:o})+l}return{url:l,method:i,body:void 0!==h?h:n,headers:void 0!==d?d:o}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;if("status"in n&&"error"===this.safeString(n,"status")){let e=this.safeString2(n,"err-code","err_code"),t=this.id+" "+o;this.throwBroadlyMatchedException(this.exceptions.broad,o,t),this.throwExactlyMatchedException(this.exceptions.exact,e,t);let i=this.safeString2(n,"err-msg","err_msg");throw this.throwExactlyMatchedException(this.exceptions.exact,i,t),new a.ExchangeError(t)}if("code"in n){let e=this.id+" "+o,t=this.safeString(n,"code");this.throwExactlyMatchedException(this.exceptions.exact,t,e)}let c=this.safeDict(n,"data"),l=this.safeList(c,"errors");if(void 0!==l){let e=this.safeDict(l,0),t=this.safeString(e,"err_code"),i=this.safeString(e,"err_msg"),s=this.id+" "+o;this.throwExactlyMatchedException(this.exceptions.exact,t,s),this.throwExactlyMatchedException(this.exceptions.exact,i,s)}}async fetchFundingHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.market(e),[o,n]=this.handleMarketTypeAndParams("fetchFundingHistory",a,s),[d,h]=this.handleUntilOption("end_time",{type:"30,31"},n);if(void 0!==t&&(!0===a.linear?d.start_time=t:d.start_date=t),"swap"===o)if(!0===a.linear){let[e,t]=this.handleMarginModeAndParams("fetchFundingHistory",h);d.margin_mode=void 0===e?"cross":e,d.contract_code=a.id,void 0!==i&&(d.limit=i),r=await this.contractPrivateGetV5AccountBills(this.extend(d,t))}else d.contract=a.id,r=await this.contractPrivatePostSwapApiV3SwapFinancialRecordExact(this.extend(d,h));else d.symbol=a.id,r=await this.contractPrivatePostApiV3ContractFinancialRecordExact(this.extend(d,h));let c=this.safeList(r,"data",[]);return this.parseIncomes(c,a,t,i)}async setLeverage(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),[o,n]=this.handleMarketTypeAndParams("setLeverage",r,i),d={lever_rate:e};if("future"===o&&!0===r.inverse?d.symbol=r.settleId:d.contract_code=r.id,!0===r.linear){let e=this.handleMarginModeAndParams("setLeverage",i)[0];d.margin_mode=void 0===e?"cross":e,s=await this.contractPrivatePostV5PositionLever(this.extend(d,n))}else if("future"===o)s=await this.contractPrivatePostApiV1ContractSwitchLeverRate(this.extend(d,n));else if("swap"===o)s=await this.contractPrivatePostSwapApiV1SwapSwitchLeverRate(this.extend(d,n));else throw new a.NotSupported(this.id+" setLeverage() not support this market type");if(void 0===s)throw new a.NullResponse(this.id+" setLeverage() returned empty response");return s}parseIncome(e,t){let i=this.safeString(e,"contract_code"),s=this.safeSymbol(i,t),r=this.safeNumber(e,"amount"),a=this.safeInteger2(e,"ts","created_time"),o=this.safeString(e,"id"),n=this.safeStringN(e,["symbol","asset","currency"]);return{info:e,symbol:s,code:this.safeCurrencyCode(n),timestamp:a,datetime:this.iso8601(a),id:o,amount:r}}parsePosition(e,t){let i,s,r,a,n,d=this.safeMarket(this.safeString(e,"contract_code")),h=d.symbol,c=this.safeString(e,"volume"),l=this.safeNumber(d,"contractSize"),u=this.numberToString(l),f=this.safeNumber2(e,"cost_open","open_avg_price"),p=this.safeString2(e,"position_margin","initial_margin"),m=this.safeString(e,"direction"),g="short";"buy"===m&&(g="long");let v=this.safeString(e,"position_side"),y=g;("long"===v||"short"===v)&&(y=v);let b=this.safeNumber(e,"profit_unreal"),w=this.safeString(e,"margin_mode"),k=this.safeString(e,"lever_rate"),S=o.Y.stringMul(this.safeString(e,"profit_rate"),"100"),O=this.safeString(e,"last_price"),T=o.Y.stringMul(c,u);!0===d.linear?i=o.Y.stringMul(T,O):(i=o.Y.stringDiv(T,O),w="cross");let P=o.Y.stringDiv(p,i),I=this.safeString2(e,"margin_balance","margin"),A=this.safeString(e,"adjust_factor"),x=this.safeString(e,"maintenance_margin"),M=this.safeString(e,"margin_rate");void 0===x?(s=o.Y.stringDiv(A,k),r=o.Y.stringMul(s,i),n=this.parseNumber(s)):r=x,a=void 0===M?o.Y.stringDiv(r,I):M;let _=this.safeInteger(e,"created_time");return this.safePosition({info:e,id:void 0,symbol:h,contracts:this.parseNumber(c),contractSize:l,entryPrice:f,collateral:this.parseNumber(I),side:y,unrealizedPnl:b,leverage:this.parseNumber(k),percentage:this.parseNumber(S),marginMode:w,notional:this.parseNumber(i),markPrice:this.safeNumber(e,"mark_price"),lastPrice:this.parseNumber(O),liquidationPrice:this.safeNumber(e,"liquidation_price"),initialMargin:this.parseNumber(p),initialMarginPercentage:this.parseNumber(P),maintenanceMargin:this.parseNumber(r),maintenanceMarginPercentage:n,marginRatio:this.parseNumber(a),timestamp:_,datetime:this.iso8601(_),hedged:void 0,lastUpdateTimestamp:this.safeInteger(e,"updated_time"),stopLossPrice:void 0,takeProfitPrice:void 0})}async fetchPositions(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e);if(void 0!==r&&r.length>0){let e=this.safeString(r,0);i=this.market(e)}let[o,n]=this.handleSubTypeAndParams("fetchPositions",i,t,"linear"),[d,h]=this.handleMarketTypeAndParams("fetchPositions",i,n),c=d;if("spot"===d&&(c="future"),"linear"===o)s=await this.contractPrivateGetV5TradePositionOpens(h);else if("future"===c)s=await this.contractPrivatePostApiV1ContractPositionInfo(h);else if("swap"===c)s=await this.contractPrivatePostSwapApiV1SwapPositionInfo(h);else throw new a.NotSupported(this.id+" fetchPositions() not support this market type");let l=this.safeList(s,"data",[]),u=this.safeInteger(s,"ts"),f=[];for(let e=0;e<l.length;e++){let t=l[e],i=this.parsePosition(t);f.push(this.extend(i,{timestamp:u,datetime:this.iso8601(u)}))}return this.filterByArrayPositions(f,"symbol",r)}async fetchPosition(e,t={}){let i,s,r;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),[n,d]=this.handleMarginModeAndParams("fetchPosition",t),h=void 0===n?"cross":n,[c,l]=this.handleMarketTypeAndParams("fetchPosition",o,d),u={};if(!0===o.future&&!0===o.inverse?u.symbol=o.settleId:(!0!==o.linear&&"cross"===h&&(u.margin_account="USDT"),u.contract_code=o.id),!0===o.linear)i=await this.contractPrivateGetV5TradePositionOpens(this.extend(u,l));else if("future"===c)i=await this.contractPrivatePostApiV1ContractAccountPositionInfo(this.extend(u,l));else if("swap"===c)i=await this.contractPrivatePostSwapApiV1SwapAccountPositionInfo(this.extend(u,l));else throw new a.NotSupported(this.id+" setLeverage() not support this market type");let f=this.safeValue(i,"data");if(!0===o.linear){let e=this.safeDict(f,0,{});return this.parsePosition(e,o)}s="cross"===h?f:this.safeDict(f,0);let p=this.omit(s,["positions"]),m=this.safeValue(s,"positions");if(!0===o.future&&!0===o.inverse)for(let e=0;e<m.length;e++){let t=m[e];if(this.safeString(t,"contract_code")===o.id){r=t;break}}else r=this.safeDict(m,0);let g=this.safeInteger(i,"ts"),v=this.parsePosition(this.extend(r,p),o);return v.timestamp=g,v.datetime=this.iso8601(g),v}parseLedgerEntryType(e){return this.safeString({trade:"trade",etf:"trade","transact-fee":"fee","fee-deduction":"fee",transfer:"transfer",credit:"credit",liquidation:"trade",interest:"credit",deposit:"deposit",withdraw:"withdrawal","withdraw-fee":"fee",exchange:"exchange","other-types":"transfer",rebate:"rebate"},e,e)}parseLedgerEntry(e,t){let i=this.safeString(e,"currency"),s=this.safeCurrencyCode(i,t),r=this.safeCurrency(i,t),a=this.safeString(e,"transactId"),o=this.safeString(e,"transferType"),n=this.safeInteger(e,"transactTime"),d=this.safeString(e,"accountId");return this.safeLedgerEntry({info:e,id:a,direction:this.safeString(e,"direction"),account:d,referenceId:a,referenceAccount:d,type:this.parseLedgerEntryType(o),currency:s,amount:this.safeNumber(e,"transactAmt"),timestamp:n,datetime:this.iso8601(n),before:void 0,after:void 0,status:void 0,fee:void 0},r)}async fetchLedger(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchLedger","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchLedger",e,t,i,o,500);let n={accountId:await this.fetchAccountIdByType("spot",void 0,void 0,o)};void 0!==e&&(n.currency=(r=this.currency(e)).id),void 0!==t&&(n.startTime=t),void 0!==i&&(n.limit=i);let[d,h]=this.handleUntilOption("endTime",n,o),c=await this.spotPrivateGetV2AccountLedger(this.extend(d,h)),l=this.safeList(c,"data",[]);return this.parseLedger(l,r,t,i)}async fetchLeverageTiers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.contractPublicGetLinearSwapApiV1SwapAdjustfactor(t),s=this.safeList(i,"data",[]);return this.parseLeverageTiers(s,e,"contract_code")}parseMarketLeverageTiers(e,t){let i=this.safeString(e,"trade_partition"),s=this.safeString(e,"contract_code"),r=[],a=this.safeList(e,"list",[]);for(let e=0;e<a.length;e++){let n=this.safeDict(a,e),d=this.safeString(n,"lever_rate"),h=this.safeList(n,"ladders",[]);for(let e=0;e<h.length;e++){let a=h[e],n=this.safeString(a,"adjust_factor");r.push({tier:this.safeInteger(a,"ladder"),symbol:this.safeSymbol(s,t,void 0,"swap"),currency:this.safeCurrencyCode(i),minNotional:this.safeNumber(a,"min_size"),maxNotional:this.safeNumber(a,"max_size"),maintenanceMarginRate:this.parseNumber(o.Y.stringDiv(n,d)),maxLeverage:this.parseNumber(d),info:a})}}return r}async fetchOpenInterestHistory(e,t="1h",i,s,r={}){let o;if("1h"!==t&&"4h"!==t&&"12h"!==t&&"1d"!==t)throw new a.BadRequest(this.id+" fetchOpenInterestHistory cannot only use the 1h, 4h, 12h and 1d timeframe");void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d={period:{"1h":"60min","4h":"4hour","12h":"12hour","1d":"1day"}[t],amount_type:this.safeInteger2(r,"amount_type","amountType",2)};void 0!==s&&(d.size=s),!0===n.future?(d.contract_type=this.safeString(n.info,"contract_type"),d.symbol=n.baseId,o=await this.contractPublicGetApiV1ContractHisOpenInterest(this.extend(d,r))):!0===n.linear?(d.contract_type="swap",d.contract_code=n.id,d.contract_code=n.id,o=await this.contractPublicGetLinearSwapApiV1SwapHisOpenInterest(this.extend(d,r))):(d.contract_code=n.id,o=await this.contractPublicGetSwapApiV1SwapHisOpenInterest(this.extend(d,r)));let h=this.safeDict(o,"data"),c=this.safeList(h,"tick");return this.parseOpenInterestsHistory(c,n,i,s)}async fetchOpenInterests(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e);if(void 0!==r&&r.length>0){let e=this.safeString(r,0);i=this.market(e)}let o={},[n,d]=this.handleSubTypeAndParams("fetchOpenInterests",i,t,"linear"),[h,c]=this.handleMarketTypeAndParams("fetchOpenInterests",i,d);if("future"===h)s=await this.contractPublicGetApiV1ContractOpenInterest(this.extend(o,c));else if("inverse"===n)s=await this.contractPublicGetSwapApiV1SwapOpenInterest(this.extend(o,c));else throw new a.NotSupported(this.id+" fetchOpenInterests() does not currently support linear markets");let l=this.safeList(s,"data",[]);return this.parseOpenInterests(l,r)}async fetchOpenInterest(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e);if(!0!==s.contract)throw new a.BadRequest(this.id+" fetchOpenInterest() supports contract markets only");if(!0===s.option)throw new a.NotSupported(this.id+" fetchOpenInterest() does not currently support option markets");let r={contract_code:s.id};!0===s.future?(r.contract_type=this.safeString(s.info,"contract_type"),r.symbol=s.baseId,i=await this.contractPublicGetApiV1ContractOpenInterest(this.extend(r,t))):i=!0===s.linear?await this.contractPublicGetV5MarketOpenInterest(this.extend(r,t)):await this.contractPublicGetSwapApiV1SwapOpenInterest(this.extend(r,t));let o=this.safeInteger(i,"ts");if(!0===s.linear){let e=this.safeDict(i,"data",{});return this.extend(this.parseOpenInterest(e,s),{timestamp:o,datetime:this.iso8601(o)})}let n=this.safeList(i,"data",[]),d=this.parseOpenInterest(n[0],s);return d.timestamp=o,d.datetime=this.iso8601(o),d}parseOpenInterest(e,t){let i=this.safeInteger(e,"ts"),s=this.safeNumber(e,"volume"),r=this.safeNumber(e,"value"),a=this.safeString(e,"contract_code");return this.safeOpenInterest({symbol:this.safeSymbol(a,t),baseVolume:s,quoteVolume:r,openInterestAmount:s,openInterestValue:r,timestamp:i,datetime:this.iso8601(i),info:e},t)}async borrowIsolatedMargin(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.currency(t),a=this.market(e),o={currency:r.id,amount:this.currencyToPrecision(t,i),symbol:a.id},n=await this.privatePostMarginOrders(this.extend(o,s)),d=this.parseMarginLoan(n,r);return this.extend(d,{amount:i,symbol:e})}async borrowCrossMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.currency(e),r={currency:s.id,amount:this.currencyToPrecision(e,t)},a=await this.privatePostCrossMarginOrders(this.extend(r,i)),o=this.parseMarginLoan(a,s);return this.extend(o,{amount:t})}async repayIsolatedMargin(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.currency(t),a=await this.fetchAccountIdByType("spot","isolated",e,s),o={currency:r.id,amount:this.currencyToPrecision(t,i),accountId:a},n=await this.v2PrivatePostAccountRepayment(this.extend(o,s)),d=this.safeList(n,"Data",[]),h=this.safeDict(d,0),c=this.parseMarginLoan(h,r);return this.extend(c,{amount:i,symbol:e})}async repayCrossMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.currency(e),r=await this.fetchAccountIdByType("spot","cross",void 0,i),a={currency:s.id,amount:this.currencyToPrecision(e,t),accountId:r},o=await this.v2PrivatePostAccountRepayment(this.extend(a,i)),n=this.safeList(o,"Data",[]),d=this.safeDict(n,0),h=this.parseMarginLoan(d,s);return this.extend(h,{amount:t})}parseMarginLoan(e,t){let i=this.safeInteger(e,"repayTime");return{id:this.safeString2(e,"repayId","data"),currency:this.safeCurrencyCode(void 0,t),amount:void 0,symbol:void 0,timestamp:i,datetime:this.iso8601(i),info:e}}async fetchSettlementHistory(e,t,i,s={}){let r;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchSettlementHistory() requires a symbol argument");let o=this.market(e),n={};!0===o.future?n.symbol=o.baseId:n.contract_code=o.id,void 0!==i&&(!0===o.linear&&!0===o.swap?n.limit=i:n.page_size=i),void 0!==t&&(n.start_time=t);let[d,h]=this.handleUntilOption("end_time",n,s);if(r=!0===o.swap?!0===o.linear?await this.contractPublicGetV5MarketSettlementHistory(this.extend(d,h)):await this.contractPublicGetSwapApiV1SwapSettlementRecords(this.extend(d,h)):await this.contractPublicGetApiV1ContractSettlementRecords(this.extend(d,h)),!0===o.linear){let e=this.safeList(r,"data",[]),t=this.parseSettlements(e,o);return this.sortBy(t,"timestamp")}let c=this.safeDict(r,"data"),l=this.safeList(c,"settlement_record"),u=this.parseSettlements(l,o);return this.sortBy(u,"timestamp")}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.spotPublicGetV2ReferenceCurrencies(t),s=this.safeList(i,"data");return this.parseDepositWithdrawFees(s,e,"currency")}parseDepositWithdrawFee(e,t){let i=this.safeList(e,"chains",[]),s=this.safeString(t,"code"),r=this.depositWithdrawFee(e);for(let e=0;e<i.length;e++){let a,o=this.safeDict(i,e),n=this.safeString(o,"chain"),d=this.safeString(o,"withdrawFeeType"),h=this.networkIdToCode(n,s);a="fixed"===d?{fee:this.safeNumber(o,"transactFeeWithdraw"),percentage:!1}:{fee:this.safeNumber(o,"transactFeeRateWithdraw"),percentage:!0},void 0!==h&&(r.networks[h]={withdraw:a,deposit:{fee:void 0,percentage:void 0}}),r=this.assignDefaultDepositWithdrawFees(r,t)}return r}parseSettlements(e,t){let i=[];for(let s=0;s<e.length;s++){let r=this.safeDict(e,s),a=this.safeList(r,"list");if(!0===t.linear){let e=this.parseSettlement(r,t);i.push(e)}else if(void 0!==a){let e=this.safeInteger(r,"settlement_time"),s={timestamp:e,datetime:this.iso8601(e)};for(let e=0;e<a.length;e++){let r=this.safeDict(a,e),o=this.parseSettlement(r,t);i.push(this.extend(o,s))}}else i.push(this.parseSettlement(e[s],t))}return i}parseSettlement(e,t){let i=this.safeInteger(e,"settlement_time"),s=this.safeString(e,"contract_code");return{info:e,symbol:this.safeSymbol(s,t),price:this.safeNumber(e,"settlement_price"),timestamp:i,datetime:this.iso8601(i)}}async fetchLiquidations(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=this.safeInteger2(s,"trade_type","tradeType",0),d={};!0!==o.linear&&(d.trade_type=n);let h=this.omit(s,["trade_type","tradeType"]);void 0!==t&&(d.start_time=t);let[c,l]=this.handleUntilOption("end_time",d,h);if(!0===o.swap)!0===o.linear?(c.contract_code=o.id,void 0!==i&&(c.limit=i),r=await this.contractPublicGetV5MarketLiquidationOrders(this.extend(c,l))):(c.contract=o.id,r=await this.contractPublicGetSwapApiV3SwapLiquidationOrders(this.extend(c,l)));else if(!0===o.future)c.symbol=o.id,r=await this.contractPublicGetApiV3ContractLiquidationOrders(this.extend(c,l));else throw new a.NotSupported(this.id+" fetchLiquidations() does not support "+o.type+" orders");let u=this.safeList(r,"data",[]);return this.parseLiquidations(u,o,t,i)}parseLiquidation(e,t){let i=this.safeString(e,"contract_code"),s=this.safeInteger2(e,"created_at","liquidation_time");return this.safeLiquidation({info:e,symbol:this.safeSymbol(i,t),contracts:this.safeNumber(e,"volume"),contractSize:this.safeNumber(t,"contractSize"),price:this.safeNumber2(e,"price","bankrupt_price"),side:this.safeStringLower2(e,"direction","side"),baseValue:this.safeNumber(e,"amount"),quoteValue:this.safeNumber(e,"trade_turnover"),timestamp:s,datetime:this.iso8601(s)})}async closePosition(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o=this.safeString(i,"clientOrderId");if(!0!==r.contract)throw new a.BadRequest(this.id+" closePosition() symbol supports contract markets only");let n={contract_code:r.id},d=void 0!==o?this.omit(i,"clientOrderId"):i;if(void 0!==o&&(n.client_order_id=o),!0===r.linear){let[e,t]=this.handleMarginModeAndParams("closePosition",d,"cross");n.margin_mode=e,s=await this.contractPrivatePostV5TradePosition(this.extend(n,t))}else{this.checkRequiredArgument("closePosition",t,"side");let i=this.safeString2(d,"volume","amount");if(void 0===i)throw new a.ArgumentsRequired(this.id+' closePosition () requires an extra argument params["amount"] for inverse markets');n.volume=this.amountToPrecision(e,i),n.direction=t;let o=this.omit(d,["volume","amount"]);s=!0===r.swap?await this.contractPrivatePostSwapApiV1SwapLightningClosePosition(this.extend(n,o)):await this.contractPrivatePostApiV1LightningClosePosition(this.extend(n,o))}if(!0===r.linear){let e=this.safeDict(s,"data",{});return this.parseOrder(e,r)}if(void 0===s)throw new a.NullResponse(this.id+" parseOrder() returned empty response");return this.parseOrder(s,r)}async setPositionMode(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r="single_side";e&&(r="dual_side"),void 0!==t&&(s=this.market(t));let o={position_mode:r};if(void 0!==s&&!0===s.inverse)throw new a.BadRequest(this.id+" setPositionMode can only be used for linear markets");return await this.contractPrivatePostV5PositionMode(this.extend(o,i))}async fetchPositionsADLRank(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!0,!0,!0);if(void 0!==r&&r.length>0){let e=this.safeString(r,0);i=this.market(e)}let[o,n]=this.handleSubTypeAndParams("fetchPositionsADLRank",i,t,"linear"),[d,h]=this.handleMarketTypeAndParams("fetchPositionsADLRank",i,n),c=d;if("spot"===d&&(c="future"),"linear"===o)s=await this.contractPrivateGetV5TradePositionOpens(h);else if("future"===c)s=await this.contractPrivatePostApiV1ContractPositionInfo(h);else if("swap"===c)s=await this.contractPrivatePostSwapApiV1SwapPositionInfo(h);else throw new a.NotSupported(this.id+" fetchPositionsADLRank() not support this market type");let l=this.safeList(s,"data",[]);return this.parseADLRanks(l,r)}parseADLRank(e,t){let i=this.safeString(e,"contract_code"),s=this.safeInteger(e,"created_time");return{info:e,symbol:this.safeSymbol(i,t,void 0,"contract"),rank:this.safeInteger(e,"adl_risk_percent"),rating:void 0,percentage:void 0,timestamp:s,datetime:this.iso8601(s)}}}i.d(t,{A:()=>n})},7450(e,t,i){"use strict";var s=i(6834),r=i(6885),a=i(6641),o=i(1453),n=i(7749),d=i(1093);class h extends a.A{describe(){return this.deepExtend(super.describe(),{id:"hyperliquid",name:"Hyperliquid",countries:[],version:"v1",rateLimit:50,certified:!0,pro:!0,dex:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!0,future:!1,option:!1,addMargin:!0,borrowCrossMargin:!1,borrowIsolatedMargin:!1,cancelAllOrders:!1,cancelAllOrdersAfter:!0,cancelOrder:!0,cancelOrders:!0,cancelOrdersForSymbols:!0,closeAllPositions:!1,closePosition:!1,createMarketBuyOrderWithCost:!1,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!0,createReduceOnlyOrder:!0,createStopOrder:!0,createTriggerOrder:!0,editOrder:!0,editOrders:!0,fetchAccounts:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchCanceledAndClosedOrders:!0,fetchCanceledOrders:!0,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDeposits:!0,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!1,fetchFundingHistory:!0,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLedger:!0,fetchLeverage:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchMarginMode:void 0,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyLiquidations:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!1,fetchOpenInterests:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchOrderTrades:!1,fetchPosition:!0,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchStatus:!0,fetchTicker:"emulated",fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!1,fetchTransfer:!1,fetchTransfers:!1,fetchWithdrawal:!1,fetchWithdrawals:!0,reduceMargin:!0,repayCrossMargin:!1,repayIsolatedMargin:!1,sandbox:!0,setLeverage:!0,setMarginMode:!0,setPositionMode:!1,transfer:!0,withdraw:!0},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","8h":"8h","12h":"12h","1d":"1d","3d":"3d","1w":"1w","1M":"1M"},hostname:"hyperliquid.xyz",urls:{logo:"https://github.com/user-attachments/assets/550769b3-d270-461e-9e02-8e8b8c0210b8",api:{public:"https://api.{hostname}",private:"https://api.{hostname}"},test:{public:"https://api.hyperliquid-testnet.xyz",private:"https://api.hyperliquid-testnet.xyz"},www:"https://hyperliquid.xyz",doc:"https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api",fees:"https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees",referral:"https://app.hyperliquid.xyz/"},api:{public:{post:{info:{cost:10,byType:{l2Book:2,allMids:2,clearinghouseState:2,orderStatus:2,spotClearinghouseState:2,exchangeStatus:2,candleSnapshot:4}}}},private:{post:{exchange:{cost:1}}}},fees:{swap:{taker:this.parseNumber("0.00045"),maker:this.parseNumber("0.00015")},spot:{taker:this.parseNumber("0.0007"),maker:this.parseNumber("0.0004")}},requiredCredentials:{apiKey:!1,secret:!1,walletAddress:!0,privateKey:!0},exceptions:{exact:{},broad:{"Price must be divisible by tick size.":o.InvalidOrder,"Order must have minimum value of $10":o.InvalidOrder,"Insufficient margin to place order.":o.InsufficientFunds,"Reduce only order would increase position.":o.InvalidOrder,"Post only order would have immediately matched,":o.InvalidOrder,"Order could not immediately match against any resting orders.":o.InvalidOrder,"Invalid TP/SL price.":o.InvalidOrder,"No liquidity available for market order.":o.InvalidOrder,"Order was never placed, already canceled, or filled.":o.OrderNotFound,"User or API Wallet ":o.InvalidOrder,"Order has invalid size":o.InvalidOrder,"Order price cannot be more than 80% away from the reference price":o.InvalidOrder,"Order has zero size.":o.InvalidOrder,"Insufficient spot balance asset":o.InsufficientFunds,"Insufficient balance for withdrawal":o.InsufficientFunds,"Insufficient balance for token transfer":o.InsufficientFunds,"TWAP order value too small. Min is $1200, which is $10 per minute.":o.InvalidOrder,"TWAP was never placed, already canceled, or filled.":o.OrderNotFound,"Too many cumulative requests sent":o.RateLimitExceeded}},precisionMode:4,commonCurrencies:{},options:{defaultType:"swap",sandboxMode:!1,builderFee:!0,defaultSlippage:.05,marketHelperProps:["hip3TokensByName","cachedCurrenciesById"],zeroAddress:"0x0000000000000000000000000000000000000000",spotCurrencyMapping:{UDZ:"2Z",UBONK:"BONK",UBTC:"BTC",UETH:"ETH",UFART:"FARTCOIN",HPENGU:"PENGU",UPUMP:"PUMP",USOL:"SOL",UUUSPX:"SPX",USDT0:"USDT",XAUT0:"XAUT",UXPL:"XPL"},fetchMarkets:{types:["spot","swap","hip3"],hip3:{limit:10,dexes:[]}}},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:{triggerPriceType:{last:!1,mark:!1,index:!1},triggerPrice:!0,type:!0,price:!0},timeInForce:{IOC:!0,FOK:!1,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:{max:1e3},fetchMyTrades:{marginMode:!1,limit:2e3,daysBack:void 0,untilDays:void 0,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:2e3,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:{marginMode:!1,limit:2e3,daysBack:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:{marginMode:!1,limit:2e3,daysBack:void 0,daysBackCanceled:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOHLCV:{limit:5e3}},spot:{extends:"default"},forPerps:{extends:"default",createOrder:{stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0}},swap:{linear:{extends:"forPerps"},inverse:{extends:"forPerps"}},future:{linear:{extends:"forPerps"},inverse:{extends:"forPerps"}}},rollingWindowSize:0})}setSandboxMode(e){super.setSandboxMode(e),this.options.sandboxMode=e}nonce(){return this.milliseconds()}market(e){if(void 0===e)throw new o.ArgumentsRequired(this.id+" market() requires a symbol argument");if(void 0===this.markets)throw new o.ExchangeError(this.id+" markets not loaded");if(void 0!==e&&!(e in this.markets)){let t=e.split("/"),i=this.safeString(t,0),s=this.safeDict(this.options,"spotCurrencyMapping",{});if(i in s){let e=this.safeString(s,i),r=this.safeString(t,1),a=this.safeCurrencyCode(e)+"/"+r;if(a in this.markets)return this.markets[a]}}return super.market(e)}async fetchStatus(e={}){let t=await this.publicPostInfo(this.extend({type:"exchangeStatus"},e));return{status:void 0===this.safeString(t,"specialStatuses")?"ok":"maintenance",updated:this.safeInteger(t,"time"),eta:void 0,url:void 0,info:t}}async fetchTime(e={}){let t=await this.publicPostInfo(this.extend({type:"exchangeStatus"},e));return this.safeInteger(t,"time")}async fetchCurrencies(e={}){this.checkRequiredCredentials(!1)&&await this.initializeClient();let t=await this.publicPostInfo(this.extend({type:"spotMeta"},e)),i=this.safeList(t,"tokens",[]);return this.options.cachedCurrenciesById={},this.parseCurrencies(i)}parseCurrency(e){let t=this.safeString(e,"index"),i=this.safeString(e,"name"),s=this.safeCurrencyCode(i);this.options.cachedCurrenciesById[t]=i;let r=this.safeCurrencyStructure({id:t,name:i,code:s,precision:this.parsePrecision(this.safeString(e,"weiDecimals")),info:e,active:void 0,deposit:void 0,withdraw:void 0,networks:void 0,fee:void 0,type:"crypto",limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}}}),a=this.safeString(e,"fullName");if(void 0!==a&&void 0!==i&&a.startsWith("Unit ")&&i.startsWith("U")){let e=i.split("U"),t="";for(let i=0;i<e.length;i++)t+=e[i];let r=this.safeCurrencyCode(t);void 0!==s&&(this.options.spotCurrencyMapping[s]=r)}return r}async fetchMarkets(e={}){let t=this.safeDict(this.options,"fetchMarkets",{}),i=this.safeList(t,"types",[]),s=[];for(let t=0;t<i.length;t++){let r=this.safeString(i,t);"swap"===r?s.push(this.fetchSwapMarkets(e)):"spot"===r?s.push(this.fetchSpotMarkets(e)):"hip3"===r&&s.push(this.fetchHip3Markets(e))}let r=await Promise.all(s),a=[];for(let e=0;e<r.length;e++)a=this.arrayConcat(a,r[e]);return a}async fetchHip3Markets(e={}){let t=await this.publicPostInfo({type:"perpDexs"}),i={};for(let e=1;e<t.length;e++){let s=this.safeDict(t,e,{}),r=(e-1)*1e4,a=this.sum(11e4,r);i[s.name]=a}let s=[],r=this.safeDict(this.options,"fetchMarkets",{}),a=this.safeDict(r,"hip3",{}),o=this.safeList(a,"dexes",[]),n=this.safeInteger(a,"limit",10),d=o.length;if(d>0)d>0&&(s=o);else{let e=t.length,i=this.sum(n,1);for(let r=1;r<i&&!(r>=e);r++){let e=this.safeDict(t,r,{});if(void 0===e)continue;let i=this.safeString(e,"name");s.push(i)}}let h=[];for(let t=0;t<s.length;t++){let i={type:"metaAndAssetCtxs",dex:this.safeString(s,t)};h.push(this.publicPostInfo(this.extend(i,e)))}let c=await Promise.all(h);this.options.hip3TokensByName={};let l=[];for(let e=0;e<c.length;e++){let t=s[e],r=i[t],a=this.safeList(c,e),o=this.safeDict(a,0,{}),n=this.safeString(o,"collateralToken"),d=this.safeList(o,"universe",[]),h=this.safeList(a,1,[]),u=[];for(let e=0;e<d.length;e++){let i=this.extend(this.safeDict(d,e,{}),this.safeDict(h,e,{}));i.baseId=this.sum(e,r),i.collateralToken=n,i.hip3=!0,i.dex=t;let s=this.safeDict(this.options,"cachedCurrenciesById",{});if(n in s){let e=this.safeString(i,"name"),t=this.safeString(s,n);i.collateralTokenName=t;let r=this.safeCurrencyCode(e),a=void 0===r?e:r.replace(":","-");this.options.hip3TokensByName[e]={quote:t,code:a}}u.push(i)}l=this.arrayConcat(l,this.parseMarkets(u))}return l}async fetchSwapMarkets(e={}){let t=await this.publicPostInfo(this.extend({type:"metaAndAssetCtxs"},e)),i=this.safeDict(t,0,{}),s=this.safeList(i,"universe",[]),r=this.safeList(t,1,[]),a=[];for(let e=0;e<s.length;e++){let t=this.extend(this.safeDict(s,e,{}),this.safeDict(r,e,{}));t.baseId=e,a.push(t)}return this.parseMarkets(a)}calculatePricePrecision(e,t,i){let s=0,r=this.numberToString(e);if(void 0===r)return 0;let a=r.split(".");if(n.Y.stringEq(r,"0"))s=Math.min(i-t,5);else if(n.Y.stringGt(r,"0")&&n.Y.stringLt(r,"1")){let e=this.safeString(a,1,""),r=0;for(;r<=e.length&&"0"===e[r];)r+=1;s=Math.min(i-t,s=r+5)}else{let e=this.safeString(a,0,"");s=Math.min(i-t,Math.max(5,e.length)-e.length)}return this.parseToInt(s)}async fetchSpotMarkets(e={}){let t=await this.publicPostInfo(this.extend({type:"spotMetaAndAssetCtxs"},e)),i=this.safeDict(t,0,{}),s=this.safeList(t,1,[]),r=this.safeList(i,"universe",[]),a=this.safeList(i,"tokens",[]),o=[];for(let e=0;e<r.length;e++){let t=this.safeDict(r,e,{}),i=this.safeInteger(t,"index"),n=this.safeDict(s,i,{}),d=this.safeString(t,"name"),h=this.safeDict(this.fees,"spot",{}),c=this.safeNumber(h,"taker"),l=this.safeNumber(h,"maker"),u=this.safeList(t,"tokens",[]),f=this.safeInteger(u,0),p=this.safeInteger(u,1),m=this.safeDict(a,f,{}),g=this.safeDict(a,p,{}),v=this.safeString(m,"name"),y=this.safeString(g,"name");if(void 0===v||void 0===y)continue;let b=this.safeDict(this.options,"spotCurrencyMapping",{}),w=this.safeString(b,v,v),k=this.safeString(b,y,y),S=this.safeCurrencyCode(w),O=this.safeCurrencyCode(k),T=S+"/"+O,P=this.safeDict(m,"spec",m),I=this.safeString(P,"szDecimals"),A=parseInt(I),x=this.safeNumber(n,"midPx"),M=0;void 0!==x&&(M=this.calculatePricePrecision(x,A,8));let _=this.numberToString(M),C={id:d,symbol:T,base:S,quote:O,settle:void 0,baseId:this.numberToString(i+1e4),baseName:v,quoteId:y,settleId:void 0,type:"spot",spot:!0,subType:void 0,margin:void 0,swap:!1,future:!1,option:!1,active:!0,contract:!1,linear:void 0,inverse:void 0,taker:c,maker:l,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(I)),price:this.parseNumber(this.parsePrecision(_))},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:this.parseNumber("10"),max:void 0}},created:void 0,info:this.extend(n,t)};o.push(this.safeMarketStructure(C))}return o}parseMarket(e){let t=this.safeString(e,"collateralTokenName"),i=t;void 0===t&&(i="USDC");let s=t;void 0===t&&(s="USDC");let r=this.safeString(e,"name"),a=this.safeCurrencyCode(r);if(void 0===a)throw new o.ExchangeError(this.id+" parseMarket() missing base currency");a=a.replace(":","-");let n=this.safeCurrencyCode(i);if(void 0===n)return;let d=this.safeString(e,"baseId"),h=this.safeCurrencyCode(s),c=a+"/"+n;c=c+":"+h;let l=this.safeDict(this.fees,"swap",{}),u=this.safeNumber(l,"taker"),f=this.safeNumber(l,"maker"),p=this.safeString(e,"szDecimals"),m=parseInt(p),g=this.safeNumber(e,"markPx",0),v=0;void 0!==g&&(v=this.calculatePricePrecision(g,m,6));let y=this.numberToString(v),b=this.safeBool(e,"isDelisted"),w=!0;return void 0!==b&&(w=!b),this.safeMarketStructure({id:d,symbol:c,base:a,quote:n,settle:h,baseId:d,baseName:r,quoteId:i,settleId:s,type:"swap",spot:!1,margin:void 0,swap:!0,future:!1,option:!1,active:w,contract:!0,linear:!0,inverse:!1,taker:u,maker:f,contractSize:this.parseNumber("1"),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(p)),price:this.parseNumber(this.parsePrecision(y))},limits:{leverage:{min:void 0,max:this.safeInteger(e,"maxLeverage")},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:this.parseNumber("10"),max:void 0}},created:void 0,info:e})}updateSpotCurrencyCode(e){if(void 0===e)return e;let t=this.safeDict(this.options,"spotCurrencyMapping",{});return this.safeString(t,e,e)}async fetchBalance(e={}){let t=void 0!==this.safeString2(e,"user","address")&&void 0===this.safeBool(e,"enableUnifiedMargin"),[i,s]=this.handlePublicAddress("fetchBalance",e),[r,a]=this.handleMarketTypeAndParams("fetchBalance",void 0,s),[o,n]=this.handleMarginModeAndParams("fetchBalance",a),[d,h]=await this.isUnifiedEnabled("fetchBalance",i,t,n),c=this.safeString(h,"dex"),l=("spot"===r||!0===d)&&void 0===c,u=await this.publicPostInfo(this.extend({type:!0===l?"spotClearinghouseState":"clearinghouseState",user:i},h)),f=this.safeList(u,"balances");if(void 0!==f){let e={info:u};for(let t=0;t<f.length;t++){let i=this.safeDict(f,t),s=this.safeCurrencyCode(this.safeString(i,"coin")),r=!0===l?this.updateSpotCurrencyCode(s):s,a=this.account(),o=this.safeString(i,"total"),n=this.safeString(i,"hold");a.total=o,a.used=n,void 0!==r&&(e[r]=a)}return this.safeBalance(e)}let p=this.safeDict(u,"marginSummary",{}),m={total:this.safeNumber(p,"accountValue")};void 0!==o&&"isolated"===o?m.free=this.safeNumber(u,"withdrawable"):m.used=this.safeNumber(p,"totalMarginUsed");let g={info:u,USDC:m},v=this.safeInteger(u,"time");return g.timestamp=v,g.datetime=this.iso8601(v),this.safeBalance(g)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={type:"l2Book",coin:!0===s.swap?this.safeString(s,"baseName"):s.id},a=await this.publicPostInfo(this.extend(r,i)),o=this.safeList(a,"levels",[]),n={bids:this.safeList(o,0,[]),asks:this.safeList(o,1,[])},d=this.safeInteger(a,"time");return this.parseOrderBook(n,s.symbol,d,"bids","asks","px","sz")}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=[],r=this.safeString(t,"type"),a=this.omit(t,"type"),[o,n]=this.handleOptionBoolAndParams(a,"fetchTickers","hip3",!1),d=o;if(void 0!==i){let e=this.safeString(i,0);if(void 0!==e){let t=this.market(e);this.safeBool(this.safeDict(t,"info"),"hip3",!1)&&(d=!0)}}s=d?await this.fetchHip3Markets(this.omit(n,"hip3")):"spot"===r?await this.fetchSpotMarkets(n):"swap"===r?await this.fetchSwapMarkets(n):await this.fetchMarkets(n);let h={};for(let e=0;e<s.length;e++){let t=s[e],i=t.info,r=this.parseTicker(i,t);h[this.safeString(r,"symbol")]=r}return this.filterByArrayTickers(h,"symbol",i)}async fetchFundingRate(e,t={}){await this.loadMarkets();let i=this.market(e),s=await this.fetchFundingRates([i.symbol],t),r=this.safeDict(s,i.symbol);if(void 0===r)throw new o.BadSymbol(this.id+" fetchFundingRate() could not find a funding rate for "+e);return r}async fetchFundingRates(e,t={}){let i=await this.publicPostInfo(this.extend({type:"metaAndAssetCtxs"},t)),s=this.safeDict(i,0,{}),r=this.safeList(s,"universe",[]),a=this.safeList(i,1,[]),o=[];for(let e=0;e<r.length;e++){let t=this.extend(this.safeDict(r,e,{}),this.safeDict(a,e,{}));o.push(t)}return this.parseFundingRates(o,e)}parseFundingRate(e,t){let i=this.safeString(e,"name"),s=this.coinToMarketId(i),r=this.safeSymbol(s,t),a=this.safeNumber(e,"funding"),o=this.safeNumber(e,"markPx"),n=this.safeNumber(e,"oraclePx"),d=(Math.floor(this.milliseconds()/60/60/1e3)+1)*36e5;return{info:e,symbol:r,markPrice:o,indexPrice:n,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:a,fundingTimestamp:d,fundingDatetime:this.iso8601(d),nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:"1h"}}parseTicker(e,t){let i=this.safeString(e,"name"),s=this.coinToMarketId(i),r=this.safeMarket(s,t),a=this.safeList(e,"impactPxs");return this.safeTicker({symbol:r.symbol,timestamp:void 0,datetime:void 0,previousClose:this.safeNumber(e,"prevDayPx"),close:this.safeNumber(e,"midPx"),last:this.safeNumber(e,"price"),bid:this.safeNumber(a,0),ask:this.safeNumber(a,1),quoteVolume:this.safeNumber(e,"dayNtlVlm"),info:e},r)}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=this.safeInteger(r,"until",this.milliseconds()),n=void 0===i,d=i;if(void 0===i)if(void 0!==s){let e=1e3*this.parseTimeframe(t);(d=this.sum(o,-(e*s*1)))<0&&(d=0),n=!1}else d=0;let h=this.omit(r,["until"]),c={type:"candleSnapshot",req:{coin:!0===a.swap?this.safeString(a,"baseName"):a.id,interval:this.safeString(this.timeframes,t,t),startTime:d,endTime:o}},l=await this.publicPostInfo(this.extend(c,h)),u=[];return Array.isArray(l)&&(u=l),this.parseOHLCVs(u,a,t,i,s,n)}parseOHLCV(e,t){return[this.safeInteger(e,"t"),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}async fetchTrades(e,t,i,s={}){let r,[a,o]=this.handlePublicAddress("fetchTrades",s);void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let n={user:a};void 0!==t?(n.type="userFillsByTime",n.startTime=t):n.type="userFills";let d=this.safeInteger(o,"until"),h=this.omit(o,"until");void 0!==d&&(n.endTime=d);let c=await this.publicPostInfo(this.extend(n,h)),l=[];return Array.isArray(c)&&(l=c),this.parseTrades(l,r,t,i)}amountToPrecision(e,t){let i=this.market(e),s=this.decimalToPrecision(t,1,i.precision.amount,this.precisionMode,this.paddingMode);if(n.Y.stringEq(s,"0")&&n.Y.stringGt(this.numberToString(t),"0"))throw new o.InvalidOrder(this.id+" amount of "+i.symbol+" must be greater than minimum amount precision of "+this.numberToString(i.precision.amount));return s}priceToPrecision(e,t){let i=this.market(e),s=Math.max(5,this.numberToString(t).split(".")[0].length),r=this.decimalToPrecision(t,1,s,3,this.paddingMode),a=(!0===i.spot?8:6)-this.precisionFromString(this.safeString(i.precision,"amount"));return this.decimalToPrecision(r,1,a,2,this.paddingMode)}hashMessage(e){return"0x"+this.hash(e,s.lY,"hex")}signHash(e,t){let i=(0,d.h1)(e.slice(-64),t.slice(-64),r.bI,void 0);return{r:"0x"+i.r,s:"0x"+i.s,v:this.sum(27,i.v)}}signMessage(e,t){return this.signHash(this.hashMessage(e),t.slice(-64))}constructPhantomAgent(e,t=!0){return{source:t?"b":"a",connectionId:e}}actionHash(e,t,i,r){let a=this.packb(e),o=this.binaryToBase16(a);return o+="00000"+this.intToBase16(i),void 0===t?o+="00":(o+="01",o+=t),void 0!==r&&(o+="00",o+="00000"+this.intToBase16(r)),this.hash(this.base16ToBinary(o),s.lY,"binary")}signL1Action(e,t,i,s){let r=this.actionHash(e,i,t,s),a=this.safeBool(this.options,"sandboxMode",!1),o=this.constructPhantomAgent(r,a),n=this.safeString(this.options,"zeroAddress"),d=this.ethEncodeStructuredData({chainId:1337,name:"Exchange",verifyingContract:n,version:"1"},{Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]},o);return this.signMessage(d,this.privateKey)}signUserSignedAction(e,t){let i=this.safeString(this.options,"zeroAddress"),s=this.ethEncodeStructuredData({chainId:421614,name:"HyperliquidSignTransaction",verifyingContract:i,version:"1"},e,t);return this.signMessage(s,this.privateKey)}buildUsdSendSig(e){return this.signUserSignedAction({"HyperliquidTransaction:UsdSend":[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}]},e)}buildUsdClassSendSig(e){return this.signUserSignedAction({"HyperliquidTransaction:UsdClassTransfer":[{name:"hyperliquidChain",type:"string"},{name:"amount",type:"string"},{name:"toPerp",type:"bool"},{name:"nonce",type:"uint64"}]},e)}buildWithdrawSig(e){return this.signUserSignedAction({"HyperliquidTransaction:Withdraw":[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}]},e)}buildUserDexAbstractionSig(e){return this.signUserSignedAction({"HyperliquidTransaction:UserDexAbstraction":[{name:"hyperliquidChain",type:"string"},{name:"user",type:"address"},{name:"enabled",type:"bool"},{name:"nonce",type:"uint64"}]},e)}buildUserAbstractionSig(e){return this.signUserSignedAction({"HyperliquidTransaction:UserSetAbstraction":[{name:"hyperliquidChain",type:"string"},{name:"user",type:"address"},{name:"abstraction",type:"string"},{name:"nonce",type:"uint64"}]},e)}buildApproveBuilderFeeSig(e){return this.signUserSignedAction({"HyperliquidTransaction:ApproveBuilderFee":[{name:"hyperliquidChain",type:"string"},{name:"maxFeeRate",type:"string"},{name:"builder",type:"address"},{name:"nonce",type:"uint64"}]},e)}async setRef(){let e;if(this.safeBool(this.options,"refSet",!1))return!0;this.options.refSet=!0;let t={type:"setReferrer",code:this.safeString(this.options,"ref","CCXT1")},i=this.incrementingNonce(),s=this.signL1Action(t,i);try{e=await this.privatePostExchange({action:t,nonce:i,signature:s})}catch(t){e=void 0}return e}async approveBuilderFee(e,t){let i=this.incrementingNonce(),s={hyperliquidChain:!0===this.safeBool(this.options,"sandboxMode",!1)?"Testnet":"Mainnet",maxFeeRate:t,builder:e,nonce:i},r=this.buildApproveBuilderFeeSig(s),a={hyperliquidChain:s.hyperliquidChain,signatureChainId:"0x66eee",maxFeeRate:s.maxFeeRate,builder:s.builder,nonce:i,type:"approveBuilderFee"};return await this.privatePostExchange({action:a,nonce:i,signature:r,vaultAddress:void 0})}async initializeClient(){try{await Promise.all([this.handleBuilderFeeApproval(),this.setRef(),this.isUnifiedEnabled("fetchBalance",void 0,!1,{})])}catch(e){return!1}return!0}async handleBuilderFeeApproval(){let e=this.safeBool(this.options,"builderFee",!0);if(!0===this.safeBool(this.options,"approvedBuilderFee",!1))return!0;try{let t=this.safeString(this.options,"builder","0x6530512A6c89C7cfCEbC3BA7fcD9aDa5f30827a6"),i=this.safeString(this.options,"feeRate","0.01%");!0!==e&&(i="0%"),await this.approveBuilderFee(t,i),this.options.approvedBuilderFee=!0}catch(e){this.options.builderFee=!1}return!0}async isUnifiedEnabled(e,t,i=!1,s={}){let r,a={};void 0===t&&([r,a]=this.handlePublicAddress("isUnifiedEnabled",s));let n=void 0!==t?t:r,d=void 0!==t?s:a,[h,c]=this.handleOptionBoolAndParams(d,e,"enableUnifiedMargin"),l=h;if(void 0===l||i){let e;try{let t=await this.publicPostInfo(this.extend({type:"userAbstraction",user:n},c));"string"==typeof t&&(e=t)}catch(t){if(t instanceof o.InvalidProxySettings)throw t;e=void 0}void 0!==e&&(l="unifiedAccount"===(e=(e=e.replace('"',"")).replace('"',""))),this.options.enableUnifiedMargin=l}return[l,c]}async setUserAbstraction(e,t={}){let[i,s]=this.handlePublicAddress("setUserAbstraction",t),r=this.incrementingNonce(),a=this.safeBool(this.options,"sandboxMode",!1),o=this.safeString(s,"type","userSetAbstraction"),n={hyperliquidChain:!0===a?"Testnet":"Mainnet",user:i,abstraction:e,nonce:r},d=this.buildUserAbstractionSig(n),h={hyperliquidChain:n.hyperliquidChain,signatureChainId:"0x66eee",abstraction:n.abstraction,user:n.user,nonce:r,type:o};return await this.privatePostExchange({action:h,nonce:r,signature:d,vaultAddress:void 0})}async enableUserDexAbstraction(e,t={}){let[i,s]=this.handlePublicAddress("enableUserDexAbstraction",t),r=this.incrementingNonce(),a=this.safeBool(this.options,"sandboxMode",!1),o=this.safeString(s,"type","userDexAbstraction"),n={hyperliquidChain:!0===a?"Testnet":"Mainnet",user:i,enabled:e,nonce:r},d=this.buildUserDexAbstractionSig(n),h={hyperliquidChain:n.hyperliquidChain,signatureChainId:"0x66eee",enabled:n.enabled,user:n.user,nonce:r,type:o};return await this.privatePostExchange({action:h,nonce:r,signature:d,vaultAddress:void 0})}async setAgentAbstraction(e,t={}){let i=this.incrementingNonce(),s={nonce:i},r={type:"agentSetAbstraction",abstraction:e},a=this.signL1Action(r,i);return s.action=r,s.signature=a,await this.privatePostExchange(this.extend(s,t))}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let[o,n]=this.parseCreateEditOrderArgs(void 0,e,t,i,s,r,a),d=await this.createOrders([o],n);return this.safeDict(d,0)}async createTwapOrder(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets(),await this.initializeClient();let a=this.market(e),o=this.incrementingNonce(),n="BUY"===t.toUpperCase(),d=this.safeBool(r,"randomize",!1),h=this.omit(r,"randomize"),[c,l]=this.handleOptionStringAndParams(h,"createOrder","vaultAddress"),u=this.formatVaultAddress(c),f=Math.floor(s/1e3/60),p={type:"twapOrder",twap:{a:this.parseToInt(a.baseId),b:n,s:this.amountToPrecision(e,i),r:this.safeBool(l,"reduceOnly",!1),m:f,t:d}},m=this.signL1Action(p,o,u),g={action:p,nonce:o,signature:m};void 0!==u&&(g.vaultAddress=u);let v=this.safeInteger(l,"expiresAfter");void 0!==v&&(g.expiresAfter=v);let y=await this.privatePostExchange(g),b=this.safeDict(y,"response",{}),w=this.safeDict(b,"data",{}),k=this.safeDict(w,"status",{}),S=this.safeDict(k,"running",{}),O=this.safeString(S,"twapId");return this.parseOrder({status:"running",oid:O},a)}async createOrders(e,t={}){void 0===this.markets&&await this.loadMarkets(),await this.initializeClient();let i=this.createOrdersRequest(e,t),s=await this.privatePostExchange(i),r=this.safeDict(s,"response",{}),a=this.safeDict(r,"data",{}),o=this.safeList(a,"statuses",[]),n=[];for(let e=0;e<o.length;e++){let t=o[e];"waitingForTrigger"===t?n.push({status:t}):n.push(t)}return this.parseOrders(n)}createOrderRequest(e,t,i,s,r,a={}){let d;if(void 0===t)throw new o.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new o.ArgumentsRequired(this.id+" requires a side argument");let h=this.market(e),c=t.toUpperCase(),l=i.toUpperCase(),u="MARKET"===c,f="BUY"===l,p=this.safeString2(a,"clientOrderId","client_id"),m=this.safeString(a,"slippage"),g="gtc";u&&(g="ioc"),!0===this.safeBool(a,"postOnly",!1)&&(g="alo");let v=this.safeStringLower(a,"timeInForce",g);v=this.capitalize(v);let y=this.safeString2(a,"triggerPrice","stopPrice"),b=this.safeString(a,"stopLossPrice",y),w=this.safeString(a,"takeProfitPrice"),k=void 0!==b||void 0!==w;if(u){if(void 0===r)throw new o.ArgumentsRequired(this.id+"  market orders require price to calculate the max slippage price. Default slippage can be set in options (default is 5%).");d=f?n.Y.stringMul(r,n.Y.stringAdd("1",m)):n.Y.stringMul(r,n.Y.stringSub("1",m)),d=this.priceToPrecision(e,d)}else d=this.priceToPrecision(e,r);let S=this.amountToPrecision(e,s),O=this.safeBool(a,"reduceOnly",!1),T={};if(k){let t=!1;void 0!==w?(y=this.priceToPrecision(e,w),t=!0):y=this.priceToPrecision(e,b);let i="sl";t&&(i="tp"),T.trigger={isMarket:u,triggerPx:y,tpsl:i}}else T.limit={tif:v};let P={a:this.parseToInt(h.baseId),b:f,p:d,s:S,r:O,t:T};return void 0!==p&&(P.c=p),P}createOrdersRequest(e,t={}){let i;this.checkRequiredCredentials();let s=this.safeString(this.options,"defaultSlippage");s=this.safeString(t,"slippage",s);let r=!1;for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s=this.safeDict(i,"params",{});void 0!==this.safeString2(s,"clientOrderId","client_id")&&(r=!0)}if(r)for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s=this.safeDict(i,"params",{});if(void 0===this.safeString2(s,"clientOrderId","client_id"))throw new o.ArgumentsRequired(this.id+" createOrders() all orders must have clientOrderId if at least one has a clientOrderId")}let a=this.omit(t,["slippage","clientOrderId","client_id","slippage","triggerPrice","stopPrice","stopLossPrice","takeProfitPrice","timeInForce"]),n=this.incrementingNonce(),d=[],h="na";for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),r=this.safeString(i,"symbol"),a=this.market(r).symbol,n=this.safeStringUpper(i,"type"),c=this.safeStringUpper(i,"side"),l=this.safeString(i,"amount"),u=this.safeString(i,"price"),f=this.safeDict(i,"params",{}),p=this.safeString(f,"slippage",s);f.slippage=p;let m=this.safeDict(f,"stopLoss"),g=this.safeDict(f,"takeProfit"),v=void 0!==m,y=void 0!==g;f=this.omit(f,["stopLoss","takeProfit"]);let b=this.createOrderRequest(a,n,c,l,u,f);if(v||y){let e=this.safeString2(m,"triggerPrice","stopPrice"),t=this.safeString(m,"type","limit"),i=this.safeString2(m,"price","stopLossPrice",e),s=this.safeString2(g,"triggerPrice","stopPrice"),r=this.safeString(g,"type","limit"),n=this.safeString2(g,"price","takeProfitPrice",s);if("positionTpsl"===(h=this.safeString(f,"grouping","normalTpsl")))l="0",t="market",r="market";else if("normalTpsl"===h)d.push(b);else throw new o.NotSupported(this.id+" only support grouping normalTpsl and positionTpsl.");f=this.omit(f,["stopLoss","takeProfit","grouping"]);let u="";if(u="BUY"===c?"sell":"buy",y){let e=this.createOrderRequest(a,r,u,l,n,this.extend(f,{takeProfitPrice:s,reduceOnly:!0}));d.push(e)}if(v){let s=this.createOrderRequest(a,t,u,l,i,this.extend(f,{stopLossPrice:e,reduceOnly:!0}));d.push(s)}}else d.push(b)}[i,a]=this.handleOptionStringAndParams(a,"createOrder","vaultAddress"),i=this.formatVaultAddress(i);let c={type:"order",orders:d,grouping:h};if(this.safeBool(this.options,"approvedBuilderFee",!1)){let e=this.safeStringLower(this.options,"builder","0x6530512a6c89c7cfcebc3ba7fcd9ada5f30827a6"),t=this.safeInteger(this.options,"feeInt",10);this.safeBool(this.options,"builderFee",!0)||(t=0),c.builder={b:e,f:t}}let l=this.signL1Action(c,n,i),u={action:c,nonce:n,signature:l};return void 0!==i&&(a=this.omit(a,"vaultAddress"),u.vaultAddress=i),u}async cancelOrder(e,t,i={}){if(this.safeBool(i,"twap",!1))return await this.cancelTwapOrder(e,t,this.omit(i,"twap"));let s=await this.cancelOrders([e],t,i);return this.safeDict(s,0)}async cancelOrders(e,t,i={}){if(this.checkRequiredCredentials(),void 0===t)throw new o.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),await this.initializeClient();let s=this.cancelOrdersRequest(e,t,i),r=await this.privatePostExchange(s),a=this.safeDict(r,"response"),n=this.safeDict(a,"data"),d=this.safeList(n,"statuses",[]),h=[];for(let e=0;e<d.length;e++){let t=d[e];h.push(this.safeOrder({info:t,status:t}))}return h}async cancelTwapOrder(e,t,i={}){let s,r;if(void 0===this.markets&&await this.loadMarkets(),void 0===t)throw new o.ArgumentsRequired(this.id+" cancelTwapOrder() requires a symbol argument");let a=this.market(t);[s,r]=this.handleOptionStringAndParams(i,"cancelTwapOrder","vaultAddress"),s=this.formatVaultAddress(s);let n={type:"twapCancel",a:this.parseToInt(a.baseId),t:this.parseToNumeric(e)},d=this.incrementingNonce(),h=this.signL1Action(n,d,s),c={action:n,nonce:d,signature:h};void 0!==s&&(r=this.omit(r,"vaultAddress"),c.vaultAddress=s);let l=this.safeInteger(r,"expiresAfter");void 0!==l&&(c.expiresAfter=l,r=this.omit(r,"expiresAfter"));let u=await this.privatePostExchange(c),f=this.safeDict(u,"response",{}),p=this.safeDict(f,"data",{}),m=this.safeString(p,"status");return this.parseOrder({status:m,oid:e},a)}cancelOrdersRequest(e,t,i={}){let s,r=this.market(t),a=this.safeValue2(i,"clientOrderId","client_id"),o=this.omit(i,["clientOrderId","client_id"]),n=this.incrementingNonce(),d={nonce:n},h=[],c={type:"",cancels:[]},l=this.parseToNumeric(r.baseId);if(void 0!==a){Array.isArray(a)||(a=[a]),c.type="cancelByCloid";for(let e=0;e<a.length;e++)h.push({asset:l,cloid:a[e]})}else{c.type="cancel";for(let t=0;t<e.length;t++){let i=this.parseToNumeric(e[t]);h.push({a:l,o:i})}}c.cancels=h,[s,o]=this.handleOptionStringAndParams2(o,"cancelOrders","vaultAddress","subAccountAddress"),s=this.formatVaultAddress(s);let u=this.signL1Action(c,n,s);return d.action=c,d.signature=u,void 0!==s&&(o=this.omit(o,"vaultAddress"),d.vaultAddress=s),d}async cancelOrdersForSymbols(e,t={}){this.checkRequiredCredentials(),void 0===this.markets&&await this.loadMarkets(),await this.initializeClient();let i=this.incrementingNonce(),s={nonce:i},r=[],a={type:"",cancels:[]},n=!1;for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s=this.safeString(i,"clientOrderId");void 0!==s&&(n=!0);let a=this.safeString(i,"id"),d=this.safeString(i,"symbol");if(void 0===d)throw new o.ArgumentsRequired(this.id+" cancelOrdersForSymbols() requires a symbol argument in each order");if(void 0!==a&&n)throw new o.BadRequest(this.id+" cancelOrdersForSymbols() all orders must have either id or clientOrderId");let h=n?"asset":"a",c=n?"cloid":"o",l=this.market(d),u={};u[h]=this.parseToNumeric(l.baseId),u[c]=n?s:this.parseToNumeric(a),r.push(u)}a.type=n?"cancelByCloid":"cancel",a.cancels=r;let d=this.handleOptionStringAndParams2(t,"cancelOrdersForSymbols","vaultAddress","subAccountAddress")[0],h=this.formatVaultAddress(d),c=this.signL1Action(a,i,h);s.action=a,s.signature=c,void 0!==h&&(s.vaultAddress=h);let l=await this.privatePostExchange(s);return[this.safeOrder({info:l})]}async cancelAllOrdersAfter(e,t={}){let i;this.checkRequiredCredentials(),void 0===this.markets&&await this.loadMarkets(),await this.initializeClient();let s=this.omit(t,["clientOrderId","client_id"]),r=this.incrementingNonce(),a={nonce:r},o={type:"scheduleCancel",time:r+e};[i,s]=this.handleOptionStringAndParams2(s,"cancelAllOrdersAfter","vaultAddress","subAccountAddress"),i=this.formatVaultAddress(i);let n=this.signL1Action(o,r,i);return a.action=o,a.signature=n,void 0!==i&&(s=this.omit(s,"vaultAddress"),a.vaultAddress=i),await this.privatePostExchange(a)}editOrdersRequest(e,t={}){let i;this.checkRequiredCredentials();let s=!1;for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),r=this.safeDict(i,"params",{});void 0!==this.safeString2(r,"clientOrderId","client_id")&&(s=!0)}if(s)for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s=this.safeDict(i,"params",{});if(void 0===this.safeString2(s,"clientOrderId","client_id"))throw new o.ArgumentsRequired(this.id+" editOrders() all orders must have clientOrderId if at least one has a clientOrderId")}let r=this.omit(t,["slippage","clientOrderId","client_id","slippage","triggerPrice","stopPrice","stopLossPrice","takeProfitPrice","timeInForce"]),a=[];for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s=this.safeString(i,"id"),r=this.safeString(i,"symbol"),o=this.market(r),d=o.symbol,h="MARKET"===this.safeStringUpper(i,"type"),c="BUY"===this.safeStringUpper(i,"side"),l=this.safeString(i,"amount"),u=this.safeString(i,"price"),f=this.safeDict(i,"params",{}),p=this.safeString(this.options,"defaultSlippage"),m=this.safeString(f,"slippage",p),g="gtc";h&&(g="ioc"),!0===this.safeBool(f,"postOnly",!1)&&(g="alo");let v=this.safeStringLower(f,"timeInForce",g);v=this.capitalize(v);let y=this.safeString2(f,"clientOrderId","client_id"),b=this.safeString2(f,"triggerPrice","stopPrice"),w=this.safeString(f,"stopLossPrice",b),k=this.safeString(f,"takeProfitPrice"),S=void 0!==w||void 0!==k,O=this.safeBool(f,"reduceOnly",!1);f=this.omit(f,["slippage","timeInForce","triggerPrice","stopLossPrice","takeProfitPrice","clientOrderId","client_id","postOnly","reduceOnly"]);let T=this.numberToString(u);h&&(T=c?n.Y.stringMul(T,n.Y.stringAdd("1",m)):n.Y.stringMul(T,n.Y.stringSub("1",m))),T=this.priceToPrecision(d,T);let P=this.amountToPrecision(d,l),I={};if(S){let e=!1;void 0!==k?(b=this.priceToPrecision(d,k),e=!0):b=this.priceToPrecision(d,w);let t="sl";e&&(t="tp"),I.trigger={isMarket:h,triggerPx:b,tpsl:t}}else I.limit={tif:v};void 0===b&&(b="0");let A={a:this.parseToInt(o.baseId),b:c,p:T,s:P,r:O,t:I};void 0!==y&&(A.c=y);let x={oid:this.parseToInt(s),order:A};a.push(x)}let d=this.incrementingNonce(),h={type:"batchModify",modifies:a};[i,r]=this.handleOptionStringAndParams(r,"editOrder","vaultAddress"),i=this.formatVaultAddress(i);let c=this.signL1Action(h,d,i),l={action:h,nonce:d,signature:c};return void 0!==i&&(l.vaultAddress=i),l}async editOrder(e,t,i,s,r,a,n={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new o.ArgumentsRequired(this.id+" editOrder() requires an id argument");let[d,h]=this.parseCreateEditOrderArgs(e,t,i,s,r,a,n),c=await this.editOrders([d],h);return this.safeDict(c,0)}async editOrders(e,t={}){void 0===this.markets&&await this.loadMarkets(),await this.initializeClient();let i=this.editOrdersRequest(e,t),s=await this.privatePostExchange(i),r=this.safeDict(s,"response",{}),a=this.safeDict(r,"data",{}),o=this.safeList(a,"statuses",[]);return this.parseOrders(o)}async createVault(e,t,i,s={}){this.checkRequiredCredentials(),void 0===this.markets&&await this.loadMarkets();let r=this.incrementingNonce(),a={nonce:r},o={type:"createVault",name:e,description:t,initialUsd:this.parseToInt(n.Y.stringMul(this.numberToString(i),"1000000")),nonce:r},d=this.signL1Action(o,r);return a.action=o,a.signature=d,await this.privatePostExchange(this.extend(a,s))}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new o.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");let r=this.market(e),a={type:"fundingHistory",coin:this.safeString(r,"baseName")};if(void 0!==t)a.startTime=t;else{let e=void 0===i?500:i;a.startTime=this.milliseconds()-60*e*6e4}let n=this.safeInteger(s,"until"),d=this.omit(s,"until");void 0!==n&&(a.endTime=n);let h=await this.publicPostInfo(this.extend(a,d)),c=[],l=[];Array.isArray(h)&&(l=h);for(let e=0;e<l.length;e++){let t=this.safeDict(l,e),i=this.safeInteger(t,"time");c.push({info:t,symbol:this.safeSymbol(void 0,r),fundingRate:this.safeNumber(t,"fundingRate"),timestamp:i,datetime:this.iso8601(i)})}let u=this.sortBy(c,"timestamp");return this.filterBySymbolSinceLimit(u,e,t,i)}getDexFromHip3Symbol(e){let t=this.safeString(e,"baseName","").split(":");if(t.length>1)return this.safeString(t,0)}async fetchOpenOrders(e,t,i,s={}){let r,[a,o]=this.handlePublicAddress("fetchOpenOrders",s),[n,d]=this.handleOptionStringAndParams(o,"fetchOpenOrders","method","frontendOpenOrders");void 0===this.markets&&await this.loadMarkets();let h={type:n,user:a};if(void 0!==e){r=this.market(e);let t=this.getDexFromHip3Symbol(r);void 0!==t&&(h.dex=t)}let c=await this.publicPostInfo(this.extend(h,d)),l=[],u=[];Array.isArray(c)&&(u=c);for(let e=0;e<u.length;e++){let t=this.safeDict(u,e),i={};void 0===this.safeString(t,"status")&&(i.ccxtStatus="open"),l.push(this.extend(t,i))}return this.parseOrders(l,r,t,i)}async fetchClosedOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.fetchOrders(e,void 0,void 0,s),a=this.filterByArray(r,"status",["closed"],!1);return this.filterBySymbolSinceLimit(a,e,t,i)}async fetchCanceledOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.fetchOrders(e,void 0,void 0,s),a=this.filterByArray(r,"status",["canceled"],!1);return this.filterBySymbolSinceLimit(a,e,t,i)}async fetchCanceledAndClosedOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.fetchOrders(e,void 0,void 0,s),a=this.filterByArray(r,"status",["canceled","closed","rejected"],!1);return this.filterBySymbolSinceLimit(a,e,t,i)}async fetchOrders(e,t,i,s={}){let r,[a,o]=this.handlePublicAddress("fetchOrders",s);void 0===this.markets&&await this.loadMarkets();let n={type:"historicalOrders",user:a};if(void 0!==e){r=this.market(e);let t=this.getDexFromHip3Symbol(r);void 0!==t&&(n.dex=t)}let d=await this.publicPostInfo(this.extend(n,o)),h={},c=[];Array.isArray(d)&&(c=d);for(let e=0;e<c.length;e++){let t=c[e],i=this.safeDict(t,"order");void 0===i&&(i=t);let s=this.safeString(i,"oid");if(void 0!==s)if(s in h){let e=this.safeInteger(h[s],"statusTimestamp"),i=this.safeInteger(t,"statusTimestamp");void 0!==i&&(void 0===e||i>e)&&(h[s]=t)}else h[s]=t}let l=Object.values(h);return this.parseOrders(l,r,t,i)}async fetchOrder(e,t,i={}){let s,r,a;[s,r]=this.handlePublicAddress("fetchOrder",i),void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(a=this.market(t));let o=this.safeString(r,"clientOrderId"),n={type:"orderStatus",user:s};void 0!==o?(r=this.omit(r,"clientOrderId"),n.oid=o):n.oid=e.length>=34?e:this.parseToNumeric(e);let d=await this.publicPostInfo(this.extend(n,r)),h=this.safeDict(d,"order");return this.parseOrder(h,a)}parseOrder(e,t){let i,s,r,a,o;if(void 0!==this.safeString(e,"error"))return this.safeOrder({info:e,status:"rejected"});let d=this.safeDictN(e,["order","resting","filled"]);void 0===d&&(d=e);let h=this.safeDict(e,"filled",{}),c=this.safeString(d,"coin");void 0!==c&&(i=this.coinToMarketId(c));let l=(s=void 0===this.safeString(d,"id")?this.safeMarket(i):this.safeMarket(i,t)).symbol,u=this.safeInteger(d,"timestamp"),f=this.safeString2(e,"status","ccxtStatus"),p=this.omit(e,["ccxtStatus"]),m=this.safeString(d,"side");void 0!==m&&(m="A"===m?"sell":"buy");let g=this.safeString2(d,"origSz","totalSz"),v=this.safeString(d,"sz"),y=this.safeStringUpper(d,"tif");void 0!==y&&(r="ALO"===y);let b=this.safeBool(d,"isTrigger",!1)?this.safeNumber(d,"triggerPx"):void 0,w=this.safeStringLower(d,"orderType","");return void 0!==b&&(w.indexOf("stop")>=0?a=b:w.indexOf("take profit")>=0&&(o=b)),this.safeOrder({info:p,id:this.safeString(d,"oid"),clientOrderId:this.safeString(d,"cloid"),timestamp:u,datetime:this.iso8601(u),lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeInteger(p,"statusTimestamp"),symbol:l,type:this.parseOrderType(this.safeStringLower(d,"orderType")),timeInForce:y,postOnly:r,reduceOnly:this.safeBool(d,"reduceOnly"),side:m,price:this.safeString(d,"limitPx"),triggerPrice:b,stopLossPrice:a,takeProfitPrice:o,amount:g,cost:void 0,average:this.safeString(d,"avgPx"),filled:this.safeString(h,"totalSz",n.Y.stringSub(g,v)),remaining:v,status:this.parseOrderStatus(f),fee:void 0,trades:void 0},s)}parseOrderStatus(e){return void 0===e?void 0:e.endsWith("Rejected")?"rejected":e.endsWith("Canceled")?"canceled":this.safeString({triggered:"open",filled:"closed",open:"open",canceled:"canceled",rejected:"rejected",marginCanceled:"canceled"},e,e)}parseOrderType(e){return this.safeString({"stop limit":"limit","stop market":"market"},e,e)}async fetchMyTrades(e,t,i,s={}){let r,[a,o]=this.handlePublicAddress("fetchMyTrades",s);void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let n={user:a};void 0!==t?(n.type="userFillsByTime",n.startTime=t):n.type="userFills";let d=this.safeInteger(o,"until"),h=this.omit(o,"until");void 0!==d&&(n.endTime=d);let c=await this.publicPostInfo(this.extend(n,h)),l=[];return Array.isArray(c)&&(l=c),this.parseTrades(l,r,t,i)}parseTrade(e,t){let i,s=this.safeInteger(e,"time"),r=this.safeString(e,"px"),a=this.safeString(e,"sz"),o=this.safeString(e,"coin"),d=this.coinToMarketId(o),h=this.safeMarket(d),c=h.symbol,l=this.safeString(e,"tid"),u=this.safeString(e,"side");void 0!==u&&(u="A"===u?"sell":"buy");let f=this.safeString(e,"fee"),p=this.safeBool(e,"crossed");void 0!==p&&(i=p?"taker":"maker");let m=this.safeString(e,"builderFee");return void 0!==m&&(f=n.Y.stringAdd(f,m)),this.safeTrade({info:e,timestamp:s,datetime:this.iso8601(s),symbol:c,id:l,order:this.safeString(e,"oid"),type:void 0,side:u,takerOrMaker:i,price:r,amount:a,cost:void 0,fee:{cost:f,currency:this.safeString(e,"feeToken"),rate:void 0}},h)}async fetchPosition(e,t={}){let i=await this.fetchPositions([e],t);return this.safeDict(i,0,{})}getDexFromSymbols(e,t){let i;if(void 0===t)return;let s=t.length;if(0!==s){for(let r=0;r<s;r++)if(void 0===i){let e=this.market(t[r]);i=this.getDexFromHip3Symbol(e)}else{let s=this.market(t[r]);if(this.getDexFromHip3Symbol(s)!==i)throw new o.NotSupported(this.id+" "+e+" only supports fetching positions for one DEX at a time for HIP3 markets")}return i}}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handlePublicAddress("fetchPositions",t),r=this.marketSymbols(e),a={type:"clearinghouseState",user:i},o=this.getDexFromSymbols("fetchPositions",r);void 0!==o&&(a.dex=o);let n=await this.publicPostInfo(this.extend(a,s)),d=this.safeList(n,"assetPositions",[]),h=[];for(let e=0;e<d.length;e++)h.push(this.parsePosition(d[e]));return this.filterByArrayPositions(h,"symbol",r)}parsePosition(e,t){let i,s,r=this.safeDict(e,"position",{}),a=this.safeString(r,"coin"),o=this.coinToMarketId(a),d=this.safeMarket(o).symbol,h=this.safeDict(r,"leverage",{}),c=this.safeString(h,"type"),l="isolated"===c,u=this.safeString(r,"szi"),f=u;void 0!==f&&(i=n.Y.stringGt(u,"0")?"long":"short",f=n.Y.stringAbs(f));let p=this.safeString(r,"unrealizedPnl"),m=n.Y.stringAbs(p),g=this.safeString(r,"marginUsed");s=l?n.Y.stringSub(g,p):g;let v=n.Y.stringMul(n.Y.stringDiv(m,g),"100");return this.safePosition({info:e,id:void 0,symbol:d,timestamp:void 0,datetime:void 0,isolated:l,hedged:void 0,side:i,contracts:this.parseNumber(f),contractSize:void 0,entryPrice:this.safeNumber(r,"entryPx"),markPrice:void 0,notional:this.safeNumber(r,"positionValue"),leverage:this.safeNumber(h,"value"),collateral:this.parseNumber(g),initialMargin:this.parseNumber(s),maintenanceMargin:void 0,initialMarginPercentage:void 0,maintenanceMarginPercentage:void 0,unrealizedPnl:this.parseNumber(p),liquidationPrice:this.safeNumber(r,"liquidationPx"),marginMode:c,percentage:this.parseNumber(v)})}async setMarginMode(e,t,i={}){let s;if(void 0===t)throw new o.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),a=this.safeInteger(i,"leverage");if(void 0===a)throw new o.ArgumentsRequired(this.id+" setMarginMode() requires a leverage parameter");let n=this.parseToInt(r.baseId),d=this.incrementingNonce(),h=this.omit(i,["leverage"]),c={type:"updateLeverage",asset:n,isCross:"cross"===e,leverage:a};[s,h]=this.handleOptionStringAndParams2(h,"setMarginMode","vaultAddress","subAccountAddress"),void 0!==s&&s.startsWith("0x")&&(s=s.replace("0x",""));let l=this.signL1Action(c,d,s),u={action:c,nonce:d,signature:l};return void 0!==s&&(u.vaultAddress=s),await this.privatePostExchange(u)}async setLeverage(e,t,i={}){let s;if(void 0===t)throw new o.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),a=this.safeString(i,"marginMode","cross"),n=this.parseToInt(r.baseId),d=this.incrementingNonce(),h=this.omit(i,"marginMode"),c={type:"updateLeverage",asset:n,isCross:"cross"===a,leverage:e};[s,h]=this.handleOptionStringAndParams2(h,"setLeverage","vaultAddress","subAccountAddress"),s=this.formatVaultAddress(s);let l=this.signL1Action(c,d,s),u={action:c,nonce:d,signature:l};return void 0!==s&&(h=this.omit(h,"vaultAddress"),u.vaultAddress=s),await this.privatePostExchange(u)}async addMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,"add",i)}async reduceMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,"reduce",i)}async modifyMarginHelper(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=this.parseToInt(r.baseId),o=this.parseToInt(n.Y.stringMul(this.amountToPrecision(e,t),"1000000"));"reduce"===i&&(o=-o);let d=this.incrementingNonce(),h={type:"updateIsolatedMargin",asset:a,isBuy:!0,ntli:o},c=this.handleOptionStringAndParams2(s,"modifyMargin","vaultAddress","subAccountAddress")[0],l=this.formatVaultAddress(c),u=this.signL1Action(h,d,l),f={action:h,nonce:d,signature:u};void 0!==l&&(f.vaultAddress=l);let p=await this.privatePostExchange(f);return this.extend(this.parseMarginModification(p,r),{code:this.safeString(p,"status")})}parseMarginModification(e,t){return{info:e,symbol:this.safeSymbol(void 0,t),type:void 0,marginMode:"isolated",amount:void 0,total:void 0,code:this.safeString(t,"settle"),status:void 0,timestamp:void 0,datetime:void 0}}async transfer(e,t,i,s,r={}){let a;this.checkRequiredCredentials(),void 0===this.markets&&await this.loadMarkets();let d=this.safeBool(this.options,"sandboxMode"),h=this.incrementingNonce();if(this.inArray(i,["spot","swap","perp"])){if(!this.inArray(s,["spot","swap","perp"]))throw new o.NotSupported(this.id+" transfer() only support spot <> swap transfer");let i=this.numberToString(t),a=this.safeString2(r,"vaultAddress","subAccountAddress");void 0!==a&&(i=i+" subaccount:"+(a=this.formatVaultAddress(a)));let n=i,c="perp"===s||"swap"===s,l={hyperliquidChain:!0===d?"Testnet":"Mainnet",amount:n,toPerp:c,nonce:h},u=this.buildUsdClassSendSig(l),f={action:{hyperliquidChain:l.hyperliquidChain,signatureChainId:"0x66eee",type:"usdClassTransfer",amount:n,toPerp:c,nonce:h},nonce:h,signature:u},p=await this.privatePostExchange(f),m=this.safeCurrency(e);return this.parseTransfer(p,m)}let c=!1;if("main"===i)a=s,c=!0;else if("main"===s)a=i;else throw new o.NotSupported(this.id+" transfer() only support main <> subaccount transfer");this.checkAddress(a);let l=this.safeString(r,"type");if("USDC"===e.toUpperCase()&&"spot"!==l){let e={type:"subAccountTransfer",subAccountUser:a,isDeposit:c,usd:this.parseToInt(n.Y.stringMul(this.numberToString(t),"1000000"))},i=this.signL1Action(e,h),s=await this.privatePostExchange({action:e,nonce:h,signature:i});return this.parseTransfer(s)}{if(void 0===e)throw new o.ArgumentsRequired(this.id+" transfer() requires a currency code for spot sub-account transfers");let i=this.currency(e),s=this.safeDict(i,"info",{}),r={type:"subAccountSpotTransfer",subAccountUser:a,isDeposit:c,token:this.safeString(s,"name")+":"+this.safeString(s,"tokenId"),amount:this.numberToString(t)},n=this.signL1Action(r,h),d=await this.privatePostExchange({action:r,nonce:h,signature:n});return this.parseTransfer(d)}}parseTransfer(e,t){return{info:e,id:void 0,timestamp:void 0,datetime:void 0,currency:this.safeCurrencyCode(void 0,t),amount:void 0,fromAccount:void 0,toAccount:void 0,status:this.safeString(e,"status","ok")}}async withdraw(e,t,i,s,r={}){let a;if(this.checkRequiredCredentials(),void 0===this.markets&&await this.loadMarkets(),this.checkAddress(i),"USDC"!==e.toUpperCase())throw new o.NotSupported(this.id+" withdraw() only support USDC");let n=this.handleOptionStringAndParams(r,"withdraw","vaultAddress")[0],d=this.formatVaultAddress(n),h=this.incrementingNonce(),c={};if(void 0!==d)c={type:"vaultTransfer",vaultAddress:"0x"+d,isDeposit:!1,usd:t},a=this.signL1Action(c,h);else{let e={hyperliquidChain:!0===this.safeBool(this.options,"sandboxMode",!1)?"Testnet":"Mainnet",destination:i,amount:t.toString(),time:h};a=this.buildWithdrawSig(e),c={hyperliquidChain:e.hyperliquidChain,signatureChainId:"0x66eee",destination:i,amount:t.toString(),time:h,type:"withdraw3"}}let l={action:c,nonce:h,signature:a},u=await this.privatePostExchange(l);return this.parseTransaction(u)}parseTransaction(e,t){let i,s,r=this.safeInteger(e,"time"),a=this.safeDict(e,"delta",{}),o=this.safeInteger(a,"fee");void 0!==o&&(i={currency:"USDC",cost:o});let n=this.safeString(a,"type");return void 0!==n&&(s="internalTransfer"===n),{info:e,id:void 0,txid:this.safeString(e,"hash"),timestamp:r,datetime:this.iso8601(r),network:void 0,address:void 0,addressTo:this.safeString(a,"destination"),addressFrom:this.safeString(a,"user"),tag:void 0,tagTo:void 0,tagFrom:void 0,type:void 0,amount:this.safeNumber(a,"usdc"),currency:void 0,status:this.safeString(e,"status"),updated:void 0,comment:void 0,internal:s,fee:i}}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handlePublicAddress("fetchTradingFee",t),r=this.market(e),a=await this.publicPostInfo(this.extend({type:"userFees",user:i},s)),o={userCrossRate:this.safeString(a,"userCrossRate"),userAddRate:this.safeString(a,"userAddRate")};return this.parseTradingFee(o,r)}parseTradingFee(e,t){return{info:e,symbol:this.safeSymbol(void 0,t),maker:this.safeNumber(e,"userAddRate"),taker:this.safeNumber(e,"userCrossRate"),percentage:void 0,tierBased:void 0}}async fetchLedger(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets(),[r,a]=this.handlePublicAddress("fetchLedger",s);let o={type:"userNonFundingLedgerUpdates",user:r};void 0!==t&&(o.startTime=t);let n=this.safeInteger(a,"until");void 0!==n&&(o.endTime=n,a=this.omit(a,["until"]));let d=await this.publicPostInfo(this.extend(o,a));return this.parseLedger(d,void 0,t,i)}parseLedgerEntry(e,t){let i,s=this.safeInteger(e,"time"),r=this.safeDict(e,"delta",{}),a=this.safeInteger(r,"fee");void 0!==a&&(i={currency:"USDC",cost:a});let o=this.safeString(r,"type"),n=this.safeString(r,"usdc");return this.safeLedgerEntry({info:e,id:this.safeString(e,"hash"),direction:void 0,account:void 0,referenceAccount:this.safeString(r,"user"),referenceId:this.safeString(e,"hash"),type:this.parseLedgerEntryType(o),currency:void 0,amount:this.parseNumber(n),timestamp:s,datetime:this.iso8601(s),before:void 0,after:void 0,status:void 0,fee:i},t)}parseLedgerEntryType(e){return this.safeString({internalTransfer:"transfer",accountClassTransfer:"transfer"},e,e)}async fetchDeposits(e,t,i,s={}){let r,a,n;void 0===this.markets&&await this.loadMarkets(),[r,a]=this.handlePublicAddress("fetchDepositsWithdrawals",s);let d={type:"userNonFundingLedgerUpdates",user:r};void 0!==t&&(d.startTime=t);let h=this.safeInteger(a,"until");if(void 0!==h){if(void 0===t)throw new o.ArgumentsRequired(this.id+" fetchDeposits requires since while until is set");d.endTime=h,a=this.omit(a,["until"])}let c=await this.publicPostInfo(this.extend(d,a)),l=[];Array.isArray(c)&&(l=c);let u=this.extractTypeFromDelta(l);[n,a]=this.handleOptionStringAndParams(a,"fetchDepositsWithdrawals","vaultAddress");let f=[];if(void 0!==(n=this.formatVaultAddress(n)))for(let e=0;e<u.length;e++){let t=u[e];"vaultDeposit"===this.safeString(t,"type")&&this.safeDict(t,"delta",{}).vault==="0x"+n&&f.push(t)}else f=this.filterByArray(u,"type",["deposit"],!1);return this.parseTransactions(f,void 0,t,i)}async fetchWithdrawals(e,t,i,s={}){let r,a,o;void 0===this.markets&&await this.loadMarkets(),[r,a]=this.handlePublicAddress("fetchDepositsWithdrawals",s);let n={type:"userNonFundingLedgerUpdates",user:r};void 0!==t&&(n.startTime=t);let d=this.safeInteger(a,"until");void 0!==d&&(n.endTime=d,a=this.omit(a,["until"]));let h=await this.publicPostInfo(this.extend(n,a)),c=[];Array.isArray(h)&&(c=h);let l=this.extractTypeFromDelta(c);[o,a]=this.handleOptionStringAndParams(a,"fetchDepositsWithdrawals","vaultAddress");let u=[];if(void 0!==(o=this.formatVaultAddress(o)))for(let e=0;e<l.length;e++){let t=l[e];"vaultWithdraw"===this.safeString(t,"type")&&this.safeDict(t,"delta",{}).vault==="0x"+o&&u.push(t)}else u=this.filterByArray(l,"type",["withdraw"],!1);return this.parseTransactions(u,void 0,t,i)}async fetchOpenInterests(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.fetchSwapMarkets();return this.parseOpenInterests(s,i)}async fetchOpenInterest(e,t={}){let i=this.symbol(e);void 0===this.markets&&await this.loadMarkets();let s=await this.fetchOpenInterests([i],t);return this.safeDict(s,i)}parseOpenInterest(e,t){let i,s=this.safeDict(e,"info",{}),r=this.safeString(s,"name");return void 0!==r&&(i=this.coinToMarketId(r)),this.safeOpenInterest({symbol:this.safeSymbol(i),openInterestAmount:this.safeNumber(s,"openInterest"),openInterestValue:void 0,timestamp:void 0,datetime:void 0,info:s},t)}async fetchFundingHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let[a,o]=this.handlePublicAddress("fetchFundingHistory",s),n={user:a,type:"userFunding"};void 0!==t&&(n.startTime=t);let d=this.safeInteger(o,"until"),h=this.omit(o,"until");void 0!==d&&(n.endTime=d);let c=await this.publicPostInfo(this.extend(n,h));return this.parseIncomes(c,r,t,i)}parseIncome(e,t){let i,s=this.safeString(e,"hash"),r=this.safeInteger(e,"time"),a=this.safeDict(e,"delta"),o=this.safeString(a,"coin");void 0!==o&&(i=this.coinToMarketId(o));let n=this.safeMarket(i,t),d=this.safeString(a,"usdc"),h=this.safeString(n,"settle","USDC"),c=this.safeNumber(a,"fundingRate");return{info:e,symbol:n.symbol,code:h,timestamp:r,datetime:this.iso8601(r),id:s,amount:this.parseNumber(d),rate:c}}async reserveRequestWeight(e,t={}){let i=this.incrementingNonce(),s={nonce:i},r={type:"reserveRequestWeight",weight:e},a=this.signL1Action(r,i);return s.action=r,s.signature=a,await this.privatePostExchange(this.extend(s,t))}async createSubAccount(e,t={}){let i=this.incrementingNonce(),s={nonce:i},r={type:"createSubAccount",name:e},a=this.safeInteger(t,"expiresAfter");void 0!==a&&(s.expiresAfter=a);let o=this.signL1Action(r,i,void 0,a);return s.action=r,s.signature=o,await this.privatePostExchange(this.extend(s,this.omit(t,"expiresAfter")))}extractTypeFromDelta(e=[]){let t=[];for(let i=0;i<e.length;i++){let s=e[i];s.type=s.delta.type,t.push(s)}return t}formatVaultAddress(e){if(void 0!==e)return e.startsWith("0x")?e.replace("0x",""):e}handlePublicAddress(e,t){let[i,s]=this.handleOptionStringAndParams2(t,e,"user","subAccountAddress"),[r,a]=this.handleOptionStringAndParams(s,e,"address",i);if(void 0!==r&&""!==r)return[r,a];if(void 0!==this.walletAddress&&""!==this.walletAddress)return[this.walletAddress,a];throw new o.ArgumentsRequired(this.id+" "+e+"() requires a user parameter inside 'params' or the wallet address set")}coinToMarketId(e){if(void 0===e)return;let t=this.safeDict(this.options,"hip3TokensByName",{});if(void 0!==this.safeDict(t,e)){let i=this.safeDict(t,e),s=this.safeString(i,"quote","USDC");return this.safeString(i,"code",e)+"/"+s+":"+s}if(e.indexOf("/")>-1||e.indexOf("@")>-1)return e;let i=e;return e.indexOf(":")>-1&&(i=e.replace(":","-")),this.safeCurrencyCode(i)+"/USDC:USDC"}handleErrors(e,t,i,s,r,a,n,d,h){let c;if(null==n)return;let l=this.safeString(n,"status",""),u=this.safeString(n,"error");if("err"===l)c=this.safeString(n,"response");else if("unknownOid"===l)throw new o.OrderNotFound(this.id+" "+a);else if(void 0!==u)c=u;else{let e=this.safeDict(n,"response",{}),t=this.safeDict(e,"data",{}),i=this.safeList(t,"statuses",[]);for(let e=0;e<i.length&&void 0===(c=this.safeString(i[e],"error"));e++);if("status"in t){let e=this.safeDict(t,"status",{}),i=this.safeString(e,"error");void 0!==e&&(c=i)}}let f=this.id+" "+a,p=void 0!==c&&""!==c;if(p&&(this.throwExactlyMatchedException(this.exceptions.exact,c,f),this.throwBroadlyMatchedException(this.exceptions.broad,c,f)),p)throw new o.ExchangeError(f)}sign(e,t="public",i="GET",s={},r,a){let n=this.safeString(this.urls.api,t);if(void 0===n)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let d=this.implodeHostname(n)+"/"+e,h="POST"===i,c=r;h&&(c={"Content-Type":"application/json"});let l=a;return h&&(l=this.json(s)),{url:d,method:i,body:l,headers:c}}calculateRateLimiterCost(e,t,i,s,r={}){if("byType"in r&&"type"in s){let e=s.type,t=r.byType;if(e in t)return t[e]}return this.safeValue(r,"cost",1)}parseCreateEditOrderArgs(e,t,i,s,r,a,o={}){let n,d,h=this.market(t);[n,d]=this.handleOptionStringAndParams2(o,"createOrder","vaultAddress","subAccountAddress"),n=this.formatVaultAddress(n);let c={symbol:h.symbol,type:i,side:s,amount:r,price:a,params:d},l={};return void 0!==n&&(l.vaultAddress=n),void 0!==e&&(c.id=e),[c,l]}}i.d(t,{A:()=>h})},7392(e,t,i){"use strict";var s=i(4721),r=i(4885),a=i(7749),o=i(1453);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"independentreserve",name:"Independent Reserve",countries:["AU","NZ"],rateLimit:1e3,pro:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createOrder:!0,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrice:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchPosition:!1,fetchPositionForSymbolWs:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsForSymbolWs:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,withdraw:!0},urls:{logo:"https://user-images.githubusercontent.com/51840849/87182090-1e9e9080-c2ec-11ea-8e49-563db9a38f37.jpg",api:{public:"https://api.independentreserve.com/Public",private:"https://api.independentreserve.com/Private"},www:"https://www.independentreserve.com",doc:"https://www.independentreserve.com/API"},api:{public:{get:{GetValidPrimaryCurrencyCodes:{cost:1},GetValidSecondaryCurrencyCodes:{cost:1},GetValidLimitOrderTypes:{cost:1},GetValidMarketOrderTypes:{cost:1},GetValidOrderTypes:{cost:1},GetValidTransactionTypes:{cost:1},GetMarketSummary:{cost:1},GetOrderBook:{cost:1},GetAllOrders:{cost:1},GetTradeHistorySummary:{cost:1},GetRecentTrades:{cost:1},GetFxRates:{cost:1},GetOrderMinimumVolumes:{cost:1},GetDepositFees:{cost:1},GetFiatWithdrawalFees:{cost:1},GetCryptoWithdrawalFees:{cost:1},GetCryptoWithdrawalFees2:{cost:1},GetNetworks:{cost:1},GetPrimaryCurrencyConfig2:{cost:1}}},private:{post:{GetOpenOrders:{cost:1},GetClosedOrders:{cost:1},GetClosedFilledOrders:{cost:1},GetOrderDetails:{cost:1},GetAccounts:{cost:1},GetTransactions:{cost:1},GetFiatBankAccounts:{cost:1},GetDigitalCurrencyDepositAddress:{cost:1},GetDigitalCurrencyDepositAddress2:{cost:1},GetDigitalCurrencyDepositAddresses:{cost:1},GetDigitalCurrencyDepositAddresses2:{cost:1},GetTrades:{cost:1},GetTradesByOrder:{cost:1},GetBrokerageFees:{cost:1},GetDigitalCurrencyWithdrawal:{cost:1},GetFiatWithdrawal:{cost:1},GetDepositLimits:{cost:1},GetWithdrawalLimits:{cost:1},PlaceLimitOrder:{cost:1},PlaceMarketOrder:{cost:1},CancelOrder:{cost:1},CancelOrders:{cost:1},SynchDigitalCurrencyDepositAddressWithBlockchain:{cost:1},RequestFiatWithdrawal:{cost:1},WithdrawFiatCurrency:{cost:1},WithdrawDigitalCurrency:{cost:1},WithdrawCrypto:{cost:1}}}},fees:{trading:{taker:this.parseNumber("0.005"),maker:this.parseNumber("0.005"),percentage:!0,tierBased:!1}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{GTC:!0,IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,selfTradePrevention:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:void 0,untilDays:void 0,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:100,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:100,daysBack:void 0,daysBackCanceled:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:void 0},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},commonCurrencies:{PLA:"PlayChip"},precisionMode:4,options:{defaultNetworks:{USDT:"Ethereum",USDC:"Ethereum",BTC:"Bitcoin",BCH:"BitcoinCash",ETH:"Ethereum",LTC:"Litecoin",XRP:"XrpLedger",ZRX:"Ethereum",EOS:"EosIo",XLM:"Stellar",BAT:"Ethereum",ETC:"EthereumClassic",LINK:"Ethereum",MKR:"Ethereum",DAI:"Ethereum",COMP:"Ethereum",SNX:"Ethereum",YFI:"Ethereum",AAVE:"Ethereum",GRT:"Ethereum",DOT:"Polkadot",UNI:"Ethereum",ADA:"Cardano",MATIC:"Ethereum",DOGE:"Dogecoin",SOL:"Solana",MANA:"Ethereum",SAND:"Ethereum",SHIB:"Ethereum",TRX:"Tron",RENDER:"Solana",WIF:"Solana",RLUSD:"Ethereum",PEPE:"Ethereum"},networks:{BTC:"Bitcoin",ETH:"Ethereum",BCH:"BitcoinCash",LTC:"Litecoin",XRP:"XrpLedger",EOS:"EosIo",XLM:"Stellar",ETC:"EthereumClassic",BSV:"BitcoinSV",DOGE:"Dogecoin",DOT:"Polkadot",ADA:"Cardano",SOL:"Solana",TRX:"Tron"}}})}async fetchMarkets(e={}){let t=this.publicGetGetValidPrimaryCurrencyCodes(e),i=this.publicGetGetValidSecondaryCurrencyCodes(e),s=this.publicGetGetOrderMinimumVolumes(e),[r,a,o]=await Promise.all([t,i,s]),n=[],d=this.toArray(r),h=this.toArray(a);for(let e=0;e<d.length;e++){let t=d[e],i=this.safeCurrencyCode(t),s=this.safeNumber(o,t);for(let e=0;e<h.length;e++){let r=h[e],a=this.safeCurrencyCode(r);if(void 0===i||void 0===a)continue;let o=t+"/"+r;n.push({id:o,symbol:i+"/"+a,base:i,quote:a,settle:void 0,baseId:t,quoteId:r,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:void 0,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:void 0,price:void 0},limits:{leverage:{min:void 0,max:void 0},amount:{min:s,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:o})}}return n}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"CurrencyCode"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(s,"AvailableBalance"),o.total=this.safeString(s,"TotalBalance"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostGetAccounts(e);return this.parseBalance(t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={primaryCurrencyCode:s.baseId,secondaryCurrencyCode:s.quoteId},a=await this.publicGetGetOrderBook(this.extend(r,i)),o=this.parse8601(this.safeString(a,"CreatedTimestampUtc"));return this.parseOrderBook(a,s.symbol,o,"BuyOrders","SellOrders","Price","Volume")}parseTicker(e,t){let i,s=this.parse8601(this.safeString(e,"CreatedTimestampUtc")),r=this.safeString(e,"PrimaryCurrencyCode"),a=this.safeString(e,"SecondaryCurrencyCode");void 0!==r&&void 0!==a&&(i=r+"/"+a);let o=this.safeMarket(i,t,"/"),n=o.symbol,d=this.safeString(e,"LastPrice");return this.safeTicker({symbol:n,timestamp:s,datetime:this.iso8601(s),high:this.safeString(e,"DayHighestPrice"),low:this.safeString(e,"DayLowestPrice"),bid:this.safeString(e,"CurrentHighestBidPrice"),bidVolume:void 0,ask:this.safeString(e,"CurrentLowestOfferPrice"),askVolume:void 0,vwap:void 0,open:void 0,close:d,last:d,previousClose:void 0,change:void 0,percentage:void 0,average:this.safeString(e,"DayAvgPrice"),baseVolume:this.safeString(e,"DayVolumeXbtInSecondaryCurrrency"),quoteVolume:void 0,info:e},o)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={primaryCurrencyCode:i.baseId,secondaryCurrencyCode:i.quoteId},r=await this.publicGetGetMarketSummary(this.extend(s,t));return this.parseTicker(r,i)}parseOrder(e,t){let i,s,r,o,n,d=this.safeString(e,"PrimaryCurrencyCode"),h=this.safeString(e,"SecondaryCurrencyCode");void 0!==d&&void 0!==h?(s=this.safeCurrencyCode(d),r=this.safeCurrencyCode(h),void 0!==s&&void 0!==r&&(i=s+"/"+r)):void 0!==t&&(i=t.symbol,s=t.base,r=this.safeString(t,"quote"));let c=this.safeString2(e,"Type","OrderType");void 0!==c&&(c.indexOf("Bid")>=0?o="buy":c.indexOf("Offer")>=0&&(o="sell"),c.indexOf("Market")>=0?c="market":c.indexOf("Limit")>=0&&(c="limit"));let l=this.parse8601(this.safeString(e,"CreatedTimestampUtc")),u=this.safeString(e,"VolumeFilled"),f=this.safeString(e,"FeePercent");return void 0!==f&&void 0!==u&&(n=a.Y.stringMul(f,u)),this.safeOrder({info:e,id:this.safeString(e,"OrderGuid"),clientOrderId:void 0,timestamp:l,datetime:this.iso8601(l),lastTradeTimestamp:void 0,symbol:i,type:c,timeInForce:this.parseTimeInForce(this.safeString(e,"TimeInForce")),postOnly:void 0,side:o,price:this.safeString(e,"Price"),triggerPrice:void 0,cost:this.safeString(e,"Value"),average:this.safeString(e,"AvgPrice"),amount:this.safeString2(e,"VolumeOrdered","Volume"),filled:u,remaining:this.safeString(e,"Outstanding"),status:this.parseOrderStatus(this.safeString(e,"Status")),fee:{rate:f,cost:n,currency:s},trades:void 0},t)}parseOrderStatus(e){return this.safeString({Open:"open",PartiallyFilled:"open",Filled:"closed",PartiallyFilledAndCancelled:"canceled",Cancelled:"canceled",PartiallyFilledAndExpired:"canceled",Expired:"canceled",Failed:"canceled"},e,e)}parseTimeInForce(e){return this.safeString({Gtc:"GTC",Moc:"PO",Fok:"FOK",Ioc:"IOC"},e,e)}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=await this.privatePostGetOrderDetails(this.extend({orderGuid:e},i));return void 0!==t&&(s=this.market(t)),this.parseOrder(r,s)}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.primaryCurrencyCode=(r=this.market(e)).baseId,a.secondaryCurrencyCode=r.quoteId);let o=i;void 0===o&&(o=50),a.pageIndex=1,a.pageSize=o;let n=await this.privatePostGetOpenOrders(this.extend(a,s)),d=this.safeList(n,"Data",[]);return this.parseOrders(d,r,t,o)}async fetchClosedOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.primaryCurrencyCode=(r=this.market(e)).baseId,a.secondaryCurrencyCode=r.quoteId);let o=i;void 0===o&&(o=50),a.pageIndex=1,a.pageSize=o;let n=await this.privatePostGetClosedOrders(this.extend(a,s)),d=this.safeList(n,"Data",[]);return this.parseOrders(d,r,t,o)}async fetchMyTrades(e,t,i=50,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.safeInteger(s,"pageIndex",1),o=i;void 0===o&&(o=50);let n={pageIndex:a,pageSize:o},d=await this.privatePostGetTrades(this.extend(n,s));void 0!==e&&(r=this.market(e));let h=this.safeList(d,"Data",[]);return this.parseTrades(h,r,t,o)}parseTrade(e,t){let i,s=this.parse8601(e.TradeTimestampUtc),r=this.safeString(e,"TradeGuid"),o=this.safeString(e,"OrderGuid"),n=this.safeString2(e,"Price","SecondaryCurrencyTradePrice"),d=this.safeString2(e,"VolumeTraded","PrimaryCurrencyAmount"),h=this.parseNumber(n),c=this.parseNumber(d),l=this.parseNumber(a.Y.stringMul(n,d)),u=this.safeString(e,"PrimaryCurrencyCode"),f=this.safeString(e,"SecondaryCurrencyCode");void 0!==u&&void 0!==f&&(i=u+"/"+f);let p=this.safeSymbol(i,t,"/"),m=this.safeString(e,"OrderType");return void 0!==m&&(m.indexOf("Bid")>=0?m="buy":m.indexOf("Offer")>=0&&(m="sell")),this.safeTrade({id:r,info:e,timestamp:s,datetime:this.iso8601(s),symbol:p,order:o,type:void 0,side:m,takerOrMaker:void 0,price:h,amount:c,cost:l,fee:void 0},t)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={primaryCurrencyCode:r.baseId,secondaryCurrencyCode:r.quoteId,numberOfRecentTradesToRetrieve:50},o=await this.publicGetGetRecentTrades(this.extend(a,s)),n=this.safeList(o,"Trades",[]);return this.parseTrades(n,r,t,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostGetBrokerageFees(e),i={},s=this.toArray(t);for(let e=0;e<s.length;e++){let t=s[e],r=this.safeString(t,"CurrencyCode"),a=this.safeCurrencyCode(r),o=this.safeNumber(t,"Fee");void 0!==a&&(i[a]={info:t,fee:o})}let r={},a=this.symbols;for(let e=0;e<a.length;e++){let t=a[e],s=this.market(t),o=this.safeDict(i,s.base,{});r[t]={info:this.safeDict(o,"info"),symbol:t,maker:this.safeNumber(o,"fee"),taker:this.safeNumber(o,"fee"),percentage:!0,tierBased:!0}}return r}async createOrder(e,t,i,s,r,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=this.capitalize(t);d+="sell"===i?"Offer":"Bid";let h={primaryCurrencyCode:n.baseId,secondaryCurrencyCode:n.quoteId,orderType:d};return h.volume=s,"limit"===t?(h.price=r,o=await this.privatePostPlaceLimitOrder(this.extend(h,a))):o=await this.privatePostPlaceMarketOrder(this.extend(h,a)),this.safeOrder({info:o,id:o.OrderGuid},n)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privatePostCancelOrder(this.extend({orderGuid:e},i));return this.parseOrder(s)}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={primaryCurrencyCode:this.currency(e).id},s=await this.privatePostGetDigitalCurrencyDepositAddress(this.extend(i,t));return this.parseDepositAddress(s)}parseDepositAddress(e,t){let i=this.safeString(e,"DepositAddress");return this.checkAddress(i),{info:e,currency:this.safeString(t,"code"),network:void 0,address:i,tag:this.safeString(e,"Tag")}}async withdraw(e,t,i,s,r={}){let[a,n]=this.handleWithdrawTagAndParams(s,r);void 0===this.markets&&await this.loadMarkets();let d=this.currency(e),h={primaryCurrencyCode:d.id,withdrawalAddress:i,amount:this.currencyToPrecision(e,t)};void 0!==a&&(h.destinationTag=a);let[c,l]=this.handleNetworkCodeAndParams(n);if(void 0!==c)throw new o.BadRequest(this.id+' withdraw () does not accept params["networkCode"]');let u=await this.privatePostWithdrawDigitalCurrency(this.extend(h,l));return this.parseTransaction(u,d)}parseTransaction(e,t){let i=this.safeDict(e,"Amount"),s=this.safeDict(e,"Destination"),r=this.safeString(e,"PrimaryCurrencyCode"),a=this.safeString(e,"CreatedTimestampUtc"),o=this.safeString(s,"Address"),n=this.safeString(s,"Tag"),d=this.safeCurrencyCode(r,t);return{info:e,id:this.safeString(e,"TransactionGuid"),txid:void 0,type:"withdraw",currency:d,network:void 0,amount:this.safeNumber(i,"Total"),status:this.safeString(e,"Status"),timestamp:this.parse8601(a),datetime:a,address:o,addressFrom:void 0,addressTo:o,tag:n,tagFrom:void 0,tagTo:n,updated:void 0,comment:void 0,fee:{currency:d,cost:this.safeNumber(i,"Fee"),rate:void 0},internal:!1}}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},a,n){let d=this.safeString(this.urls.api,t);if(void 0===d)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let h=d+"/"+e;if("public"===t)Object.keys(r).length>0&&(h+="?"+this.urlencode(r));else{this.checkRequiredCredentials();let e=this.incrementingNonce(),t=[h,"apiKey="+this.apiKey,"nonce="+e.toString()],a=Object.keys(r);for(let e=0;e<a.length;e++){let i=a[e],s=r[i].toString();t.push(i+"="+s)}let o=t.join(","),n=this.hmac(this.encode(o),this.encode(this.secret),s.sc),d={};d.apiKey=this.apiKey,d.nonce=e,d.signature=n.toUpperCase();for(let e=0;e<a.length;e++){let t=a[e];d[t]=r[t]}return{url:h,method:i,body:this.json(d),headers:{"Content-Type":"application/json"}}}return{url:h,method:i,body:n,headers:a}}}i.d(t,{A:()=>n})},4987(e,t,i){"use strict";var s=i(4721),r=i(8740),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"indodax",name:"INDODAX",countries:["ID"],rateLimit:50,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!1,cancelOrder:!0,cancelOrders:!1,closeAllPositions:!1,closePosition:!1,createDepositAddress:!1,createOrder:!0,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDeposit:!1,fetchDepositAddress:"emulated",fetchDepositAddresses:!0,fetchDepositAddressesByNetwork:!1,fetchDeposits:!1,fetchDepositsWithdrawals:!0,fetchDepositWithdrawFee:!0,fetchDepositWithdrawFees:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrice:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!1,fetchPosition:!1,fetchPositionForSymbolWs:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsForSymbolWs:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTransactionFee:!0,fetchTransactionFees:!1,fetchTransactions:"emulated",fetchTransfer:!1,fetchTransfers:!1,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,fetchWithdrawal:!1,fetchWithdrawals:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,withdraw:!0},version:"2.0",urls:{logo:"https://user-images.githubusercontent.com/51840849/87070508-9358c880-c221-11ea-8dc5-5391afbbb422.jpg",api:{public:"https://indodax.com",private:"https://indodax.com/tapi"},www:"https://www.indodax.com",doc:"https://github.com/btcid/indodax-official-api-docs",referral:"https://indodax.com/ref/testbitcoincoid/1"},api:{public:{get:{"api/server_time":{cost:5},"api/pairs":{cost:5},"api/price_increments":{cost:5},"api/summaries":{cost:5},"api/ticker/{pair}":{cost:5},"api/ticker_all":{cost:5},"api/trades/{pair}":{cost:5},"api/depth/{pair}":{cost:5},"tradingview/history_v2":{cost:5}}},private:{post:{getInfo:{cost:4},transHistory:{cost:4},trade:{cost:1},tradeHistory:{cost:4},openOrders:{cost:4},orderHistory:{cost:4},getOrder:{cost:4},getOrderByClientOrderId:{cost:4},cancelOrder:{cost:4},cancelByClientOrderId:{cost:4},withdrawFee:{cost:4},withdrawCoin:{cost:4},listDownline:{cost:4},checkDownline:{cost:4},createVoucher:{cost:4}}}},fees:{trading:{tierBased:!1,percentage:!0,maker:0,taker:.003}},exceptions:{exact:{invalid_pair:a.BadSymbol,"Insufficient balance.":a.InsufficientFunds,"invalid order.":a.OrderNotFound,"Invalid credentials. API not found or session has expired.":a.AuthenticationError,"Invalid credentials. Bad sign.":a.AuthenticationError},broad:{"Minimum price":a.InvalidOrder,"Minimum order":a.InvalidOrder}},timeframes:{"1m":"1","15m":"15","30m":"30","1h":"60","4h":"240","1d":"1D","3d":"3D","1w":"1W"},options:{recvWindow:5e3,timeDifference:0,adjustForTimeDifference:!1,networks:{XLM:"Stellar Token",BSC:"bep20",TRC20:"trc20",MATIC:"polygon"}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!1,PO:!1,GTD:!1},hedged:!1,selfTradePrevention:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:void 0,fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:1e3,daysBack:1e5,daysBackCanceled:1,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOHLCV:{limit:2e3}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},commonCurrencies:{STR:"XLM",BCHABC:"BCH",BCHSV:"BSV",DRK:"DASH",NEM:"XEM"},precisionMode:4})}nonce(){return this.milliseconds()-this.safeInteger(this.options,"timeDifference",0)}async fetchTime(e={}){let t=await this.publicGetApiServerTime(e);return this.safeInteger(t,"server_time")}async fetchMarkets(e={}){let t=await this.publicGetApiPairs(e),i=[],s=this.toArray(t);for(let e=0;e<s.length;e++){let t=s[e],r=this.safeString(t,"id"),a=this.safeString(t,"traded_currency"),o=this.safeString(t,"base_currency"),n=this.safeCurrencyCode(a),d=this.safeCurrencyCode(o);if(void 0===n||void 0===d)continue;let h=this.safeInteger(t,"is_maintenance"),c=void 0!==h&&0!==h;i.push({id:r,symbol:n+"/"+d,base:n,quote:d,settle:void 0,baseId:a,quoteId:o,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:!c,contract:!1,linear:void 0,inverse:void 0,taker:this.safeNumber(t,"trade_fee_percent"),contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,percentage:!0,precision:{amount:this.parseNumber("1e-8"),price:this.parseNumber(this.parsePrecision(this.safeString(t,"price_round"))),cost:this.parseNumber(this.parsePrecision(this.safeString(t,"volume_precision")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(t,"trade_min_traded_currency"),max:void 0},price:{min:this.safeNumber(t,"trade_min_base_currency"),max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:t})}return i}parseBalance(e){let t=this.safeDict(e,"return",{}),i=this.safeDict(t,"balance",{}),s=this.safeDict(t,"balance_hold",{}),r=this.safeTimestamp(t,"server_time"),a={info:e,timestamp:r,datetime:this.iso8601(r)},o=Object.keys(i);for(let e=0;e<o.length;e++){let t=o[e],r=this.safeCurrencyCode(t),n=this.account();n.free=this.safeString(i,t),n.used=this.safeString(s,t),void 0!==r&&(a[r]=n)}return this.safeBalance(a)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostGetInfo(e);return this.parseBalance(t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={pair:s.id},a=await this.publicGetApiDepthPair(this.extend(r,i));return this.parseOrderBook(a,s.symbol,void 0,"buy","sell")}parseTicker(e,t){let i=this.safeSymbol(void 0,t),s=this.safeTimestamp(e,"server_time"),r="vol_"+this.safeStringLower(t,"baseId"),a="vol_"+this.safeStringLower(t,"quoteId"),o=this.safeString(e,"last");return this.safeTicker({symbol:i,timestamp:s,datetime:this.iso8601(s),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"buy"),bidVolume:void 0,ask:this.safeString(e,"sell"),askVolume:void 0,vwap:void 0,open:void 0,close:o,last:o,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,r),quoteVolume:this.safeString(e,a),info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={pair:i.id},r=await this.publicGetApiTickerPair(this.extend(s,t)),a=this.safeDict(r,"ticker",{});return this.parseTicker(a,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetApiTickerAll(t),s=this.safeDict(i,"tickers",{}),r=Object.keys(s),a={};for(let e=0;e<r.length;e++){let t=r[e],i=s[t],o=t.replace("_",""),n=this.safeMarket(o),d=this.parseTicker(i,n);a[o]=d}return this.filterByArray(a,"symbol",e)}parseTrade(e,t){let i=this.safeTimestamp(e,"date");return this.safeTrade({id:this.safeString(e,"tid"),info:e,timestamp:i,datetime:this.iso8601(i),symbol:this.safeSymbol(void 0,t),type:void 0,side:this.safeString(e,"type"),order:void 0,takerOrMaker:void 0,price:this.safeString(e,"price"),amount:this.safeString(e,"amount"),cost:void 0,fee:void 0},t)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={pair:r.id},o=await this.publicGetApiTradesPair(this.extend(a,s));return this.parseTrades(o,r,t,i)}parseOHLCV(e,t){return[this.safeTimestamp(e,"Time"),this.safeNumber(e,"Open"),this.safeNumber(e,"High"),this.safeNumber(e,"Low"),this.safeNumber(e,"Close"),this.safeNumber(e,"Volume")]}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=this.safeString(this.timeframes,t,t),n=this.seconds(),d=this.safeInteger(r,"until",n),h=this.omit(r,["until"]),c={to:d,tf:o,symbol:a.id},l=void 0===s?1e3:s;void 0!==i?c.from=Math.floor(i/1e3):c.from=n-l*this.parseTimeframe(t)-1;let u=await this.publicGetTradingviewHistoryV2(this.extend(c,h));return this.parseOHLCVs(this.toArray(u),a,t,i,l)}parseOrderStatus(e){return this.safeString({open:"open",filled:"closed",cancelled:"canceled"},e,e)}parseOrder(e,t){let i,s,r,a,o,n;"type"in e&&(i=this.safeString(e,"type"));let d=this.parseOrderStatus(this.safeString(e,"status","open")),h=this.safeString(e,"price"),c=this.safeString(e,"pair"),l=this.safeMarket(c,t);if(void 0!==l){s=l.symbol;let t=l.quoteId,i=l.baseId;"idr"===l.quoteId&&"order_rp"in e&&(t="rp"),"idr"===l.baseId&&"remain_rp"in e&&(i="rp"),r=this.safeString(e,"order_"+t),a=this.safeString(e,"order_"+i),o=this.safeString(e,"remain_"+i),n=this.safeString(e,"receive_"+i)}let u=this.safeInteger(e,"submit_time"),f=this.safeString(e,"order_id");return this.safeOrder({info:e,id:f,clientOrderId:this.safeString(e,"client_order_id"),timestamp:u,datetime:this.iso8601(u),lastTradeTimestamp:void 0,symbol:s,type:"limit",timeInForce:void 0,postOnly:void 0,side:i,price:h,triggerPrice:void 0,cost:r,average:void 0,amount:a,filled:n,remaining:o,status:d,fee:void 0,trades:void 0})}async fetchOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r={pair:s.id,order_id:e},o=await this.privatePostGetOrder(this.extend(r,i)),n=this.safeDict(o,"return",{}),d=this.parseOrder(this.extend({id:e},n.order),s);return d.info=o,d}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.pair=(r=this.market(e)).id);let o=await this.privatePostOpenOrders(this.extend(a,s)),n=this.safeDict(o,"return",{}).orders;if(null==n)return[];if(void 0!==e)return this.parseOrders(n,r,t,i);let d=Object.keys(n),h=[];for(let e=0;e<d.length;e++){let s=d[e],a=n[s];r=this.safeMarket(s);let o=this.parseOrders(a,r,t,i);h=this.arrayConcat(h,o)}return h}async fetchClosedOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchClosedOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={pair:r.id},n=await this.privatePostOrderHistory(this.extend(o,s)),d=this.safeDict(n,"return",{}),h=this.parseOrders(d.orders,r);return h=this.filterBy(h,"status","closed"),this.filterBySymbolSinceLimit(h,e,t,i)}async createOrder(e,t,i,s,r,n={}){void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h={pair:d.id,type:i,price:r},c=!1,l=!1,u=n;if("market"===t&&"buy"===i&&(u=this.omit(n,"cost")),"market"===t)if("buy"===i){let t,i=this.safeNumber(n,"cost");if(void 0!==i)t=this.costToPrecision(e,i);else{if(void 0===r)throw new a.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price).");let i=this.numberToString(s),n=this.numberToString(r),d=o.Y.stringMul(i,n);t=this.costToPrecision(e,d)}h[d.quoteId]=t}else l=!0;else"limit"===t&&(c=!0,l=!0,"buy"===i&&(h[d.quoteId]=this.parseToNumeric(this.costToPrecision(e,o.Y.stringMul(this.numberToString(s),this.numberToString(r))))));if(c){if(void 0===r)throw new a.InvalidOrder(this.id+" createOrder() requires a price argument for a "+t+" order");h.price=r}l&&(h[d.baseId]=this.amountToPrecision(e,s));let f=await this.privatePostTrade(this.extend(h,u)),p=this.safeDict(f,"return",{}),m=this.safeString(p,"order_id");return this.safeOrder({info:f,id:m},d)}async cancelOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");let s=this.safeString(i,"side");if(void 0===s)throw new a.ArgumentsRequired(this.id+' cancelOrder() requires an extra "side" param');void 0===this.markets&&await this.loadMarkets();let r={order_id:e,pair:this.market(t).id,type:s},o=await this.privatePostCancelOrder(this.extend(r,i)),n=this.safeDict(o,"return");return this.parseOrder(n)}async fetchTransactionFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={currency:i.id},r=await this.privatePostWithdrawFee(this.extend(s,t)),a=this.safeDict(r,"return",{}),o=this.safeString(a,"currency");return{info:r,rate:this.safeNumber(a,"withdraw_fee"),currency:this.safeCurrencyCode(o,i)}}async fetchDepositWithdrawFee(e,t={}){await this.loadMarkets();let i=this.currency(e),s={currency:i.id},r=await this.privatePostWithdrawFee(this.extend(s,t)),a=this.safeDict(r,"return",{}),o=this.depositWithdrawFee(r);return o.withdraw.fee=this.safeNumber(a,"withdraw_fee"),o.withdraw.percentage=!1,o.deposit.fee=0,o.deposit.percentage=!1,this.assignDefaultDepositWithdrawFees(o,i)}async fetchDepositsWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==t&&(a.start=this.yyyymmdd(t),a.end=this.yyyymmdd(this.milliseconds()));let o=await this.privatePostTransHistory(this.extend(a,s)),n=this.safeDict(o,"return",{}),d=this.safeDict(n,"withdraw",{}),h=this.safeDict(n,"deposit",{}),c=[];if(void 0===e){let e=Object.keys(d);for(let t=0;t<e.length;t++){let i=e[t];c=this.arrayConcat(c,d[i])}e=Object.keys(h);for(let t=0;t<e.length;t++){let i=e[t];c=this.arrayConcat(c,h[i])}}else{r=this.currency(e);let t=this.safeList(d,r.id,[]),i=this.safeList(h,r.id,[]);c=this.arrayConcat(t,i)}return this.parseTransactions(c,r,t,i)}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d=this.milliseconds(),h={currency:n.id,withdraw_amount:t,withdraw_address:i,request_id:d.toString()};void 0!==a&&""!==a&&(h.withdraw_memo=a);let c=await this.privatePostWithdrawCoin(this.extend(h,o));return this.parseTransaction(c,n)}parseTransaction(e,t){let i,s=this.safeString(e,"status"),r=this.safeTimestamp2(e,"success_time","submit_time"),a=this.safeString(e,"deposit_id"),o=this.safeNumber(e,"fee");return void 0!==o&&(i={currency:this.safeCurrencyCode(void 0,t),cost:o,rate:void 0}),{id:this.safeString2(e,"withdraw_id","deposit_id"),txid:this.safeString2(e,"txid","tx"),timestamp:r,datetime:this.iso8601(r),network:void 0,addressFrom:void 0,address:this.safeString(e,"withdraw_address"),addressTo:void 0,amount:this.safeNumberN(e,["amount","withdraw_amount","deposit_amount"]),type:void 0===a?"withdraw":"deposit",currency:this.safeCurrencyCode(void 0,t),status:this.parseTransactionStatus(s),updated:void 0,tagFrom:void 0,tag:void 0,tagTo:void 0,comment:this.safeString(e,"withdraw_memo"),internal:void 0,fee:i,info:e}}parseTransactionStatus(e){return this.safeString({success:"ok"},e,e)}async fetchDepositAddresses(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privatePostGetInfo(t),s=this.safeDict(i,"return"),r=this.safeDict(s,"address",{}),o=this.safeDict(s,"network",{}),n=Object.keys(r),d={info:s};for(let t=0;t<n.length;t++){let i=n[t],s=this.safeCurrencyCode(i),h=this.safeString(r,i);if(void 0!==h&&(void 0===e||this.inArray(s,e))){let e;if(this.checkAddress(h),i in o){let t=this.safeString(o,i);if(void 0===t)throw new a.ExchangeError(this.id+" fetchDepositAddresses() missing networkId");if(t.indexOf(",")>=0){if(e=[],void 0===t)throw new a.ExchangeError(this.id+" fetchDepositAddresses() missing networkId");let i=t.split(",");for(let t=0;t<i.length;t++){let r=this.networkIdToCode(i[t],s);void 0!==r&&e.push(r.toUpperCase())}}else{let i=this.networkIdToCode(t,s);void 0!==i&&(e=i.toUpperCase())}}let t=e;void 0!==s&&(d[s]={info:{},currency:s,network:t,address:h,tag:void 0})}}return d}sign(e,t="public",i="GET",r={},o,n){let d,h,c=this.safeString(this.urls.api,t);if(void 0===c)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let l=c,u="public"===t;if(u){let t=this.omit(r,this.extractParams(e));l+="/"+this.implodeParams(e,r),Object.keys(t).length>0&&(l+="?"+this.urlencodeWithArrayRepeat(t))}else this.checkRequiredCredentials(),d=this.urlencode(this.extend({method:e,timestamp:this.nonce(),recvWindow:this.options.recvWindow},r)),h={"Content-Type":"application/x-www-form-urlencoded",Key:this.apiKey,Sign:this.hmac(this.encode(d),this.encode(this.secret),s.Zf)};let f=d;u&&(f=n);let p=h;return u&&(p=o),{url:l,method:i,body:f,headers:p}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n||Array.isArray(n))return;let c=this.safeString(n,"error","");if(!("success"in n)&&""===c||"approved"===this.safeString(n,"success"))return;if(1===this.safeInteger(n,"success",0))if("return"in n)return;else throw new a.ExchangeError(this.id+": malformed response: "+this.json(n));let l=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,c,l),this.throwBroadlyMatchedException(this.exceptions.broad,c,l),new a.ExchangeError(l)}}i.d(t,{A:()=>n})},4436(e,t,i){"use strict";var s=i(4721),r=i(6253),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"kraken",name:"Kraken",countries:["US"],version:"0",rateLimit:1e3,certified:!1,pro:!0,has:{CORS:void 0,spot:!0,margin:!0,swap:!1,future:!1,option:!1,addMargin:!1,cancelAllOrders:!0,cancelAllOrdersAfter:!0,cancelOrder:!0,cancelOrders:!0,createDepositAddress:!0,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!0,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,createTrailingAmountOrder:!0,createTrailingPercentOrder:!0,editOrder:!0,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchFundingHistory:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLedger:!0,fetchLedgerEntry:!0,fetchLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterestHistory:!1,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrderTrades:"emulated",fetchPositions:!0,fetchPremiumIndexOHLCV:!1,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!1,fetchWithdrawals:!0,setLeverage:!1,setMarginMode:!1,transfer:!0,withdraw:!0},timeframes:{"1m":1,"5m":5,"15m":15,"30m":30,"1h":60,"4h":240,"1d":1440,"1w":10080,"2w":21600},urls:{logo:"https://user-images.githubusercontent.com/51840849/76173629-fc67fb00-61b1-11ea-84fe-f2de582f58a3.jpg",api:{public:"https://api.kraken.com",private:"https://api.kraken.com",zendesk:"https://kraken.zendesk.com/api/v2/help_center/en-us/articles"},www:"https://www.kraken.com",doc:"https://docs.kraken.com/api-reference/",fees:"https://www.kraken.com/en-us/features/fee-schedule"},fees:{trading:{tierBased:!0,percentage:!0,taker:this.parseNumber("0.0026"),maker:this.parseNumber("0.0016"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.0026")],[this.parseNumber("50000"),this.parseNumber("0.0024")],[this.parseNumber("100000"),this.parseNumber("0.0022")],[this.parseNumber("250000"),this.parseNumber("0.0020")],[this.parseNumber("500000"),this.parseNumber("0.0018")],[this.parseNumber("1000000"),this.parseNumber("0.0016")],[this.parseNumber("2500000"),this.parseNumber("0.0014")],[this.parseNumber("5000000"),this.parseNumber("0.0012")],[this.parseNumber("10000000"),this.parseNumber("0.0001")]],maker:[[this.parseNumber("0"),this.parseNumber("0.0016")],[this.parseNumber("50000"),this.parseNumber("0.0014")],[this.parseNumber("100000"),this.parseNumber("0.0012")],[this.parseNumber("250000"),this.parseNumber("0.0010")],[this.parseNumber("500000"),this.parseNumber("0.0008")],[this.parseNumber("1000000"),this.parseNumber("0.0006")],[this.parseNumber("2500000"),this.parseNumber("0.0004")],[this.parseNumber("5000000"),this.parseNumber("0.0002")],[this.parseNumber("10000000"),this.parseNumber("0.0")]]}}},handleContentTypeApplicationZip:!0,api:{zendesk:{get:{"360000292886":{cost:1},0xc08a6e8:{cost:1}}},public:{get:{Time:{cost:1},SystemStatus:{cost:1},MaintenanceSchedule:{cost:1},Assets:{cost:1},AssetPairs:{cost:1},Ticker:{cost:1},OHLC:{cost:1.2},Depth:{cost:1.2},GroupedBook:{cost:1.2},Trades:{cost:1.2},Spread:{cost:1},PreTrade:{cost:1},PostTrade:{cost:1}}},private:{post:{Level3:{cost:1.2},Balance:{cost:3},BalanceEx:{cost:3},CreditLines:{cost:3},TradeBalance:{cost:3},OpenOrders:{cost:3},ClosedOrders:{cost:3},QueryOrders:{cost:3},OrderAmends:{cost:3},TradesHistory:{cost:6},QueryTrades:{cost:3},OpenPositions:{cost:3},Ledgers:{cost:6},QueryLedgers:{cost:3},TradeVolume:{cost:3},AddExport:{cost:3},ExportStatus:{cost:3},RetrieveExport:{cost:3},RemoveExport:{cost:3},GetApiKeyInfo:{cost:3},ListWalletAccounts:{cost:3},AddOrder:{cost:0},AmendOrder:{cost:0},CancelOrder:{cost:0},CancelAll:{cost:3},CancelAllOrdersAfter:{cost:3},GetWebSocketsToken:{cost:3},AddOrderBatch:{cost:0},CancelOrderBatch:{cost:0},EditOrder:{cost:0},DepositMethods:{cost:3},DepositAddresses:{cost:3},DepositStatus:{cost:3},WithdrawMethods:{cost:3},WithdrawAddresses:{cost:3},WithdrawInfo:{cost:3},Withdraw:{cost:3},WithdrawStatus:{cost:3},WithdrawCancel:{cost:3},WalletTransfer:{cost:3},CreateSubaccount:{cost:3},AccountTransfer:{cost:3},"Earn/Allocate":{cost:3},"Earn/Deallocate":{cost:3},"Earn/AllocateStatus":{cost:3},"Earn/DeallocateStatus":{cost:3},"Earn/Strategies":{cost:3},"Earn/Allocations":{cost:3}}}},commonCurrencies:{LUNA:"LUNC",LUNA2:"LUNA",REPV2:"REP",REP:"REPV1",UST:"USTC",XBT:"BTC",XDG:"DOGE",FEE:"KFEE",XETC:"ETC",XETH:"ETH",XLTC:"LTC",XMLN:"MLN",XREP:"REP",XXBT:"BTC",XXDG:"DOGE",XXLM:"XLM",XXMR:"XMR",XXRP:"XRP",XZEC:"ZEC",ZAUD:"AUD",ZCAD:"CAD",ZEUR:"EUR",ZGBP:"GBP",ZJPY:"JPY",ZUSD:"USD"},options:{mica:!0,timeDifference:0,adjustForTimeDifference:!1,marketsByAltname:{},delistedMarketsById:{},inactiveCurrencies:["CAD","USD","JPY","GBP"],networks:{ETH:"ERC20",TRX:"TRC20"},depositMethods:{"1INCH":"1inch (1INCH)",AAVE:"Aave",ADA:"ADA",ALGO:"Algorand",ANKR:"ANKR (ANKR)",ANT:"Aragon (ANT)",ATOM:"Cosmos",AXS:"Axie Infinity Shards (AXS)",BADGER:"Bager DAO (BADGER)",BAL:"Balancer (BAL)",BAND:"Band Protocol (BAND)",BAT:"BAT",BCH:"Bitcoin Cash",BNC:"Bifrost (BNC)",BNT:"Bancor (BNT)",BTC:"Bitcoin",CHZ:"Chiliz (CHZ)",COMP:"Compound (COMP)",CQT:"	Covalent Query Token (CQT)",CRV:"Curve DAO Token (CRV)",CTSI:"Cartesi (CTSI)",DAI:"Dai",DASH:"Dash",DOGE:"Dogecoin",DOT:"Polkadot",DYDX:"dYdX (DYDX)",ENJ:"Enjin Coin (ENJ)",EOS:"EOS",ETC:"Ether Classic (Hex)",ETH:"Ether (Hex)",EWT:"Energy Web Token",FEE:"Kraken Fee Credit",FIL:"Filecoin",FLOW:"Flow",GHST:"Aavegotchi (GHST)",GNO:"GNO",GRT:"GRT",ICX:"Icon",INJ:"Injective Protocol (INJ)",KAR:"Karura (KAR)",KAVA:"Kava",KEEP:"Keep Token (KEEP)",KNC:"Kyber Network (KNC)",KSM:"Kusama",LINK:"Link",LPT:"Livepeer Token (LPT)",LRC:"Loopring (LRC)",LSK:"Lisk",LTC:"Litecoin",MANA:"MANA",MATIC:"Polygon (MATIC)",MINA:"Mina",MIR:"Mirror Protocol (MIR)",MKR:"Maker (MKR)",MLN:"MLN",MOVR:"Moonriver (MOVR)",NANO:"NANO",OCEAN:"OCEAN",OGN:"Origin Protocol (OGN)",OMG:"OMG",OXT:"Orchid (OXT)",OXY:"Oxygen (OXY)",PAXG:"PAX (Gold)",PERP:"Perpetual Protocol (PERP)",PHA:"Phala (PHA)",QTUM:"QTUM",RARI:"Rarible (RARI)",RAY:"Raydium (RAY)",REN:"Ren Protocol (REN)",REP:"REPv2",REPV1:"REP",SAND:"The Sandbox (SAND)",SC:"Siacoin",SDN:"Shiden (SDN)",SOL:"Solana",SNX:"Synthetix  Network (SNX)",SRM:"Serum",STORJ:"Storj (STORJ)",SUSHI:"Sushiswap (SUSHI)",TBTC:"tBTC",TRX:"Tron",UNI:"UNI",USDC:"USDC",USDT:"Tether USD (ERC20)","USDT-TRC20":"Tether USD (TRC20)",WAVES:"Waves",WBTC:"Wrapped Bitcoin (WBTC)",XLM:"Stellar XLM",XMR:"Monero",XRP:"Ripple XRP",XTZ:"XTZ",YFI:"YFI",ZEC:"Zcash (Transparent)",ZRX:"0x (ZRX)"},withdrawMethods:{Lightning:"Lightning",Bitcoin:"BTC",Ripple:"XRP",Litecoin:"LTC",Dogecoin:"DOGE",Stellar:"XLM",Ethereum:"ERC20","Arbitrum One":"Arbitrum",Polygon:"MATIC","Arbitrum Nova":"Arbitrum",Optimism:"Optimism","zkSync Era":"zkSync","Ethereum Classic":"ETC",Zcash:"ZEC",Monero:"XMR",Tron:"TRC20",Solana:"SOL",EOS:"EOS","Bitcoin Cash":"BCH",Cardano:"ADA",Qtum:"QTUM",Tezos:"XTZ",Cosmos:"ATOM",Nano:"NANO",Siacoin:"SC",Lisk:"LSK",Waves:"WAVES",ICON:"ICX",Algorand:"ALGO","Polygon - USDC.e":"MATIC","Arbitrum One - USDC.e":"Arbitrum",Polkadot:"DOT",Kava:"KAVA",Filecoin:"FIL",Kusama:"KSM",Flow:"FLOW","Energy Web":"EW",Mina:"MINA",Centrifuge:"CFG",Karura:"KAR",Moonriver:"MOVR",Shiden:"SDN",Khala:"PHA","Bifrost Kusama":"BNC",Songbird:"SGB","Terra classic":"LUNC",KILT:"KILT",Basilisk:"BSX",Flare:"FLR","Avalanche C-Chain":"AVAX",Kintsugi:"KINT",Altair:"AIR",Moonbeam:"GLMR",Acala:"ACA",Astar:"ASTR",Akash:"AKT",Robonomics:"XRT",Fantom:"FTM",Elrond:"EGLD",THORchain:"RUNE",Secret:"SCRT",Near:"NEAR","Internet Computer Protocol":"ICP",Picasso:"PICA","Crust Shadow":"CSM",Integritee:"TEER","Parallel Finance":"PARA",HydraDX:"HDX",Interlay:"INTR","Fetch.ai":"FET",NYM:"NYM","Terra 2.0":"LUNA2",Juno:"JUNO",Nodle:"NODL",Stacks:"STX","Ethereum PoW":"ETHW",Aptos:"APT",Sui:"SUI",Genshiro:"GENS",Aventus:"AVT",Sei:"SEI",OriginTrail:"OTP",Celestia:"TIA"},marketHelperProps:["marketsByAltname","delistedMarketsById"]},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!0,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,selfTradePrevention:!0,iceberg:!0},createOrders:{min:2,max:15,sameSymbolOnly:!0},fetchMyTrades:{marginMode:!1,limit:void 0,daysBack:void 0,untilDays:void 0,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:void 0,daysBack:void 0,daysBackCanceled:void 0,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:720}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},precisionMode:4,rollingWindowSize:1e4,exceptions:{exact:{"EQuery:Invalid asset pair":a.BadSymbol,"EAPI:Invalid key":a.AuthenticationError,"EFunding:Unknown withdraw key":a.InvalidAddress,"EFunding:Invalid amount":a.InsufficientFunds,"EService:Unavailable":a.ExchangeNotAvailable,"EDatabase:Internal error":a.ExchangeNotAvailable,"EService:Busy":a.ExchangeNotAvailable,"EQuery:Unknown asset":a.BadSymbol,"EAPI:Rate limit exceeded":a.DDoSProtection,"EOrder:Rate limit exceeded":a.DDoSProtection,"EGeneral:Internal error":a.ExchangeNotAvailable,"EGeneral:Temporary lockout":a.DDoSProtection,"EGeneral:Permission denied":a.PermissionDenied,"EGeneral:Invalid arguments:price":a.InvalidOrder,"EOrder:Unknown order":a.InvalidOrder,"EOrder:Invalid price:Invalid price argument":a.InvalidOrder,"EOrder:Order minimum not met":a.InvalidOrder,"EOrder:Insufficient funds":a.InsufficientFunds,"EGeneral:Invalid arguments":a.BadRequest,"ESession:Invalid session":a.AuthenticationError,"EAPI:Invalid nonce":a.InvalidNonce,"EFunding:No funding method":a.BadRequest,"EFunding:Unknown asset":a.BadSymbol,"EService:Market in post_only mode":a.OnMaintenance,"EService:Market in cancel_only mode":a.OnMaintenance,"EGeneral:Too many requests":a.DDoSProtection,"ETrade:User Locked":a.AccountSuspended},broad:{":Invalid order":a.InvalidOrder,":Invalid arguments:volume":a.InvalidOrder,":Invalid arguments:viqc":a.InvalidOrder,":Invalid nonce":a.InvalidNonce,":IInsufficient funds":a.InsufficientFunds,":Cancel pending":a.CancelPending,":Rate limit exceeded":a.RateLimitExceeded}}})}feeToPrecision(e,t){return this.decimalToPrecision(t,0,this.market(e).precision.amount,this.precisionMode)}async fetchMarkets(e={}){let t=[];t.push(this.publicGetAssetPairs(e)),this.safeBool(this.options,"adjustForTimeDifference",!1)&&t.push(this.loadTimeDifference());let i=await Promise.all(t),s=this.safeDict(i,0),r=this.safeDict(s,"result",{}),n=this.safeDict(this.options,"cachedCurrencies",{}),d=Object.keys(r),h=[];for(let e=0;e<d.length;e++){let t,i,s=d[e],c=!1;s.indexOf(":BTNL")>=0&&(c=!0);let l=r[s],u=this.safeString(l,"base"),f=this.safeString(l,"quote"),p=this.safeCurrencyCode(u),m=this.safeCurrencyCode(f);if(void 0===p||void 0===m)continue;let g=this.safeList(l,"fees_maker",[]),v=this.safeList(g,0,[]),y=this.safeString(v,1);void 0!==y&&(t=this.parseNumber(o.Y.stringDiv(y,"100")));let b=this.safeList(l,"fees",[]),w=this.safeList(b,0,[]),k=this.safeString(w,1);void 0!==k&&(i=this.parseNumber(o.Y.stringDiv(k,"100")));let S=this.safeList(l,"leverage_buy",[]),O=S.length,T=this.parseNumber(this.parsePrecision(this.safeString(l,"pair_decimals"))),P=this.parseNumber(this.parsePrecision(this.safeString(l,"lot_decimals")));if(p in n){let e=this.safeDict(n,p),t=this.safeNumber(e,"precision");if(void 0===t)throw new a.ExchangeError(this.id+" method() missing currencyPrecision");t>P&&(P=t)}let I="online"===this.safeString(l,"status"),A=s;c||(A=p+"/"+m),h.push({id:s,wsId:this.safeString(l,"wsname"),symbol:A,base:p,quote:m,settle:void 0,baseId:p,quoteId:m,settleId:void 0,altname:l.altname,type:"spot",spot:!0,margin:O>0,swap:!1,future:!1,option:!1,active:I,contract:!1,linear:void 0,inverse:void 0,taker:i,maker:t,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:P,price:T},limits:{leverage:{min:this.parseNumber("1"),max:this.safeNumber(S,O-1,1)},amount:{min:this.safeNumber(l,"ordermin"),max:void 0},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(l,"costmin"),max:void 0}},created:void 0,info:l})}return this.options.marketsByAltname=this.indexBy(h,"altname"),h}async fetchStatus(e={}){let t=await this.publicGetSystemStatus(e),i=this.safeDict(t,"result");return{status:"online"===this.safeString(i,"status")?"ok":"maintenance",updated:void 0,eta:void 0,url:void 0,info:t}}async fetchCurrencies(e={}){let t=await this.publicGetAssets(e),i=this.safeDict(t,"result",{}),s=this.addKeyInArrayItems(i,"_coin_id");return this.parseCurrencies(s)}parseCurrency(e){let t=this.safeString(e,"_coin_id"),i=this.safeCurrencyCode(t);if(void 0===t)throw new a.ExchangeError(this.id+" parseCurrency() missing id");if(0>t.indexOf(".")){let s=this.safeString(e,"altname");if(void 0===t)throw new a.ExchangeError(this.id+" parseCurrency() missing id");t!==s&&(t.startsWith("X")||t.startsWith("Z"))?(i=this.safeCurrencyCode(s),void 0!==t&&void 0!==i&&(this.commonCurrencies[t]=i)):i=this.safeCurrencyCode(t)}if(void 0===i)throw new a.ExchangeError(this.id+" parseCurrency() missing code");let s=i.indexOf(".HOLD")>=0,r=this.omit(e,"_coin_id");return this.safeCurrencyStructure({id:t,code:i,info:r,name:this.safeString(r,"altname"),active:"enabled"===this.safeString(r,"status"),type:s?"fiat":"crypto",deposit:void 0,withdraw:void 0,fee:void 0,precision:this.parseNumber(this.parsePrecision(this.safeString(r,"decimals"))),limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}},networks:{}})}safeCurrencyCode(e,t){if(void 0===e)return e;if(e.indexOf(".")>0){let i=e.split("."),s=this.safeString(i,0),r=this.safeString(i,1);return super.safeCurrencyCode(s,t)+"."+r}return super.safeCurrencyCode(e,t)}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={pair:i.id,"fee-info":!0},r=await this.privatePostTradeVolume(this.extend(s,t)),a=this.safeDict(r,"result",{});return this.parseTradingFee(a,i)}parseTradingFee(e,t){let i=this.safeDict(e,"fees_maker",{}),s=this.safeDict(e,"fees",{}),r=this.safeDict(i,t.id,{}),a=this.safeDict(s,t.id,{});return{info:e,symbol:t.symbol,maker:this.parseNumber(o.Y.stringDiv(this.safeString(r,"fee"),"100")),taker:this.parseNumber(o.Y.stringDiv(this.safeString(a,"fee"),"100")),percentage:!0,tierBased:!0}}parseOrderBookBidAsk(e,t=0,i=1,s=2){return[this.safeNumber(e,t),this.safeNumber(e,i),this.safeInteger(e,2)]}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={pair:s.id};void 0!==t&&(r.count=t);let a=await this.publicGetDepth(this.extend(r,i)),o=this.safeDict(a,"result",{}),n=this.safeDict(o,s.id),d=this.safeDict(s,"info",{}),h=this.safeString(d,"wsname");return void 0!==h&&(n=this.safeDict(o,h,n)),this.parseOrderBook(n,e)}parseTicker(e,t){let i=this.safeSymbol(void 0,t),s=this.safeList(e,"v",[]),r=this.safeString(s,1),a=this.safeList(e,"p",[]),n=this.safeString(a,1),d=o.Y.stringMul(r,n),h=this.safeList(e,"c",[]),c=this.safeString(h,0),l=this.safeList(e,"h",[]),u=this.safeList(e,"l",[]),f=this.safeList(e,"b",[]),p=this.safeList(e,"a",[]);return this.safeTicker({symbol:i,timestamp:void 0,datetime:void 0,high:this.safeString(l,1),low:this.safeString(u,1),bid:this.safeString(f,0),bidVolume:this.safeString(f,2),ask:this.safeString(p,0),askVolume:this.safeString(p,2),vwap:n,open:this.safeString(e,"o"),close:c,last:c,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:r,quoteVolume:d,info:e},t)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={},s=this.marketSymbols(e);if(void 0!==s){let e=[];for(let t=0;t<s.length;t++){let i=s[t],r=this.market(i);!0===r.active&&e.push(r.id)}i.pair=e.join(",")}let r=await this.publicGetTicker(this.extend(i,t)),a=this.safeDict(r,"result",{}),o=Object.keys(a),n={};for(let e=0;e<o.length;e++){let t=o[e],i=this.safeMarket(t),s=i.symbol,r=a[t];n[s]=this.parseTicker(r,i)}return this.filterByArrayTickers(n,"symbol",s)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={pair:i.id},r=await this.publicGetTicker(this.extend(s,t)),a=this.safeDict(r,"result",{}),o=this.safeValue(a,i.id);return this.parseTicker(o,i)}parseOHLCV(e,t){return[this.safeTimestamp(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,6)]}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(o)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,n,720);let d=this.market(e),h=this.safeInteger(this.timeframes,t),c={pair:d.id};if(void 0!==h?c.interval=h:c.interval=t,void 0!==i){let e=this.parseToInt(i/1e3);if(void 0===h)throw new a.ExchangeError(this.id+" fetchOHLCV() missing parsedTimeframe");let t=60*h;c.since=this.numberToString(e-t)}let l=await this.publicGetOHLC(this.extend(c,n)),u=this.safeDict(l,"result",{}),f=this.safeList(u,d.id,[]);return this.parseOHLCVs(f,d,t,i,s)}parseLedgerEntryType(e){return this.safeString({trade:"trade",withdrawal:"transaction",deposit:"transaction",transfer:"transfer",margin:"margin"},e,e)}parseLedgerEntry(e,t){let i,s=this.safeString(e,"id"),r=this.safeString(e,"refid"),a=this.parseLedgerEntryType(this.safeString(e,"type")),n=this.safeString(e,"asset"),d=this.safeCurrencyCode(n,t),h=this.safeCurrency(n,t),c=this.safeString(e,"amount");o.Y.stringLt(c,"0")?(i="out",c=o.Y.stringAbs(c)):i="in";let l=this.safeIntegerProduct(e,"time",1e3);return this.safeLedgerEntry({info:e,id:s,direction:i,account:void 0,referenceId:r,referenceAccount:void 0,type:a,currency:d,amount:this.parseNumber(c),before:void 0,after:this.safeNumber(e,"balance"),status:"ok",timestamp:l,datetime:this.iso8601(l),fee:{cost:this.safeNumber(e,"fee"),currency:d}},h)}async fetchLedger(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.asset=(r=this.currency(e)).id),void 0!==t&&(a.start=this.parseToInt(t/1e3));let n=this.safeString2(s,"until","till"),d=void 0!==n?this.omit(s,["until","till"]):s;if(void 0!==n){let e=o.Y.stringDiv(n,"1000");a.end=this.parseToInt(o.Y.stringAdd(e,"1"))}let h=await this.privatePostLedgers(this.extend(a,d)),c=this.safeDict(h,"result",{}),l=this.safeDict(c,"ledger",{}),u=Object.keys(l),f=[];for(let e=0;e<u.length;e++){let t=u[e],i=l[t];i.id=t,f.push(i)}return this.parseLedger(f,r,t,i)}async fetchLedgerEntriesByIds(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=e.join(","),r=this.extend({id:s},i),a=await this.privatePostQueryLedgers(r),o=this.safeDict(a,"result",{}),n=Object.keys(o),d=[];for(let e=0;e<n.length;e++){let t=n[e],i=o[t];i.id=t,d.push(i)}return this.parseLedger(d)}async fetchLedgerEntry(e,t,i={}){let s=await this.fetchLedgerEntriesByIds([e],t,i);return this.safeDict(s,0)}parseTrade(e,t){let i,s,r,a,o,n,d,h,c,l,u,f=!Array.isArray(e)&&"string"!=typeof e&&"ordertxid"in e,p=t;if(f&&(p=this.resolveMarketByAltnameOrId(this.safeString(e,"pair"),t)),Array.isArray(e))i=this.safeTimestamp(e,2),r="s"===this.safeString(e,3)?"sell":"buy",a="l"===this.safeString(e,4)?"limit":"market",o=this.safeString(e,0),n=this.safeString(e,1),e.length>6&&(d=this.safeString(e,6));else if("string"==typeof e)d=e;else if("ordertxid"in e){if(h=this.safeString(e,"ordertxid"),d=this.safeString2(e,"id","postxid"),i=this.safeTimestamp(e,"time"),r=this.safeString(e,"type"),a=this.safeString(e,"ordertype"),o=this.safeString(e,"price"),n=this.safeString(e,"vol"),"fee"in e){let t;void 0!==p&&(t=this.safeString(p,"quote")),c={cost:this.safeString(e,"fee"),currency:t}}}else l=this.safeString(e,"symbol"),s=this.safeString(e,"timestamp"),d=this.safeString(e,"trade_id"),r=this.safeString(e,"side"),a=this.safeString(e,"ord_type"),o=this.safeString(e,"price"),n=this.safeString(e,"qty");void 0!==p&&(l=this.safeString(p,"symbol"));let m=this.safeString(e,"cost"),g=this.safeBool(e,"maker");return void 0!==g&&(u=g?"maker":"taker"),void 0===s?s=this.iso8601(i):i=this.parse8601(s),this.safeTrade({id:d,order:h,info:e,timestamp:i,datetime:s,symbol:l,type:a,side:r,takerOrMaker:u,price:o,amount:n,cost:m,fee:c},p)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.id,o={pair:a};void 0!==t&&(o.since=this.numberToString(this.parseToInt(t/1e3))),void 0!==i&&(o.count=i);let n=await this.publicGetTrades(this.extend(o,s)),d=this.safeDict(n,"result",{}),h=this.safeValue(d,a),c=h.length;if(c<=0)return[];let l=h[c-1],u=this.safeString(d,"last");return l.push(u),h[c-1]=l,this.parseTrades(h,r,t,i)}parseBalance(e){let t=this.safeDict(e,"result",{}),i={info:e,timestamp:void 0,datetime:void 0},s=Object.keys(t);for(let e=0;e<s.length;e++){let r=s[e],a=this.safeCurrencyCode(r),o=this.safeDict(t,r,{}),n=this.account();n.used=this.safeString(o,"hold_trade"),n.total=this.safeString(o,"balance"),void 0!==a&&(i[a]=n)}return this.safeBalance(i)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostBalanceEx(e);return this.parseBalance(t)}async createMarketOrderWithCost(e,t,i,s={}){return void 0===this.markets&&await this.loadMarkets(),await this.createOrder(e,"market",t,i,void 0,this.extend({cost:i},s))}async createMarketBuyOrderWithCost(e,t,i={}){return void 0===this.markets&&await this.loadMarkets(),await this.createMarketOrderWithCost(e,"buy",t,i)}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o={pair:this.market(e).id,type:i,ordertype:t,volume:this.amountToPrecision(e,s)},n=this.orderRequest("createOrder",e,t,o,s,r,a),d=this.safeString(n[0],"oflags","").indexOf("viqc")>-1,h=await this.privatePostAddOrder(this.extend(n[0],n[1])),c=this.safeDict(h,"result",{});return c.usingCost=d,this.parseOrder(c)}async createOrders(e,t={}){let i,s,r;void 0===this.markets&&await this.loadMarkets();let o=[],n=[];for(let t=0;t<e.length;t++){let r=this.safeDict(e,t),d=this.safeString(r,"symbol");if(void 0===i)i=d;else if(i!==d)throw new a.BadRequest(this.id+" createOrders() requires all orders to have the same symbol");s=this.market(d),n.push(d);let h=this.safeString(r,"type"),c=this.safeString(r,"side"),l=this.safeValue(r,"amount"),u=this.safeValue(r,"price"),f=this.safeDict(r,"params",{}),p={type:c,ordertype:h,volume:this.amountToPrecision(s.symbol,l)},m=this.orderRequest("createOrders",d,h,p,l,u,f);o.push(m[0])}n=this.marketSymbols(n,void 0,!1,!0,!0);let d={orders:o,pair:this.safeString(s,"id")};d=this.extend(d,t),r=await this.privatePostAddOrderBatch(d);let h=this.safeDict(r,"result",{});return this.parseOrders(this.safeList(h,"orders"))}findMarketByAltnameOrId(e){let t=this.safeDict(this.options,"marketsByAltname",{});return e in t?t[e]:this.safeMarket(e)}resolveMarketByAltnameOrId(e,t){let i=this.findMarketByAltnameOrId(e);return void 0!==i?i:void 0!==e?this.getDelistedMarketById(e):t}getDelistedMarketById(e){if(void 0===e)return e;let t=this.safeDict(this.options.delistedMarketsById,e);if(void 0!==t)return t;let i=3,s=3,r=6;8===e.length?(i=4,s=4,r=8):7===e.length&&(i=4,s=4,r=7);let a=e.slice(0,i),o=e.slice(s,r),n=this.safeCurrencyCode(a),d=this.safeCurrencyCode(o);if(void 0!==n&&void 0!==d)return t={symbol:n+"/"+d,base:n,quote:d,baseId:a,quoteId:o},this.options.delistedMarketsById[e]=t,t}parseOrderStatus(e){return this.safeString({pending:"open",open:"open",pending_new:"open",new:"open",partially_filled:"open",filled:"closed",closed:"closed",canceled:"canceled",expired:"expired"},e,e)}parseOrderType(e){return this.safeString({"take-profit":"market","stop-loss":"market","stop-loss-limit":"limit","take-profit-limit":"limit","trailing-stop-limit":"limit"},e,e)}parseOrder(e,t){let i,s,r,a,n,d,h,c,l,u,f,p,m=this.safeBool(e,"usingCost",!1),g=this.omit(e,"usingCost"),v=this.safeDict(g,"descr",{}),y=this.safeDict(g,"descr");if(void 0!==(i=void 0!==y?this.safeString(y,"order"):this.safeString(g,"descr"))){let e=i.split(" ");s=this.safeString(e,0),!0!==m?d=this.safeString(e,1):h=this.safeString(e,1),a=this.safeString(e,2);let t=this.safeString(e,4),o=this.safeString(e,5);"stop loss"===(r="limit"===t||"market"===t?t:t+" "+o)||"take profit"===r?(c=this.safeString(e,6),n=this.safeString(e,9)):"limit"===r&&(n=this.safeString(e,5))}s=this.safeString(v,"type",s),r=this.safeString(v,"ordertype",r),a=this.safeString(v,"pair",a);let b=this.resolveMarketByAltnameOrId(a,t),w=this.safeTimestamp(g,"opentm");d=this.safeString(g,"vol",d);let k=this.safeString(g,"vol_exec");void 0!==(n=this.safeString(v,"price",n))&&(n.endsWith("%")||o.Y.stringEquals(n,"0.00000")||o.Y.stringEquals(n,"0"))&&(n=void 0),void 0===n&&(n=this.safeString(v,"price2"),n=this.safeString2(g,"limitprice","price",n));let S=this.safeString(g,"oflags",""),O=S.indexOf("post")>-1,T=this.safeNumber(g,"price");void 0!==b&&(l=this.safeString(b,"symbol"),"fee"in g&&(u={cost:this.safeString(g,"fee"),rate:void 0},S.indexOf("fciq")>=0?u.currency=b.quote:S.indexOf("fcib")>=0&&(u.currency=b.base)));let P=this.parseOrderStatus(this.safeString(g,"status")),I=this.safeStringN(g,["id","txid","order_id","amend_id"]);if(void 0===I||I.startsWith("[")){let e=this.safeList(g,"txid");I=this.safeString(e,0)}let A=this.safeString(g,"userref"),x=this.safeString(g,"cl_ord_id",A),M=this.safeList(g,"trades",[]),_=[];for(let e=0;e<M.length;e++){let t=M[e];"string"==typeof t?_.push(this.safeTrade({id:t,order:I,symbol:l,info:{}})):_.push(t)}void 0!==r&&(r.startsWith("take-profit")?(p=this.safeString(v,"price"),n=this.omitZero(this.safeString(v,"price2"))):r.startsWith("stop-loss")?(f=this.safeString(v,"price"),n=this.omitZero(this.safeString(v,"price2"))):"take profit"===r?p=c:"stop loss"===r&&(f=c));let C=this.parseOrderType(r);return this.inArray(C,["stop loss","take profit"])&&(C=void 0===n?"market":"limit"),void 0!==this.safeString(g,"amend_id")&&(O=void 0),this.safeOrder({id:I,clientOrderId:x,info:g,timestamp:w,datetime:this.iso8601(w),lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeTimestamp(g,"closetm"),status:P,symbol:l,type:C,timeInForce:void 0,postOnly:O,side:s,price:n,triggerPrice:c,takeProfitPrice:p,stopLossPrice:f,cost:h,amount:d,filled:k,average:T,remaining:void 0,reduceOnly:this.safeBool2(g,"reduceOnly","reduce_only"),fee:u,trades:_},b)}orderRequest(e,t,i,s,r,a,o={}){let n=this.safeString(o,"clientOrderId"),d=this.omit(o,["clientOrderId"]);void 0!==n&&(s.cl_ord_id=n);let h=this.safeString(d,"stopLossPrice"),c=this.safeString(d,"takeProfitPrice"),l=void 0!==h,u=void 0!==c,f=this.safeString(d,"trailingAmount"),p=this.safeString(d,"trailingPercent"),m=this.safeString(d,"trailingLimitAmount"),g=this.safeString(d,"trailingLimitPercent"),v=void 0!==f,y=void 0!==p,b=void 0!==i&&i.endsWith("limit"),w="market"===i,k=this.safeString(d,"cost"),S=this.safeString(d,"oflags"),O=this.omit(d,["cost","oflags"]),T=void 0!==S&&S.indexOf("viqc")>-1;if(w&&(void 0!==k||T)){void 0===k&&void 0!==r?s.volume=this.costToPrecision(t,this.numberToString(r)):s.volume=this.costToPrecision(t,k);let e="viqc";void 0!==S&&(e=S+",viqc"),s.oflags=e}else!b||v||y||(s.price=this.priceToPrecision(t,a));let P=this.safeBool2(O,"reduceOnly","reduce_only");if(l||u)l?(s.price=this.priceToPrecision(t,h),b?s.ordertype="stop-loss-limit":s.ordertype="stop-loss"):u&&(s.price=this.priceToPrecision(t,c),b?s.ordertype="take-profit-limit":s.ordertype="take-profit"),b&&(s.price2=this.priceToPrecision(t,a));else if(v||y){let e;void 0!==p&&(e=p.endsWith("%")?"+"+p:"+"+p+"%");let t=void 0!==f?"+"+f:void 0,i=this.safeString(O,"offset","-"),r=void 0!==m?i+this.numberToString(m):void 0;if(s.trigger=this.safeString(O,"trigger","last"),b||void 0!==m||void 0!==g)if(s.ordertype="trailing-stop-limit",void 0!==g){let t=g.endsWith("%")?i+g:i+g+"%";s.price=e,s.price2=t}else void 0!==m&&(s.price=t,s.price2=r);else s.ordertype="trailing-stop",void 0!==p?s.price=e:s.price=t}!0===P&&("createOrderWs"===e?s.reduce_only=!0:s.reduce_only="true");let I=this.safeDict(O,"close");if(void 0!==I){I=void 0===(I=this.extend({},I))?{}:I;let e=this.safeValue(I,"price");void 0!==e&&(I.price=this.priceToPrecision(t,e));let i=this.safeValue(I,"price2");void 0!==i&&(I.price2=this.priceToPrecision(t,i)),s.close=I}let A=this.safeString2(O,"timeInForce","timeinforce");void 0!==A&&(s.timeinforce=A);let x="market"===i,[M,_]=this.handlePostOnly(x,!1,O);if(!0===M){let e="post";void 0!==S&&(e=S+",post"),s.oflags=e}return void 0===S||"oflags"in s||(s.oflags=S),[s,this.omit(_,["timeInForce","reduceOnly","stopLossPrice","takeProfitPrice","trailingAmount","trailingPercent","trailingLimitAmount","trailingLimitPercent","offset"])]}async editOrder(e,t,i,s,r,o,n={}){let d;void 0===this.markets&&await this.loadMarkets();let h=this.market(t);if(!0!==h.spot)throw new a.NotSupported(this.id+" editOrder() does not support "+h.type+" orders, only spot orders are accepted");let c={txid:e},l=this.safeString2(n,"clientOrderId","cl_ord_id"),u=void 0!==l?this.omit(n,["clientOrderId","cl_ord_id"]):n;void 0!==l&&(c.cl_ord_id=l,c=this.omit(c,"txid")),[d,u]=this.handlePostOnly("market"===i,!1,u),!0===d&&(c.post_only="true"),void 0!==r&&(c.order_qty=this.amountToPrecision(t,r)),void 0!==o&&(c.limit_price=this.priceToPrecision(t,o));let f=this.safeStringN(u,["stopLossPrice","takeProfitPrice","trailingAmount","trailingPercent","trailingLimitAmount","trailingLimitPercent"]);if(void 0!==f){let e=this.safeString(u,"offset");u=this.omit(u,["stopLossPrice","takeProfitPrice","trailingAmount","trailingPercent","trailingLimitAmount","trailingLimitPercent","offset"]),void 0!==e?(f=e+f,c.trigger_price=f):c.trigger_price=this.priceToPrecision(t,f)}let p=await this.privatePostAmendOrder(this.extend(c,u)),m=this.safeDict(p,"result",{});return this.parseOrder(m,h)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.safeValue2(i,"userref","clientOrderId"),r={trades:!0,txid:e},o=i;void 0!==s&&(r.userref=s,o=this.omit(i,["userref","clientOrderId"]));let n=await this.privatePostQueryOrders(this.extend(r,o)),d=this.safeDict(n,"result",[]);if(!(e in d))throw new a.OrderNotFound(this.id+" fetchOrder() could not find order id "+e);return this.parseOrder(this.extend({id:e},d[e]))}async fetchOrderTrades(e,t,i,s,r={}){let o=this.safeValue(r,"trades"),n=[];if(void 0===o)throw new a.ArgumentsRequired(this.id+" fetchOrderTrades() requires a unified order structure in the params argument or a 'trades' param (an array of trade id strings)");for(let e=0;e<o.length;e++){let t=o[e];"string"==typeof t?n.push(t):n.push(t.id)}void 0===this.markets&&await this.loadMarkets();let d=void 0!==t?this.symbol(t):t,h=this.safeDict(this.options,"fetchOrderTrades",{}),c=this.safeInteger(h,"batchSize",20),l=n.length,u=this.parseToInt(l/c);u=this.sum(u,1);let f=[];for(let e=0;e<u;e++){let t=[];for(let i=0;i<c;i++){let s=this.sum(e*c,i);s<l&&t.push(n[s])}let r={txid:t.join(",")},a=await this.privatePostQueryTrades(r),o=this.safeValue(a,"result"),h=Object.keys(o);for(let e=0;e<h.length;e++)o[h[e]].id=h[e];let u=this.parseTrades(o,void 0,i,s),p=this.filterBySymbol(u,d);f=this.arrayConcat(f,p)}return f}async fetchOrdersByIds(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privatePostQueryOrders(this.extend({trades:!0,txid:e.join(",")},i)),r=this.safeDict(s,"result",{}),a=[],o=Object.keys(r);for(let e=0;e<o.length;e++){let t=o[e],i=r[t],s=this.parseOrder(this.extend({id:t},i));a.push(s)}return a}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==t&&(a.start=this.parseToInt(t/1e3));let n=this.safeString2(s,"until","till"),d=void 0!==n?this.omit(s,["until","till"]):s;if(void 0!==n){let e=o.Y.stringDiv(n,"1000");a.end=this.parseToInt(o.Y.stringAdd(e,"1"))}let h=await this.privatePostTradesHistory(this.extend(a,d)),c=this.safeDict(h,"result",{}),l=this.safeDict(c,"trades",{}),u=Object.keys(l);for(let e=0;e<u.length;e++)l[u[e]].id=u[e];void 0!==e&&(r=this.market(e));let f=this.toArray(l);return this.parseTrades(f,r,t,i)}async cancelOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.safeValue(i,"userref",e),o=this.omit(i,"userref"),n={txid:r},d=this.safeString2(o,"clientOrderId","cl_ord_id"),h=void 0!==d?this.omit(o,["clientOrderId","cl_ord_id"]):o;void 0!==d&&(n.cl_ord_id=d,n=this.omit(n,"txid"));try{s=await this.privatePostCancelOrder(this.extend(n,h))}catch(e){if(void 0!==this.last_http_response&&""!==this.last_http_response&&this.last_http_response.indexOf("EOrder:Unknown order")>=0)throw new a.OrderNotFound(this.id+" cancelOrder() error "+this.last_http_response);throw e}return this.safeOrder({info:s})}async cancelOrders(e,t,i={}){let s=await this.privatePostCancelOrderBatch(this.extend({orders:e},i));return[this.safeOrder({info:s})]}async cancelAllOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privatePostCancelAll(t);return[this.safeOrder({info:i})]}async cancelAllOrdersAfter(e,t={}){if(void 0===e)throw new a.ExchangeError(this.id+" cancelAllOrdersAfter() missing timeout");if(e>864e5)throw new a.BadRequest(this.id+" cancelAllOrdersAfter timeout should be less than 86400000 milliseconds");if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ExchangeError(this.id+" cancelAllOrdersAfter() missing timeout");let i={timeout:e>0?this.parseToInt(e/1e3):0};return await this.privatePostCancelAllOrdersAfter(this.extend(i,t))}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==t&&(a.start=this.parseToInt(t/1e3));let o=this.safeInteger(s,"userref"),n=void 0!==o?this.omit(s,"userref"):s;void 0!==o&&(a.userref=o);let d=this.safeString(n,"clientOrderId");void 0!==d&&(a.cl_ord_id=d,n=this.omit(n,"clientOrderId"));let h=await this.privatePostOpenOrders(this.extend(a,n));void 0!==e&&(r=this.market(e));let c=this.safeDict(h,"result",{}),l=this.safeDict(c,"open",{}),u=[],f=Object.keys(l);for(let e=0;e<f.length;e++){let t=f[e],i=l[t];u.push(this.extend({id:t},i))}return this.parseOrders(u,r,t,i)}async fetchClosedOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==t&&(a.start=this.parseToInt(t/1e3));let o=this.safeInteger(s,"userref"),n=void 0!==o?this.omit(s,"userref"):s;void 0!==o&&(a.userref=o);let d=this.safeString(n,"clientOrderId");void 0!==d&&(a.cl_ord_id=d,n=this.omit(n,"clientOrderId")),[a,n]=this.handleUntilOption("end",a,n);let h=await this.privatePostClosedOrders(this.extend(a,n));void 0!==e&&(r=this.market(e));let c=this.safeDict(h,"result",{}),l=this.safeDict(c,"closed",{}),u=[],f=Object.keys(l);for(let e=0;e<f.length;e++){let t=f[e],i=l[t];u.push(this.extend({id:t},i))}return this.parseOrders(u,r,t,i)}parseTransactionStatus(e){return this.safeString({Initial:"pending",Pending:"pending",Success:"ok",Settled:"pending",Failure:"failed",Partial:"ok"},e,e)}parseNetwork(e){let t=this.safeDict(this.options,"withdrawMethods",{});return this.safeString(t,e,e)}parseTransaction(e,t){let i=this.safeString(e,"refid"),s=this.safeString(e,"txid"),r=this.safeTimestamp(e,"time"),a=this.safeString(e,"asset"),o=this.safeCurrencyCode(a,t),n=this.safeString(e,"info"),d=this.safeNumber(e,"amount"),h=this.parseTransactionStatus(this.safeString(e,"status")),c=this.safeString(e,"status-prop");("on-hold"===c||"cancel-pending"===c||"onhold"===c)&&(h="pending");let l=this.safeString(e,"type"),u=this.safeNumber(e,"fee");return void 0===u&&"deposit"===l&&(u=0),{info:e,id:i,currency:o,amount:d,network:this.parseNetwork(this.safeString(e,"network")),address:n,addressTo:void 0,addressFrom:void 0,tag:void 0,tagTo:void 0,tagFrom:void 0,status:h,type:l,updated:void 0,txid:s,timestamp:r,datetime:this.iso8601(r),comment:void 0,internal:void 0,fee:{currency:o,cost:u}}}parseTransactionsByType(e,t,i,s,r){let a=[];for(let i=0;i<t.length;i++){let s=this.parseTransaction(this.extend({type:e},t[i]));a.push(s)}return this.filterByCurrencySinceLimit(a,i,s,r)}async fetchDeposits(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={};if(void 0!==e&&(r.asset=this.currency(e).id),void 0!==t){let e=this.numberToString(t);r.start=o.Y.stringDiv(e,"1000")}let a=this.safeString2(s,"until","till"),n=void 0!==a?this.omit(s,["until","till"]):s;if(void 0!==a){let e=o.Y.stringDiv(a,"1000");r.end=o.Y.stringAdd(e,"1")}let d=await this.privatePostDepositStatus(this.extend(r,n)),h=this.safeList(d,"result",[]);return this.parseTransactionsByType("deposit",h,e,t,i)}async fetchTime(e={}){let t=await this.publicGetTime(e),i=this.safeDict(t,"result",{});return this.safeTimestamp(i,"unixtime")}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,n]=this.handleOptionBoolAndParams(s,"fetchWithdrawals","paginate",!1);if(a)return n.cursor=!0,await this.fetchPaginatedCallCursor("fetchWithdrawals",e,t,i,n,"next_cursor","cursor");let d={};if(void 0!==e&&(d.asset=this.currency(e).id),void 0!==t){let e=this.numberToString(t);d.start=o.Y.stringDiv(e,"1000")}let h=this.safeString2(n,"until","till"),c=void 0!==h?this.omit(n,["until","till"]):n;if(void 0!==h){let e=o.Y.stringDiv(h,"1000");d.end=o.Y.stringAdd(e,"1")}let l=await this.privatePostWithdrawStatus(this.extend(d,c)),u=this.safeValue(l,"result");return r=Array.isArray(u)?u:this.addPaginationCursorToResult(u),this.parseTransactionsByType("withdrawal",r,e,t,i)}addPaginationCursorToResult(e){let t=this.safeString(e,"next_cursor"),i=this.safeValue(e,"withdrawals"),s=i.length;if(void 0!==t&&s>0){let e=i[s-1];e.next_cursor=t,i[s-1]=e}return i}async createDepositAddress(e,t={}){return await this.fetchDepositAddress(e,this.extend({new:"true"},t))}async fetchDepositMethods(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={asset:this.currency(e).id},s=await this.privatePostDepositMethods(this.extend(i,t));return this.safeValue(s,"result")}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s=this.safeStringUpper(t,"network"),r=this.safeDict(this.options,"networks",{});s=this.safeString(r,s,s);let o=this.omit(t,"network"),n=e;"USDT"===e&&"TRC20"===s&&(n=e+"-"+s);let d=this.safeDict(this.options,"depositMethods",{}),h=this.safeString(d,n),c=this.safeString(o,"method",h);if(void 0===c){let e=await this.fetchDepositMethods(n);if(void 0!==s)for(let t=0;t<e.length;t++){let i=this.safeString(e[t],"method");if(void 0===i)throw new a.ExchangeError(this.id+" fetchDepositAddress() missing entry");if(i.indexOf(s)>=0){c=i;break}}if(void 0===c){let t=this.safeDict(e,0,{});c=this.safeString(t,"method")}}let l={asset:i.id,method:c},u=await this.privatePostDepositAddresses(this.extend(l,o)),f=this.safeList(u,"result",[]),p=this.safeDict(f,0,{});if(void 0===p)throw new a.InvalidAddress(this.id+" privatePostDepositAddresses() returned no addresses for "+n);return this.parseDepositAddress(p,i)}parseDepositAddress(e,t){let i=this.safeString(e,"address"),s=this.safeString(e,"tag"),r=this.safeCurrency(void 0,t).code;return this.checkAddress(i),{info:e,currency:r,network:void 0,address:i,tag:s}}async withdraw(e,t,i,s,r={}){let o=this.handleWithdrawTagAndParams(s,r)[1];if("key"in o){await this.loadMarkets();let s=this.currency(e),r={asset:s.id,amount:t};void 0!==i&&""!==i&&(r.address=i,this.checkAddress(i));let a=await this.privatePostWithdraw(this.extend(r,o)),n=this.safeDict(a,"result",{});return this.parseTransaction(n,s)}throw new a.ExchangeError(this.id+" withdraw() requires a 'key' parameter (withdrawal key name, as set up on your account)")}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privatePostOpenPositions(this.extend({docalcs:"true",consolidation:"market"},t)),s=this.marketSymbols(e),r=this.safeList(i,"result"),a=this.parsePositions(r,s);return this.filterByArrayPositions(a,"symbol",s)}parsePosition(e,t){let i=this.safeString(e,"pair"),s=this.safeString(e,"type"),r="short";return"buy"===s&&(r="long"),this.safePosition({info:e,id:void 0,symbol:this.safeSymbol(i,t),notional:void 0,marginMode:void 0,liquidationPrice:void 0,entryPrice:void 0,unrealizedPnl:this.safeNumber(e,"net"),realizedPnl:void 0,percentage:void 0,contracts:this.safeNumber(e,"vol"),contractSize:void 0,markPrice:void 0,lastPrice:void 0,side:r,hedged:void 0,timestamp:void 0,datetime:void 0,lastUpdateTimestamp:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,collateral:void 0,initialMargin:this.safeNumber(e,"margin"),initialMarginPercentage:void 0,leverage:this.safeNumber(e,"leverage"),marginRatio:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}parseAccountType(e){return this.safeString({spot:"Spot Wallet",swap:"Futures Wallet",future:"Futures Wallet"},e,e)}async transferOut(e,t,i={}){return await this.transfer(e,t,"spot","swap",i)}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let o=this.currency(e),n=this.parseAccountType(i),d=this.parseAccountType(s),h={amount:this.currencyToPrecision(e,t),from:n,to:d,asset:o.id};if("Spot Wallet"!==n)throw new a.BadRequest(this.id+" transfer cannot transfer from "+n+" to "+d+". Use krakenfutures instead to transfer from the futures account.");let c=await this.privatePostWalletTransfer(this.extend(h,r)),l=this.parseTransfer(c,o);return this.extend(l,{amount:t,fromAccount:n,toAccount:d})}parseTransfer(e,t){let i=this.safeDict(e,"result",{});return{info:e,id:this.safeString(i,"refid"),timestamp:void 0,datetime:void 0,currency:this.safeString(t,"code"),amount:void 0,fromAccount:void 0,toAccount:void 0,status:"sucess"}}sign(e,t="public",i="GET",r={},o,n){let d="/"+this.version+"/"+t+"/"+e;if("public"===t)Object.keys(r).length>0&&(d+="?"+this.urlencodeNested(r));else if("private"===t){let o,n=this.safeString(r,"price"),h=!1;void 0!==n&&(h=!!n.endsWith("%")),this.checkRequiredCredentials();let c=this.incrementingNonce().toString(),l="CancelOrderBatch"===e||h||"AddOrderBatch"===e;o=l?this.json(this.extend({nonce:c},r)):this.urlencodeNested(this.extend({nonce:c},r));let u=this.encode(c+o),f=this.hash(u,s.sc,"binary"),p=this.encode(d),m=this.binaryConcat(p,f),g=this.base64ToBinary(this.secret),v=this.hmac(m,g,s.Zf,"base64"),y={"API-Key":this.apiKey,"API-Sign":v};l?y["Content-Type"]="application/json":y["Content-Type"]="application/x-www-form-urlencoded";let b=this.safeString(this.urls.api,t);if(void 0===b)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");return{url:b+d,method:i,body:o,headers:y}}else d="/"+e;let h=this.safeString(this.urls.api,t);if(void 0===h)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");return{url:h+d,method:i,body:n,headers:o}}nonce(){return this.milliseconds()-this.safeInteger(this.options,"timeDifference",0)}handleErrors(e,t,i,s,r,o,n,d,h){if(520===e)throw new a.ExchangeNotAvailable(this.id+" "+e.toString()+" "+t);if(void 0!==n&&"{"===o[0]&&"string"!=typeof n){let e=this.id+" "+o;if("error"in n&&n.error.length>0){for(let t=0;t<n.error.length;t++){let i=n.error[t];this.throwExactlyMatchedException(this.exceptions.exact,i,e),this.throwBroadlyMatchedException(this.exceptions.broad,i,e)}throw new a.ExchangeError(e)}if("result"in n){let t=this.safeDict(n,"result",{});if("orders"in t){let i=this.safeList(t,"orders",[]);for(let t=0;t<i.length;t++){let s=this.safeDict(i,t),r=this.safeString(s,"error");if(void 0!==r)throw this.throwExactlyMatchedException(this.exceptions.exact,r,e),this.throwBroadlyMatchedException(this.exceptions.broad,r,e),new a.ExchangeError(e)}}}}}}i.d(t,{A:()=>n})},5262(e,t,i){"use strict";var s=i(4721),r=i(3217),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"krakenfutures",name:"Kraken Futures",countries:["US"],version:"v3",userAgent:void 0,rateLimit:600,pro:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!0,option:!1,cancelAllOrders:!0,cancelAllOrdersAfter:!0,cancelOrder:!0,cancelOrders:!0,createMarketOrder:!0,createOrder:!0,createOrders:!0,createPostOnlyOrder:!0,createReduceOnlyOrder:!0,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,createTriggerOrder:!0,editOrder:!0,fetchBalance:!0,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchCanceledOrders:!0,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchFundingHistory:!0,fetchFundingRate:"emulated",fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchIndexOHLCV:!0,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLedger:!0,fetchLeverage:!0,fetchLeverages:!0,fetchLeverageTiers:!0,fetchMarketLeverageTiers:"emulated",fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPositions:!0,fetchPositionsHistory:!0,fetchPremiumIndexOHLCV:!1,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchTradingFee:"emulated",fetchTradingFees:!0,sandbox:!0,setLeverage:!0,setMarginMode:!1,transfer:!0},urls:{test:{public:"https://demo-futures.kraken.com/derivatives/api/",private:"https://demo-futures.kraken.com/derivatives/api/",charts:"https://demo-futures.kraken.com/api/charts/",history:"https://demo-futures.kraken.com/api/history/",www:"https://demo-futures.kraken.com"},logo:"https://user-images.githubusercontent.com/24300605/81436764-b22fd580-9172-11ea-9703-742783e6376d.jpg",api:{charts:"https://futures.kraken.com/api/charts/",history:"https://futures.kraken.com/api/history/",feeschedules:"https://futures.kraken.com/api/feeschedules/",public:"https://futures.kraken.com/derivatives/api/",private:"https://futures.kraken.com/derivatives/api/"},www:"https://futures.kraken.com/",doc:["https://docs.kraken.com/api/docs/futures-api/trading/market-data/"],fees:"https://support.kraken.com/hc/en-us/articles/360022835771-Transaction-fees-and-rebates-for-Kraken-Futures",referral:void 0},api:{public:{get:{feeschedules:{cost:1},instruments:{cost:1},"instruments/status":{cost:1},"instruments/{symbol}/status":{cost:1},orderbook:{cost:1},tickers:{cost:1},"tickers/{symbol}":{cost:1},history:{cost:1},historicalfundingrates:{cost:1}}},private:{get:{"feeschedules/volumes":{cost:1},openpositions:{cost:1},notifications:{cost:1},accounts:{cost:1},openorders:{cost:1},recentorders:{cost:1},fills:{cost:1},transfers:{cost:1},leveragepreferences:{cost:1},pnlpreferences:{cost:1},"assignmentprogram/current":{cost:1},"assignmentprogram/history":{cost:1},"orders/status":{cost:1},unwindqueue:{cost:1},"self-trade-strategy":{cost:1},subaccounts:{cost:1},"subaccount/{uid}/trading-enabled":{cost:1},"rfq-assignment/max-leverage":{cost:1}},post:{sendorder:{cost:1},editorder:{cost:1},cancelorder:{cost:1},transfer:{cost:1},"transfer/subaccount":{cost:1},batchorder:{cost:1},cancelallorders:{cost:1},cancelallordersafter:{cost:1},withdrawal:{cost:1},"assignmentprogram/add":{cost:1},"assignmentprogram/delete":{cost:1}},put:{leveragepreferences:{cost:1},pnlpreferences:{cost:1},"self-trade-strategy":{cost:1},"subaccount/{uid}/trading-enabled":{cost:1},"rfq-assignment/max-leverage":{cost:1}},delete:{"rfq-assignment/max-leverage":{cost:1}}},charts:{get:{"{price_type}/{symbol}/{interval}":{cost:1},"analytics/liquidity-pool":{cost:1}}},history:{get:{orders:{cost:1},executions:{cost:1},triggers:{cost:1},accountlogcsv:{cost:1},"account-log":{cost:1},"market/{symbol}/orders":{cost:1},"market/{symbol}/executions":{cost:1},"market/{symbol}/price":{cost:1},positions:{cost:1}}}},fees:{trading:{tierBased:!0,percentage:!0,taker:this.parseNumber("0.0005"),maker:this.parseNumber("0.0002"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.0005")],[this.parseNumber("100000"),this.parseNumber("0.0004")],[this.parseNumber("1000000"),this.parseNumber("0.0003")],[this.parseNumber("5000000"),this.parseNumber("0.00025")],[this.parseNumber("10000000"),this.parseNumber("0.0002")],[this.parseNumber("20000000"),this.parseNumber("0.00015")],[this.parseNumber("50000000"),this.parseNumber("0.000125")],[this.parseNumber("100000000"),this.parseNumber("0.0001")]],maker:[[this.parseNumber("0"),this.parseNumber("0.0002")],[this.parseNumber("100000"),this.parseNumber("0.0015")],[this.parseNumber("1000000"),this.parseNumber("0.000125")],[this.parseNumber("5000000"),this.parseNumber("0.0001")],[this.parseNumber("10000000"),this.parseNumber("0.000075")],[this.parseNumber("20000000"),this.parseNumber("0.00005")],[this.parseNumber("50000000"),this.parseNumber("0.000025")],[this.parseNumber("100000000"),this.parseNumber("0")]]}}},exceptions:{exact:{apiLimitExceeded:a.RateLimitExceeded,marketUnavailable:a.ContractUnavailable,requiredArgumentMissing:a.BadRequest,unavailable:a.ExchangeNotAvailable,authenticationError:a.AuthenticationError,accountInactive:a.ExchangeError,invalidAccount:a.BadRequest,invalidAmount:a.BadRequest,insufficientFunds:a.InsufficientFunds,INSUFFICIENT_MARGIN:a.InsufficientFunds,"Bad Request":a.BadRequest,Unavailable:a.ExchangeNotAvailable,invalidUnit:a.BadRequest,"Json Parse Error":a.ExchangeError,nonceBelowThreshold:a.InvalidNonce,nonceDuplicate:a.InvalidNonce,notFound:a.BadRequest,"Server Error":a.ExchangeError,unknownError:a.ExchangeError,contractNotFound:a.BadSymbol},broad:{invalidArgument:a.BadRequest,nonceBelowThreshold:a.InvalidNonce,nonceDuplicate:a.InvalidNonce}},precisionMode:4,options:{access:{history:{GET:{orders:"private",executions:"private",triggers:"private",accountlogcsv:"private","account-log":"private",positions:"private"}}},settlementCurrencies:{flex:["USDT","BTC","USD","GBP","EUR","USDC"]},symbol:{quoteIds:["USD","XBT"],reversed:!1},versions:{public:{GET:{historicalfundingrates:"v4"}},charts:{GET:{"{price_type}/{symbol}/{interval}":"v1","analytics/liquidity-pool":"v1"}},history:{GET:{orders:"v2",executions:"v2",triggers:"v2",accountlogcsv:"v2"}}},fetchTrades:{method:"historyGetMarketSymbolExecutions"}},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:{last:!0,mark:!0,index:!0},triggerDirection:!1,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:{max:100},fetchMyTrades:{marginMode:!1,limit:void 0,daysBack:void 0,untilDays:1e5,symbolRequired:!1},fetchOrder:void 0,fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:void 0,daysBack:void 0,daysBackCanceled:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:2e3}},spot:void 0,swap:{linear:{extends:"default"},inverse:{extends:"default"}},future:{linear:{extends:"default"},inverse:{extends:"default"}}},timeframes:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","4h":"4h","12h":"12h","1d":"1d","1w":"1w"}})}async fetchMarkets(e={}){let t=await this.publicGetInstruments(e),i=this.safeList(t,"instruments",[]),s=[];for(let e=0;e<i.length;e++){let t,r,a,o,n,d,h=i[e],c=this.safeString(h,"symbol"),l=this.safeString(h,"type"),u=l.indexOf(" index")>=0;if(u)t="index";else{a=!(r=l.indexOf("_vanilla")>=0);let e=this.safeString(h,"lastTradingTime");t=void 0===e?"swap":"future",o=this.parse8601(e)}let f="swap"===t,p="future"===t,m=c,g=c.split("_"),v=this.safeString(g,1),y=v.slice(0,v.length-3),b=this.safeCurrencyCode(y),w=this.safeCurrencyCode("usd");if(void 0===b||void 0===w)continue;let k=this.safeString(h,"contractValueTradePrecision"),S=this.parseNumber(this.integerPrecisionToAmount(k)),O=this.safeNumber(h,"tickSize"),T=f||p||u;(f||p)&&("futures_inverse"===this.safeString(h,"type")?(n=b,d=y,a=!0):(n=w,d="usd",a=!1),r=!a,m=b+"/"+w+":"+n,p&&(m=m+"-"+this.yymmdd(o))),s.push({id:c,symbol:m,base:b,quote:w,settle:n,baseId:y,quoteId:"usd",settleId:d,type:t,spot:!1,margin:!1,swap:f,future:p,option:!1,index:u,active:this.safeBool(h,"tradeable"),contract:T,linear:r,inverse:a,contractSize:this.safeNumber(h,"contractSize"),taker:this.safeNumber(this.fees.trading,"taker"),maker:this.safeNumber(this.fees.trading,"maker"),maintenanceMarginRate:void 0,expiry:o,expiryDatetime:this.iso8601(o),strike:void 0,optionType:void 0,precision:{amount:S,price:O},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:this.parse8601(this.safeString(h,"openingDate")),info:h})}let r=this.options.settlementCurrencies.flex,a=[];for(let e=0;e<r.length;e++){let t=r[e];a.push({id:t.toLowerCase(),numericId:void 0,code:t,precision:void 0})}return this.currencies=this.mapToSafeMap(this.deepExtend(a,this.currencies)),s}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={symbol:this.market(e).id},r=await this.publicGetOrderbook(this.extend(s,i)),a=this.parse8601(this.safeString(r,"serverTime")),o=this.safeDict(r,"orderBook",{});return this.parseOrderBook(o,e,a)}async fetchTicker(e,t={}){await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.publicGetTickersSymbol(this.extend(s,t)),a=this.safeDict(r,"ticker",{});return this.parseTicker(a,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetTickers(t),s=this.safeList(i,"tickers");return this.parseTickers(s,e)}parseTicker(e,t){let i,s,r=this.safeString(e,"symbol"),a=this.safeMarket(r,t),n=a.symbol,d=this.parse8601(this.safeString(e,"lastTime")),h=this.safeString(e,"open24h"),c=this.safeString(e,"last"),l=o.Y.stringSub(c,h),u=o.Y.stringMul(o.Y.stringDiv(l,h),"100"),f=o.Y.stringDiv(o.Y.stringAdd(h,c),"2"),p=this.safeString(e,"vol24h");return!0!==this.safeBool(a,"index",!1)&&(!0===a.linear?i=p:!0===a.inverse&&(s=p)),this.safeTicker({symbol:n,timestamp:d,datetime:this.iso8601(d),high:void 0,low:void 0,bid:this.safeString(e,"bid"),bidVolume:this.safeString(e,"bidSize"),ask:this.safeString(e,"ask"),askVolume:this.safeString(e,"askSize"),vwap:void 0,open:h,close:c,last:c,previousClose:void 0,change:l,percentage:u,average:f,baseVolume:i,quoteVolume:s,markPrice:this.safeString(e,"markPrice"),indexPrice:this.safeString(e,"indexPrice"),info:e})}async fetchTradingFees(e={}){await this.loadMarkets();let t=await this.publicGetFeeschedules(e),i={};if(this.checkRequiredCredentials(!1)){let e=await this.privateGetFeeschedulesVolumes();i=this.safeDict(e,"volumesByFeeSchedule",{})}let s=this.safeList(t,"feeSchedules",[]),r={};for(let e=0;e<s.length;e++){let t=s[e],i=this.safeString(t,"uid");void 0!==i&&(r[i]=t)}let a={},o=this.symbols;for(let e=0;e<o.length;e++){let t=o[e],s=this.market(t),n=this.safeString(s.info,"feeScheduleUid"),d=this.safeDict(r,n);if(void 0===d)continue;let h=this.safeString(i,n,"0");a[t]=this.parseTradingFee(d,s,h)}return a}parseTradingFee(e,t,i){let s,r,a=this.safeList(e,"tiers",[]);for(let e=0;e<a.length;e++){let t=this.safeDict(a,e),n=this.safeString(t,"usdVolume");if((void 0===i||o.Y.stringGe(i,n))&&(s=this.safeString(t,"makerFee"),r=this.safeString(t,"takerFee"),void 0===i))break}return{info:e,symbol:this.safeSymbol(void 0,t),maker:this.parseNumber(o.Y.stringDiv(s,"100")),taker:this.parseNumber(o.Y.stringDiv(r,"100")),percentage:!0,tierBased:!0}}async fetchOHLCV(e,t="1m",i,s,r={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),[d,h]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(d)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,h,2e3);let c=this.safeString(h,"price","trade");if("index"===c)c="spot";else if("trade"!==c&&"mark"!==c&&"spot"!==c)throw new a.NotSupported(this.id+' fetchOHLCV() price parameter must be one of "trade", "mark", "index" or "spot"');let l={symbol:n.id,price_type:c,interval:this.safeString(this.timeframes,t,t)},u=this.omit(h,"price"),f=void 0===s?2e3:Math.min(s,2e3);if((void 0!==i||void 0!==s)&&(o=f),void 0!==i){let e=this.parseTimeframe(t);l.from=this.parseToInt(i/1e3);let s=this.sum(l.from,f*e-1);l.to=Math.min(s,this.seconds())}else if(void 0!==o){let e=this.parseTimeframe(t);l.to=this.seconds(),l.from=this.parseToInt(l.to-e*o)}let p=await this.chartsGetPriceTypeSymbolInterval(this.extend(l,u)),m=this.safeList(p,"candles");return this.parseOHLCVs(m,n,t,i,o)}parseOHLCV(e,t){return[this.safeInteger(e,"time"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchTrades","paginate",!1);if(r)return await this.fetchPaginatedCallDynamic("fetchTrades",e,t,i,a);let o=this.market(e),n={symbol:o.id},[d,h]=this.handleOptionStringAndParams(a,"fetchTrades","method","historyGetMarketSymbolExecutions"),c=[];if("historyGetMarketSymbolExecutions"===d){let[e,s]=this.handleUntilOption("before",n,h);void 0!==t&&(e.since=t,e.sort="asc"),void 0!==i&&(e.count=i);let r=await this.historyGetMarketSymbolExecutions(this.extend(e,s)),a=this.safeList(r,"elements",[]);c=[];let o=a.length;for(let e=0;e<o;e++){let t=o-1-e,i=this.safeDict(a,t),s=this.safeDict(i,"event",{}),r=this.safeDict(s,"Execution",{}),n=this.safeDict(r,"execution",{});c.push(n)}}else{let[e,t]=this.handleUntilOption("lastTime",n,h),i=await this.publicGetHistory(this.extend(e,t));c=this.safeList(i,"history",[])}return this.parseTrades(c,o,t,i)}parseTrade(e,t){let i,s,r,a,n=this.parse8601(this.safeString2(e,"time","fillTime")),d=this.safeString(e,"price"),h=this.safeStringN(e,["size","amount","quantity"],"0.0"),c=this.safeString2(e,"uid","fill_id");void 0===c&&(c=this.safeString(e,"executionId"));let l=this.safeString(e,"order_id"),u=this.safeString(e,"symbol"),f=this.safeString(e,"side"),p=this.safeDict(e,"orderPriorEdit"),m=this.safeDict(e,"orderPriorExecution");void 0!==m?(l=this.safeString(m,"orderId"),u=this.safeString(m,"symbol"),f=this.safeString(m,"side"),i=this.safeString(m,"type")):void 0!==p&&(l=this.safeString(p,"orderId"),u=this.safeString(p,"symbol"),f=this.safeString(p,"type"),i=this.safeString(p,"type")),void 0!==i&&(i=this.parseOrderType(i));let g=this.safeMarket(u,t),v=this.safeBool(g,"linear");if(void 0!==h&&void 0!==d&&void 0!==g){s=!0===v?o.Y.stringMul(h,d):o.Y.stringDiv(h,d);let e=this.safeString(g,"contractSize");s=o.Y.stringMul(s,e)}let y=this.safeString(e,"fillType");if(void 0!==y&&(y.indexOf("taker")>=0?r="taker":y.indexOf("maker")>=0&&(r="maker")),"takerOrder"in e){n=this.safeInteger(e,"timestamp");let t=this.safeDict(e,"takerOrder",{});void 0!==t&&(f=this.safeStringLower(t,"direction"),r="taker")}if(void 0!==r&&void 0!==s){let e=this.safeString(g,r),t=this.safeString(g,"settle");void 0===t&&(t=this.safeString(g,"quote")),a={cost:o.Y.stringMul(s,e),currency:t,rate:e}}return this.safeTrade({info:e,id:c,symbol:this.safeString(g,"symbol"),timestamp:n,datetime:this.iso8601(n),order:l,type:i,side:f,takerOrMaker:r,price:d,amount:!0===v?h:void 0,cost:s,fee:a})}createOrderRequest(e,t,i,s,r,o={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let n=this.market(e),d=n.symbol,h=this.safeString(o,"orderType",t),c=this.safeString(o,"timeInForce"),[l,u]=this.handlePostOnly("market"===h,"post"===h,o);l?h="post":"ioc"===c?h="ioc":"limit"===h?h="lmt":"market"===h&&(h="mkt");let f={symbol:n.id,side:i,size:this.amountToPrecision(d,s)},p=this.safeString2(u,"clientOrderId","cliOrdId");void 0!==p&&(f.cliOrdId=p);let m=this.safeString2(u,"triggerPrice","stopPrice"),g=void 0!==m,v=this.safeString(u,"stopLossPrice"),y=this.safeString(u,"takeProfitPrice"),b=void 0!==v,w=void 0!==y,k=b||w,S=this.safeString(u,"triggerSignal","last"),O=this.safeBool(u,"reduceOnly");(k||g)&&(f.triggerSignal=S),g?(h="stp",f.stopPrice=this.priceToPrecision(d,m)):k&&(O=!0,b?(h="stp",f.stopPrice=this.priceToPrecision(d,v)):w&&(h="take_profit",f.stopPrice=this.priceToPrecision(d,y))),!0===O&&(f.reduceOnly=!0),f.orderType=h;let T=this.parseNumber(r),P="lmt"===h||"post"===h||"ioc"===h,I=this.safeString(u,"limitPrice");if(P&&void 0===T&&void 0===I)throw new a.ArgumentsRequired(this.id+" createOrder () requires a price argument for "+h+" orders");let A="mkt"===h;void 0===T||A||(f.limitPrice=this.priceToPrecision(d,T));let x=this.omit(u,["clientOrderId","timeInForce","triggerPrice","stopLossPrice","takeProfitPrice"]);return this.extend(f,x)}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=this.createOrderRequest(e,t,i,s,r,a),d=await this.privatePostSendorder(n),h=this.safeValue(d,"sendStatus"),c=this.safeString(h,"status");return this.verifyOrderActionSuccess(c,"createOrder",["filled"]),this.parseOrder(h,o)}async createOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=[];for(let s=0;s<e.length;s++){let r=this.safeDict(e,s),a=this.safeString(r,"symbol"),o=this.safeString(r,"type"),n=this.safeString(r,"side"),d=this.safeValue(r,"amount"),h=this.safeValue(r,"price"),c=this.safeDict(r,"params",{}),l=this.extend(c,t);"order_tag"in l||(l.order_tag=this.sum(s,1).toString()),l.order="send";let u=this.createOrderRequest(a,o,n,d,h,l);i.push(u)}let s=await this.privatePostBatchorder(this.extend({batchOrder:i},t)),r=this.safeList(s,"batchStatus",[]);return this.parseOrders(r)}async editOrder(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets();let n={orderId:e};void 0!==r&&(n.size=r),void 0!==a&&(n.limitPrice=a);let d=await this.privatePostEditorder(this.extend(n,o)),h=this.safeDict(d,"editStatus",{}),c=this.safeString(h,"status");this.verifyOrderActionSuccess(c,"editOrder",["filled"]);let l=this.parseOrder(h);return l.info=d,l}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privatePostCancelorder(this.extend({order_id:e},i)),r=this.safeString(this.safeDict(s,"cancelStatus",{}),"status");this.verifyOrderActionSuccess(r,"cancelOrder");let a={};return"cancelStatus"in s&&(a=this.parseOrder(s.cancelStatus)),this.extend({info:s},a)}async cancelOrders(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=[],r=this.safeList(i,"clientOrderIds",[]);if(r.length>0)for(let e=0;e<r.length;e++)s.push({order:"cancel",cliOrdId:r[e]});else for(let t=0;t<e.length;t++)s.push({order:"cancel",order_id:e[t]});let a=await this.privatePostBatchorder(this.extend({batchOrder:s},i)),o=this.safeList(a,"batchStatus",[]);return this.parseOrders(o)}async cancelAllOrders(e,t={}){let i={};void 0!==e&&(i.symbol=this.marketId(e));let s=await this.privatePostCancelallorders(this.extend(i,t)),r=this.safeDict(s,"cancelStatus"),a=this.safeList(r,"orderEvents",[]),o=[];for(let e=0;e<a.length;e++){let e=this.safeDict(a,0),t=this.safeDict(e,"order",{});o.push(t)}return this.parseOrders(o)}async cancelAllOrdersAfter(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={timeout:e>0?this.parseToInt(e/1e3):0};return await this.privatePostCancelallordersafter(this.extend(i,t))}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a=await this.privateGetOpenorders(s),o=this.safeList(a,"openOrders",[]);return this.parseOrders(o,r,t,i)}async fetchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a=await this.privateGetOrdersStatus(s),o=this.safeList(a,"orders",[]);return this.parseOrders(o,r,t,i)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.fetchOrders(void 0,void 0,void 0,this.extend({orderIds:[e]},i)),r=this.safeDict(s,0);if(void 0===r)throw new a.OrderNotFound(this.id+" fetchOrder could not find order id "+e);return r}async fetchClosedOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(a=this.market(e));let o={};void 0!==i&&(o.count=i),void 0!==t&&(o.since=t);let n=this.safeBool2(s,"trigger","stop",!1),d=this.omit(s,["trigger","stop"]);r=!0===n?await this.historyGetTriggers(this.extend(o,d)):await this.historyGetOrders(this.extend(o,s));let h=this.safeList(r,"elements",[]),c=[];for(let e=0;e<h.length;e++){let t=this.safeDict(h,e),i=this.safeDict(t,"event",{}),s=this.safeDict2(i,"OrderPlaced","OrderTriggerActivated"),r=this.safeDict(i,"OrderUpdated");if(void 0!==s){let e=this.safeDict(s,"order",{});"0"!==this.safeString(e,"filled")&&(e.status="closed",c.push(e))}else if(void 0!==r&&"full_fill"===this.safeString(r,"reason")){let e=this.safeDict(r,"newOrder",{});e.status="closed",c.push(e)}}return this.parseOrders(c,a,t,i)}async fetchCanceledOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(a=this.market(e));let o={};void 0!==i&&(o.count=i),void 0!==t&&(o.from=t);let n=this.safeBool2(s,"trigger","stop",!1),d=this.omit(s,["trigger","stop"]);r=!0===n?await this.historyGetTriggers(this.extend(o,d)):await this.historyGetOrders(this.extend(o,s));let h=this.safeList(r,"elements",[]),c=[];for(let e=0;e<h.length;e++){let t=this.safeDict(h,e),i=this.safeDict(t,"event",{}),s="OrderTriggerCancelled"in i,r=this.safeDict2(i,"OrderPlaced","OrderTriggerCancelled");if(void 0!==r){let e=this.safeDict(r,"order",{});("0"===this.safeString(e,"filled")||s)&&(e.status="canceled",c.push(e))}let a=this.safeDict(i,"OrderCancelled");if(void 0!==a){let e=this.safeDict(a,"order",{});e.status="canceled",c.push(e)}let o=this.safeDict(i,"OrderRejected");if(void 0!==o){let e=this.safeDict(o,"order",{});e.status="rejected",c.push(e)}}return this.parseOrders(c,a,t,i)}parseOrderType(e){return this.safeString({lmt:"limit",mkt:"market",post:"limit",ioc:"market"},e,e)}verifyOrderActionSuccess(e,t,i=[]){let s={invalidOrderType:a.InvalidOrder,invalidSide:a.InvalidOrder,invalidSize:a.InvalidOrder,invalidPrice:a.InvalidOrder,insufficientAvailableFunds:a.InsufficientFunds,selfFill:a.ExchangeError,tooManySmallOrders:a.ExchangeError,maxPositionViolation:a.BadRequest,marketSuspended:a.ExchangeNotAvailable,marketInactive:a.ExchangeNotAvailable,clientOrderIdAlreadyExist:a.DuplicateOrderId,clientOrderIdTooLong:a.BadRequest,outsidePriceCollar:a.InvalidOrder,postWouldExecute:a.OrderImmediatelyFillable,iocWouldNotExecute:a.OrderNotFillable,wouldNotReducePosition:a.ExchangeError,orderForEditNotFound:a.OrderNotFound,orderForEditNotAStop:a.InvalidOrder,filled:a.OrderNotFound,notFound:a.OrderNotFound};if(e in s&&!this.inArray(e,i))throw new s[e](this.id+": "+t+" failed due to "+e)}parseOrderStatus(e){return this.safeString({placed:"open",cancelled:"canceled",invalidOrderType:"rejected",invalidSide:"rejected",invalidSize:"rejected",invalidPrice:"rejected",insufficientAvailableFunds:"rejected",selfFill:"rejected",tooManySmallOrders:"rejected",maxPositionViolation:"rejected",marketSuspended:"rejected",marketInactive:"rejected",clientOrderIdAlreadyExist:"rejected",clientOrderIdTooLong:"rejected",outsidePriceCollar:"rejected",postWouldExecute:"rejected",iocWouldNotExecute:"rejected",wouldNotReducePosition:"rejected",edited:"open",orderForEditNotFound:"rejected",orderForEditNotAStop:"rejected",filled:"closed",notFound:"rejected",untouched:"open",partiallyFilled:"open",ENTERED_BOOK:"open",FULLY_EXECUTED:"closed",CANCELLED:"canceled",TRIGGER_PLACED:"open",PARTIALLY_FILLED:"open",UNTOUCHED:"open"},e,e)}parseOrder(e,t){let i,s,r,a,n,d=this.safeDict(e,"order");if(void 0!==d){let i=this.safeString(d,"timestamp"),s=this.safeString(e,"status"),r=this.safeDict(d,"priceTriggerOptions",{}),a=this.safeString(r,"triggerPrice"),o=this.safeSymbol(this.safeString(d,"symbol"),t);return this.safeOrder({info:e,id:this.safeString(d,"orderId"),clientOrderId:this.safeString(d,"cliOrdId"),timestamp:this.parse8601(i),datetime:i,lastTradeTimestamp:void 0,lastUpdateTimestamp:this.parse8601(this.safeString(d,"lastUpdateTimestamp")),symbol:o,type:void 0,timeInForce:void 0,postOnly:void 0,reduceOnly:this.safeBool(d,"reduceOnly"),side:this.safeString(d,"side"),price:void 0,triggerPrice:a,stopPrice:a,amount:this.safeString(d,"quantity"),cost:void 0,average:void 0,filled:this.safeString(d,"filled"),remaining:void 0,status:this.parseOrderStatus(s),fee:void 0,fees:void 0,trades:void 0})}let h=this.safeList(e,"orderEvents",[]),c=this.safeString(e,"status"),l=h.length;if("orderEvents"in e&&void 0!==c&&0===l)return this.safeOrder({info:e,status:"rejected"});let u=!1,f=!1,p=[];if(l>0){let t=[];for(let e=0;e<h.length;e++){let s=h[e];"EXECUTION"===this.safeString(s,"type")&&t.push(s);let a=this.safeValue(s,"orderTrigger");if(void 0===i){if(void 0!==(i=this.safeValue2(s,"new","order",a)))u=!1,f=!0;else if(!f){let e=this.safeString(s,"price"),t=this.safeDict(s,"orderPriorExecution");i=this.safeValue2(s,"orderPriorExecution","orderPriorEdit"),r=void 0===e?this.safeString(t,"limitPrice"):e,void 0!==i&&(u=!0)}}}p=this.parseTrades(t),s=this.safeString(e,"status")}void 0===i&&(i=e),void 0===s&&(s=this.safeString(i,"status"));let m=this.parseOrderStatus(s),g=this.inArray(m,["canceled","rejected","closed"]),v=this.safeString2(i,"symbol","tradeable"),y=this.safeMarket(v,t),b=this.safeString(y,"symbol"),w=this.parse8601(this.safeString2(i,"timestamp","receivedTime")),k=this.parse8601(this.safeString(i,"lastUpdateTime")),S=this.safeString(i,"quantity"),O=this.safeString2(i,"filledSize","filled","0.0"),T=this.safeString(i,"unfilledSize"),P="0.0";if(p.length>0){let e="0.0";for(let t=0;t<p.length;t++){let i=this.safeDict(p,t),s=this.safeString(i,"amount"),r=this.safeString(i,"price");P=o.Y.stringAdd(P,s),e=o.Y.stringAdd(e,o.Y.stringMul(s,r))}a=o.Y.stringDiv(e,P),void 0!==S&&!g&&u&&o.Y.stringGe(P,S)&&(m="closed",g=!0),O=u?o.Y.stringAdd(O,P):o.Y.stringMax(O,P)}if(void 0===T&&(u?void 0!==S&&(T=o.Y.stringSub(S,P)):T=S),void 0!==S||u||void 0===T||(S=o.Y.stringAdd(O,T)),void 0!==O&&void 0!==y){let e=r;void 0!==a&&(e=a),void 0!==e&&(n=!0===y.linear?o.Y.stringMul(O,e):o.Y.stringDiv(O,e))}let I=this.safeString2(e,"order_id","orderId");void 0===I&&(I=this.safeString2(i,"orderId","uid"));let A=this.safeStringLower2(i,"type","orderType"),x="gtc";("ioc"===A||"market"===this.parseOrderType(A))&&(x="ioc");let M=this.safeInteger(i,"timestamp",w),_=this.safeDict(i,"priceTriggerOptions",{}),C=this.safeString2(i,"triggerPrice","stopPrice");return void 0===C&&(C=this.safeString(_,"triggerPrice")),this.safeOrder({info:e,id:I,clientOrderId:this.safeStringN(i,["clientOrderId","clientId","cliOrdId"]),timestamp:M,datetime:this.iso8601(M),lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeInteger(i,"lastUpdateTimestamp",k),symbol:b,type:this.parseOrderType(A),timeInForce:x,postOnly:"post"===A,reduceOnly:this.safeBool2(i,"reduceOnly","reduce_only"),side:this.safeStringLower2(i,"side","direction"),price:r,triggerPrice:C,stopPrice:C,amount:S,cost:n,average:a,filled:O,remaining:T,status:m,fee:void 0,fees:void 0,trades:p})}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a=await this.privateGetFills(s),o=this.safeList(a,"fills",[]);return this.parseTrades(o,r,t,i)}async fetchLedger(e,t,i,s={}){let r;await this.loadMarkets(),void 0!==e&&(r=this.currency(e));let a={};void 0!==t&&(a.since=t,a.sort="asc"),void 0!==i&&(a.count=2*i);let o=this.safeInteger(s,"until");void 0!==o&&(a.before=o);let n=void 0!==o?this.omit(s,"until"):s,d=await this.historyGetAccountLog(this.extend(a,n)),h=this.safeList(d,"logs",[]),c=[];for(let e=0;e<h.length;e++){let t=h[e],i=this.safeString(t,"asset"),s=this.safeString(t,"contract");void 0!==i&&i!==s&&c.push(t)}return this.parseLedger(c,r,t,i)}async fetchFundingHistory(e,t,i,s={}){let r;await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a={info:"funding rate change"};void 0!==t&&(a.since=t,a.sort="asc"),void 0!==i&&void 0===e&&(a.count=i);let o=this.safeInteger(s,"until");void 0!==o&&(a.before=o);let n=void 0!==o?this.omit(s,"until"):s,d=await this.historyGetAccountLog(this.extend(a,n)),h=this.safeList(d,"logs",[]);return this.parseIncomes(h,r,t,i)}parseIncome(e,t){let i=this.safeStringUpper(e,"contract"),s=this.safeString(e,"asset"),r=this.parse8601(this.safeString(e,"date"));return{info:e,symbol:this.safeSymbol(i),code:this.safeCurrencyCode(s),timestamp:r,datetime:this.iso8601(r),id:this.safeString(e,"id"),amount:this.safeNumber(e,"realized_funding")}}parseLedgerEntryType(e){return this.safeString({"futures trade":"trade","futures liquidation":"trade","futures assignee":"trade","futures assignor":"trade","futures unwind counterparty":"trade","futures unwind bankrupt":"trade","covered liquidation":"trade",settlement:"trade",conversion:"trade","funding rate change":"fee","interest payment":"fee","kfee applied":"fee","tax withheld":"fee","tax refund":"rebate",transfer:"transfer","subaccount transfer":"transfer","cross-exchange transfer":"transfer","admin transfer":"transfer"},e,e)}parseLedgerEntry(e,t){let i,s,r=this.parse8601(this.safeString(e,"date")),a=this.safeString(e,"asset"),n=this.safeCurrencyCode(a,t),d=this.safeCurrency(a,t),h=this.safeString(e,"old_balance"),c=this.safeString(e,"new_balance"),l=this.safeString(e,"fee");return void 0!==h&&void 0!==c&&(i=o.Y.stringSub(c,h),void 0!==l&&(i=o.Y.stringAdd(i,l)),o.Y.stringLt(i,"0")?(s="out",i=o.Y.stringAbs(i)):s="in"),this.safeLedgerEntry({info:e,id:this.safeString(e,"id"),direction:s,account:this.safeString(e,"margin_account"),referenceId:this.safeString2(e,"execution","booking_uid"),referenceAccount:void 0,type:this.parseLedgerEntryType(this.safeString(e,"info")),currency:n,amount:this.parseNumber(i),before:this.parseNumber(h),after:this.parseNumber(c),status:"ok",timestamp:r,datetime:this.iso8601(r),fee:{cost:this.parseNumber(l),currency:n}},d)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=this.safeString2(e,"type","account"),i=this.safeString(e,"symbol"),s=this.omit(e,["type","account","symbol"]),r=await this.privateGetAccounts(s),o=this.safeString(r,"serverTime");if("marginAccount"===t||"margin"===t){if(void 0===i)throw new a.ArgumentsRequired(this.id+" fetchBalance requires symbol argument for margin accounts");t=i}void 0===t&&(t=void 0===i?"flex":i);let n=this.parseAccount(t),d=this.safeDict(r,"accounts"),h=this.safeDict(d,n);if(void 0===h)throw void 0===t&&(t=""),void 0===i&&(i=""),new a.BadRequest(this.id+" fetchBalance has no account for "+t);let c=this.parseBalance(h);return c.info=r,c.timestamp=this.parse8601(o),c.datetime=o,c}parseBalance(e){let t=this.safeString2(e,"accountType","type"),i="multiCollateralMarginAccount"===t,s="cashAccount"===t,r=this.safeDict2(e,"balances","currencies",{}),a={},o=Object.keys(r);for(let t=0;t<o.length;t++){let n=o[t],d=r[n],h=this.safeCurrencyCode(n);if(void 0===h||h.split("_").length>1)continue;let c=this.account();if(i)c.total=this.safeString(d,"quantity"),c.free=this.safeString(d,"available");else if(s)c.used="0.0",c.total=d;else{let t=this.safeDict(e,"auxiliary");c.free=this.safeString(t,"af"),c.total=this.safeString(t,"pv")}void 0!==h&&(a[h]=c)}return this.safeBalance(a)}async fetchFundingRates(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketIds(e),s=await this.publicGetTickers(t),r=this.safeList(s,"tickers",[]),a=[];for(let e=0;e<r.length;e++){let t=this.safeDict(r,e),s=this.safeString(t,"symbol");if(void 0!==i&&!this.inArray(s,i))continue;let o=this.safeMarket(s),n=this.parseFundingRate(t,o);a.push(n)}return this.indexBy(a,"symbol")}parseFundingRate(e,t){let i=this.safeString(e,"symbol"),s=this.symbol(i),r=this.parse8601(this.safeString(e,"lastTime")),a=this.safeString(e,"markPrice"),n=this.safeString(e,"fundingRate"),d=o.Y.stringDiv(n,a),h=this.safeString(e,"fundingRatePrediction"),c=o.Y.stringDiv(h,a);return o.Y.stringGt(d,"0.25")?d="0.25":o.Y.stringLt(d,"-0.25")&&(d="-0.25"),o.Y.stringGt(c,"0.25")?c="0.25":o.Y.stringLt(c,"-0.25")&&(c="-0.25"),{info:e,symbol:s,markPrice:this.parseNumber(a),indexPrice:this.safeNumber(e,"indexPrice"),interestRate:void 0,estimatedSettlePrice:void 0,timestamp:r,datetime:this.iso8601(r),fundingRate:this.parseNumber(d),fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:this.parseNumber(c),nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:"1h"}}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e);if(!0!==r.swap)throw new a.BadRequest(this.id+" fetchFundingRateHistory() supports swap contracts only");let o={symbol:this.safeStringUpper(r,"id")},n=await this.publicGetHistoricalfundingrates(this.extend(o,s)),d=this.safeValue(n,"rates"),h=[];for(let t=0;t<d.length;t++){let i=this.safeDict(d,t),s=this.safeString(i,"timestamp");h.push({info:i,symbol:e,fundingRate:this.safeNumber(i,"relativeFundingRate"),timestamp:this.parse8601(s),datetime:s})}let c=this.sortBy(h,"timestamp");return this.filterBySymbolSinceLimit(c,e,t,i)}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privateGetOpenpositions({}),s=this.safeList(i,"openPositions");if(void 0===s)throw new a.ExchangeNotAvailable(this.id+' fetchPositions() returned a response without an "openPositions" list');return this.parsePositions(s,e)}async fetchPositionsHistory(e,t,i,s={}){let r;await this.loadMarkets(),void 0!==e&&1===e.length&&(r=this.market(e[0]));let a={closed:!0};void 0!==r&&(a.tradeable=r.id),void 0!==t&&(a.since=t,a.sort="asc"),void 0!==i&&(a.count=i);let o=this.safeInteger(s,"until");void 0!==o&&(a.before=o);let n=void 0!==o?this.omit(s,"until"):s,d=await this.historyGetPositions(this.extend(a,n)),h=this.safeList(d,"elements",[]),c=[];for(let e=0;e<h.length;e++){let t=this.safeDict(h[e],"event",{}),i=this.safeDict(t,"PositionUpdate");void 0!==i&&c.push(i)}let l=this.parsePositions(c,e);return this.filterBySinceLimit(l,t,i)}parsePosition(e,t){let i,s,r=this.safeString(e,"positionChange"),a=void 0!==r,n=this.safeNumber(e,"maxFixedLeverage"),d="cross";void 0!==n&&(d="isolated"),a?(i=this.safeInteger(e,"timestamp"),s=this.iso8601(i)):(s=this.safeString(e,"fillTime"),i=this.parse8601(s));let h=this.safeString(e,"side"),c=this.safeString(e,"price"),l=this.safeString(e,"size");if(a){let t=this.safeString(e,"oldPosition");c=this.safeString(e,"oldAverageEntryPrice"),l=this.safeString(e,"executionSize"),"open"===r||"increase"===r?(t=this.safeString(e,"newPosition"),c=this.safeString(e,"newAverageEntryPrice"),l=o.Y.stringAbs(t)):"reverse"===r&&(l=o.Y.stringAbs(t)),o.Y.stringGt(t,"0")?h="long":o.Y.stringLt(t,"0")&&(h="short")}let u=this.safeString2(e,"symbol","tradeable"),f=this.safeMarket(u,t);return{info:e,id:this.safeString(e,"executionUid"),symbol:f.symbol,timestamp:i,datetime:s,initialMargin:void 0,initialMarginPercentage:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,entryPrice:this.parseNumber(c),notional:void 0,leverage:n,unrealizedPnl:this.safeNumber(e,"unrealizedPnl"),realizedPnl:this.safeNumber(e,"realizedPnL"),contracts:this.parseNumber(l),contractSize:this.safeNumber(f,"contractSize"),marginRatio:void 0,liquidationPrice:void 0,markPrice:void 0,lastPrice:this.safeNumber(e,"executionPrice"),collateral:void 0,marginMode:d,side:h,percentage:void 0}}async fetchLeverageTiers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetInstruments(t),s=this.safeList(i,"instruments");return this.parseLeverageTiers(s,e,"symbol")}parseMarketLeverageTiers(e,t){let i=this.safeList(e,"marginLevels"),s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=[];if(void 0===i)return a;for(let e=0;e<i.length;e++){let t=i[e],n=this.safeString(t,"initialMargin"),d=this.safeNumber2(t,"numNonContractUnits","contracts");if(0!==e){let e=a.length;a[e-1].maxNotional=d}a.push({tier:this.sum(e,1),symbol:this.safeSymbol(s,r),currency:r.quote,minNotional:d,maxNotional:void 0,maintenanceMarginRate:this.safeNumber(t,"maintenanceMargin"),maxLeverage:this.parseNumber(o.Y.stringDiv("1",n)),info:t})}return a}parseTransfer(e,t){let i=this.safeString(e,"serverTime");return{info:e,id:void 0,timestamp:this.parse8601(i),datetime:i,currency:this.safeString(t,"code"),amount:void 0,fromAccount:void 0,toAccount:void 0,status:this.safeString(e,"result")}}parseAccount(e){let t={main:"cash",funding:"cash",future:"cash",futures:"cash",cashAccount:"cash",multiCollateralMarginAccount:"flex",multiCollateral:"flex",multiCollateralMargin:"flex"};if(e in t)return t[e];if(void 0===this.markets||!(e in this.markets))return e;{let t=this.market(e),i=t.id.split("_");return!0===t.inverse?"fi_"+this.safeString(i,1):"fv_"+this.safeString(i,1)}}async transferOut(e,t,i={}){return await this.transfer(e,t,"future","spot",i)}async transfer(e,t,i,s,r={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.currency(e);if("spot"===i)throw new a.BadRequest(this.id+" transfer does not yet support transfers from spot");let d={amount:t};if("spot"===s){if("cash"!==this.parseAccount(i))throw new a.BadRequest(this.id+" transfer cannot transfer from "+i+" to "+s);d.currency=n.id,o=await this.privatePostWithdrawal(this.extend(d,r))}else d.fromAccount=this.parseAccount(i),d.toAccount=this.parseAccount(s),d.unit=n.id,o=await this.privatePostTransfer(this.extend(d,r));let h=this.parseTransfer(o,n);return this.extend(h,{amount:t,fromAccount:i,toAccount:s})}async setLeverage(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.marketId(t);if(void 0===s)throw new a.ArgumentsRequired(this.id+" marketId is required");let r={maxLeverage:e,symbol:s.toUpperCase()};return await this.privatePutLeveragepreferences(this.extend(r,i))}async fetchLeverages(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privateGetLeveragepreferences(t),s=this.safeList(i,"leveragePreferences",[]);return this.parseLeverages(s,e,"symbol")}async fetchLeverage(e,t={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchLeverage() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.marketId(e);if(void 0===s)throw new a.ArgumentsRequired(this.id+" marketId is required");let r={symbol:s.toUpperCase()},o=await this.privateGetLeveragepreferences(this.extend(r,t)),n=this.safeList(o,"leveragePreferences",[]),d=this.safeDict(n,0,{});return this.parseLeverage(d,i)}parseLeverage(e,t){let i=this.safeString(e,"symbol"),s=this.safeInteger(e,"maxLeverage");return{info:e,symbol:this.safeSymbol(i,t),marginMode:void 0,longLeverage:s,shortLeverage:s}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;if(429===e)throw new a.DDoSProtection(this.id+" "+o);let c=this.safeList(n,"errors"),l=this.safeDict(c,0),u=this.safeString(l,"message"),f=this.safeString(n,"error",u);if(void 0===f)return;let p=this.id+" "+o;if(this.throwExactlyMatchedException(this.exceptions.exact,f,p),this.throwBroadlyMatchedException(this.exceptions.broad,f,p),400===e)throw new a.BadRequest(p);throw new a.ExchangeError(p)}sign(e,t="public",i="GET",r={},o,n){let d,h=this.safeDict(this.options.versions,t,{}),c=this.safeDict(h,i,{}),l=this.safeString(c,e,this.version),u=this.safeString(r,"version",l),f=this.omit(r,"version"),p=this.safeDict(this.options.access,t,{}),m=this.safeDict(p,i,{}),g=this.safeString(m,e,"public"),v=u+"/"+this.implodeParams(e,f),y=this.omit(f,this.extractParams(e)),b=v,w="";"batchorder"===e?w="json="+this.json(y):Object.keys(y).length>0&&(b+="?"+(w="orderIds"in y?this.urlencodeWithArrayRepeat(y):this.urlencode(y)));let k=this.safeString(this.urls.api,t);if(void 0===k)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let S=k+b,O="batchorder"===e?w:n;if("private"===t||"private"===g){this.checkRequiredCredentials();let e=w+"/api/";"private"!==t&&(e+=t+"/"),e+=v;let i=this.hash(this.encode(e),s.sc,"binary"),r=this.base64ToBinary(this.secret),a=this.hmac(i,r,s.Zf,"base64");d={"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",APIKey:this.apiKey,Authent:a}}return{url:S,method:i,body:O,headers:void 0!==d?d:o}}}i.d(t,{A:()=>n})},455(e,t,i){"use strict";var s=i(4721),r=i(7790),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"kucoin",name:"KuCoin",countries:["SC"],rateLimit:7.5,version:"v2",certified:!0,pro:!0,comment:"Platform 2.0",quoteJsonNumbers:!1,has:{CORS:void 0,spot:!0,margin:!0,swap:!0,future:!0,option:!1,addMargin:!0,borrowCrossMargin:!0,borrowIsolatedMargin:!0,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!1,closePosition:!0,createDepositAddress:!0,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!0,createMarketSellOrderWithCost:!0,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!0,createPostOnlyOrder:!0,createStopLimitOrder:!0,createStopLossOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,createTakeProfitOrder:!0,createTriggerOrder:!0,editOrder:!0,fetchAccounts:!0,fetchBalance:!0,fetchBorrowInterest:!0,fetchBorrowRateHistories:!0,fetchBorrowRateHistory:!0,fetchClosedOrders:!0,fetchCrossBorrowRate:!0,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!0,fetchDeposits:!0,fetchDepositWithdrawFee:!0,fetchDepositWithdrawFees:!0,fetchFundingHistory:!0,fetchFundingInterval:!0,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchIndexOHLCV:!0,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchL3OrderBook:!0,fetchLedger:!0,fetchLeverage:!0,fetchLeverageTiers:!0,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!0,fetchMarketLeverageTiers:!0,fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMarkPrice:!0,fetchMarkPrices:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!0,fetchOpenInterests:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrdersByStatus:!0,fetchOrderTrades:!0,fetchPosition:!0,fetchPositionADLRank:!0,fetchPositionHistory:!0,fetchPositionMode:!0,fetchPositions:!0,fetchPositionsADLRank:!0,fetchPositionsHistory:!0,fetchPremiumIndexOHLCV:!0,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!1,fetchTransactionFee:!0,fetchTransfers:!0,fetchWithdrawals:!0,reduceMargin:!0,repayCrossMargin:!0,repayIsolatedMargin:!0,setLeverage:!0,setMarginMode:!0,setPositionMode:!0,signIn:!1,transfer:!0,withdraw:!0},urls:{logo:"https://user-images.githubusercontent.com/51840849/87295558-132aaf80-c50e-11ea-9801-a2fb0c57c799.jpg",referral:"https://www.kucoin.com/ucenter/signup?rcode=E5wkqe",api:{public:"https://api.kucoin.com",private:"https://api.kucoin.com",futuresPrivate:"https://api-futures.kucoin.com",futuresPublic:"https://api-futures.kucoin.com",webExchange:"https://kucoin.com/_api",broker:"https://api-broker.kucoin.com",earn:"https://api.kucoin.com",uta:"https://api.kucoin.com",utaV2:"https://api.kucoin.com",utaPrivate:"https://api.kucoin.com"},www:"https://www.kucoin.com",doc:["https://docs.kucoin.com"]},requiredCredentials:{apiKey:!0,secret:!0,password:!0},api:{public:{get:{currencies:{cost:3},"currencies/{currency}":{cost:3},symbols:{cost:4},"market/orderbook/level1":{cost:2},"market/allTickers":{cost:15},"market/stats":{cost:15},markets:{cost:3},"market/orderbook/level{level}_{limit}":{cost:4},"market/orderbook/level2_20":{cost:2},"market/orderbook/level2_100":{cost:4},"market/histories":{cost:3},"market/candles":{cost:3},prices:{cost:3},timestamp:{cost:3},status:{cost:3},"mark-price/{symbol}/current":{cost:2},"mark-price/all-symbols":{cost:10},"margin/config":{cost:25},announcements:{cost:20},"margin/collateralRatio":{cost:10},"margin/available-inventory":{cost:10},"convert/symbol":{cost:5},"convert/currencies":{cost:5}},post:{"bullet-public":{cost:10}}},private:{get:{"user-info":{cost:20},"user/api-key":{cost:20},accounts:{cost:5},"accounts/{accountId}":{cost:5},"accounts/ledgers":{cost:2},"hf/accounts/ledgers":{cost:2},"hf/margin/account/ledgers":{cost:2},"transaction-history":{cost:2},"sub/user":{cost:20},"sub-accounts/{subUserId}":{cost:15},"sub-accounts":{cost:20},"sub/api-key":{cost:20},"margin/account":{cost:40},"margin/accounts":{cost:15},"isolated/accounts":{cost:15},"deposit-addresses":{cost:5},deposits:{cost:5},"hist-deposits":{cost:5},withdrawals:{cost:20},"hist-withdrawals":{cost:20},"withdrawals/quotas":{cost:20},"accounts/transferable":{cost:20},"transfer-list":{cost:20},"base-fee":{cost:3},"trade-fees":{cost:3},"market/orderbook/level{level}":{cost:3},"market/orderbook/level2":{cost:3},"market/orderbook/level3":{cost:3},"hf/accounts/opened":{cost:2},"hf/orders/active":{cost:2},"hf/orders/active/symbols":{cost:2},"hf/margin/order/active/symbols":{cost:2},"hf/orders/done":{cost:2},"hf/orders/{orderId}":{cost:2},"hf/orders/client-order/{clientOid}":{cost:2},"hf/orders/dead-cancel-all/query":{cost:2},"hf/fills":{cost:2},orders:{cost:2},"limit/orders":{cost:3},"orders/{orderId}":{cost:2},"order/client-order/{clientOid}":{cost:2},fills:{cost:10},"limit/fills":{cost:20},"stop-order":{cost:8},"stop-order/{orderId}":{cost:3},"stop-order/queryOrderByClientOid":{cost:3},"oco/order/{orderId}":{cost:2},"oco/order/details/{orderId}":{cost:2},"oco/client-order/{clientOid}":{cost:2},"oco/orders":{cost:2},"hf/margin/orders/active":{cost:4},"hf/margin/orders/done":{cost:10},"hf/margin/orders/{orderId}":{cost:4},"hf/margin/orders/client-order/{clientOid}":{cost:5},"hf/margin/fills":{cost:5},"hf/margin/stop-orders":{cost:8},"hf/margin/stop-order/orderId":{cost:3},"hf/margin/stop-order/clientOid":{cost:3},"hf/margin/oco-order/orderId":{cost:2},"hf/margin/oco-order/clientOid":{cost:2},"hf/margin/oco-order/detail/orderId":{cost:2},"hf/margin/oco-orders":{cost:2},"etf/info":{cost:25},"margin/currencies":{cost:20},"risk/limit/strategy":{cost:20},"isolated/symbols":{cost:3},"margin/symbols":{cost:3},"isolated/account/{symbol}":{cost:50},"margin/borrow":{cost:15},"margin/repay":{cost:15},"margin/interest":{cost:20},"margin/borrowRate":{cost:20},"project/list":{cost:10},"project/marketInterestRate":{cost:5},"redeem/orders":{cost:10},"purchase/orders":{cost:10},"broker/api/rebase/download":{cost:3},"broker/queryMyCommission":{cost:3},"broker/queryUser":{cost:3},"broker/queryDetailByUid":{cost:3},"migrate/user/account/status":{cost:3},"convert/quote":{cost:20},"convert/order/detail":{cost:5},"convert/order/history":{cost:5},"convert/limit/quote":{cost:20},"convert/limit/order/detail":{cost:5},"convert/limit/orders":{cost:5},"affiliate/inviter/statistics":{cost:30},"affiliate/queryInvitees":{cost:30},"affiliate/queryMyCommission":{cost:30},"affiliate/queryTransactionByUid":{cost:30},"affiliate/queryTransactionByTime":{cost:30},"affiliate/queryKumining":{cost:30}},post:{"sub/user/created":{cost:15},"sub/api-key":{cost:20},"sub/api-key/update":{cost:30},"deposit-addresses":{cost:20},withdrawals:{cost:5},"accounts/universal-transfer":{cost:4},"accounts/sub-transfer":{cost:30},"accounts/inner-transfer":{cost:15},"transfer-out":{cost:20},"transfer-in":{cost:20},"hf/orders":{cost:1},"hf/orders/test":{cost:1},"hf/orders/sync":{cost:1},"hf/orders/multi":{cost:1},"hf/orders/multi/sync":{cost:1},"hf/orders/alter":{cost:1},"hf/orders/dead-cancel-all":{cost:2},orders:{cost:2},"orders/test":{cost:2},"orders/multi":{cost:3},"stop-order":{cost:2},"oco/order":{cost:2},"hf/margin/order":{cost:2},"hf/margin/order/test":{cost:2},"hf/margin/stop-order":{cost:3},"margin/order":{cost:5},"margin/order/test":{cost:5},"hf/margin/oco-order":{cost:2},"margin/borrow":{cost:15},"margin/repay":{cost:10},purchase:{cost:15},redeem:{cost:15},"lend/purchase/update":{cost:10},"convert/order":{cost:20},"convert/limit/order":{cost:20},"bullet-private":{cost:10},"position/update-user-leverage":{cost:5},"deposit-address/create":{cost:20}},delete:{"sub/api-key":{cost:30},"withdrawals/{withdrawalId}":{cost:20},"hf/orders/{orderId}":{cost:1},"hf/orders/sync/{orderId}":{cost:1},"hf/orders/client-order/{clientOid}":{cost:1},"hf/orders/sync/client-order/{clientOid}":{cost:1},"hf/orders/cancel/{orderId}":{cost:1},"hf/orders":{cost:2},"hf/orders/cancelAll":{cost:30},"orders/{orderId}":{cost:3},"order/client-order/{clientOid}":{cost:5},orders:{cost:20},"stop-order/{orderId}":{cost:3},"stop-order/cancelOrderByClientOid":{cost:5},"stop-order/cancel":{cost:3},"oco/order/{orderId}":{cost:3},"oco/client-order/{clientOid}":{cost:3},"oco/orders":{cost:3},"hf/margin/orders/{orderId}":{cost:2},"hf/margin/orders/client-order/{clientOid}":{cost:2},"hf/margin/orders":{cost:5},"hf/margin/stop-order/cancel-by-id":{cost:3},"hf/margin/stop-order/cancel-by-clientOid":{cost:5},"hf/margin/stop-order/cancel":{cost:3},"hf/margin/oco-order/cancel-by-id":{cost:3},"hf/margin/oco-order/cancel-by-clientOid":{cost:3},"hf/margin/oco-order/cancel":{cost:3},"convert/limit/order/cancel":{cost:5}}},futuresPublic:{get:{"contracts/active":{cost:6},"contracts/{symbol}":{cost:6},ticker:{cost:4},allTickers:{cost:10},"level2/snapshot":{cost:6},"level2/depth20":{cost:10},"level2/depth100":{cost:20},"trade/history":{cost:10},"kline/query":{cost:6},"interest/query":{cost:10},"index/query":{cost:4},"mark-price/{symbol}/current":{cost:6},"premium/query":{cost:6},"trade-statistics":{cost:6},"funding-rate/{symbol}/current":{cost:4},"contract/funding-rates":{cost:10},timestamp:{cost:4},status:{cost:8},"level2/message/query":{cost:1.3953},"contracts/risk-limit/{symbol}":{cost:3},"level3/message/query":{cost:3},"level3/snapshot":{cost:3}},post:{"bullet-public":{cost:20}}},futuresPrivate:{get:{"transaction-history":{cost:4},"account-overview":{cost:10},"account-overview-all":{cost:12},"transfer-list":{cost:20},orders:{cost:4},stopOrders:{cost:12},recentDoneOrders:{cost:10},"orders/{orderId}":{cost:10},"orders/byClientOid":{cost:10},fills:{cost:10},recentFills:{cost:6},"trade-fees":{cost:6},openOrderStatistics:{cost:20},position:{cost:4},positions:{cost:4},"margin/maxWithdrawMargin":{cost:20},"contracts/risk-limit/{symbol}":{cost:10},"funding-history":{cost:10},"copy-trade/futures/get-max-open-size":{cost:8},"copy-trade/futures/position/margin/max-withdraw-margin":{cost:20},"history-positions":{cost:4},"position/getMarginMode":{cost:4},"position/getPositionMode":{cost:4},"deposit-address":{cost:4},"deposit-list":{cost:4},"withdrawals/quotas":{cost:4},"withdrawal-list":{cost:4},"sub/api-key":{cost:4},"trade-statistics":{cost:4},getMaxOpenSize:{cost:4},getCrossUserLeverage:{cost:4}},post:{"transfer-out":{cost:20},"transfer-in":{cost:20},orders:{cost:4},"st-orders":{cost:4},"orders/test":{cost:4},"orders/multi":{cost:6},"position/margin/auto-deposit-status":{cost:8},"margin/withdrawMargin":{cost:10},"position/margin/deposit-margin":{cost:8},"position/risk-limit-level/change":{cost:8},"copy-trade/futures/orders":{cost:4},"copy-trade/futures/orders/test":{cost:4},"copy-trade/futures/st-orders":{cost:4},"copy-trade/futures/position/margin/deposit-margin":{cost:8},"copy-trade/futures/position/margin/withdraw-margin":{cost:20},"copy-trade/futures/position/risk-limit-level/change":{cost:4},"copy-trade/futures/position/margin/auto-deposit-status":{cost:8},"copy-trade/futures/position/changeMarginMode":{cost:4},"copy-trade/futures/position/changeCrossUserLeverage":{cost:4},"copy-trade/getCrossModeMarginRequirement":{cost:6},"copy-trade/position/switchPositionMode":{cost:4},changeCrossUserLeverage:{cost:4},withdrawals:{cost:4},"sub/api-key":{cost:4},"sub/api-key/update":{cost:4},"position/changeMarginMode":{cost:4},"position/switchPositionMode":{cost:4},"bullet-private":{cost:20}},delete:{"orders/{orderId}":{cost:2},"orders/client-order/{clientOid}":{cost:2},orders:{cost:20},stopOrders:{cost:30},"copy-trade/futures/orders":{cost:1.5},"copy-trade/futures/orders/client-order":{cost:1.5},"orders/multi-cancel":{cost:40},"withdrawals/{withdrawalId}":{cost:10},"cancel/transfer-out":{cost:10},"sub/api-key":{cost:10}}},webExchange:{get:{"currency/currency/chain-info":{cost:1},"contract/{symbol}/funding-rates":{cost:2}}},broker:{get:{"broker/nd/info":{cost:4},"broker/nd/account":{cost:4},"broker/nd/account/apikey":{cost:4},"broker/nd/rebase/download":{cost:4},"broker/nd/mark-up":{cost:4},"asset/ndbroker/deposit/list":{cost:2},"broker/nd/transfer/detail":{cost:2},"broker/nd/deposit/detail":{cost:2},"broker/nd/withdraw/detail":{cost:2}},post:{"broker/nd/transfer":{cost:2},"broker/nd/account":{cost:6},"broker/nd/account/apikey":{cost:6},"broker/nd/account/update-apikey":{cost:6},"broker/nd/mark-up":{cost:6}},delete:{"broker/nd/account/apikey":{cost:6}}},earn:{get:{"otc-loan/discount-rate-configs":{cost:20},"otc-loan/loan":{cost:2},"otc-loan/accounts":{cost:2},"earn/redeem-preview":{cost:10},"earn/saving/products":{cost:10},"earn/hold-assets":{cost:10},"earn/promotion/products":{cost:10},"earn/kcs-staking/products":{cost:10},"earn/staking/products":{cost:10},"earn/eth-staking/products":{cost:10},"struct-earn/dual/products":{cost:6},"struct-earn/orders":{cost:10}},post:{"earn/orders":{cost:10},"struct-earn/orders":{cost:10}},delete:{"earn/orders":{cost:10}}},uta:{get:{"market/announcement":{cost:40},"market/currency":{cost:6},"asset/currencies":{cost:6},"market/instrument":{cost:8},"market/ticker":{cost:30},"market/trade":{cost:6},"market/kline":{cost:6},"market/funding-rate":{cost:4},"market/funding-rate-history":{cost:10},"market/cross-config":{cost:50},"market/collateral-discount-ratio":{cost:20},"market/index-price":{cost:20},"market/position-tiers":{cost:40},"market/open-interest":{cost:20},"server/status":{cost:6},"market/borrowable-currency":{cost:30},"user/my-ip":{cost:20},"market/fiat-price":{cost:6}}},utaV2:{get:{"market/funding-rate":{cost:6}}},utaPrivate:{get:{"market/orderbook":{cost:6},"account/balance":{cost:10},"account/transfer-quota":{cost:40},"account/mode":{cost:60},"account/ledger":{cost:4},"account/interest-history":{cost:30},"asset/deposit/address":{cost:10},"account/deposit/address":{cost:5},"{accountMode}/account/balance":{cost:10},"{accountMode}/account/overview":{cost:10},"{accountMode}/order/detail":{cost:8},"{accountMode}/order/open-list":{cost:8},"{accountMode}/order/history":{cost:8},"{accountMode}/order/execution":{cost:8},"{accountMode}/position/open-list":{cost:6},"{accountMode}/position/history":{cost:4},"position/history":{cost:4},"{accountMode}/position/tiers":{cost:40},"sub-account/balance":{cost:10},"user/fee-rate":{cost:6},"dcp/query":{cost:4},"unified/account/leverage":{cost:20},"position/funding-history":{cost:30},"account/interest-limits":{cost:20}},post:{"account/transfer":{cost:8},"account/mode":{cost:60},"{accountMode}/account/modify-leverage":{cost:40},"{accountMode}/order/place":{cost:2},"{accountMode}/order/place-batch":{cost:8},"{accountMode}/order/cancel":{cost:2},"{accountMode}/order/cancel-batch":{cost:8},"{accountMode}/order/cancel-all":{cost:40},"sub-account/canTransferOut":{cost:10},"dcp/set":{cost:4},"{accountMode}/account/modify-leverage-margin-cross":{cost:40}}}},timeframes:{"1m":"1min","3m":"3min","5m":"5min","15m":"15min","30m":"30min","1h":"1hour","2h":"2hour","4h":"4hour","6h":"6hour","8h":"8hour","12h":"12hour","1d":"1day","1w":"1week","1M":"1month"},precisionMode:4,exceptions:{exact:{"Order not exist or not allow to be cancelled":a.OrderNotFound,"The order does not exist.":a.OrderNotFound,"order not exist":a.OrderNotFound,"order not exist.":a.OrderNotFound,order_not_exist:a.OrderNotFound,order_not_exist_or_not_allow_to_cancel:a.OrderNotFound,"Order size below the minimum requirement.":a.InvalidOrder,"Order size increment invalid.":a.InvalidOrder,"The withdrawal amount is below the minimum requirement.":a.ExchangeError,"Unsuccessful! Exceeded the max. funds out-transfer limit":a.InsufficientFunds,"The amount increment is invalid.":a.BadRequest,"The quantity is below the minimum requirement.":a.InvalidOrder,"not in the given range!":a.BadRequest,"recAccountType not in the given range":a.BadRequest,"Unsupported trading pair.":a.BadSymbol,400:a.BadRequest,401:a.AuthenticationError,403:a.NotSupported,404:a.NotSupported,405:a.NotSupported,415:a.NotSupported,429:a.RateLimitExceeded,500:a.ExchangeNotAvailable,503:a.ExchangeNotAvailable,101030:a.PermissionDenied,103e3:a.InvalidOrder,112010:a.PermissionDenied,130101:a.BadRequest,130102:a.ExchangeError,130103:a.OrderNotFound,130104:a.ExchangeError,130105:a.InsufficientFunds,130106:a.NotSupported,130107:a.ExchangeError,130108:a.OrderNotFound,130201:a.PermissionDenied,130202:a.ExchangeError,130203:a.InsufficientFunds,130204:a.BadRequest,130301:a.InsufficientFunds,130302:a.PermissionDenied,130303:a.NotSupported,130304:a.NotSupported,130305:a.NotSupported,130306:a.NotSupported,130307:a.NotSupported,130308:a.InvalidOrder,130309:a.InvalidOrder,130310:a.ExchangeError,130311:a.InvalidOrder,130312:a.InvalidOrder,130313:a.InvalidOrder,130314:a.InvalidOrder,130315:a.NotSupported,126e3:a.ExchangeError,126001:a.NotSupported,126002:a.ExchangeError,126003:a.InvalidOrder,126004:a.ExchangeError,126005:a.PermissionDenied,126006:a.ExchangeError,126007:a.ExchangeError,126009:a.ExchangeError,126010:a.ExchangeError,126011:a.ExchangeError,126013:a.InsufficientFunds,126015:a.ExchangeError,126021:a.NotSupported,126022:a.InvalidOrder,126027:a.InvalidOrder,126028:a.InvalidOrder,126029:a.InvalidOrder,126030:a.InvalidOrder,126033:a.InvalidOrder,126034:a.InvalidOrder,126036:a.InvalidOrder,126037:a.ExchangeError,126038:a.ExchangeError,126039:a.ExchangeError,126041:a.ExchangeError,126042:a.ExchangeError,126043:a.OrderNotFound,126044:a.InvalidOrder,126045:a.NotSupported,126046:a.NotSupported,126047:a.PermissionDenied,126048:a.PermissionDenied,135005:a.ExchangeError,135018:a.ExchangeError,200004:a.InsufficientFunds,210014:a.InvalidOrder,210021:a.InsufficientFunds,230003:a.InsufficientFunds,26e4:a.InvalidAddress,260100:a.InsufficientFunds,3e5:a.InvalidOrder,4e5:a.BadSymbol,400001:a.AuthenticationError,400002:a.InvalidNonce,400003:a.AuthenticationError,400004:a.AuthenticationError,400005:a.AuthenticationError,400006:a.AuthenticationError,400007:a.AuthenticationError,400008:a.NotSupported,400100:a.BadRequest,400200:a.InvalidOrder,400330:a.InvalidOrder,400350:a.InvalidOrder,400370:a.InvalidOrder,400400:a.BadRequest,400401:a.AuthenticationError,400500:a.RestrictedLocation,400600:a.BadSymbol,400760:a.InvalidOrder,401e3:a.BadRequest,408e3:a.BadRequest,411100:a.AccountSuspended,415e3:a.BadRequest,400303:a.PermissionDenied,5e5:a.ExchangeNotAvailable,260220:a.InvalidAddress,600100:a.InsufficientFunds,600101:a.InvalidOrder,900014:a.BadRequest,330012:a.InvalidOrder,330005:a.InvalidOrder,100001:a.OrderNotFound,100004:a.BadRequest,300003:a.InsufficientFunds,300012:a.InvalidOrder,404e3:a.NotSupported,300009:a.InvalidOrder,330008:a.InsufficientFunds},broad:{"pageSize should not greater than 500":a.BadRequest,"Exceeded the access frequency":a.RateLimitExceeded,"require more permission":a.PermissionDenied,"Position does not exist":a.OrderNotFound}},fees:{trading:{tierBased:!0,percentage:!0,taker:this.parseNumber("0.001"),maker:this.parseNumber("0.001"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.001")],[this.parseNumber("50"),this.parseNumber("0.001")],[this.parseNumber("200"),this.parseNumber("0.0009")],[this.parseNumber("500"),this.parseNumber("0.0008")],[this.parseNumber("1000"),this.parseNumber("0.0007")],[this.parseNumber("2000"),this.parseNumber("0.0007")],[this.parseNumber("4000"),this.parseNumber("0.0006")],[this.parseNumber("8000"),this.parseNumber("0.0005")],[this.parseNumber("15000"),this.parseNumber("0.00045")],[this.parseNumber("25000"),this.parseNumber("0.0004")],[this.parseNumber("40000"),this.parseNumber("0.00035")],[this.parseNumber("60000"),this.parseNumber("0.0003")],[this.parseNumber("80000"),this.parseNumber("0.00025")]],maker:[[this.parseNumber("0"),this.parseNumber("0.001")],[this.parseNumber("50"),this.parseNumber("0.0009")],[this.parseNumber("200"),this.parseNumber("0.0007")],[this.parseNumber("500"),this.parseNumber("0.0005")],[this.parseNumber("1000"),this.parseNumber("0.0003")],[this.parseNumber("2000"),this.parseNumber("0")],[this.parseNumber("4000"),this.parseNumber("0")],[this.parseNumber("8000"),this.parseNumber("0")],[this.parseNumber("15000"),this.parseNumber("-0.00005")],[this.parseNumber("25000"),this.parseNumber("-0.00005")],[this.parseNumber("40000"),this.parseNumber("-0.00005")],[this.parseNumber("60000"),this.parseNumber("-0.00005")],[this.parseNumber("80000"),this.parseNumber("-0.00005")]]}},spot:{tierBased:!0,percentage:!0,taker:this.parseNumber("0.001"),maker:this.parseNumber("0.001"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.001")],[this.parseNumber("50"),this.parseNumber("0.001")],[this.parseNumber("200"),this.parseNumber("0.0009")],[this.parseNumber("500"),this.parseNumber("0.0008")],[this.parseNumber("1000"),this.parseNumber("0.0007")],[this.parseNumber("2000"),this.parseNumber("0.0007")],[this.parseNumber("4000"),this.parseNumber("0.0006")],[this.parseNumber("8000"),this.parseNumber("0.0005")],[this.parseNumber("15000"),this.parseNumber("0.00045")],[this.parseNumber("25000"),this.parseNumber("0.0004")],[this.parseNumber("40000"),this.parseNumber("0.00035")],[this.parseNumber("60000"),this.parseNumber("0.0003")],[this.parseNumber("80000"),this.parseNumber("0.00025")]],maker:[[this.parseNumber("0"),this.parseNumber("0.001")],[this.parseNumber("50"),this.parseNumber("0.0009")],[this.parseNumber("200"),this.parseNumber("0.0007")],[this.parseNumber("500"),this.parseNumber("0.0005")],[this.parseNumber("1000"),this.parseNumber("0.0003")],[this.parseNumber("2000"),this.parseNumber("0")],[this.parseNumber("4000"),this.parseNumber("0")],[this.parseNumber("8000"),this.parseNumber("0")],[this.parseNumber("15000"),this.parseNumber("-0.00005")],[this.parseNumber("25000"),this.parseNumber("-0.00005")],[this.parseNumber("40000"),this.parseNumber("-0.00005")],[this.parseNumber("60000"),this.parseNumber("-0.00005")],[this.parseNumber("80000"),this.parseNumber("-0.00005")]]}},contract:{tierBased:!0,percentage:!0,taker:this.parseNumber("0.0006"),maker:this.parseNumber("0.0002"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.0006")],[this.parseNumber("50"),this.parseNumber("0.0006")],[this.parseNumber("200"),this.parseNumber("0.0006")],[this.parseNumber("500"),this.parseNumber("0.0005")],[this.parseNumber("1000"),this.parseNumber("0.0004")],[this.parseNumber("2000"),this.parseNumber("0.0004")],[this.parseNumber("4000"),this.parseNumber("0.00038")],[this.parseNumber("8000"),this.parseNumber("0.00035")],[this.parseNumber("15000"),this.parseNumber("0.00032")],[this.parseNumber("25000"),this.parseNumber("0.0003")],[this.parseNumber("40000"),this.parseNumber("0.0003")],[this.parseNumber("60000"),this.parseNumber("0.0003")],[this.parseNumber("80000"),this.parseNumber("0.0003")]],maker:[[this.parseNumber("0"),this.parseNumber("0.02")],[this.parseNumber("50"),this.parseNumber("0.015")],[this.parseNumber("200"),this.parseNumber("0.01")],[this.parseNumber("500"),this.parseNumber("0.01")],[this.parseNumber("1000"),this.parseNumber("0.01")],[this.parseNumber("2000"),this.parseNumber("0")],[this.parseNumber("4000"),this.parseNumber("0")],[this.parseNumber("8000"),this.parseNumber("0")],[this.parseNumber("15000"),this.parseNumber("-0.003")],[this.parseNumber("25000"),this.parseNumber("-0.006")],[this.parseNumber("40000"),this.parseNumber("-0.009")],[this.parseNumber("60000"),this.parseNumber("-0.012")],[this.parseNumber("80000"),this.parseNumber("-0.015")]]}},funding:{tierBased:!1,percentage:!1,withdraw:{},deposit:{}}},commonCurrencies:{BIFI:"BIFIF",VAI:"VAIOT",WAX:"WAXP",ALT:"APTOSLAUNCHTOKEN",KALT:"ALT",FUD:"FTX Users' Debt"},options:{hf:void 0,uta:void 0,version:"v1",symbolSeparator:"-",fetchMyTradesMethod:"private_get_fills",timeDifference:0,adjustForTimeDifference:!1,fetchCurrencies:{brokenCurrencies:["00","OPEN_ERROR","HUF","BDT"]},fetchMarkets:{types:["spot","swap","future","contract"],fetchTickersFees:!0},withdraw:{includeFee:!1},transfer:{fillResponseFromRequest:!0},fetchBalance:{code:"USDT"},setLeverage:{code:"USDT"},timeInForce:{IOC:"IOC",FOK:"FOK",PO:"PO",GTD:"GTT",RPI:"RPI"},timeframes:{swap:{"1m":1,"3m":void 0,"5m":5,"15m":15,"30m":30,"1h":60,"2h":120,"4h":240,"6h":void 0,"8h":480,"12h":720,"1d":1440,"1w":10080}},versions:{public:{GET:{currencies:"v3","currencies/{currency}":"v3",symbols:"v2","mark-price/all-symbols":"v3",announcements:"v3","margin/available-inventory":"v3"}},private:{GET:{"user-info":"v2","hf/margin/account/ledgers":"v3","sub/user":"v2","sub-accounts":"v2","margin/accounts":"v3","isolated/accounts":"v3","deposit-addresses":"v1","market/orderbook/level2":"v3","market/orderbook/level3":"v3","market/orderbook/level{level}":"v3","oco/order/{orderId}":"v3","oco/order/details/{orderId}":"v3","oco/client-order/{clientOid}":"v3","oco/orders":"v3","hf/margin/orders/active":"v3","hf/margin/order/active/symbols":"v3","hf/margin/orders/done":"v3","hf/margin/orders/{orderId}":"v3","hf/margin/orders/client-order/{clientOid}":"v3","hf/margin/fills":"v3","hf/margin/stop-orders":"v3","hf/margin/stop-order/orderId":"v3","hf/margin/stop-order/clientOid":"v3","hf/margin/oco-order/orderId":"v3","hf/margin/oco-order/clientOid":"v3","hf/margin/oco-order/detail/orderId":"v3","hf/margin/oco-orders":"v3","etf/info":"v3","margin/currencies":"v3","margin/borrow":"v3","margin/repay":"v3","margin/interest":"v3","margin/borrowRate":"v3","project/list":"v3","project/marketInterestRate":"v3","redeem/orders":"v3","purchase/orders":"v3","migrate/user/account/status":"v3","margin/symbols":"v3","affiliate/inviter/statistics":"v2","affiliate/queryInvitees":"v2","affiliate/queryMyCommission":"v2","affiliate/queryTransactionByUid":"v2","affiliate/queryTransactionByTime":"v2","affiliate/queryKumining":"v2","asset/ndbroker/deposit/list":"v1"},POST:{"sub/user/created":"v2","accounts/universal-transfer":"v3","accounts/sub-transfer":"v2","accounts/inner-transfer":"v2","transfer-out":"v3","deposit-address/create":"v3","oco/order":"v3","hf/margin/order":"v3","hf/margin/order/test":"v3","hf/margin/stop-order":"v3","margin/borrow":"v3","margin/repay":"v3","hf/margin/oco-order":"v3",purchase:"v3",redeem:"v3","lend/purchase/update":"v3","position/update-user-leverage":"v3",withdrawals:"v3"},DELETE:{"hf/margin/orders/{orderId}":"v3","hf/margin/orders/client-order/{clientOid}":"v3","hf/margin/orders":"v3","hf/margin/stop-order/cancel-by-id":"v3","hf/margin/stop-order/cancel-by-clientOid":"v3","hf/margin/stop-order/cancel":"v3","oco/order/{orderId}":"v3","oco/client-order/{clientOid}":"v3","oco/orders":"v3","hf/margin/oco-order/cancel-by-id":"v3","hf/margin/oco-order/cancel-by-clientOid":"v3","hf/margin/oco-order/cancel":"v3"}},futuresPrivate:{GET:{getMaxOpenSize:"v2",getCrossUserLeverage:"v2","position/getMarginMode":"v2","position/getPositionMode":"v2"},POST:{"transfer-out":"v2",changeCrossUserLeverage:"v2","position/changeMarginMode":"v2","position/switchPositionMode":"v2"}},futuresPublic:{GET:{"level3/snapshot":"v2"}}},partner:{spot:{id:"ccxt",key:"9e58cc35-5b5e-4133-92ec-166e3f077cb8"},future:{id:"ccxtfutures",key:"1b327198-f30c-4f14-a0ac-918871282f15"}},accountsByType:{spot:"trade",margin:"margin",cross:"margin",marginV2:"margin",isolated:"isolated",main:"main",funding:"main",future:"contract",swap:"contract",mining:"pool",hf:"trade_hf",contract:"contract",uta:"unified",unified:"unified"},utaAccountsByType:{trade:"SPOT",spot:"SPOT",margin:"CROSS",cross:"CROSS",isolated:"ISOLATED",main:"FUNDING",funding:"FUNDING",future:"FUTURES",swap:"FUTURES",contract:"FUTURES",uta:"unified",unified:"unified"},networks:{BTC:"btc",BRC20:"btc",BTCNATIVESEGWIT:"bech32",ETH:"eth",ERC20:"eth",TRX:"trx",TRC20:"trx",HECO:"heco",HRC20:"heco",MATIC:"matic",KCC:"kcc",SOL:"sol",ALGO:"algo",EOS:"eos",BEP20:"bsc",BEP2:"bnb",ARBITRUM:"arbitrum",AVAXX:"avax",AVAXC:"avaxc",TLOS:"tlos",CFX:"cfx",ACA:"aca",OP:"optimism",OPTIMISM:"optimism",ONT:"ont",GLMR:"glmr",CSPR:"cspr",KLAY:"klay",XRD:"xrd",RVN:"rvn",NEAR:"near",APT:"aptos",ETHW:"ethw",TON:"ton",BCH:"bch",BSV:"bchsv",BCHA:"bchabc",OSMO:"osmo",NANO:"nano",XLM:"xlm",VET:"vet",IOST:"iost",ZIL:"zil",XRP:"xrp",TOMO:"tomo",XMR:"xmr",COTI:"coti",XTZ:"xtz",ADA:"ada",WAX:"waxp",THETA:"theta",ONE:"one",IOTEX:"iotx",NULS:"nuls",KSM:"ksm",LTC:"ltc",WAVES:"waves",DOT:"dot",STEEM:"steem",QTUM:"qtum",DOGE:"doge",FIL:"fil",XYM:"xym",FLUX:"flux",ATOM:"atom",XDC:"xdc",KDA:"kda",ICP:"icp",CELO:"celo",LSK:"lsk",VSYS:"vsys",KAR:"kar",XCH:"xch",FLOW:"flow",BAND:"band",EGLD:"egld",HBAR:"hbar",XPR:"xpr",AR:"ar",FTM:"ftm",KAVA:"kava",KMA:"kma",XEC:"xec",IOTA:"iota",HNT:"hnt",ASTR:"astr",PDEX:"pdex",METIS:"metis",ZEC:"zec",POKT:"pokt",OASYS:"oas",OASIS:"oasis",ETC:"etc",AKT:"akt",FSN:"fsn",SCRT:"scrt",CFG:"cfg",ICX:"icx",KMD:"kmd",NEM:"NEM",STX:"stx",DGB:"dgb",DCR:"dcr",CKB:"ckb",ELA:"ela",HYDRA:"hydra",BTM:"btm",KARDIA:"kai",SXP:"sxp",NEBL:"nebl",ZEN:"zen",SDN:"sdn",LTO:"lto",WEMIX:"wemix",EVER:"ever",BNC:"bnc",BNCDOT:"bncdot",AION:"aion",GRIN:"grin",LOKI:"loki",QKC:"qkc",TT:"TT",PIVX:"pivx",SERO:"sero",METER:"meter",STATEMINE:"statemine",DVPN:"dvpn",XPRT:"xprt",MOVR:"movr",ERGO:"ergo",ABBC:"abbc",DIVI:"divi",PURA:"pura",DFI:"dfi",NEON3:"neon3",DOCK:"dock",TRUE:"true",CS:"cs",ORAI:"orai",BASE:"base",TARA:"tara"},networksById:{btc:"BTC",trx:"TRC20",eth:"ERC20",heco:"HRC20",optimism:"OP",op:"OP"},marginModes:{cross:"MARGIN_TRADE",isolated:"MARGIN_ISOLATED_TRADE",spot:"TRADE"}},features:{spot:{sandbox:!1,createOrder:{marginMode:!0,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!0},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,selfTradePrevention:!0,iceberg:!0},createOrders:{max:5},fetchMyTrades:{marginMode:!0,limit:void 0,daysBack:void 0,untilDays:7,symbolRequired:!0},fetchOrder:{marginMode:!0,trigger:!0,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!0,limit:500,trigger:!0,trailing:!1,symbolRequired:!0},fetchOrders:void 0,fetchClosedOrders:{marginMode:!0,limit:500,daysBack:void 0,daysBackCanceled:void 0,untilDays:7,trigger:!0,trailing:!1,symbolRequired:!0},fetchOHLCV:{limit:1500}},forDerivs:{sandbox:!1,createOrder:{marginMode:!0,triggerPrice:!0,triggerPriceType:{last:!0,mark:!0,index:!0},triggerDirection:!0,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:{triggerPriceType:{last:!0,mark:!0,index:!0},price:!0},timeInForce:{IOC:!0,FOK:!1,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!0,marketBuyByCost:!0,marketBuyRequiresPrice:!1,selfTradePrevention:!0,iceberg:!0},createOrders:{max:20},fetchMyTrades:{marginMode:!0,limit:1e3,daysBack:void 0,untilDays:7,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:1e3,trigger:!0,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:1e3,daysBack:void 0,daysBackCanceled:void 0,untilDays:void 0,trigger:!0,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:500}},swap:{linear:{extends:"forDerivs"},inverse:{extends:"forDerivs"}},future:{linear:{extends:"forDerivs"},inverse:{extends:"forDerivs"}}},rollingWindowSize:3e4})}nonce(){return this.milliseconds()-this.safeInteger(this.options,"timeDifference",0)}async fetchTime(e={}){let t,[i,s]=this.handleMarketTypeAndParams("fetchTime",void 0,e);return t="spot"!==i&&"margin"!==i?await this.futuresPublicGetTimestamp(s):await this.publicGetTimestamp(s),this.safeInteger(t,"data")}async fetchStatus(e={}){let t,[i,s]=this.handleOptionBoolAndParams(e,"fetchStatus","uta",!1),[r,a]=this.handleMarketTypeAndParams("fetchStatus",void 0,s);if(i){let e=this.safeString(this.options,"defaultType","spot"),i="FUTURES";"spot"===e&&(i="SPOT");let s=this.safeStringUpper(a,"tradeType",i);t=await this.utaGetServerStatus(this.extend({tradeType:s},a))}else t="spot"!==r&&"margin"!==r?await this.futuresPublicGetStatus(a):await this.publicGetStatus(a);let o=this.safeDict(t,"data",{});return{status:"open"===this.safeString2(o,"status","serverStatus")?"ok":"maintenance",updated:void 0,eta:void 0,url:void 0,info:t}}async fetchMarkets(e={}){let t,i;[t,i]=this.handleOptionBoolAndParams(e,"fetchMarkets","fetchTickersFees",!0);let s=!1;if([s,i]=this.handleOptionBoolAndParams(i,"fetchMarkets","uta",s),s)return await this.fetchUTAMarkets(i);let r=this.safeDict(this.options,"fetchMarkets"),a=this.safeList(r,"types",["spot","swap","future","contract"]),n=this.checkRequiredCredentials(!1),d=n&&this.safeBool(i,"marginables",!0);i=this.omit(i,"marginables");let h=!1;(this.inArray("swap",a)||this.inArray("future",a)||this.inArray("contract",a))&&(h=!0);let c=this.inArray("spot",a);t=t&&c;let l=[];c&&l.push(this.publicGetSymbols(i)),!0===d&&(l.push(this.privateGetMarginSymbols(i)),l.push(this.privateGetIsolatedSymbols(i))),t&&l.push(this.publicGetMarketAllTickers(i)),h&&l.push(this.fetchContractMarkets(i)),n&&l.push(this.loadMigrationStatus());let u=await Promise.all(l),f=c?this.safeList(u[0],"data",[]):[],p=0,m=0,g=0,v=0,y=0;c&&(y=1),!0===d&&(p=y,y=this.sum(y,2),m=this.sum(p,1)),t&&(g=y,y=this.sum(y,1)),h&&(v=y);let b=!0===d?this.safeDict(u[p],"data",{}):{},w=this.safeList(b,"items",[]),k=this.indexBy(w,"symbol"),S=!0===d?u[m]:{},O=this.safeList(S,"data",[]),T=this.indexBy(O,"symbol"),P=t?this.safeDict(u,g,{}):{},I=this.safeList(this.safeDict(P,"data",{}),"ticker",[]),A=this.indexBy(I,"symbol"),x=[];for(let e=0;e<f.length;e++){let t=f[e],i=this.safeString(t,"symbol");if(void 0===i)continue;let[s,r]=i.split("-"),a=this.safeCurrencyCode(s),n=this.safeCurrencyCode(r);if(void 0===a||void 0===n)continue;let d=this.safeDict(A,i,{}),h=this.safeString(d,"makerFeeRate"),c=this.safeString(d,"takerFeeRate"),l=this.safeString(d,"makerCoefficient"),u=this.safeString(d,"takerCoefficient"),p=i in k,m=i in T,g=this.safeBool(t,"isMarginEnabled",!1)||p||m;x.push({id:i,symbol:a+"/"+n,base:a,quote:n,settle:void 0,baseId:s,quoteId:r,settleId:void 0,type:"spot",spot:!0,margin:g,marginModes:{cross:p,isolated:m},swap:!1,future:!1,option:!1,active:this.safeBool(t,"enableTrading"),contract:!1,linear:void 0,inverse:void 0,taker:this.parseNumber(o.Y.stringMul(c,u)),maker:this.parseNumber(o.Y.stringMul(h,l)),contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(t,"baseIncrement"),price:this.safeNumber(t,"priceIncrement")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(t,"baseMinSize"),max:this.safeNumber(t,"baseMaxSize")},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(t,"quoteMinSize"),max:this.safeNumber(t,"quoteMaxSize")}},created:void 0,info:t})}if(h){let e=this.safeList(u,v,[]);x=this.arrayConcat(x,e)}return this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference(),x}async fetchContractMarkets(e={}){let t=await this.futuresPublicGetContractsActive(e),i=[],s=this.safeList(t,"data",[]);for(let e=0;e<s.length;e++){let t=s[e],r=this.safeString(t,"symbol"),a=this.safeInteger(t,"expireDate"),n=void 0===this.safeString(t,"nextFundingRateTime"),d=!n,h=this.safeString(t,"baseCurrency"),c=this.safeString(t,"quoteCurrency"),l=this.safeString(t,"settleCurrency"),u=this.safeCurrencyCode(h),f=this.safeCurrencyCode(c);if(void 0===u||void 0===f)continue;let p=this.safeCurrencyCode(l),m=u+"/"+f+":"+p,g="swap";n&&(m=m+"-"+this.yymmdd(a,""),g="future");let v=this.safeBool(t,"isInverse"),y=this.safeString(t,"status"),b=this.safeString(t,"multiplier"),w=this.safeNumber(t,"tickSize"),k=this.safeNumber(t,"lotSize"),S=k;void 0===S&&(S=this.safeNumber(t,"baseMinSize"));let O=this.safeNumber(t,"maxOrderQty");void 0===O&&(O=this.safeNumber(t,"baseMaxSize"));let T=this.safeNumber(t,"maxPrice");if(void 0===T){let e=this.safeString(t,"baseMinSize"),i=this.safeString(t,"quoteMaxSize");T=this.parseNumber(o.Y.stringDiv(i,e))}i.push({id:r,symbol:m,base:u,quote:f,settle:p,baseId:h,quoteId:c,settleId:l,type:g,spot:!1,margin:!1,swap:d,future:n,option:!1,active:"Open"===y,contract:!0,linear:!0!==v,inverse:v,taker:this.safeNumber(t,"takerFeeRate"),maker:this.safeNumber(t,"makerFeeRate"),contractSize:this.parseNumber(o.Y.stringAbs(b)),expiry:a,expiryDatetime:this.iso8601(a),strike:void 0,optionType:void 0,precision:{amount:k,price:w},limits:{leverage:{min:this.parseNumber("1"),max:this.safeNumber(t,"maxLeverage")},amount:{min:S,max:O},price:{min:w,max:T},cost:{min:this.safeNumber(t,"quoteMinSize"),max:this.safeNumber(t,"quoteMaxSize")}},created:this.safeInteger(t,"firstOpenDate"),info:t})}return i}async fetchUTAMarkets(e={}){let t=[];t.push(this.utaGetMarketInstrument(this.extend(e,{tradeType:"SPOT"}))),t.push(this.utaGetMarketInstrument(this.extend(e,{tradeType:"FUTURES"})));let i=await Promise.all(t),s=this.safeDict(i[0],"data",{}),r=this.safeDict(i[1],"data",{}),a=this.safeList(s,"list",[]),o=this.safeList(r,"list",[]),n=this.arrayConcat(a,o),d=[];for(let e=0;e<n.length;e++){let t,i=n[e],s=this.safeString(i,"symbol"),r=this.safeString(i,"baseCurrency"),a=this.safeString(i,"quoteCurrency"),o=this.safeString(i,"settlementCurrency"),h=this.safeCurrencyCode(r),c=this.safeCurrencyCode(a);if(void 0===h||void 0===c)continue;let l=this.safeCurrencyCode(o),u=this.safeString(i,"marginMode"),f=!1;"1"===u&&(f=!0);let p=h+"/"+c;void 0!==l&&(p+=":"+l);let m=this.safeString(i,"contractType"),g=this.safeInteger(i,"expiryTime"),v=this.safeString(i,"tradingStatus"),y=!1,b=!1,w=!1,k=!1,S=!1,O=!1;void 0!==m?(k=!0,c===l?S=!0:O=!0,"0"===m?(t="swap",b=!0):(t="future",w=!0)):(t="spot",y=!0),d.push({id:s,symbol:p,base:h,quote:c,settle:l,baseId:r,quoteId:a,settleId:o,type:t,spot:y,margin:f,swap:b,future:w,option:!1,active:"1"===v,contract:k,linear:S,inverse:O,taker:this.safeNumber(i,"makerFeeRate"),maker:this.safeNumber(i,"takerFeeRate"),contractSize:this.safeNumber(i,"unitSize"),expiry:g,expiryDatetime:this.iso8601(g),strike:void 0,optionType:void 0,precision:{amount:this.safeNumber2(i,"lotSize","baseOrderStep"),price:this.safeNumber(i,"tickSize")},limits:{leverage:{min:void 0,max:this.safeInteger(i,"maxLeverage")},amount:{min:this.safeNumber(i,"minBaseOrderSize"),max:this.safeNumber(i,"maxBaseOrderSize")},price:{min:void 0,max:this.safeNumber(i,"maxPrice")},cost:{min:this.safeNumber(i,"minQuoteOrderSize"),max:this.safeNumber(i,"maxQuoteOrderSize")}},created:this.safeInteger(i,"launchTime"),info:i})}return this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference(),d}async loadMigrationStatus(e=!1){if(!("hf"in this.options)||void 0===this.options.hf||e){let e=await this.privateGetHfAccountsOpened();this.options.hf=this.safeBool(e,"data")}return!0}handleHfAndParams(e={}){let t,i=this.safeBool(this.options,"hf",!1);return void 0!==i&&(t=!!i),[this.safeBool(e,"hf",t),this.omit(e,"hf")]}async fetchCurrencies(e={}){let t,i=!1;this.checkRequiredCredentials(!1)&&(i=await this.isUTAEnabled());let[s,r]=this.handleOptionBoolAndParams(e,"fetchCurrencies","uta",i);t=s?await this.utaGetAssetCurrencies(r):await this.publicGetCurrencies(r);let a=this.safeList(t,"data",[]),o=this.handleOption("fetchCurrencies","brokenCurrencies",[]),n=this.filterOutByArray(a,"currency",o);return this.parseCurrencies(n)}parseCurrency(e){let t=this.safeString(e,"currency"),i=this.safeCurrencyCode(t),s={},r=this.safeList2(e,"chains","items",[]),a=r.length;for(let e=0;e<a;e++){let t=this.safeDict(r,e),a=this.safeString(t,"chainId"),o=this.networkIdToCode(a,i);void 0!==o&&(s[o]={info:t,id:a,name:this.safeString(t,"chainName"),code:o,active:void 0,fee:this.safeNumber2(t,"withdrawalMinFee","minWithdrawFee"),deposit:this.safeBool(t,"isDepositEnabled"),withdraw:this.safeBool(t,"isWithdrawEnabled"),precision:this.parseNumber(this.parsePrecision(this.safeString(t,"withdrawPrecision"))),limits:{withdraw:{min:this.safeNumber2(t,"withdrawalMinSize","minWithdrawSize"),max:this.safeNumber2(t,"maxWithdraw","maxWithdrawSize")},deposit:{min:this.safeNumber2(t,"depositMinSize","minDepositSize"),max:this.safeNumber2(t,"maxDeposit","maxDepositSize")}}})}let o=this.safeString(e,"precision"),n=this.parseNumber(this.parsePrecision(o));return this.safeCurrencyStructure({id:t,name:this.safeString(e,"fullName"),code:i,type:0===a?"fiat":"crypto",precision:n,info:e,networks:s,deposit:void 0,withdraw:void 0,active:void 0,fee:void 0,limits:void 0})}async fetchAccounts(e={}){let t,i=await this.isUTAEnabled(),[s,r]=this.handleOptionBoolAndParams(e,"fetchAccounts","uta",i),a=[];s?(t=await this.utaPrivateGetAccountModeAccountOverview(this.extend(r,{accountMode:"unified"})),a=[this.safeDict(t,"data",{})]):(t=await this.privateGetAccounts(r),a=this.safeList(t,"data",[]));let o=[];for(let e=0;e<a.length;e++){let t=a[e],i=this.safeString(t,"id"),s=this.safeString(t,"currency"),r=this.safeCurrencyCode(s),n=this.safeStringLower2(t,"type","accountType");o.push({id:i,type:n,currency:r,code:r,info:t})}return o}async fetchTransactionFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={currency:i.id},[r,a]=this.handleNetworkCodeAndParams(t);if(void 0!==r){let e=this.networkCodeToId(r,this.safeString(i,"code"));void 0!==e&&(s.chain=e.toLowerCase())}let o=await this.privateGetWithdrawalsQuotas(this.extend(s,a)),n=this.safeDict(o,"data",{}),d={};return d[e]=this.safeNumber(n,"withdrawMinFee"),{info:o,withdraw:d,deposit:{}}}async fetchDepositWithdrawFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={currency:i.id},[r,a]=this.handleNetworkCodeAndParams(t);if(void 0!==r){let e=this.networkCodeToId(r,this.safeString(i,"code"));void 0!==e&&(s.chain=e.toLowerCase())}let o=await this.privateGetWithdrawalsQuotas(this.extend(s,a)),n=this.safeDict(o,"data");return this.parseDepositWithdrawFee(n,i)}parseDepositWithdrawFee(e,t){if("chains"in e){let i={info:e,withdraw:{fee:void 0,percentage:!1},deposit:{fee:void 0,percentage:void 0},networks:{}},s=this.safeList(e,"chains",[]);for(let e=0;e<s.length;e++){let r=this.safeDict(s,e),a=this.safeString(r,"chainId"),o=this.networkIdToCode(a,this.safeString(t,"code"));void 0!==o&&(i.networks[o]={withdraw:{fee:this.safeNumber2(r,"withdrawalMinFee","withdrawMinFee"),percentage:!1},deposit:{fee:void 0,percentage:void 0}})}return i}let i=this.safeNumber(e,"withdrawMinFee"),s={info:e,withdraw:{fee:i,percentage:!1},deposit:{fee:void 0,percentage:void 0},networks:{}},r=this.safeString(e,"chain"),a=this.safeString(e,"currency"),o=this.safeCurrency(a,t),n=this.networkIdToCode(r,this.safeString(o,"code"));return void 0!==n&&(s.networks[n]={withdraw:i,deposit:{fee:void 0,percentage:void 0}}),s}isFuturesMethod(e,t){let i=this.safeString2(this.options,e,"defaultType","trade"),s=this.safeString(t,"type",i),r=this.safeDict(this.options,"accountsByType",{}),o=this.safeString(r,s);if(void 0===o){let e=Object.keys(r);throw new a.ExchangeError(this.id+" isFuturesMethod() type must be one of "+e.join(", "))}return"contract"===o||"future"===o||"futures"===o}parseSpotOrUtaTicker(e,t){let i=this.safeStringN(e,["last","lastTradedPrice","lastPrice"]);i=this.safeString(e,"price",i);let s=this.safeString(e,"symbol"),r=this.safeMarket(s,t,"-"),a=r.symbol,n=this.safeString(e,"changeRate");void 0!==n?n=o.Y.stringMul(n,"100"):(n=this.safeString(e,"priceChangePercent"),this.safeBool(r,"spot",!1)&&(n=o.Y.stringMul(n,"100")));let d=this.safeString2(e,"vol","baseVolume"),h=this.safeString2(e,"volValue","quoteVolume"),c=this.safeIntegerN(e,["time","datetime","timePoint"]);return this.safeTicker({symbol:a,timestamp:c,datetime:this.iso8601(c),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeStringN(e,["buy","bestBid","bestBidPrice"]),bidVolume:this.safeString(e,"bestBidSize"),ask:this.safeStringN(e,["sell","bestAsk","bestAskPrice"]),askVolume:this.safeString(e,"bestAskSize"),vwap:void 0,open:this.safeString(e,"open"),close:i,last:i,previousClose:void 0,change:this.safeString2(e,"changePrice","priceChange"),percentage:n,average:this.safeString(e,"averagePrice"),baseVolume:d,quoteVolume:h,markPrice:this.safeString2(e,"markPrice","value"),indexPrice:this.safeString(e,"indexPrice"),info:e},r)}parseTicker(e,t){return this.parseContractTicker(e,t)}parseContractTicker(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t,"-"),a=this.safeString2(e,"price","lastTradePrice"),n=this.safeIntegerProduct(e,"ts",1e-6),d=this.safeString(e,"priceChg");return(void 0===a||void 0===d)&&(i=o.Y.stringMul(this.safeString(e,"priceChgPct"),"100")),this.safeTicker({symbol:r.symbol,timestamp:n,datetime:this.iso8601(n),high:this.safeString(e,"highPrice"),low:this.safeString(e,"lowPrice"),bid:this.safeString(e,"bestBidPrice"),bidVolume:this.safeString(e,"bestBidSize"),ask:this.safeString(e,"bestAskPrice"),askVolume:this.safeString(e,"bestAskSize"),vwap:void 0,open:void 0,close:a,last:a,previousClose:void 0,change:d,percentage:i,average:void 0,baseVolume:this.safeString(e,"volumeOf24h"),quoteVolume:this.safeString(e,"turnoverOf24h"),markPrice:this.safeString2(e,"markPrice","value"),indexPrice:this.safeString(e,"indexPrice"),info:e},r)}typeToTradeType(e){if(void 0!==e)return this.safeString({spot:"SPOT",margin:"MARGIN",swap:"FUTURES"},e,e)}async fetchTickers(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r={},a=this.marketSymbols(e,void 0,!0,!0),[o,n]=this.handleOptionBoolAndParams(t,"fetchTickers","uta",!1),d=this.safeString(n,"tradeType");if(void 0!==a){let e=this.safeString(a,0);void 0!==e&&(s=this.market(e))}let[h,c]=this.handleMarketTypeAndParams("fetchTickers",s,n);if(void 0!==d||o)void 0===d&&(r.tradeType=this.typeToTradeType(h)),i=await this.utaGetMarketTicker(this.extend(r,c));else{if("spot"!==h&&"margin"!==h)return await this.fetchContractTickers(a,c);i=await this.publicGetMarketAllTickers(c)}let l=this.safeDict(i,"data",{}),u=this.safeList2(l,"ticker","list",[]),f=this.safeInteger2(l,"time","ts"),p={};for(let e=0;e<u.length;e++){u[e].time=f;let t=this.parseSpotOrUtaTicker(u[e]),i=this.safeString(t,"symbol");void 0!==i&&(p[i]=t)}return this.filterByArrayTickers(p,"symbol",a)}async fetchContractTickers(e,t={}){let i,[s,r]=this.handleOptionStringAndParams(t,"fetchTickers","method","futuresPublicGetContractsActive");i="futuresPublicGetAllTickers"===s?await this.futuresPublicGetAllTickers(r):await this.futuresPublicGetContractsActive(r);let a=this.safeList(i,"data"),o=this.parseTickers(a,e);return this.filterByArrayTickers(o,"symbol",e)}async fetchMarkPrices(e,t={}){void 0===this.markets&&await this.loadMarkets(),this.marketSymbols(e);let i=await this.publicGetMarkPriceAllSymbols(t),s=this.safeList(i,"data",[]);return this.parseTickers(s)}async fetchTicker(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id},[o,n]=this.handleOptionBoolAndParams(t,"fetchTicker","uta",!1),[d,h]=this.handleMarketTypeAndParams("fetchTicker",r,n);if(o){a.tradeType=this.typeToTradeType(d),i=await this.utaGetMarketTicker(this.extend(a,h));let e=this.safeDict(i,"data",{}),t=this.safeList(e,"list",[]);s=this.safeDict(t,0,{})}else if(!0===r.contract){i=await this.futuresPublicGetTicker(this.extend(a,h));let e=this.safeDict(i,"data",{});return this.parseTicker(e,r)}else i=await this.publicGetMarketStats(this.extend(a,h)),s=this.safeDict(i,"data",{});return this.parseSpotOrUtaTicker(s,r)}async fetchMarkPrice(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};if(!0===s.contract){i=await this.futuresPublicGetMarkPriceSymbolCurrent(this.extend(r,t));let e=this.safeDict(i,"data",{});return this.parseTicker(e,s)}{i=await this.publicGetMarkPriceSymbolCurrent(this.extend(r,t));let e=this.safeDict(i,"data",{});return this.parseSpotOrUtaTicker(e,s)}}parseOHLCV(e,t){let i=this.safeString(e,0);return void 0!==i&&i.length<=10?[this.safeTimestamp(e,0),this.safeNumber(e,1),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,2),this.safeNumber(e,5)]:[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]}async fetchOHLCV(e,t="1m",i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=!1;return([n,a]=this.handleOptionBoolAndParams(r,"fetchOHLCV","uta",n),void 0===this.safeString(a,"price")||n||(n=!0),n)?await this.fetchUTAOHLCV(e,t,i,s,a):!0===o.contract?await this.fetchContractOHLCV(e,t,i,s,a):await this.fetchSpotOHLCV(e,t,i,s,a)}async fetchUTAOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(o)return await this.fetchPaginatedCallDeterministic("fetchUTAOHLCV",e,i,s,t,n,1500);let d=this.market(e),h={symbol:d.id,interval:this.safeString(this.timeframes,t,t)},c=1e3*this.parseTimeframe(t),l=this.milliseconds(),u=void 0===s?this.safeInteger(this.options,"fetchOHLCVLimit",1500):s,f=void 0!==i?u:s,p=i;void 0===i&&void 0!==s&&(p=l-s*c),void 0!==i?(h.startAt=this.parseToInt(Math.floor(i/1e3)),l=this.sum(i,u*c)):void 0!==s&&(h.startAt=this.parseToInt(Math.floor((l-s*c)/1e3))),h.endAt=this.parseToInt(Math.floor(l/1e3));let[m,g]=this.handleMarketTypeAndParams("fetchOHLCV",d,n);"spot"===m||"margin"===m?h.tradeType="SPOT":h.tradeType="FUTURES";let[v,y]=this.handleOptionStringAndParams(g,"fetchOHLCV","price",void 0);if(void 0!==v){let e=this.safeString({mark:"mark-price",index:"index-price",premiumIndex:"premium-index"},v);if(void 0===e)throw new a.NotSupported(this.id+' fetchOHLCV() price parameter must be one of "mark", "index", or "premiumIndex"');h.symbol=d.id+"-"+e}let b=await this.utaGetMarketKline(this.extend(h,y)),w=this.safeDict(b,"data",{}),k=this.safeList(w,"list",[]);return this.parseOHLCVs(k,d,t,p,f)}async fetchSpotOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchSpotOHLCV",e,i,s,t,o,1500);let n=this.market(e),d={symbol:n.id,type:this.safeString(this.timeframes,t,t)},h=1e3*this.parseTimeframe(t),c=this.milliseconds(),l=void 0===s?this.safeInteger(this.options,"fetchOHLCVLimit",1500):s,u=void 0!==i?l:s,f=i;void 0===i&&void 0!==s&&(f=c-s*h),void 0!==i?(d.startAt=this.parseToInt(Math.floor(i/1e3)),c=this.sum(i,l*h)):void 0!==s&&(d.startAt=this.parseToInt(Math.floor((c-s*h)/1e3))),d.endAt=this.parseToInt(Math.floor(c/1e3));let p=await this.publicGetMarketCandles(this.extend(d,o)),m=this.safeList(p,"data",[]);return this.parseOHLCVs(m,n,t,f,u)}async fetchContractOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchContractOHLCV",e,i,s,t,o,200);let n=this.market(e),d={symbol:n.id},h=this.safeDict(this.options,"timeframes",{}),c=this.safeDict(h,"swap",{}),l=this.safeInteger(c,t);void 0!==l?d.granularity=l:d.granularity=t;let u=1e3*this.parseTimeframe(t),f=this.milliseconds(),p=void 0===s?this.safeInteger(this.options,"fetchOHLCVLimit",200):s,m=void 0!==i?p:s,g=i;void 0===i&&void 0!==s&&(g=f-s*u),void 0!==i?(d.from=i,f=this.sum(i,p*u)):void 0!==s&&(d.from=g),d.to=f;let v=await this.futuresPublicGetKlineQuery(this.extend(d,o)),y=this.safeList(v,"data",[]);return this.parseOHLCVs(y,n,t,g,m)}async createDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={currency:i.id},[r,a]=this.handleNetworkCodeAndParams(t);void 0!==r&&(s.chain=this.networkCodeToId(r,this.safeString(i,"code")));let o=await this.privatePostDepositAddressCreate(this.extend(s,a)),n=this.safeDict(o,"data",{});return this.parseDepositAddress(n,i)}async fetchDepositAddress(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r="main";[r,i]=this.handleOptionStringAndParams(t,"fetchDepositAddress","accountType",r);let o=this.safeDict(this.options,"accountsByType",{});r=this.safeString(o,r,r);let n=await this.isUTAEnabled();if([n,i]=this.handleOptionBoolAndParams(i,"fetchDepositAddress","uta",n),"contract"===r)return await this.fetchContractDepositAddress(e,i);if(n||"uta"===r||"unified"===r)return await super.fetchDepositAddress(e,this.extend(i,{uta:!0}));let d=this.currency(e),h={currency:d.id};if([s,i]=this.handleNetworkCodeAndParams(i),void 0!==s){let e=this.networkCodeToId(s,this.safeString(d,"code"));void 0!==e&&(h.chain=e.toLowerCase())}let c=this.options.versions.private.GET["deposit-addresses"];this.options.versions.private.GET["deposit-addresses"]="v1";let l=await this.privateGetDepositAddresses(this.extend(h,i));this.options.versions.private.GET["deposit-addresses"]=c;let u=this.safeDict(l,"data");if(void 0===u)throw new a.ExchangeError(this.id+" fetchDepositAddress() returned an empty response, you might try to run createDepositAddress() first and try again");return this.parseDepositAddress(u,d)}async fetchContractDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e).id,s=await this.futuresPrivateGetDepositAddress(this.extend({currency:i},t)),r=this.safeDict(s,"data",{}),a=this.safeString(r,"address");return"NIM"!==i&&this.checkAddress(a),{info:s,currency:i,network:this.safeString(r,"chain"),address:a,tag:this.safeString(r,"memo")}}parseDepositAddress(e,t){let i,s=this.safeString(e,"address");void 0!==s&&(s=s.replace("bitcoincash:","")),void 0!==t&&"NIM"!==(i=this.safeCurrencyCode(t.id))&&this.checkAddress(s);let r=this.safeString(e,"chainId");return{info:e,currency:i,network:this.networkIdToCode(r,i),address:s,tag:this.safeString(e,"memo")}}async fetchDepositAddressesByNetwork(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),a={currency:r.id},o=await this.isUTAEnabled();if([o,i]=this.handleOptionBoolAndParams(t,"fetchDepositAddressesByNetwork","uta",o),o){let t;if([t,i]=this.handleNetworkCodeAndParams(i),void 0!==t){let i=this.networkCodeToId(t,e);void 0!==i&&(a.chain=i.toLowerCase())}s=await this.utaPrivateGetAssetDepositAddress(this.extend(a,i))}else{let e=this.options.versions.private.GET["deposit-addresses"];this.options.versions.private.GET["deposit-addresses"]="v2",s=await this.privateGetDepositAddresses(this.extend(a,i)),this.options.versions.private.GET["deposit-addresses"]=e}let n=this.safeList(s,"data",[]),d=this.parseDepositAddresses(n,[r.code],!1,{currency:r.code});return this.indexBy(d,"network")}async fetchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o=this.safeInteger(i,"level",2),n={symbol:r.id},d=this.checkRequiredCredentials(!1),[h,c]=this.handleOptionBoolAndParams(i,"fetchOrderBook","uta",!1),[l,u]=this.handleMarketTypeAndParams("fetchOrderBook",r,c);if(h){let e="20";void 0===t||t>=100?e="FULL":t>20&&(e="100"),n.limit=e,n.symbol=r.id,"spot"===l||"margin"===l?n.tradeType="SPOT":n.tradeType="FUTURES",s=await this.utaPrivateGetMarketOrderbook(this.extend(n,u))}else if("spot"!==l&&"margin"!==l){if(2!==o&&void 0!==o)throw new a.BadRequest(this.id+" fetchOrderBook() can only return level 2");if(void 0===t)s=await this.futuresPublicGetLevel2Snapshot(this.extend(n,u));else if(20===t)s=await this.futuresPublicGetLevel2Depth20(this.extend(n,u));else if(100===t)s=await this.futuresPublicGetLevel2Depth100(this.extend(n,u));else throw new a.BadRequest(this.id+" fetchOrderBook() limit argument must be 20 or 100")}else if(d&&void 0===t)s=await this.privateGetMarketOrderbookLevel2(this.extend(n,u));else{if(2===o){if(n.level=o,void 0!==t)if(20===t||100===t)n.limit=t;else throw new a.ExchangeError(this.id+" fetchOrderBook() limit argument must be 20 or 100");n.limit=void 0!==t?t:100}s=await this.publicGetMarketOrderbookLevelLevelLimit(this.extend(n,u))}let f=this.safeDict(s,"data",{}),p=this.safeInteger(f,"time");if(void 0===p){let e=this.safeInteger(f,"ts");void 0!==e&&(p=this.parseToInt(e/1e6))}let m=this.parseOrderBook(f,r.symbol,p,"bids","asks",o-2,o-1);return m.nonce=this.safeInteger(f,"sequence"),m}handleTriggerPrices(e){let t=this.safeNumber2(e,"triggerPrice","stopPrice"),i=this.safeNumber(e,"stopLossPrice"),s=this.safeNumber(e,"takeProfitPrice"),r=void 0!==s;if(void 0!==i&&r||void 0!==t&&void 0!==i||void 0!==t&&r)throw new a.ExchangeError(this.id+" createOrder() - you should use either triggerPrice or stopLossPrice or takeProfitPrice");return[t,i,s]}async createOrder(e,t,i,s,r,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=await this.isUTAEnabled(),[h,c]=this.handleOptionBoolAndParams(o,"createOrder","uta",d);if(h)return await this.createUtaOrder(e,t,i,s,r,c);if(!0===n.spot)return await this.createSpotOrder(e,t,i,s,r,c);if(!0===n.contract)return await this.createContractOrder(e,t,i,s,r,c);throw new a.NotSupported(this.id+" createOrder() does not support market "+n.type)}async createSpotOrder(e,t,i,s,r,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=this.safeBool(a,"test",!1),h=this.omit(a,"test"),[c,l]=this.handleHfAndParams(h),[u,f]=this.handleOptionBoolAndParams(l,"createOrder","sync",!1),[p,m,g]=this.handleTriggerPrices(f),v=this.safeString(f,"tradeType"),y=this.handleMarginModeAndParams("createOrder",f)[0],b="MARGIN_TRADE"===v||void 0!==y,w=this.createSpotOrderRequest(e,t,i,s,r,f);o=!0===d?b?!0===c?await this.privatePostHfMarginOrderTest(w):await this.privatePostMarginOrderTest(w):!0===c?await this.privatePostHfOrdersTest(w):await this.privatePostOrdersTest(w):void 0!==p||void 0!==m||void 0!==g?b?await this.privatePostHfMarginStopOrder(w):await this.privatePostStopOrder(w):b?!0===c?await this.privatePostHfMarginOrder(w):await this.privatePostMarginOrder(w):u?await this.privatePostHfOrdersSync(w):!0===c?await this.privatePostHfOrders(w):await this.privatePostOrders(w);let k=this.safeDict(o,"data",{});return this.parseOrder(k,n)}createSpotOrderRequest(e,t,i,s,r,o={}){let n,d;if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let h=this.market(e),c=this.safeString2(o,"clientOid","clientOrderId",this.uuid()),l=this.omit(o,["clientOid","clientOrderId"]),u={clientOid:c,side:i,symbol:h.id,type:t},f=this.safeNumber2(l,"cost","funds");[n,l]=this.handleMarginModeAndParams("createOrder",l),"market"===t?void 0!==f?(l=this.omit(l,["cost","funds"]),u.funds=this.marketOrderAmountToPrecision(e,f)):(this.amountToPrecision(e,s),u.size=this.amountToPrecision(e,s)):(u.size=this.amountToPrecision(e,s),u.price=this.priceToPrecision(e,r));let p=this.safeString(l,"tradeType"),[m,g,v]=this.handleTriggerPrices(l),y=void 0!==m||void 0!==g||void 0!==v;if(l=this.omit(l,["stopLossPrice","takeProfitPrice","triggerPrice","stopPrice"]),y){if(void 0!==m?u.stopPrice=this.priceToPrecision(e,m):(void 0!==g||void 0!==v)&&(void 0!==g?(u.stop="buy"===i?"entry":"loss",u.stopPrice=this.priceToPrecision(e,g)):(u.stop="buy"===i?"loss":"entry",u.stopPrice=this.priceToPrecision(e,v))),"isolated"===n)throw new a.BadRequest(this.id+" createOrder does not support isolated margin for stop orders");"cross"===n&&(u.tradeType=this.options.marginModes[n])}else("MARGIN_TRADE"===p||void 0!==n)&&"isolated"===n&&(u.marginModel="isolated");return[d,l]=this.handlePostOnly("market"===t,!1,l),!0===d&&(u.postOnly=!0),this.extend(u,l)}marketOrderAmountToPrecision(e,t){let i=this.market(e),s=this.decimalToPrecision(t,0,i.info.quoteIncrement,this.precisionMode,this.paddingMode);if("0"===s)throw new a.InvalidOrder(this.id+" amount of "+i.symbol+" must be greater than minimum amount precision of "+this.numberToString(i.precision.amount));return s}async createContractOrder(e,t,i,s,r,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=this.safeBool(a,"test",!1),h=this.omit(a,"test"),c=void 0!==this.safeValue(h,"stopLoss")||void 0!==this.safeValue(h,"takeProfit"),l=this.createContractOrderRequest(e,t,i,s,r,h);o=!0===d?await this.futuresPrivatePostOrdersTest(l):c?await this.futuresPrivatePostStOrders(l):await this.futuresPrivatePostOrders(l);let u=this.safeDict(o,"data",{});return this.parseOrder(u,n)}createContractOrderRequest(e,t,i,s,r,o={}){let n,d;if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let h=this.market(e),c=this.safeString2(o,"clientOid","clientOrderId",this.uuid()),l=this.omit(o,["clientOid","clientOrderId"]),u={clientOid:c,side:i,symbol:h.id,type:t,leverage:1},f=this.safeStringUpper(l,"marginMode"),p=void 0!==f?this.omit(l,"marginMode"):l;void 0!==f&&(u.marginMode=f);let m=this.safeString(p,"cost");if(p=this.omit(p,"cost"),void 0!==m)u.valueQty=this.costToPrecision(e,m);else{if(void 0===s)throw new a.ArgumentsRequired(this.id+" requires an amount argument");if(s<1)throw new a.InvalidOrder(this.id+" createOrder() minimum contract order amount is 1");let t=this.amountToPrecision(e,s);void 0!==t&&(u.size=parseInt(t))}let[g,v,y]=this.handleTriggerPrices(p),b=this.safeDict(p,"stopLoss"),w=this.safeDict(p,"takeProfit"),k=void 0!==b,S=void 0!==w,O={mark:"MP",last:"TP",index:"IP"},T=this.safeString(p,"triggerPriceType","mark"),P=this.safeString(O,T,T);if(p=this.omit(p,["stopLossPrice","takeProfitPrice","triggerPrice","stopPrice","takeProfit","stopLoss"]),void 0!==g)u.stop="buy"===i?"up":"down",u.stopPrice=this.priceToPrecision(e,g),u.stopPriceType=P;else if(k||S){let t=P;if(k){let i=this.safeString2(b,"triggerPrice","stopPrice");u.triggerStopDownPrice=this.priceToPrecision(e,i),t=this.safeString(b,"triggerPriceType","mark"),t=this.safeString(O,t,t)}if(S){let i=this.safeString2(w,"triggerPrice","takeProfitPrice");u.triggerStopUpPrice=this.priceToPrecision(e,i),t=this.safeString(w,"triggerPriceType","mark"),t=this.safeString(O,t,t)}u.stopPriceType=t}else(void 0!==v||void 0!==y)&&(void 0!==v?(u.stop="buy"===i?"up":"down",u.stopPrice=this.priceToPrecision(e,v)):(u.stop="buy"===i?"down":"up",u.stopPrice=this.priceToPrecision(e,y)),u.reduceOnly=!0,u.stopPriceType=P);let I=t.toUpperCase(),A=this.safeStringUpper(p,"timeInForce");if("LIMIT"===I){if(void 0===r)throw new a.ArgumentsRequired(this.id+" createOrder() requires a price argument for limit orders");u.price=this.priceToPrecision(e,r),void 0!==A&&(u.timeInForce=A)}[n,p]=this.handlePostOnly("market"===t,!1,p),!0===n&&(u.postOnly=!0);let x=this.safeValue(p,"hidden");if(!0===n&&void 0!==x)throw new a.BadRequest(this.id+" createOrder() does not support the postOnly parameter together with a hidden parameter");let M=this.safeValue(p,"iceberg");if(void 0!==M&&!1!==M&&void 0===this.safeString(p,"visibleSize"))throw new a.ArgumentsRequired(this.id+" createOrder() requires a visibleSize parameter for iceberg orders");let _=this.safeBool(p,"reduceOnly",!1);if([d,p]=this.handleParamBool(p,"hedged",!1),!0===_){if(u.reduceOnly=_,!0===d){let e="SHORT";"sell"===i&&(e="LONG"),u.positionSide=e}}else if(!0===d){let e="SHORT";"buy"===i&&(e="LONG"),u.positionSide=e}return p=this.omit(p,["timeInForce","stopPrice","triggerPrice","stopLossPrice","takeProfitPrice","reduceOnly","hedged"]),this.extend(u,p)}async createUtaOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=this.createUtaOrderRequest(e,t,i,s,r,a),d=await this.utaPrivatePostAccountModeOrderPlace(n),h=this.safeDict(d,"data",{});return this.parseOrder(h,o)}createUtaOrderRequest(e,t,i,s,r,o={}){let n,d,h;if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");let c=this.market(e);if(void 0===i)throw new a.ArgumentsRequired(this.id+" createOrder() requires a side argument");let l=c.spot,u=c.contract,f="unified";[f,n]=this.handleOptionStringAndParams(o,"createOrder","accountMode",f);let p="unified"===f;[d,n]=this.handleMarginModeAndParams("createOrder",n);let m=this.handleTradeType(u,d,p,n),g=this.safeString2(n,"clientOid","clientOrderId",this.uuid());n=this.omit(n,["clientOid","clientOrderId"]);let v={accountMode:f,tradeType:m,clientOid:g,symbol:c.id,side:i.toUpperCase(),orderType:t.toUpperCase()};void 0!==m&&(v.tradeType=m),v.clientOid=g;let y="market"===t,b=this.safeString(n,"cost");if(void 0!==b)if(n=this.omit(n,"cost"),!0===l&&y)v.sizeUnit="QUOTECCY",v.size=this.marketOrderAmountToPrecision(e,b);else throw new a.NotSupported(this.id+" createOrder() with cost is supported for spot market orders only");else{let t="BASECCY";!0===u&&([t,n]=this.handleOptionStringAndParams(n,"createOrder","sizeUnit","UNIT")),v.sizeUnit=t,v.size=this.amountToPrecision(e,s)}y||(v.price=this.priceToPrecision(e,r)),[h,n]=this.handlePostOnly(y,!1,n);let w=this.handleTimeInForce(n),k=void 0!==w?this.omit(n,"timeInForce"):n;if(void 0!==w&&(v.timeInForce=w),!0===h&&(v.postOnly=!0),!0===u&&!p){void 0!==d&&(v.marginMode=d.toUpperCase(),"isolated"===d&&void 0===this.safeInteger(k,"leverage")&&(v.leverage=1));let e=this.safeBool(k,"reduceOnly",!1),t=!1;if([t,k]=this.handleParamBool(k,"hedged",t),!0===t){let t="SHORT";"buy"===i&&(t="LONG"),!0===e&&(t="LONG"===t?"SHORT":"LONG"),v.positionSide=t}}let[S,O,T]=this.handleTriggerPrices(k),P=this.safeDict(k,"stopLoss"),I=this.safeDict(k,"takeProfit"),A=void 0!==P,x=void 0!==I,M={mark:"MP",last:"TP",index:"IP"};if(void 0!==S){let t=this.safeString(k,"triggerDirection");if(void 0===t)throw new a.ArgumentsRequired(this.id+" createOrder() requires a triggerDirection parameter for trigger orders. Provide params.tringgerDirection or use params.stopLossPrice or params.takeProfitPrice instead of params.triggerPrice");v.triggerDirection="ascending"===t?"UP":"DOWN",v.triggerPrice=this.priceToPrecision(e,S)}else if(A||x){if(!0!==u)throw new a.NotSupported(this.id+" createOrder() stopLoss and takeProfit parameters are only supported for contract orders");if(A){let t=this.safeString2(P,"triggerPrice","stopPrice"),i=this.safeString(P,"triggerPriceType","mark");v.slTriggerPrice=this.priceToPrecision(e,t),v.slTriggerPriceType=this.safeString(M,i,i)}if(x){let t=this.safeString2(I,"triggerPrice","takeProfitPrice"),i=this.safeString(I,"triggerPriceType","mark");v.tpTriggerPrice=this.priceToPrecision(e,t),v.tpTriggerPriceType=this.safeString(M,i,i)}}else if(void 0!==O||void 0!==T){if(void 0!==O){if(v.triggerDirection="buy"===i?"UP":"DOWN",v.triggerPrice=this.priceToPrecision(e,O),!0===u){let e=this.safeString2(k,"stopLossPriceType","triggerPriceType","mark");v.triggerPriceType=this.safeString(M,e,e)}}else if(v.triggerDirection="buy"===i?"DOWN":"UP",v.triggerPrice=this.priceToPrecision(e,T),!0===u){let e=this.safeString2(k,"takeProfitPriceType","triggerPriceType","mark");v.triggerPriceType=this.safeString(M,e,e)}}return k=this.omit(k,["triggerPrice","stopLossPrice","takeProfitPrice","stopPriceType","stopLossPriceType","takeProfitPriceType","triggerPriceType","triggerDirection","stopLoss","takeProfit","hedged"]),this.extend(v,k)}async createMarketOrderWithCost(e,t,i,s={}){return void 0===this.markets&&await this.loadMarkets(),await this.createOrder(e,"market",t,i,void 0,this.extend({cost:i},s))}async createMarketBuyOrderWithCost(e,t,i={}){return void 0===this.markets&&await this.loadMarkets(),await this.createMarketOrderWithCost(e,"buy",t,i)}async createMarketSellOrderWithCost(e,t,i={}){return void 0===this.markets&&await this.loadMarkets(),await this.createMarketOrderWithCost(e,"sell",t,i)}async createOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=!1,s=!1;for(let t=0;t<e.length;t++){let r=this.safeDict(e,t),o=this.safeString(r,"symbol");if(void 0===o)throw new a.ArgumentsRequired(this.id+" createOrders() requires a symbol for each order");let n=this.market(o);!0===n.spot?i=!0:!0===n.contract&&(s=!0)}if(i&&s)throw new a.BadRequest(this.id+" createOrders() requires all orders to be either spot or contract");if(i)return await this.createSpotOrders(e,t);if(s)return await this.createContractOrders(e,t);throw new a.NotSupported(this.id+" createOrders() does not support the markets of the orders provided")}async createSpotOrders(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=[];for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),o=this.safeString(i,"symbol");if(void 0===o)throw new a.ArgumentsRequired(this.id+" createOrders() requires a symbol for each order");if(void 0===s)s=o;else if(s!==o)throw new a.BadRequest(this.id+" createOrders() requires all orders to have the same symbol");let n=this.safeString(i,"type");if("limit"!==n)throw new a.BadRequest(this.id+" createOrders() only supports limit orders");let d=this.safeString(i,"side"),h=this.safeValue(i,"amount"),c=this.safeValue(i,"price"),l=this.safeDict(i,"params",{}),u=this.createSpotOrderRequest(o,n,d,h,c,l);r.push(u)}if(void 0===s)throw new a.ArgumentsRequired(this.id+" createOrders() requires at least one order with a symbol");let o={symbol:this.market(s).id,orderList:r},[n,d]=this.handleHfAndParams(t),[h,c]=this.handleOptionBoolAndParams(d,"createOrders","sync",!1);i=h?await this.privatePostHfOrdersMultiSync(this.extend(o,c)):!0===n?await this.privatePostHfOrdersMulti(this.extend(o,c)):await this.privatePostOrdersMulti(this.extend(o,c));let l=this.safeDict(i,"data",{});return l=this.safeList(l,"data",[]),this.parseOrders(l)}async createContractOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=[];for(let t=0;t<e.length;t++){let s=this.safeDict(e,t),r=this.safeString(s,"symbol");if(void 0===r)throw new a.ArgumentsRequired(this.id+" createOrders() requires a symbol for each order");let o=this.safeString(s,"type",""),n=this.safeString(s,"side"),d=this.safeValue(s,"amount"),h=this.safeValue(s,"price"),c=this.safeDict(s,"params",{}),l=this.createContractOrderRequest(r,o,n,d,h,c);i.push(l)}let s=await this.futuresPrivatePostOrdersMulti(i),r=this.safeList(s,"data",[]);return this.parseOrders(r)}async editOrder(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(t),d={symbol:n.id},h=this.safeString2(o,"clientOid","clientOrderId");void 0!==h?d.clientOid=h:d.orderId=e,void 0!==r&&(d.newSize=this.amountToPrecision(t,r)),void 0!==a&&(d.newPrice=this.priceToPrecision(t,a));let c=await this.privatePostHfOrdersAlter(this.extend(d,o)),l=this.safeDict(c,"data",{});return this.parseOrder(l,n)}async cancelOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=await this.isUTAEnabled(),[a,o]=this.handleOptionBoolAndParams(i,"cancelOrder","uta",r);if(a)return await this.cancelUtaOrder(e,t,o);void 0!==t&&(s=this.market(t));let[n,d]=this.handleMarketTypeAndParams("cancelOrder",s,o);return"spot"===n||"margin"===n?await this.cancelSpotOrder(e,t,d):await this.cancelContractOrder(e,t,d)}async cancelSpotOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r={},o=this.safeString2(i,"clientOid","clientOrderId"),n=this.safeBool2(i,"stop","trigger",!1),[d,h]=this.handleHfAndParams(i),[c,l]=this.handleOptionBoolAndParams(h,"cancelOrder","sync",!1),[u,f]=this.handleMarginModeAndParams("cancelOrder",l),p="MARGIN_TRADE"===this.safeString(f,"tradeType")||void 0!==u;if((!0===d||c||p)&&!0!==n){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol parameter for hf orders");r.symbol=this.market(t).id}let m=this.omit(f,["clientOid","clientOrderId","stop","trigger","tradeType"]);if(void 0!==o){if(r.clientOid=o,!0===n)if(p){s=await this.privateDeleteHfMarginStopOrderCancelByClientOid(this.extend(r,m));let e=this.safeDict(s,"data"),t=this.safeList(e,"cancelledOrderIds",[]),i=this.safeString(t,0);return this.safeOrder({info:e,id:i})}else s=await this.privateDeleteStopOrderCancelOrderByClientOid(this.extend(r,m));else s=p?await this.privateDeleteHfMarginOrdersClientOrderClientOid(this.extend(r,m)):c?await this.privateDeleteHfOrdersSyncClientOrderClientOid(this.extend(r,m)):!0===d?await this.privateDeleteHfOrdersClientOrderClientOid(this.extend(r,m)):await this.privateDeleteOrderClientOrderClientOid(this.extend(r,m));return s=this.safeDict(s,"data"),this.parseOrder(s)}{if(r.orderId=e,!0===n)s=p?await this.privateDeleteHfMarginStopOrderCancelById(this.extend(r,m)):await this.privateDeleteStopOrderOrderId(this.extend(r,m));else if(p)s=await this.privateDeleteHfMarginOrdersOrderId(this.extend(r,m));else if(c)s=await this.privateDeleteHfOrdersSyncOrderId(this.extend(r,m));else{if(!0===d)return s=await this.privateDeleteHfOrdersOrderId(this.extend(r,m)),s=this.safeDict(s,"data",{}),this.parseOrder(s);s=await this.privateDeleteOrdersOrderId(this.extend(r,m))}let t=this.safeDict(s,"data"),i=this.safeString(t,"orderId"),a=this.safeList(t,"cancelledOrderIds",[]);return i=this.safeString(a,0,i),this.safeOrder({info:t,id:i})}}async cancelContractOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.safeString2(i,"clientOid","clientOrderId"),o=this.omit(i,["clientOrderId"]),n={};if(void 0!==r){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument when cancelling by clientOrderId");n.symbol=this.market(t).id,n.clientOid=r,s=await this.futuresPrivateDeleteOrdersClientOrderClientOid(this.extend(n,o))}else n.orderId=e,s=await this.futuresPrivateDeleteOrdersOrderId(this.extend(n,o));return this.safeOrder({info:s})}async cancelUtaOrder(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument for uta endpoint");void 0===this.markets&&await this.loadMarkets();let r={},o=this.safeString2(i,"clientOid","clientOrderId"),n=void 0!==o?this.omit(i,["clientOid","clientOrderId"]):i;if(void 0!==o)r.clientOid=o;else{if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires an id argument or clientOrderId parameter");r.orderId=e}void 0===this.markets&&await this.loadMarkets();let d=this.market(t);r.symbol=d.id;let h="unified";[h,n]=this.handleOptionStringAndParams(n,"cancelOrder","accountMode",h),r.accountMode=h,[s,n]=this.handleMarginModeAndParams("cancelOrder",n);let c="unified"===h;r.tradeType=this.handleTradeType(d.contract,s,c,n);let l=await this.utaPrivatePostAccountModeOrderCancel(this.extend(r,n)),u=this.safeDict(l,"data",{});return this.parseOrder(u,d)}async cancelAllOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=await this.isUTAEnabled(),[r,a]=this.handleOptionBoolAndParams(t,"cancelAllOrders","uta",s);if(r)return await this.cancelAllUtaOrders(e,a);void 0!==e&&(i=this.market(e));let[o,n]=this.handleMarketTypeAndParams("cancelAllOrders",i,a);return"spot"===o||"margin"===o?await this.cancelAllSpotOrders(e,n):await this.cancelAllContractOrders(e,n)}async cancelAllSpotOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={},r=this.safeBool2(t,"trigger","stop",!1),[o,n]=this.handleHfAndParams(t),d=this.omit(n,["stop","trigger"]),[h,c]=this.handleMarginModeAndParams("cancelAllOrders",d),l=void 0!==h;if(void 0!==e)s.symbol=this.marketId(e);else if(!0!==r&&l)throw new a.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument for margin non-trigger orders");if(l&&(s.tradeType=this.options.marginModes[h],"isolated"===h&&!0===r))throw new a.BadRequest(this.id+" cancelAllOrders does not support isolated margin for stop orders");return i=!0===r?l?await this.privateDeleteHfMarginStopOrderCancel(this.extend(s,c)):await this.privateDeleteStopOrderCancel(this.extend(s,c)):l?await this.privateDeleteHfMarginOrders(this.extend(s,c)):!0===o?void 0===e?await this.privateDeleteHfOrdersCancelAll(this.extend(s,c)):await this.privateDeleteHfOrders(this.extend(s,c)):await this.privateDeleteOrders(this.extend(s,c)),[this.safeOrder({info:i})]}async cancelAllContractOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={};void 0!==e&&(s.symbol=this.marketId(e));let r=this.safeValue2(t,"stop","trigger"),a=this.omit(t,["stop","trigger"]);i=void 0!==r&&!1!==r?await this.futuresPrivateDeleteStopOrders(this.extend(s,a)):await this.futuresPrivateDeleteOrders(this.extend(s,a));let o=this.safeDict(i,"data");return[this.safeOrder({info:o})]}async cancelAllUtaOrders(e,t={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument for uta endpoint");void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.contract,r="SPOT";!0===s&&(r="FUTURES");let[o,n]=this.handleParamBool(t,"trigger",!1),d="NORMAL";!0===o&&(d="ADVANCED");let h={accountMode:"unified",symbol:i.id,tradeType:r,orderFilter:d},c=await this.utaPrivatePostAccountModeOrderCancelAll(this.extend(h,n)),l=this.safeDict(c,"data",{}),u=this.safeList(l,"items",[]);return this.parseOrders(u,i,void 0,void 0,{status:"canceled"})}async fetchOrdersByStatus(e,t,i,s,r={}){let a,o;void 0===this.markets&&await this.loadMarkets();let n=await this.isUTAEnabled();if([n,a]=this.handleOptionBoolAndParams(r,"fetchOrdersByStatus","uta",n),void 0===t){let e=this.safeString(a,"type");if("spot"===e||"margin"===e||"swap"===e||"future"===e||"contract"===e)o=e,a=this.omit(a,"type");else{let e=this.safeDict(this.options,"fetchOrdersByStatus",{}),t=this.safeString2(e,"defaultType","type");o=void 0===t?this.safeString2(this.options,"defaultType","type","spot"):t}}else o=this.market(t).type;return n?(a=this.omit(a,"uta"),a=this.extend(a,{marketType:o}),await this.fetchUtaOrdersByStatus(e,t,i,s,a)):"spot"===o||"margin"===o?await this.fetchSpotOrdersByStatus(e,t,i,s,a):await this.fetchContractOrdersByStatus(e,t,i,s,a)}async fetchSpotOrdersByStatus(e,t,i,s,r={}){let o,n;void 0===this.markets&&await this.loadMarkets();let d=e.toLowerCase(),h=this.safeInteger(r,"until"),c=this.safeBool2(r,"stop","trigger",!1),[l,u]=this.handleHfAndParams(r);if(!0===l&&void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrdersByStatus() requires a symbol parameter for hf orders");let f=this.omit(u,["stop","trigger","till","until"]),[p,m]=this.handleMarginModeAndParams("fetchOrdersByStatus",f),g=void 0!==p;"open"===d?d="active":"closed"===d&&(d="done");let v={};void 0!==t&&(v.symbol=(o=this.market(t)).id),v.tradeType=this.safeString(this.options.marginModes,p,"TRADE"),g&&"active"===d&&!0!==c?n=await this.privateGetHfMarginOrdersActive(this.extend(v,m)):(g||(v.status=d),void 0!==i&&(v.startAt=i),void 0!==s&&(v.pageSize=s),void 0!==h&&0!==h&&(v.endAt=h),!0===c?n=g?await this.privateGetHfMarginStopOrders(this.extend(v,m)):await this.privateGetStopOrder(this.extend(v,m)):g?n=await this.privateGetHfMarginOrdersDone(this.extend(v,m)):!0===l?"active"===d?n=await this.privateGetHfOrdersActive(this.extend(v,m)):"done"===d&&(n=await this.privateGetHfOrdersDone(this.extend(v,m))):n=await this.privateGetOrders(this.extend(v,m)));let y=this.safeList(n,"data");if(void 0!==y)return this.parseOrders(y,o,i,s);let b=this.safeDict(n,"data",{}),w=this.safeList(b,"items",[]);return this.parseOrders(w,o,i,s)}async fetchContractOrdersByStatus(e,t,i,s,r={}){let o,n;void 0===this.markets&&await this.loadMarkets();let[d,h]=this.handleOptionBoolAndParams(r,"fetchOrdersByStatus","paginate",!1);if(d)return await this.fetchPaginatedCallDynamic("fetchOrdersByStatus",t,i,s,h);let c=this.safeBool2(h,"stop","trigger"),l=this.safeInteger(h,"until"),u=this.omit(h,["stop","until","trigger"]),f=this.safeString({closed:"done",open:"active"},e,e),p={};if(!0!==c)p.status=f;else if("active"!==f)throw new a.BadRequest(this.id+" fetchOrdersByStatus() can only fetch untriggered stop orders");void 0!==t&&(p.symbol=(n=this.market(t)).id),void 0!==i&&(p.startAt=i),void 0!==l&&(p.endAt=l),o=!0===c?await this.futuresPrivateGetStopOrders(this.extend(p,u)):await this.futuresPrivateGetOrders(this.extend(p,u));let m=this.safeDict(o,"data",{}),g=this.safeList(m,"items",[]);return this.parseOrders(g,n,i,s)}async fetchUtaOrdersByStatus(e,t,i,s,r={}){let o,n,d;void 0===this.markets&&await this.loadMarkets();let[h,c]=this.handleOptionBoolAndParams(r,"fetchOrdersByStatus","paginate",!1);if(h)return await this.fetchPaginatedCallDynamic("fetchOrdersByStatus",t,i,s,c,200);let[l,u]=this.handleOptionStringAndParams(c,"fetchUtaOrdersByStatus","accountMode","unified"),f={accountMode:l};void 0!==t?(d=this.market(t),n=this.safeString(d,"type"),f.symbol=d.id):n=this.safeString(u,"marketType");let p=this.omit(u,"marketType"),m="spot"!==n&&"margin"!==n;if(!m&&void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrdersByStatus() requires a symbol argument for spot and margin markets when using uta endpoint");let[g,v]=this.handleMarginModeAndParams("fetchOrdersByStatus",p),y="unified"===l,b=this.handleTradeType(m,g,y,v);v.tradeType=b,void 0!==i&&(f.startAt=i);let[w,k]=this.handleUntilOption("endAt",f,v);void 0!==s&&(w.pageSize=s);let S=e.toLowerCase();"open"===S?S="active":"closed"===S&&(S="done"),o="active"===S?await this.utaPrivateGetAccountModeOrderOpenList(this.extend(w,k)):await this.utaPrivateGetAccountModeOrderHistory(this.extend(w,k));let O=this.safeDict(o,"data",{}),T=this.safeList(O,"items",[]);return this.parseOrders(T,d,i,s)}async fetchClosedOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchClosedOrders","paginate",!1);return r?await this.fetchPaginatedCallDynamic("fetchClosedOrders",e,t,i,a):await this.fetchOrdersByStatus("done",e,t,i,a)}async fetchOpenOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchOpenOrders","paginate",!1);return r?await this.fetchPaginatedCallDynamic("fetchOpenOrders",e,t,i,a):await this.fetchOrdersByStatus("active",e,t,i,a)}async fetchOrder(e,t,i={}){let s,r;if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires an id argument");let o=await this.isUTAEnabled();[o,s]=this.handleOptionBoolAndParams(i,"fetchOrder","uta",o);let n=s;if(o&&(n=this.omit(s,"uta")),o)return await this.fetchUtaOrder(e,t,n);if(void 0===t)[r,n]=this.handleMarketTypeAndParams("fetchOrder",void 0,n);else{let e=this.market(t);r=this.safeString(e,"type")}return"spot"===r||"margin"===r?await this.fetchSpotOrder(e,t,n):await this.fetchContractOrder(e,t,n)}async fetchSpotOrder(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets();let o={},n=this.safeString2(i,"clientOid","clientOrderId"),d=this.safeBool2(i,"stop","trigger",!1),[h,c]=this.handleHfAndParams(i),[l,u]=this.handleMarginModeAndParams("fetchOrder",c),f=void 0!==l;if(void 0!==t&&(r=this.market(t)),(!0===h||f)&&!0!==d){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol parameter for hf and margin orders");o.symbol=this.safeString(r,"id")}let p=this.omit(u,["stop","clientOid","clientOrderId","trigger"]);if(void 0!==n)o.clientOid=n,!0===d?f?s=await this.privateGetHfMarginStopOrderClientOid(this.extend(o,p)):(void 0!==t&&(o.symbol=this.safeString(r,"id")),s=await this.privateGetStopOrderQueryOrderByClientOid(this.extend(o,p))):s=f?await this.privateGetHfMarginOrdersClientOrderClientOid(this.extend(o,p)):!0===h?await this.privateGetHfOrdersClientOrderClientOid(this.extend(o,p)):await this.privateGetOrderClientOrderClientOid(this.extend(o,p));else{if(void 0===e)throw new a.InvalidOrder(this.id+" fetchOrder() requires an order id");o.orderId=e,s=!0===d?f?await this.privateGetHfMarginStopOrderOrderId(this.extend(o,p)):await this.privateGetStopOrderOrderId(this.extend(o,p)):f?await this.privateGetHfMarginOrdersOrderId(this.extend(o,p)):!0===h?await this.privateGetHfOrdersOrderId(this.extend(o,p)):await this.privateGetOrdersOrderId(this.extend(o,p))}let m=this.safeDict(s,"data",{});return Array.isArray(m)&&(m=this.safeValue(m,0)),this.parseOrder(m,r)}async fetchContractOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r={},o=this.safeString2(i,"clientOid","clientOrderId");if(void 0!==o)r.clientOid=o,s=await this.futuresPrivateGetOrdersByClientOid(this.extend(r,this.omit(i,["clientOid","clientOrderId"])));else{if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires an order id argument or clientOrderId in params");r.orderId=e,s=await this.futuresPrivateGetOrdersOrderId(this.extend(r,i))}let n=void 0!==t?this.market(t):void 0,d=this.safeDict(s,"data",{});return this.parseOrder(d,n)}async fetchUtaOrder(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument for uta orders");let r={},o=this.safeString2(i,"clientOid","clientOrderId"),n=void 0!==o?this.omit(i,["clientOid","clientOrderId"]):i;if(void 0!==o)r.clientOid=o;else{if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires an id argument or clientOrderId parameter");r.orderId=e}void 0===this.markets&&await this.loadMarkets();let d=this.market(t);r.symbol=d.id;let h="unified";[h,n]=this.handleOptionStringAndParams(n,"fetchOrder","accountMode",h),r.accountMode=h,[s,n]=this.handleMarginModeAndParams("fetchOrder",n);let c="unified"===h;r.tradeType=this.handleTradeType(d.contract,s,c,n);let l=await this.utaPrivateGetAccountModeOrderDetail(this.extend(r,n)),u=this.safeDict(l,"data",{});return this.parseOrder(u,d)}handleTradeType(e=!1,t,i=!1,s={}){let r=this.safeString(s,"tradeType");if(void 0===r)if(e)r="FUTURES";else if(void 0!==t){if(r=t.toUpperCase(),i)if("ISOLATED"===r)throw new a.NotSupported(this.id+" spot isolated margin is not supported for unified accountMode");else r="MARGIN"}else r="SPOT";return r}parseOrder(e,t){let i=this.safeString(e,"tradeType"),s=this.inArray(i,["SPOT","CROSS","ISOLATED","FUTURES"]);if("sizeUnit"in e&&(s=!0),s)return this.parseUtaOrder(e,t);let r=this.safeString(e,"symbol"),a=this.safeMarket(r,t);return void 0!==a&&!0===a.contract?this.parseContractOrder(e,a):this.parseSpotOrder(e,a)}parseContractOrder(e,t){let i,s,r=this.safeString(e,"symbol"),a=this.safeMarket(r,t),n=a.symbol,d=this.safeString2(e,"id","orderId"),h=this.safeString(e,"type"),c=this.safeInteger(e,"createdAt"),l=this.iso8601(c),u=this.safeString(e,"price"),f=this.safeString(e,"side"),p=this.safeString(e,"feeCurrency"),m=this.safeCurrencyCode(p),g=this.safeNumber(e,"fee"),v=this.safeString(e,"size"),y=this.safeString(e,"filledSize"),b=this.safeString(e,"filledValue"),w=this.safeString(e,"avgDealPrice");if(void 0===w&&o.Y.stringGt(y,"0")){let e=this.safeString(a,"contractSize");w=!0===a.linear?o.Y.stringDiv(b,o.Y.stringMul(e,y)):o.Y.stringDiv(o.Y.stringMul(e,y),b)}let k=this.safeBool(e,"isActive"),S=this.safeBool(e,"cancelExist",!1);void 0!==k&&(i=!0===k?"open":"closed"),i=!0===S?"canceled":i,void 0!==g&&(s={currency:m,cost:g});let O=this.safeString(e,"clientOid"),T=this.safeString(e,"timeInForce"),P=this.safeBool(e,"postOnly"),I=this.safeBool(e,"reduceOnly"),A=this.safeInteger(e,"updatedAt");return this.safeOrder({id:d,clientOrderId:O,symbol:n,type:h,timeInForce:T,postOnly:P,reduceOnly:I,side:f,amount:v,price:u,triggerPrice:this.safeNumber(e,"stopPrice"),cost:b,filled:y,remaining:void 0,timestamp:c,datetime:l,fee:s,status:i,info:e,lastTradeTimestamp:void 0,lastUpdateTimestamp:A,average:w,trades:void 0},a)}parseSpotOrder(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeInteger(e,"createdAt"),a=this.safeString(e,"feeCurrency"),o=this.safeBool(e,"cancelExist",!1),n=this.safeString(e,"stop"),d=this.safeBool(e,"stopTriggered",!1),h=this.safeBool2(e,"isActive","active"),c=this.safeString(e,"status");return void 0!==h&&(i=!0===h?"open":"closed"),void 0!==n&&("NEW"===c?i="open":!0!==h&&!0!==d&&(i="cancelled")),!0===o&&(i="canceled"),"fail"===c&&(i="rejected"),this.safeOrder({info:e,id:this.safeStringN(e,["id","orderId","newOrderId","cancelledOrderId"]),clientOrderId:this.safeString(e,"clientOid"),symbol:this.safeSymbol(s,t,"-"),type:this.safeString(e,"type"),timeInForce:this.safeString(e,"timeInForce"),postOnly:this.safeBool(e,"postOnly"),side:this.safeString(e,"side"),amount:this.safeString(e,"size"),price:this.safeString(e,"price"),triggerPrice:this.safeNumber(e,"stopPrice"),cost:this.safeString(e,"dealFunds"),filled:this.safeString(e,"dealSize"),remaining:void 0,timestamp:r,datetime:this.iso8601(r),fee:{currency:this.safeCurrencyCode(a),cost:this.safeNumber(e,"fee")},status:i,lastTradeTimestamp:void 0,average:this.safeString(e,"avgDealPrice"),trades:void 0},t)}parseUtaOrder(e,t){let i,s,r=this.safeString(e,"symbol"),a=this.safeMarket(r,t),n=a.symbol,d=this.safeIntegerProduct2(e,"orderTime","ts",1e-6),h=this.safeIntegerProduct(e,"updatedTime",1e-6),c=this.safeString(e,"timeInForce"),l=this.safeString(e,"sizeUnit"),u=this.safeString(e,"size"),f=this.safeString(e,"status"),p=this.safeString(e,"avgPrice"),m=this.safeString(e,"filledSize");"BASECCY"===l||"UNIT"===l?i=u:(s=m,m=o.Y.stringDiv(m,p),m=this.amountToPrecision(n,m));let g={currency:this.safeCurrencyCode(this.safeString(e,"feeCurrency")),cost:this.safeString(e,"fee")};return this.safeOrder({id:this.safeString(e,"orderId"),clientOrderId:this.safeString(e,"clientOid"),symbol:n,type:this.safeStringLower(e,"orderType"),timeInForce:this.parseOrderTimeInForce(c),postOnly:this.safeBool(e,"postOnly"),reduceOnly:this.safeBool(e,"reduceOnly"),side:this.safeStringLower(e,"side"),amount:i,price:this.safeString(e,"price"),triggerPrice:this.safeString2(e,"stopPrice","triggerPrice"),cost:s,filled:m,remaining:void 0,timestamp:d,datetime:this.iso8601(d),fee:g,status:this.parseOrderStatus(f),lastTradeTimestamp:void 0,lastUpdateTimestamp:h,average:p,trades:void 0,stopLossPrice:this.safeString(e,"slTriggerPrice"),takeProfitPrice:this.safeString(e,"tpTriggerPrice"),info:e},a)}parseOrderTimeInForce(e){if(void 0!==e)return this.safeString({GTC:"GTC",IOC:"IOC",FOK:"FOK",GTT:"GTD"},e,e)}parseOrderStatus(e){if(void 0!==e)return this.safeString({0:"open",1:"open",2:"open",3:"closed",4:"open",5:"canceled",6:"closed"},e,e)}async fetchOrderTrades(e,t,i,s,r={}){return await this.fetchMyTrades(t,i,s,this.extend({orderId:e},r))}async fetchMyTrades(e,t,i,s={}){let r,a,o;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(a=this.market(e)),[r,o]=this.handleMarketTypeAndParams("fetchMyTrades",a,s);let n=await this.isUTAEnabled();return([n,o]=this.handleOptionBoolAndParams(o,"fetchMyTrades","uta",n),n)?(o=this.extend(o,{marketType:r}),await this.fetchMyUtaTrades(e,t,i,o)):"spot"===r||"margin"===r?await this.fetchMySpotTrades(e,t,i,o):await this.fetchMyContractTrades(e,t,i,o)}async fetchMySpotTrades(e,t,i,s={}){let r,o,n,d,h,c;void 0===this.markets&&await this.loadMarkets();let l=!1;if([l,r]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1),l)return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,r);let u={};[o,r]=this.handleHfAndParams(r),[n,r]=this.handleMarginModeAndParams("fetchMyTrades",r);let f=void 0!==n;if(f&&(o=!0,u.tradeType=void 0===n?void 0:this.safeString(this.options.marginModes,n,n)),!0===o&&void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol parameter for hf or margin orders");void 0!==e&&(d=this.market(e),u.symbol=d.id);let p=this.safeString(this.options,"fetchMyTradesMethod"),m=!1;if([u,r]=this.handleUntilOption("endAt",u,r),!0===o)void 0!==i&&(u.limit=i),void 0!==t&&(u.startAt=t),h=f?await this.privateGetHfMarginFills(this.extend(u,r)):await this.privateGetHfFills(this.extend(u,r));else if("private_get_fills"===p)void 0!==t&&(u.startAt=t),h=await this.privateGetFills(this.extend(u,r));else if("private_get_limit_fills"===p)m=!0,h=await this.privateGetLimitFills(this.extend(u,r));else throw new a.ExchangeError(this.id+" fetchMyTradesMethod() invalid method");let g=this.safeDict(h,"data",{});c=m?g:this.safeList(g,"items",[]);let v=[];return void 0!==c&&(v=this.toArray(c)),this.parseTrades(v,d,t,i)}async fetchMyContractTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,o);let n={};void 0!==e&&(n.symbol=(r=this.market(e)).id),void 0!==t&&(n.startAt=t),void 0!==i&&(n.pageSize=Math.min(1e3,i));let[d,h]=this.handleUntilOption("endAt",n,o),c=await this.futuresPrivateGetFills(this.extend(d,h)),l=this.safeDict(c,"data",{}),u=this.safeList(l,"items",[]),f=[];return void 0!==u&&(f=u),this.parseTrades(f,r,t,i)}async fetchMyUtaTrades(e,t,i,s={}){let r,o;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(n)return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,d);let h=this.safeString(d,"marketType"),c=void 0!==h?this.omit(d,"marketType"):d,l={},u=!1;if(void 0!==e)r=this.market(e),l.symbol=r.id,u=r.contract;else if("spot"===h||"margin"===h)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol parameter for uta spot or margin trades");else u=!0;let f="unified";[f,c]=this.handleOptionStringAndParams(c,"fetchMyTrades","accountMode",f),l.accountMode=f,[o,c]=this.handleMarginModeAndParams("fetchMyTrades",c);let p="unified"===f,m=this.handleTradeType(u,o,p,c);l.tradeType=m,void 0!==t&&(l.startAt=t),void 0!==i&&(l.pageSize=i),[l,c]=this.handleUntilOption("endAt",l,c);let g=await this.utaPrivateGetAccountModeOrderExecution(this.extend(l,c)),v=this.safeDict(g,"data",{}),y=this.safeList(v,"items",[]),b=[];return void 0!==y&&(b=y),this.parseTrades(b,r,t,i)}async fetchTrades(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={symbol:o.id},[d,h]=this.handleOptionBoolAndParams(s,"fetchTrades","uta",!1),[c,l]=this.handleMarketTypeAndParams("fetchTrades",o,h);if(d){"spot"===c||"margin"===c?n.tradeType="SPOT":n.tradeType="FUTURES",r=await this.utaGetMarketTrade(this.extend(n,l));let e=this.safeDict(r,"data",{});a=this.safeList(e,"list",[])}else r="spot"===c||"margin"===c?await this.publicGetMarketHistories(this.extend(n,l)):await this.futuresPublicGetTradeHistory(this.extend(n,l)),a=this.safeList(r,"data",[]);let u=[];return void 0!==a&&(u=a),this.parseTrades(u,o,t,i)}parseTrade(e,t){if("liquidityRole"in e)return this.parseMyUtaTrade(e,t);let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t);return void 0===s||!0===s.spot?this.parseSpotOrUtaTrade(e,s):this.parseContractTrade(e,s)}parseSpotOrUtaTrade(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t,"-"),a=this.safeString2(e,"tradeId","id"),o=this.safeString(e,"orderId"),n=this.safeString(e,"liquidity"),d=this.safeInteger2(e,"time","ts");void 0!==d?d=this.parseToInt(d/1e6):(d=this.safeInteger(e,"createdAt"),"dealValue"in e&&void 0!==d&&(d*=1e3));let h=this.safeString2(e,"price","dealPrice"),c=this.safeString2(e,"size","amount"),l=this.safeString(e,"side"),u=this.safeString(e,"fee");if(void 0!==u){let t=this.safeString(e,"feeCurrency"),s=this.safeCurrencyCode(t);void 0===s&&(s="sell"===l?r.quote:r.base),i={cost:u,currency:s,rate:this.safeString(e,"feeRate")}}let f=this.safeString(e,"type");"match"===f&&(f=void 0);let p=this.safeString2(e,"funds","dealValue");return this.safeTrade({info:e,id:a,order:o,timestamp:d,datetime:this.iso8601(d),symbol:r.symbol,type:f,takerOrMaker:n,side:l,price:h,amount:c,cost:p,fee:i},r)}parseContractTrade(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t,"-"),a=this.safeString2(e,"tradeId","id"),n=this.safeString(e,"orderId"),d=this.safeString(e,"liquidity"),h=this.safeInteger(e,"ts");void 0!==h?h=this.parseToInt(h/1e6):(h=this.safeInteger(e,"createdAt"),"dealValue"in e&&void 0!==h&&(h*=1e3));let c=this.safeString2(e,"price","dealPrice"),l=this.safeString2(e,"size","amount"),u=this.safeString(e,"side"),f=this.safeString(e,"fee");if(void 0!==f){let t=this.safeString(e,"feeCurrency"),s=this.safeCurrencyCode(t);void 0===s&&(s="sell"===u?r.quote:r.base),i={cost:f,currency:s,rate:this.safeString(e,"feeRate")}}let p=this.safeString2(e,"type","orderType");"match"===p&&(p=void 0);let m=this.safeString2(e,"funds","value");if(void 0===m){let e=this.safeString(r,"contractSize"),t=o.Y.stringMul(c,l);m=o.Y.stringMul(t,e)}return this.safeTrade({info:e,id:a,order:n,timestamp:h,datetime:this.iso8601(h),symbol:r.symbol,type:p,takerOrMaker:d,side:u,price:c,amount:l,cost:m,fee:i},r)}parseMyUtaTrade(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeIntegerProduct(e,"executionTime",1e-6),a={cost:this.safeString(e,"fee"),currency:this.safeCurrencyCode(this.safeString(e,"feeCurrency"))};return this.safeTrade({info:e,id:this.safeString(e,"tradeId"),order:this.safeString(e,"orderId"),timestamp:r,datetime:this.iso8601(r),symbol:s.symbol,type:this.safeStringLower(e,"orderType"),takerOrMaker:this.safeStringLower(e,"liquidityRole"),side:this.safeStringLower(e,"side"),price:this.safeString(e,"price"),amount:this.safeString(e,"size"),cost:this.safeString(e,"value"),fee:a},s)}async fetchTradingFee(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=await this.isUTAEnabled(),[o,n]=this.handleOptionBoolAndParams(t,"fetchTradingFee","uta",a),d={};if(o){!0===r.spot?d.tradeType="SPOT":d.tradeType="FUTURES",d.symbol=r.id,i=await this.utaPrivateGetUserFeeRate(this.extend(d,n));let e=this.safeDict(i,"data",{}),t=this.safeList(e,"list",[]);s=this.safeDict(t,0)}else if(!0===r.spot){d.symbols=r.id,i=await this.privateGetTradeFees(this.extend(d,n));let e=this.safeList(i,"data",[]);s=this.safeDict(e,0)}else d.symbol=r.id,i=await this.futuresPrivateGetTradeFees(this.extend(d,n)),s=this.safeDict(i,"data");let h=this.safeString(s,"symbol");return{info:i,symbol:this.safeSymbol(h,r),maker:this.safeNumber(s,"makerFeeRate"),taker:this.safeNumber(s,"takerFeeRate"),percentage:!0,tierBased:!0}}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);void 0===this.markets&&await this.loadMarkets(),this.checkAddress(i);let n=this.currency(e),d={currency:n.id,toAddress:i,withdrawType:"ADDRESS"};void 0!==a&&(d.memo=a);let[h,c]=this.handleNetworkCodeAndParams(o);if(void 0!==h){let e=this.networkCodeToId(h,this.safeString(n,"code"));void 0!==e&&(d.chain=e.toLowerCase())}let l=this.currencyToPrecision(e,t,h);void 0!==l&&(d.amount=parseFloat(l));let[u,f]=this.handleOptionBoolAndParams(c,"withdraw","includeFee",!1);u&&(d.feeDeductType="INTERNAL");let p=await this.privatePostWithdrawals(this.extend(d,f)),m=this.safeDict(p,"data",{});return this.parseTransaction(m,n)}parseTransactionStatus(e){if(void 0!==e)return this.safeString({SUCCESS:"ok",PROCESSING:"pending",WALLET_PROCESSING:"pending",FAILURE:"failed"},e,e)}parseTransaction(e,t){let i,s=this.safeString(e,"currency"),r=this.safeCurrencyCode(s,t),a=this.safeString(e,"address"),n=this.safeString(e,"amount"),d=this.safeString(e,"walletTxId");if(void 0!==d){let e=d.split("@");e.length>1&&void 0===a&&e[1].length>1&&(a=e[1]),d=e[0]}let h="deposit";void 0===d&&(h="withdrawal");let c=this.safeString(e,"status"),l=this.safeString(e,"fee");if(void 0!==l){let e;void 0!==n&&(e=o.Y.stringDiv(l,n)),i={cost:this.parseNumber(l),rate:this.parseNumber(e),currency:r}}let u=this.safeInteger2(e,"createdAt","createAt"),f=this.safeInteger(e,"updatedAt");"createdAt"in e||(h="address"in e?"withdrawal":"deposit",void 0!==u&&(u*=1e3),void 0!==f&&(f*=1e3));let p=this.safeBool(e,"isInner"),m=this.safeString(e,"memo"),g=this.safeString(e,"chain");return{info:e,id:this.safeString2(e,"id","withdrawalId"),timestamp:u,datetime:this.iso8601(u),network:this.networkIdToCode(g,r),address:a,addressTo:a,addressFrom:void 0,tag:m,tagTo:m,tagFrom:void 0,currency:r,amount:this.parseNumber(n),txid:d,type:h,status:this.parseTransactionStatus(c),comment:this.safeString(e,"remark"),internal:p,fee:i,updated:f}}async fetchDeposits(e,t,i,s={}){let r,a,o;void 0===this.markets&&await this.loadMarkets();let n="main";[n,r]=this.handleOptionStringAndParams(s,"fetchDeposits","accountType",n);let d=this.safeDict(this.options,"accountsByType",{});if("contract"===(n=this.safeString(d,n,n)))return await this.fetchContractDeposits(e,t,i,r);let h=!1;if([h,r]=this.handleOptionBoolAndParams(r,"fetchDeposits","paginate",!1),h)return await this.fetchPaginatedCallDynamic("fetchDeposits",e,t,i,r);let c={};void 0!==e&&(a=this.currency(e),c.currency=a.id),void 0!==i&&(c.pageSize=i),[c,r]=this.handleUntilOption("endAt",c,r),void 0!==t&&t<1550448e6?(c.startAt=this.parseToInt(t/1e3),o=await this.privateGetHistDeposits(this.extend(c,r))):(void 0!==t&&(c.startAt=t),o=await this.privateGetDeposits(this.extend(c,r)));let l=this.safeDict(o,"data",{}),u=this.safeList(l,"items",[]);return this.parseTransactions(u,a,t,i,{type:"deposit"})}async fetchContractDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.currency=(r=this.currency(e)).id),void 0!==i&&(a.pageSize=i),void 0!==t&&(a.startAt=t);let o=await this.futuresPrivateGetDepositList(this.extend(a,s)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"items",[]);return this.parseTransactions(d,r,t,i,{type:"deposit"})}async fetchWithdrawals(e,t,i,s={}){let r,a,o;void 0===this.markets&&await this.loadMarkets();let n="main";[n,r]=this.handleOptionStringAndParams(s,"fetchWithdrawals","accountType",n);let d=this.safeDict(this.options,"accountsByType",{});if("contract"===(n=this.safeString(d,n,n)))return await this.fetchContractWithdrawals(e,t,i,r);let h=!1;if([h,r]=this.handleOptionBoolAndParams(r,"fetchWithdrawals","paginate",!1),h)return await this.fetchPaginatedCallDynamic("fetchWithdrawals",e,t,i,r,500);let c={};void 0!==e&&(a=this.currency(e),c.currency=a.id),void 0!==i&&(c.pageSize=i),[c,r]=this.handleUntilOption("endAt",c,r),void 0!==t&&t<1550448e6?(c.startAt=this.parseToInt(t/1e3),o=await this.privateGetHistWithdrawals(this.extend(c,r))):(void 0!==t&&(c.startAt=t),o=await this.privateGetWithdrawals(this.extend(c,r)));let l=this.safeDict(o,"data",{}),u=this.safeList(l,"items",[]);return this.parseTransactions(u,a,t,i,{type:"withdrawal"})}async fetchContractWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.currency=(r=this.currency(e)).id),void 0!==i&&(a.pageSize=i),void 0!==t&&(a.startAt=t);let o=await this.futuresPrivateGetWithdrawalList(this.extend(a,s)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"items",[]);return this.parseTransactions(d,r,t,i,{type:"withdrawal"})}parseBalanceHelper(e){let t=this.account();t.used=this.safeString2(e,"holdBalance","hold"),t.free=this.safeString2(e,"availableBalance","available"),t.total=this.safeString2(e,"totalBalance","total");let i=this.safeString(e,"liability"),s=this.safeString(e,"interest");return t.debt=o.Y.stringAdd(i,s),t}async fetchBalance(e={}){let t,i;void 0===this.markets&&await this.loadMarkets();let s=await this.isUTAEnabled(),[r,a]=this.handleOptionBoolAndParams(e,"fetchBalance","uta",s);if(r)return await this.fetchUtaBalance(a);let o={},n=this.safeString(a,"code");void 0!==n&&(i=this.currency(n));let[d,h]=this.handleMarketTypeAndParams("fetchBalance",void 0,a),c=this.safeDict(this.options,"accountsByType",{}),l=this.safeString(c,d,d),u=this.omit(h,"type");if("contract"===l)return await this.fetchContractBalance(u);let[f,p]=this.handleHfAndParams(u);!0===f&&"main"!==l&&(l="trade_hf");let[m,g]=this.handleMarginModeAndParams("fetchBalance",p),v="isolated"===m||"isolated"===l,y="cross"===m||"margin"===l;v?(void 0!==i&&(o.balanceCurrency=i.id),t=await this.privateGetIsolatedAccounts(this.extend(o,g))):y?t=await this.privateGetMarginAccount(this.extend(o,g)):(void 0!==i&&(o.currency=i.id),o.type=l,t=await this.privateGetAccounts(this.extend(o,g)));let b={info:t,timestamp:void 0,datetime:void 0};if(v){let e=this.safeDict(t,"data",{}),i=this.safeValue(e,"assets",e);for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),s=this.safeDict(t,"baseAsset",{}),r=this.safeDict(t,"quoteAsset",{}),a=this.safeCurrencyCode(this.safeString(s,"currency")),o=this.safeCurrencyCode(this.safeString(r,"currency"));void 0!==a&&(b=this.mergeBalanceAccount(b,a,this.parseBalanceHelper(s))),void 0!==o&&(b=this.mergeBalanceAccount(b,o,this.parseBalanceHelper(r)))}}else if(y){let e=this.safeDict(t,"data",{}),i=this.safeList(e,"accounts",[]);for(let e=0;e<i.length;e++){let t=i[e],s=this.safeString(t,"currency"),r=this.safeCurrencyCode(s);void 0!==r&&(b[r]=this.parseBalanceHelper(t))}}else{let e=this.safeList(t,"data",[]);for(let t=0;t<e.length;t++){let i=this.safeDict(e,t);if(this.safeString(i,"type")===l){let e=this.safeString(i,"currency"),t=this.safeCurrencyCode(e),s=this.account();s.total=this.safeString(i,"balance"),s.free=this.safeString(i,"available"),s.used=this.safeString(i,"holds"),void 0!==t&&(b[t]=s)}}}return this.safeBalance(b)}async fetchContractBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=this.safeString(this.options,"code"),i=this.safeDict(this.options,"fetchBalance",{});t=this.safeString(i,"code",t);let s=this.safeString(e,"code",t);if(void 0===s)throw new a.ArgumentsRequired(this.id+" fetchContractBalance() requires a code parameter");let r=this.currency(s),o={currency:r.id},n=await this.futuresPrivateGetAccountOverview(this.extend(o,e)),d={info:n,timestamp:void 0,datetime:void 0},h=this.safeDict(n,"data"),c=this.safeString(h,"currency"),l=this.safeCurrencyCode(c,r),u=this.account();return u.free=this.safeString(h,"availableBalance"),u.total=this.safeString(h,"accountEquity"),void 0!==l&&(d[l]=u),this.safeBalance(d)}async fetchUtaBalance(e={}){let t,i,s;void 0===this.markets&&await this.loadMarkets();let r="unified";if([r,t]=this.handleMarketTypeAndParams("fetchUtaBalance",void 0,e,r),"margin"===r){let e="cross";[e,t]=this.handleOptionStringAndParams(t,"fetchUtaBalance","marginMode",e),r=e}let a=this.safeDict(this.options,"utaAccountsByType",{}),o="ISOLATED"===(s=this.safeString(a,r,r)),n={};"unified"===s?(n.accountMode=s,i=await this.utaPrivateGetAccountModeAccountBalance(this.extend(n,t))):(n.accountType=s,i=await this.utaPrivateGetAccountBalance(this.extend(n,t)));let d=this.safeDict(i,"data",{}),h=this.safeInteger(d,"ts"),c={info:i,timestamp:h,datetime:this.iso8601(h)},l=this.safeList(d,"accounts",[]);if(o)for(let e=0;e<l.length;e++){let t=this.safeDict(l,e),i=this.safeList(t,"currencies",[]);for(let e=0;e<i.length;e++){let t=this.safeDict(i,e,{}),s=this.safeString(t,"currency"),r=this.safeCurrencyCode(s);void 0!==r&&(c=this.mergeBalanceAccount(c,r,this.parseBalanceHelper(t)))}}else{let e=this.safeDict(l,0,{}),t=this.safeList(e,"currencies",[]);for(let e=0;e<t.length;e++){let i=this.safeDict(t,e,{}),s=this.safeString(i,"currency"),r=this.safeCurrencyCode(s);void 0!==r&&(c[r]=this.parseBalanceHelper(i))}}return this.safeBalance(c)}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=await this.isUTAEnabled(),[o,n]=this.handleOptionBoolAndParams(r,"transfer","uta",a);return o?await this.transferUta(e,t,i,s,n):await this.transferClassic(e,t,i,s,n)}async transferUta(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let o=this.currency(e),n=this.currencyToPrecision(e,t),d={currency:o.id,amount:n},[h,c]=this.handleParamString2(r,"transferType","type","INTERNAL"),[l,u]=this.handleParamString2(c,"fromUserId","fromUid",void 0),[f,p]=this.handleParamString2(u,"toUserId","toUid",void 0);if("PARENT_TO_SUB"===h||"SUB_TO_SUB"===h)if(void 0===f)throw new a.ExchangeError(this.id+" transfer() requires a toUserId param for PARENT_TO_SUB or SUB_TO_SUB transfers");else d.toUid=f;else if("SUB_TO_PARENT"===h||"SUB_TO_SUB"===h)if(void 0===l)throw new a.ExchangeError(this.id+" transfer() requires a fromUserId param for SUB_TO_PARENT or SUB_TO_SUB transfers");else d.fromUid=l;let m=this.uuid(),[g,v]=this.handleParamString2(p,"clientOid","clientOrderId",m);d.clientOid=g;let y=this.convertTypeToAccount(i),b=this.convertTypeToAccount(s),w=void 0===this.ids?[]:this.ids,k=this.inArray(y,w),S=this.inArray(b,w);k&&(d.fromAccountSymbol=y,y="ISOLATED"),S&&(d.toAccountSymbol=b,b="ISOLATED");let O=this.safeDict(this.options,"utaAccountsByType",{});y=this.safeString(O,y,y),b=this.safeString(O,b,b),d.fromAccountType=y.toUpperCase(),d.toAccountType=b.toUpperCase(),d.type=this.safeString({INTERNAL:"0",PARENT_TO_SUB:"1",SUB_TO_PARENT:"2",SUB_TO_SUB:"3"},h,h);let T=await this.utaPrivatePostAccountTransfer(this.extend(d,v)),P=this.safeDict(T,"data",{}),I=this.parseTransfer(P,o),A=this.safeDict(this.options,"transfer",{});return!0===this.safeBool(A,"fillResponseFromRequest",!0)&&(I.amount=t,I.fromAccount=i,I.toAccount=s,I.status="ok"),I}async transferClassic(e,t,i,s,r={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d=this.currencyToPrecision(e,t),h={currency:n.id,amount:d},[c,l]=this.handleParamString2(r,"transferType","type","INTERNAL");if("PARENT_TO_SUB"===c){if(!("toUserId"in l))throw new a.ExchangeError(this.id+" transfer() requires a toUserId param for PARENT_TO_SUB transfers")}else if("SUB_TO_PARENT"===c&&!("fromUserId"in l))throw new a.ExchangeError(this.id+" transfer() requires a fromUserId param for SUB_TO_PARENT transfers");"clientOid"in l||(h.clientOid=this.uuid());let u=this.convertTypeToAccount(i),f=this.convertTypeToAccount(s),p=void 0===this.ids?[]:this.ids,m=this.inArray(u,p),g=this.inArray(f,p);m&&(h.fromAccountTag=u,u="isolated"),g&&(h.toAccountTag=f,f="isolated"),this.isHfOrMining(u,f)?(h.from=u,h.to=f,o=await this.privatePostAccountsInnerTransfer(this.extend(h,l))):(h.type=c,h.fromAccountType=u.toUpperCase(),h.toAccountType=f.toUpperCase(),o=await this.privatePostAccountsUniversalTransfer(this.extend(h,l)));let v=this.safeDict(o,"data",{}),y=this.parseTransfer(v,n),b=this.safeDict(this.options,"transfer",{});return!0===this.safeBool(b,"fillResponseFromRequest",!0)&&(y.amount=t,y.fromAccount=i,y.toAccount=s,y.status="ok"),y}isHfOrMining(e,t){return"trade_hf"===e||"trade_hf"===t||"pool"===e||"pool"===t}parseTransfer(e,t){let i,s,r=this.safeInteger2(e,"createdAt","time"),a=this.safeString(e,"currency"),o=this.safeString(e,"status");if(void 0!==this.safeString(e,"bizType")){let t=this.safeStringLower(e,"accountType"),r=this.safeString(e,"direction");"out"===r?i=t:"in"===r&&(s=t)}else i=this.safeStringLower(e,"payAccountType"),s=this.safeStringLower(e,"recAccountType");let n=this.safeDict(this.options,"accountsByType"),d=void 0===i?void 0:this.safeString(n,i,i),h=void 0===s?void 0:this.safeString(n,s,s);return{id:this.safeStringN(e,["id","applyId","orderId"]),currency:this.safeCurrencyCode(a,t),timestamp:r,datetime:this.iso8601(r),amount:this.safeNumber(e,"amount"),fromAccount:d,toAccount:h,status:this.parseTransferStatus(o),info:e}}parseTransferStatus(e){if(void 0!==e)return this.safeString({PROCESSING:"pending"},e,e)}parseLedgerEntryType(e){return this.safeString({"Assets Transferred in After Upgrading":"transfer",Deposit:"transaction",Withdrawal:"transaction",Transfer:"transfer",Trade_Exchange:"trade","KuCoin Bonus":"bonus","Referral Bonus":"referral",Rewards:"bonus","Airdrop/Fork":"airdrop","Other rewards":"bonus","Fee Rebate":"rebate","Buy Crypto":"trade","Sell Crypto":"sell","Public Offering Purchase":"trade","Refunded Fees":"fee","KCS Pay Fees":"fee","Margin Trade":"trade",Loans:"Loans","Instant Exchange":"trade","Sub-account transfer":"transfer","Liquidation Fees":"fee",RealisedPNL:"trade",TransferIn:"transfer",TransferOut:"transfer",TRADE_EXCHANGE:"trade",TRANSFER:"transfer",SUB_TRANSFER:"transfer",RETURNED_FEES:"fee",DEDUCTION_FEES:"fee",OTHER:"other",SUB_TO_SUB_TRANSFER:"transfer",SPOT_EXCHANGE:"trade",SPOT_EXCHANGE_REBATE:"rebate",FUTURES_EXCHANGE_OPEN:"trade",FUTURES_EXCHANGE_CLOSE:"trade",FUTURES_EXCHANGE_REBATE:"rebate",FUNDING_FEE:"fee",LIABILITY_INTEREST:"fee",KCS_DEDUCTION_FEES:"fee",KCS_RETURNED_FEES:"fee",AUTO_EXCHANGE_USER:"trade"},e,e)}parseLedgerDirection(e){return this.safeString({in:"in",out:"out",TransferIn:"in",TransferOut:"out",IN:"in",OUT:"out"},e,e)}parseLedgerStatus(e){return this.safeString({Completed:"ok",Pending:"pending"},e,e)}parseLedgerEntry(e,t){let i,s,r=this.safeString(e,"id"),a=this.safeString(e,"currency"),n=this.safeCurrencyCode(a,t),d=this.safeCurrency(a,t),h=this.safeString(e,"amount"),c=this.safeNumberOmitZero(e,"balance"),l=this.safeStringN(e,["bizType","businessType","type"]),u=this.parseLedgerEntryType(l),f=this.safeString2(e,"direction","type"),p=this.safeString(e,"accountType"),m=this.safeInteger(e,"createdAt");void 0===m&&(void 0!==(m=this.safeInteger(e,"time"))?p="CONTRACT":m=this.safeIntegerProduct(e,"ts",1e-6));let g=this.iso8601(m),v=this.safeString(e,"context");if(void 0!==v&&""!==v)try{let e=JSON.parse(v),t=this.safeString(e,"orderId"),s=this.safeString(e,"tradeId");i=void 0!==s?s:t}catch(e){i=v}let y=this.safeString(e,"fee"),b=void 0===y?void 0:this.omitZero(y);void 0!==b&&(s={cost:this.parseNumber(b),currency:n});let w=this.safeString(e,"status");return this.safeLedgerEntry({info:e,id:r,direction:this.parseLedgerDirection(f),account:p,referenceId:i,referenceAccount:p,type:u,currency:n,amount:this.parseNumber(o.Y.stringAbs(h)),timestamp:m,datetime:g,before:void 0,after:c,status:this.parseLedgerStatus(w),fee:s},d)}async fetchLedger(e,t,i,s={}){let r,a,o,n,d,h,c;void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let l=await this.isUTAEnabled();[l,a]=this.handleOptionBoolAndParams(s,"fetchLedger","uta",l),[o,a]=this.handleHfAndParams(a),l&&(n="UNIFIED"),[n,a]=this.handleMarketTypeAndParams("fetchLedger",void 0,a,n),[d,a]=this.handleMarginModeAndParams("fetchLedger",a),l&&"margin"===n&&(n=d=void 0===d?"cross":d);let u=this.safeDict(this.options,"accountsByType");l&&(u=this.safeDict(this.options,"utaAccountsByType")),h=this.safeString(u,n,n);let f=500;!0===o?f=200:"contract"===h?f=50:l&&("UNIFIED"===h||"SPOT"===h?f=200:"FUTURES"===h&&(f=100));let p=!1;if([p,a]=this.handleOptionBoolAndParams(a,"fetchLedger","paginate",!1),p)return await this.fetchPaginatedCallDynamic("fetchLedger",e,t,i,a,f);let m={};void 0!==t&&(m.startAt=t),void 0!==e&&(c=this.currency(e),m.currency=c.id),[m,a]=this.handleUntilOption("endAt",m,a),void 0!==i&&("contract"===h?m.maxCount=i:!0===o?m.limit=i:m.pageSize=i),l?(m.accountType=h,r=await this.utaPrivateGetAccountLedger(this.extend(m,a))):r=!0===o?void 0!==d?await this.privateGetHfMarginAccountLedgers(this.extend(m,a)):await this.privateGetHfAccountsLedgers(this.extend(m,a)):"contract"===h?await this.futuresPrivateGetTransactionHistory(this.extend(m,a)):await this.privateGetAccountsLedgers(this.extend(m,a));let g=this.safeList(r,"data");if(void 0!==g)return this.parseLedger(g,c,t,i);let v=this.safeDict(r,"data"),y=this.safeList2(v,"items","dataList",[]);return this.parseLedger(y,c,t,i)}calculateRateLimiterCost(e,t,i,s,r={}){let a=this.safeDict(this.options,"versions",{}),o=this.safeDict(a,e,{}),n=this.safeDict(o,t,{}),d=this.safeString(n,i,this.options.version),h=this.safeString(s,"version",d);return"v3"===h&&"v3"in r?r.v3:"v2"===h&&"v2"in r?r.v2:"v1"===h&&"v1"in r?r.v1:this.safeValue(r,"cost",1)}parseBorrowRate(e,t){let i,s=this.safeString2(e,"createdAt","timestamp");void 0!==s&&(i=this.parseToInt(s.slice(0,13)));let r=this.safeString(e,"currency");return{currency:this.safeCurrencyCode(r,t),rate:this.safeNumberN(e,["dailyIntRate","dayRatio","currentRateDaily"]),period:864e5,timestamp:i,datetime:this.iso8601(i),info:e}}async fetchBorrowInterest(e,t,i,s,r={}){let a,o,n,d;void 0===this.markets&&await this.loadMarkets();let[h,c]=this.handleMarginModeAndParams("fetchBorrowInterest",r,"cross"),l={};void 0!==e&&(o=this.currency(e),"isolated"===h?l.balanceCurrency=o.id:l.quoteCurrency=o.id),void 0!==t&&(n=this.market(t)),a="isolated"===h?await this.privateGetIsolatedAccounts(this.extend(l,c)):await this.privateGetMarginAccounts(this.extend(l,c));let u=this.safeDict(a,"data",{});d="isolated"===h?this.safeList(u,"assets",[]):this.safeList(u,"accounts",[]);let f=this.parseBorrowInterests(d,n),p=this.filterByCurrencySinceLimit(f,e,i,s);return this.filterBySymbolSinceLimit(p,t,i,s)}parseBorrowInterest(e,t){let i,s,r,a=this.safeString(e,"symbol"),o="isolated";void 0===a&&(o="cross");let n=this.safeMarket(a,t),d=this.safeString(n,"symbol"),h=this.safeDict(e,"baseAsset",{});return"isolated"===o?(i=this.safeNumber(h,"liabilityPrincipal"),s=this.safeNumber(h,"liabilityInterest"),r=this.safeString(h,"currency")):(i=this.safeNumber(e,"liabilityPrincipal"),s=this.safeNumber(e,"liabilityInterest"),r=this.safeString(e,"currency")),{info:e,symbol:d,currency:this.safeCurrencyCode(r),interest:s,interestRate:this.safeNumber(e,"dailyIntRate"),amountBorrowed:i,marginMode:o,timestamp:void 0,datetime:void 0}}async fetchBorrowRateHistories(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={isIsolated:"isolated"===this.handleMarginModeAndParams("fetchBorrowRateHistories",s,"cross")[0]};void 0!==t&&(r.startTime=t);let[a,o]=this.handleUntilOption("endTime",r,s);void 0!==i&&(a.pageSize=i);let n=await this.privateGetMarginInterest(this.extend(a,o)),d=this.safeDict(n,"data"),h=this.safeList(d,"items",[]);return this.parseBorrowRateHistories(h,e,t,i)}async fetchBorrowRateHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={isIsolated:"isolated"===this.handleMarginModeAndParams("fetchBorrowRateHistories",s,"cross")[0],currency:this.currency(e).id};void 0!==t&&(r.startTime=t);let[a,o]=this.handleUntilOption("endTime",r,s);void 0!==i&&(a.pageSize=i);let n=await this.privateGetMarginInterest(this.extend(a,o)),d=this.safeDict(n,"data"),h=this.safeList(d,"items",[]);return this.parseBorrowRateHistory(h,e,t,i)}parseBorrowRateHistories(e,t,i,s){let r={};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),a=this.safeCurrencyCode(this.safeString(s,"currency"));if(void 0!==a&&(void 0===t||this.inArray(a,t))){a in r||(r[a]=[]);let e=this.parseBorrowRate(s);r[a].push(e)}}let a=Object.keys(r);for(let e=0;e<a.length;e++){let t=a[e];r[t]=this.filterByCurrencySinceLimit(r[t],t,i,s)}return r}async fetchCrossBorrowRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={currency:i.id},r=await this.utaPrivateGetAccountInterestLimits(this.extend(s,t)),a=this.safeDict(r,"data",{});return this.parseBorrowRate(a,i)}async borrowCrossMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.currency(e),r={currency:s.id,size:this.currencyToPrecision(e,t),timeInForce:"FOK"},a=await this.privatePostMarginBorrow(this.extend(r,i)),o=this.safeDict(a,"data",{});return this.parseMarginLoan(o,s)}async borrowIsolatedMargin(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=this.currency(t),o={currency:a.id,size:this.currencyToPrecision(t,i),symbol:r.id,timeInForce:"FOK",isIsolated:!0},n=await this.privatePostMarginBorrow(this.extend(o,s)),d=this.safeDict(n,"data",{});return this.parseMarginLoan(d,a)}async repayCrossMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.currency(e),r={currency:s.id,size:this.currencyToPrecision(e,t)},a=await this.privatePostMarginRepay(this.extend(r,i)),o=this.safeDict(a,"data",{});return this.parseMarginLoan(o,s)}async repayIsolatedMargin(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=this.currency(t),o={currency:a.id,size:this.currencyToPrecision(t,i),symbol:r.id,isIsolated:!0},n=await this.privatePostMarginRepay(this.extend(o,s)),d=this.safeDict(n,"data",{});return this.parseMarginLoan(d,a)}parseMarginLoan(e,t){let i=this.safeString(e,"currency");return{id:this.safeString(e,"orderNo"),currency:this.safeCurrencyCode(i,t),amount:this.safeNumber(e,"actualSize"),symbol:void 0,timestamp:void 0,datetime:void 0,info:e}}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetCurrencies(t),s=this.safeList(i,"data",[]);return this.parseDepositWithdrawFees(s,e,"currency")}async fetchLeverage(e,t={}){let[i,s]=this.handleMarginModeAndParams(e,t);if("cross"!==i)throw new a.NotSupported(this.id+' fetchLeverage() currently supports only params["marginMode"] = "cross"');void 0===this.markets&&await this.loadMarkets();let r=this.market(e);if(!0!==r.contract)throw new a.NotSupported(this.id+" fetchLeverage() supports contract markets only");let o={symbol:r.id},n=await this.futuresPrivateGetGetCrossUserLeverage(this.extend(o,s)),d=this.safeDict(n,"data",{}),h=this.parseLeverage(d,r);return this.extend(h,{marginMode:i})}async setLeverage(e,t,i={}){let s,r,o,n;if(void 0===this.markets&&await this.loadMarkets(),[o,s]=this.handleMarketTypeAndParams("setLeverage",void 0,i),void 0!==t||"spot"!==o&&"margin"!==o){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage requires a symbol argument for contract markets");if(!0===(r=this.market(t)).contract)return await this.setContractLeverage(e,t,s)}let d={leverage:this.numberToString(e)};[n,s]=this.handleMarginModeAndParams("setLeverage",s);let h=await this.isUTAEnabled();[h,s]=this.handleOptionBoolAndParams(s,"setLeverage","uta",h);let c={};if(h){let e;if("isolated"===n)throw new a.NotSupported(this.id+" unified trading account does not support isolated margin");if(d.accountMode="unified",[e,s]=this.handleOptionStringAndParams2(s,"setLeverage","currency","code"),void 0===e)throw new a.ArgumentsRequired(this.id+' setLeverage requires a currency code in the params["code"] for unified trading account');d.currency=this.currencyId(e),c=await this.utaPrivatePostAccountModeAccountModifyLeverageMarginCross(this.extend(d,s))}else{if(void 0===n)throw new a.ArgumentsRequired(this.id+" setLeverage requires a marginMode parameter");if("isolated"===n&&void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage requires a symbol parameter for isolated margin");void 0!==t&&(d.symbol=this.safeString(r,"id")),d.isIsolated="isolated"===n,c=await this.privatePostPositionUpdateUserLeverage(this.extend(d,s))}return c}async setContractLeverage(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");let[r,o]=this.handleMarginModeAndParams(t,i);if(void 0!==r&&"cross"!==r)throw new a.NotSupported(this.id+' setLeverage() currently supports only params["marginMode"] = "cross" for contracts');void 0===this.markets&&await this.loadMarkets();let n=this.market(t),d={symbol:n.id,leverage:e.toString()},h=await this.isUTAEnabled(),[c,l]=this.handleOptionBoolAndParams(o,"setLeverage","uta",h);c?(d.accountMode="unified",s=await this.utaPrivatePostAccountModeAccountModifyLeverage(this.extend(d,l))):s=await this.futuresPrivatePostChangeCrossUserLeverage(this.extend(d,l));let u=this.safeDict(s,"data",{}),f=this.safeNumber(u,"leverage");return{info:s,symbol:n.symbol,marginMode:void 0,longLeverage:f,shortLeverage:f}}async fetchFundingInterval(e,t={}){return await this.fetchFundingRate(e,t)}async fetchFundingRate(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id},[a,o]=this.handleOptionBoolAndParams(t,"fetchFundingRate","uta",!1);i=a?await this.utaGetMarketFundingRate(this.extend(r,o)):await this.futuresPublicGetFundingRateSymbolCurrent(this.extend(r,o));let n=this.safeDict(i,"data",{});return this.parseFundingRate(n,s)}async fetchFundingRates(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.utaV2GetMarketFundingRate(t),r=this.safeList(s,"data",[]),a=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.safeString(t,"symbol");void 0!==i&&i.startsWith(".")||a.push(t)}return this.parseFundingRates(a,i)}parseFundingRate(e,t){let i=this.safeInteger(e,"fundingTime"),s=this.safeInteger(e,"timePoint"),r=this.safeInteger(e,"newGranularityStartTime"),a=this.safeString(e,"symbol"),o=this.safeString2(e,"granularity","currentGranularity");return{info:e,symbol:this.safeSymbol(a,t,void 0,"contract"),markPrice:void 0,indexPrice:void 0,interestRate:this.safeNumber(e,"dailyInterestRate"),estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:this.safeNumber2(e,"nextFundingRate","value"),fundingTimestamp:i,fundingDatetime:this.iso8601(i),nextFundingRate:void 0,nextFundingTimestamp:r,nextFundingDatetime:this.iso8601(r),previousFundingRate:void 0,previousFundingTimestamp:s,previousFundingDatetime:this.iso8601(s),interval:this.parseFundingInterval(o)}}parseFundingInterval(e){return this.safeString({36e5:"1h",144e5:"4h",288e5:"8h",576e5:"16h",864e5:"24h"},e,e)}async fetchFundingRateHistory(e,t,i,s={}){let r;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={symbol:o.id},d=this.safeInteger(s,"until"),[h,c]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","uta",!1),l=this.omit(c,"until"),u=t,f=d;void 0===t&&(u=0),void 0===d&&(f=this.milliseconds());let p="data";if(h){n.startAt=u,n.endAt=f;let e=await this.utaGetMarketFundingRateHistory(this.extend(n,l));r=this.safeDict(e,"data",{}),p="list"}else n.from=u,n.to=f,r=await this.futuresPublicGetContractFundingRates(this.extend(n,l));let m=this.safeList(r,p,[]);return this.parseFundingRateHistories(m,o,t,i)}parseFundingRateHistory(e,t){let i=this.safeString(e,"symbol"),s=this.safeInteger2(e,"ts","timepoint");return{info:e,symbol:this.safeSymbol(i,t),fundingRate:this.safeNumber(e,"fundingRate"),timestamp:s,datetime:this.iso8601(s)}}async fetchFundingHistory(e,t,i,s={}){let r,o;void 0===this.markets&&await this.loadMarkets();let n=await this.isUTAEnabled();[n,r]=this.handleOptionBoolAndParams(s,"fetchFundingHistory","uta",n);let d={};if(void 0!==e)o=this.market(e),d.symbol=o.id;else if(!n)throw new a.ArgumentsRequired(this.id+" fetchFundingHistory() requires a symbol argument");void 0!==t&&(d.startAt=t);let h=[];if(n){void 0!==i&&(d.pageSize=i),[d,r]=this.handleUntilOption("endAt",d,r);let e=await this.utaPrivateGetPositionFundingHistory(this.extend(d,r)),t=this.safeDict(e,"data");h=this.safeList(t,"items",[])}else{void 0!==i&&(d.maxCount=i);let e=await this.futuresPrivateGetFundingHistory(this.extend(d,r)),t=this.safeDict(e,"data");h=this.safeList(t,"dataList",[])}let c=[];for(let e=0;e<h.length;e++){let t=h[e],i=this.safeInteger2(t,"timePoint","settlementTime"),s=this.safeString(t,"symbol");c.push({info:t,symbol:this.safeSymbol(s,o),code:this.safeCurrencyCode(this.safeString(t,"settleCurrency")),timestamp:i,datetime:this.iso8601(i),id:this.safeNumber(t,"id"),amount:this.safeNumber2(t,"funding","fundingFee"),fundingRate:this.safeNumber(t,"fundingRate"),markPrice:this.safeNumber(t,"markPrice"),positionQty:this.safeNumber2(t,"positionQty","size"),positionCost:this.safeNumber2(t,"positionCost","positionValue")})}return c}async fetchPosition(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id},o=await this.isUTAEnabled(),[n,d]=this.handleOptionBoolAndParams(t,"fetchPosition","uta",o);if(n){a.accountMode="unified",i=await this.utaPrivateGetAccountModePositionOpenList(this.extend(a,d));let e=this.safeList(i,"data",[]);s=this.safeDict(e,0,{})}else i=await this.futuresPrivateGetPosition(this.extend(a,d)),s=this.safeDict(i,"data",{});return this.parsePosition(s,r)}async fetchPositions(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=await this.isUTAEnabled(),[r,a]=this.handleOptionBoolAndParams(t,"fetchPositions","uta",s);i=r?await this.utaPrivateGetAccountModePositionOpenList(this.extend({accountMode:"unified",limit:200},a)):await this.futuresPrivateGetPositions(a);let o=this.safeList(i,"data",[]);return this.parsePositions(o,e)}async fetchPositionsHistory(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o=await this.isUTAEnabled();[o,a]=this.handleOptionBoolAndParams(s,"fetchPositionsHistory","uta",o);let n={},d=this.marketSymbols(e);if(void 0!==d&&1===d.length){let e=this.market(d[0]);n.symbol=e.id}if(o)void 0!==t&&(n.startAt=t),void 0!==i&&(n.pageSize=i),[n,a]=this.handleUntilOption("endAt",n,a),r=await this.utaPrivateGetPositionHistory(this.extend(n,a));else{n.limit=void 0===i?200:i,void 0!==t&&(n.from=t);let e=this.safeInteger(a,"until");void 0!==e&&(a=this.omit(a,"until"),n.to=e),r=await this.futuresPrivateGetHistoryPositions(this.extend(n,a))}let h=this.safeDict(r,"data"),c=this.safeList(h,"items",[]);return this.parsePositions(c,d)}parsePosition(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeInteger(e,"currentTimestamp");void 0===r&&(r=this.safeIntegerProduct(e,"creationTime",1e-6));let a=this.safeStringN(e,["currentQty","size","maxSize","closeSize"]),n=this.safeStringLower(e,"side"),d=this.safeStringLower(e,"type");void 0===n&&(void 0!==a?o.Y.stringGt(a,"0")?n="long":o.Y.stringLt(a,"0")&&(n="short"):void 0!==d&&(n=d.indexOf("long")>-1?"long":"short"));let h=o.Y.stringAbs(this.safeString2(e,"posCost","positionValue")),c=this.safeString2(e,"posInit","initialMargin"),l=o.Y.stringDiv(c,h),u=this.safeString2(e,"unrealisedPnl","unrealizedPnL"),f=this.safeBool(e,"crossMode"),p=this.safeStringLower(e,"marginMode");void 0!==f&&(p=!0===f?"cross":"isolated");let m=this.safeInteger(e,"closeTime");return void 0===m&&("closingTime"in e?m=this.safeIntegerProduct(e,"closingTime",1e-6):"updateTime"in e&&(m=this.safeIntegerProduct(e,"updateTime",1e-6))),this.safePosition({info:e,id:this.safeStringN(e,["id","positionId","closeId"]),symbol:this.safeString(s,"symbol"),timestamp:r,datetime:this.iso8601(r),lastUpdateTimestamp:m,initialMargin:this.parseNumber(c),initialMarginPercentage:this.parseNumber(l),maintenanceMargin:this.safeNumber2(e,"posMaint","maintenanceMargin"),maintenanceMarginPercentage:this.safeNumber2(e,"maintMarginReq","mmr"),entryPrice:this.safeNumberN(e,["avgEntryPrice","openPrice","entryPrice"]),notional:this.parseNumber(h),leverage:this.safeNumber2(e,"realLeverage","leverage"),unrealizedPnl:this.parseNumber(u),contracts:this.parseNumber(o.Y.stringAbs(a)),contractSize:this.safeValue(s,"contractSize"),realizedPnl:this.safeNumberN(e,["realisedPnl","pnl","realizedPnL"]),marginRatio:void 0,liquidationPrice:this.safeNumber(e,"liquidationPrice"),markPrice:this.safeNumber(e,"markPrice"),lastPrice:this.safeNumber(e,"closePrice"),collateral:this.safeNumber(e,"maintMargin"),marginMode:p,side:n,percentage:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}async cancelOrders(e,t,i={}){let s,r,o;void 0===this.markets&&await this.loadMarkets();let n=await this.isUTAEnabled();[n,r]=this.handleOptionBoolAndParams(i,"cancelOrders","uta",n);let d=!0;if(void 0!==t)!0!==(d=(o=this.market(t)).contract)&&(n=!0);else if(n)throw new a.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument for uta endpoint");let h=[],c=this.safeList2(r,"clientOrderIds","clientOids",[]);r=this.omit(r,["clientOrderIds","clientOids"]);let l=!1;for(let e=0;e<c.length;e++){if(l=!0,void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument when cancelling by clientOrderIds");h.push({symbol:this.safeString(o,"id"),clientOid:this.safeString(c,e)})}for(let t=0;t<e.length;t++){let i=e[t];n?h.push({orderId:i,symbol:this.safeString(o,"id")}):h.push(e[t])}let u={},f=[];if(n){let e,t="unified";[t,r]=this.handleOptionStringAndParams(r,"cancelOrders","accountMode",t),u.accountMode=t,[e,r]=this.handleMarginModeAndParams("cancelOrders",r);let i="unified"===t;u.tradeType=this.handleTradeType(d,e,i,r),u.cancelOrderList=h,s=await this.utaPrivatePostAccountModeOrderCancelBatch(this.extend(u,r));let a=this.safeDict(s,"data",{});f=this.safeList(a,"items",[])}else{let e="orderIdsList";l&&(e="clientOidsList"),u[e]=h,s=await this.futuresPrivateDeleteOrdersMultiCancel(this.extend(u,r)),f=this.safeList(s,"data",[])}return this.parseOrders(f,o)}async addMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=this.uuid(),a={symbol:s.id,margin:this.amountToPrecision(e,t),bizNo:r},o=await this.futuresPrivatePostPositionMarginDepositMargin(this.extend(a,i)),n=this.safeDict(o,"data",{});return this.extend(this.parseMarginModification(n,s),{amount:this.amountToPrecision(e,t),direction:"in"})}async reduceMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=this.amountToPrecision(e,t),a={symbol:s.id,withdrawAmount:r},o=await this.futuresPrivatePostMarginWithdrawMargin(this.extend(a,i)),n=this.safeString(s,"settle"),d=this.safeString(o,"code");return{info:o,symbol:s.symbol,type:"reduce",marginMode:"isolated",amount:this.parseNumber(r),total:void 0,code:this.safeCurrencyCode(n),status:"200000"===d?"ok":void 0,timestamp:void 0,datetime:void 0}}parseMarginModification(e,t){let i=this.safeString(e,"id"),s=this.safeMarket(i,t),r=this.safeString(e,"settleCurrency"),a=this.safeBool(e,"crossMode"),o=this.safeString(s,"symbol"),n=this.safeInteger(e,"currentTimestamp");return{info:e,symbol:this.safeSymbol(o,s),type:void 0,marginMode:!0===a?"cross":"isolated",amount:void 0,total:void 0,code:this.safeCurrencyCode(r),status:void 0,timestamp:n,datetime:this.iso8601(n)}}async fetchMarginMode(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.futuresPrivateGetPositionGetMarginMode(this.extend(s,t)),a=this.safeDict(r,"data",{});return this.parseMarginMode(a,i)}parseMarginMode(e,t){let i=this.safeString(e,"marginMode");return i="ISOLATED"===i?"isolated":"cross",{info:e,symbol:this.safeString(t,"symbol"),marginMode:i}}async setMarginMode(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");this.checkRequiredArgument("setMarginMode",e,"marginMode",["cross","isolated"]),void 0===this.markets&&await this.loadMarkets();let s=this.market(t);if(!0!==s.contract)throw new a.NotSupported(this.id+" setMarginMode() supports contract markets only");let r={symbol:s.id,marginMode:e.toUpperCase()},o=await this.futuresPrivatePostPositionChangeMarginMode(this.extend(r,i)),n=this.safeDict(o,"data",{});return this.parseMarginMode(n,s)}async setPositionMode(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s="0";e&&(s="1");let r={positionMode:s};return await this.futuresPrivatePostPositionSwitchPositionMode(this.extend(r,i))}async fetchPositionMode(e,t={}){let i=await this.futuresPrivateGetPositionGetPositionMode(t),s=this.safeDict(i,"data",{}),r=this.safeInteger(s,"positionMode");return{info:s,hedged:1===r}}async closePosition(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=this.safeString(i,"clientOrderId"),o=this.safeBool(i,"test",!1),n=this.omit(i,["test","clientOrderId"]);void 0===a&&(a=this.numberToString(this.nonce()));let d={symbol:r.id,closeOrder:!0,clientOid:a,type:"market"};return s=!0===o?await this.futuresPrivatePostOrdersTest(this.extend(d,n)):await this.futuresPrivatePostOrders(this.extend(d,n)),this.parseOrder(s,r)}async fetchMarketLeverageTiers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.contract)throw new a.BadRequest(this.id+" fetchMarketLeverageTiers() supports contract markets only");let[s,r]=this.handleOptionBoolAndParams(t,"fetchMarketLeverageTiers","uta",!1);if(s){let t=await this.fetchLeverageTiers([e],r);return this.safeList(t,e,[])}let o={symbol:i.id},n=await this.futuresPublicGetContractsRiskLimitSymbol(this.extend(o,r)),d=this.safeList(n,"data",[]);return this.parseMarketLeverageTiers(d,i)}parseMarketLeverageTiers(e,t){let i=t,s=[];for(let t=0;t<e.length;t++){let r=this.safeDict(e,t,{}),a=this.safeString(r,"symbol");i=this.safeMarket(a,i),s.push({tier:this.safeNumber2(r,"level","tier"),symbol:i.symbol,currency:i.base,minNotional:this.safeNumber2(r,"minRiskLimit","minSize"),maxNotional:this.safeNumber2(r,"maxRiskLimit","maxSize"),maintenanceMarginRate:this.safeNumber2(r,"maintainMargin","maintainMarginRate"),maxLeverage:this.safeNumber(r,"maxLeverage"),info:r})}return s}async fetchLeverageTiers(e,t={}){let i;if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ArgumentsRequired(this.id+" fetchLeverageTiers() requires a symbols argument");let s=this.marketSymbols(e,"swap",!1,!0),r="cross";if([r,i]=this.handleOptionStringAndParams(t,"fetchLeverageTiers","marginMode",r),"CROSS"!==(r=r.toUpperCase()))throw new a.BadRequest(this.id+" fetchLeverageTiers() supports cross margin only");let o={tradeType:"FUTURES",marginMode:r,data:"RISK_LIMIT",accountType:"UNIFIED",symbol:this.marketIds(s).join(",")},n=await this.utaGetMarketPositionTiers(this.extend(o,i)),d=this.safeList(n,"data",[]),h={},c=this.parseMarketLeverageTiers(d);for(let e=0;e<c.length;e++){let t=this.safeDict(c,e),i=this.safeString(t,"symbol");void 0!==i&&(i in h||(h[i]=[]),h[i].push(t))}return h}async fetchOpenInterests(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s={};void 0!==i&&i.length<11&&(s.symbol=this.marketIds(i).join(","));let r=await this.utaGetMarketOpenInterest(this.extend(s,t)),a=this.safeList(r,"data",[]);return this.parseOpenInterests(a,i)}parseOpenInterest(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeInteger(e,"ts");return this.safeOpenInterest({symbol:this.safeSymbol(i),openInterestAmount:this.safeNumber(e,"openInterest"),openInterestValue:void 0,timestamp:r,datetime:this.iso8601(r),info:e},s)}async fetchOpenInterestHistory(e,t="5m",i,s,r={}){let o=this.safeString({"5m":"5min","15m":"15min","30m":"30min","1h":"1hour","4h":"4hour","1d":"1day","5min":"5min","15min":"15min","30min":"30min","1hour":"1hour","4hour":"4hour","1day":"1day"},t);if(void 0===o)throw new a.BadRequest(this.id+" fetchOpenInterestHistory() invalid timeframe, supported are 5m, 15m, 30m, 1h, 4h, 1d");void 0===this.markets&&await this.loadMarkets();let n=this.market(e),[d,h]=this.handleOptionBoolAndParams(r,"fetchOpenInterestHistory","paginate",!1);if(d)return await this.fetchPaginatedCallDeterministic("fetchOpenInterestHistory",e,i,s,t,h,200);let c={symbol:n.id,interval:o};void 0!==i&&(c.startAt=i),void 0!==s&&(c.pageSize=s);let[l,u]=this.handleUntilOption("endAt",c,h),f=await this.utaGetMarketOpenInterest(this.extend(l,u)),p=this.safeList(f,"data");return this.parseOpenInterestsHistory(p,n,i,s)}async isUTAEnabled(e={}){let t=this.safeBool(this.options,"uta");if(void 0===t){let i=await this.utaPrivateGetAccountMode(e),s=this.safeDict(i,"data",{});t="UNIFIED"===this.safeString(s,"selfAccountMode"),this.options.uta=t}return t}sign(e,t="public",i="GET",r={},o,n){let d=this.safeDict(this.options,"versions",{}),h=this.safeDict(d,t,{}),c=this.safeDict(h,i,{}),l=this.safeString(c,e,this.options.version),u=this.safeString(r,"version",l),f=this.omit(r,"version"),p="/api/"+u+"/"+this.implodeParams(e,f);"utaV2"===t&&(p="/api/ua/v2/"+this.implodeParams(e,f)),"webExchange"===t&&(p="/"+this.implodeParams(e,f)),"earn"===t&&(p="/api/v1/"+this.implodeParams(e,f));let m=!1;("uta"===t||"utaPrivate"===t)&&(p="/api/ua/v1/"+this.implodeParams(e,f),"utaPrivate"===t&&(m=!0));let g=this.omit(f,this.extractParams(e)),v="",y={};void 0!==o&&(y=o);let b=n,w=this.safeString(this.urls.api,t);if(void 0===w)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let k=this.safeString(g,"tradeType");this.isEmpty(g)||(("GET"===i||"DELETE"===i)&&"orders/multi-cancel"!==e?p+="?"+this.rawencode(g):(("/api/ua/v1/classic/order/place"===p||"/api/ua/v1/classic/order/place/batch"===p||"/api/ua/v1/classic/order/cancel"===p||"/api/ua/v1/classic/order/cancel/batch"===p)&&(p+="?tradeType="+k),v=b=this.json(g),y["Content-Type"]="application/json"));let S=y,O="futuresPrivate"===t,T="private"===t,P="broker"===t,I="earn"===t;if(T||O||P||I||m){this.checkRequiredCredentials();let e=this.nonce().toString(),t=this.extend({"KC-API-KEY-VERSION":"2","KC-API-KEY":this.apiKey,"KC-API-TIMESTAMP":e},y);if("2"===this.safeString(t,"KC-API-KEY-VERSION")){let e=this.hmac(this.encode(this.password),this.encode(this.secret),s.sc,"base64");t["KC-API-PASSPHRASE"]=e}else t["KC-API-PASSPHRASE"]=this.password;let r=e+i+p+v,a=this.hmac(this.encode(r),this.encode(this.secret),s.sc,"base64");t["KC-API-SIGN"]=a;let o=this.safeDict(this.options,"partner",{}),n=m&&"FUTURES"===k;o=O||n?this.safeValue(o,"future",o):this.safeValue(o,"spot",o);let d=this.safeString(o,"id"),h=this.safeString2(o,"secret","key");if(void 0!==d&&void 0!==h){let i=e+d+this.apiKey,r=this.hmac(this.encode(i),this.encode(h),s.sc,"base64");t["KC-API-PARTNER-SIGN"]=r,t["KC-API-PARTNER"]=d,t["KC-API-PARTNER-VERIFY"]="true"}if(P){let e=this.safeString(o,"name");void 0!==e&&(t["KC-BROKER-NAME"]=e)}S=t}return{url:w+p,method:i,body:b,headers:S}}handleErrors(e,t,i,s,r,o,n,d,h){if(null==n)return void this.throwBroadlyMatchedException(this.exceptions.broad,o,o);let c=this.safeString(n,"code"),l=this.safeString2(n,"msg","data",""),u=this.id+" "+o;if(this.throwExactlyMatchedException(this.exceptions.exact,l,u),this.throwExactlyMatchedException(this.exceptions.exact,c,u),this.throwBroadlyMatchedException(this.exceptions.broad,o,u),"200000"!==c&&"200"!==c)throw new a.ExchangeError(u)}async fetchTransfers(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchTransfers","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchTransfers",e,t,i,o);let n={bizType:"TRANSFER"},d=this.safeInteger(o,"until"),h=void 0!==d?this.omit(o,"until"):o;void 0!==d&&(n.endAt=d),void 0!==e&&(r=this.currency(e),n.currency=r.id),void 0!==t&&(n.startAt=t),void 0!==i?n.pageSize=i:n.pageSize=500,[n,h]=this.handleUntilOption("endAt",n,h);let c=await this.privateGetAccountsLedgers(this.extend(n,h)),l=this.safeDict(c,"data",{}),u=this.safeList(l,"items",[]);return this.parseTransfers(u,r,t,i)}async fetchPositionsADLRank(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s=await this.futuresPrivateGetPositions(t),r=this.safeList(s,"data",[]);return this.parseADLRanks(r,i)}parseADLRank(e,t){let i=this.safeString(e,"symbol"),s=this.safeInteger(e,"openingTimestamp"),r=this.safeString(e,"delevPercentage");return{info:e,symbol:this.safeSymbol(i,t,void 0,"contract"),rank:void 0,rating:void 0,percentage:this.parseNumber(o.Y.stringMul(r,"100")),timestamp:s,datetime:this.iso8601(s)}}}i.d(t,{A:()=>n})},9787(e,t,i){"use strict";var s=i(455),r=i(1453);class a extends s.A{describe(){return this.deepExtend(super.describe(),{id:"kucoinfutures",name:"KuCoin Futures",urls:{logo:"https://user-images.githubusercontent.com/1294454/147508995-9e35030a-d046-43a1-a006-6fabd981b554.jpg",www:"https://futures.kucoin.com/",referral:"https://futures.kucoin.com/?rcode=E5wkqe"},has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!0,option:void 0,fetchBidsAsks:!0,transfer:!0},options:{fetchMarkets:{types:["swap","future","contract"],fetchTickersFees:!1},defaultType:"swap",defaultAccountType:"contract"}})}async fetchBidsAsks(e,t={}){let i=this.extend({method:"futuresPublicGetAllTickers"},t);return await this.fetchTickers(e,i)}async transfer(e,t,i,s,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d=this.currencyToPrecision(e,t),h={currency:this.safeString(n,"id"),amount:d},c=this.parseTransferType(s);if("TRADE"===c||"MAIN"===c)h.recAccountType=c,o=await this.futuresPrivatePostTransferOut(this.extend(h,a));else if("future"===s||"swap"===s||"contract"===s)h.payAccountType=this.parseTransferType(i),o=await this.futuresPrivatePostTransferIn(this.extend(h,a));else throw new r.BadRequest(this.id+" transfer() only supports transfers between future/swap, spot and funding accounts");let l=this.safeDict(o,"data",{});return this.extend(this.parseTransfer(l,n),{amount:this.parseNumber(d),fromAccount:i,toAccount:s})}parseTransferType(e){return this.safeStringUpper({spot:"TRADE",funding:"MAIN"},e,e)}}i.d(t,{A:()=>a})},9252(e,t,i){"use strict";var s=i(4721),r=i(3851),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"latoken",name:"Latoken",countries:["KY"],version:"v2",rateLimit:1e3,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createOrder:!0,createPostOnlyOrder:!1,createStopLimitOrder:!0,createStopMarketOrder:!1,createStopOrder:!0,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDepositsWithdrawals:!0,fetchDepositWithdrawFees:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrice:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!1,fetchTransactions:"emulated",fetchTransfer:!1,fetchTransfers:!0,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!0},urls:{logo:"https://user-images.githubusercontent.com/1294454/61511972-24c39f00-aa01-11e9-9f7c-471f1d6e5214.jpg",api:{rest:"https://api.latoken.com"},www:"https://latoken.com",doc:["https://api.latoken.com"],fees:"https://latoken.com/fees",referral:"https://latoken.com/invite?r=mvgp2djk"},api:{public:{get:{"book/{currency}/{quote}":{cost:1},"chart/week":{cost:1},"chart/week/{currency}/{quote}":{cost:1},currency:{cost:1},"currency/available":{cost:1},"currency/quotes":{cost:1},"currency/{currency}":{cost:1},pair:{cost:1},"pair/available":{cost:1},ticker:{cost:1},"ticker/{base}/{quote}":{cost:1},time:{cost:1},"trade/history/{currency}/{quote}":{cost:1},"trade/fee/{currency}/{quote}":{cost:1},"trade/feeLevels":{cost:1},"transaction/bindings":{cost:1}}},private:{get:{"auth/account":{cost:1},"auth/account/currency/{currency}/{type}":{cost:1},"auth/account/filtered":{cost:1},"auth/order":{cost:1},"auth/order/active":{cost:1},"auth/order/getOrder/{id}":{cost:1},"auth/order/pair/{currency}/{quote}":{cost:1},"auth/order/pair/{currency}/{quote}/active":{cost:1},"auth/stopOrder":{cost:1},"auth/stopOrder/getOrder/{id}":{cost:1},"auth/stopOrder/pair/{currency}/{quote}":{cost:1},"auth/stopOrder/pair/{currency}/{quote}/active":{cost:1},"auth/trade":{cost:1},"auth/trade/pair/{currency}/{quote}":{cost:1},"auth/trade/fee/{currency}/{quote}":{cost:1},"auth/transaction":{cost:1},"auth/transaction/bindings":{cost:1},"auth/transaction/bindings/{currency}":{cost:1},"auth/transaction/{id}":{cost:1},"auth/transfer":{cost:1}},post:{"auth/order/cancel":{cost:1},"auth/order/cancelAll":{cost:1},"auth/order/cancelAll/{currency}/{quote}":{cost:1},"auth/order/cancelBulk":{cost:1},"auth/order/place":{cost:1},"auth/order/placeBulk":{cost:1},"auth/spot/deposit":{cost:1},"auth/spot/withdraw":{cost:1},"auth/stopOrder/cancel":{cost:1},"auth/stopOrder/cancelAll":{cost:1},"auth/stopOrder/cancelAll/{currency}/{quote}":{cost:1},"auth/stopOrder/place":{cost:1},"auth/transaction/depositAddress":{cost:1},"auth/transaction/withdraw":{cost:1},"auth/transaction/withdraw/cancel":{cost:1},"auth/transaction/withdraw/confirm":{cost:1},"auth/transaction/withdraw/resendCode":{cost:1},"auth/transfer/email":{cost:1},"auth/transfer/id":{cost:1},"auth/transfer/phone":{cost:1}}}},precisionMode:4,fees:{trading:{feeSide:"get",tierBased:!1,percentage:!0,maker:this.parseNumber("0.0049"),taker:this.parseNumber("0.0049")}},commonCurrencies:{BUX:"Buxcoin",CBT:"Community Business Token",CTC:"CyberTronchain",DMD:"Diamond Coin",FREN:"Frenchie",GDX:"GoldenX",GEC:"Geco One",GEM:"NFTmall",GMT:"GMT Token",IMC:"IMCoin",MT:"Monarch",TPAY:"Tetra Pay",TRADE:"Smart Trade Coin",TSL:"Treasure SL",UNO:"Unobtanium",WAR:"Warrior Token"},exceptions:{exact:{INTERNAL_ERROR:a.ExchangeError,SERVICE_UNAVAILABLE:a.ExchangeNotAvailable,NOT_AUTHORIZED:a.AuthenticationError,FORBIDDEN:a.PermissionDenied,BAD_REQUEST:a.BadRequest,NOT_FOUND:a.ExchangeError,ACCESS_DENIED:a.PermissionDenied,REQUEST_REJECTED:a.ExchangeError,HTTP_MEDIA_TYPE_NOT_SUPPORTED:a.BadRequest,MEDIA_TYPE_NOT_ACCEPTABLE:a.BadRequest,METHOD_ARGUMENT_NOT_VALID:a.BadRequest,VALIDATION_ERROR:a.BadRequest,ACCOUNT_EXPIRED:a.AccountSuspended,BAD_CREDENTIALS:a.AuthenticationError,COOKIE_THEFT:a.AuthenticationError,CREDENTIALS_EXPIRED:a.AccountSuspended,INSUFFICIENT_AUTHENTICATION:a.AuthenticationError,UNKNOWN_LOCATION:a.AuthenticationError,TOO_MANY_REQUESTS:a.RateLimitExceeded,INSUFFICIENT_FUNDS:a.InsufficientFunds,ORDER_VALIDATION:a.InvalidOrder,BAD_TICKS:a.InvalidOrder},broad:{"invalid API key, signature or digest":a.AuthenticationError,"The API key was revoked":a.AuthenticationError,"request expired or bad":a.InvalidNonce,"For input string":a.BadRequest,"Unable to resolve currency by tag":a.BadSymbol,"Can't find currency with tag":a.BadSymbol,"Unable to place order because pair is in inactive state":a.BadSymbol,"API keys are not available for":a.AccountSuspended}},options:{defaultType:"spot",types:{wallet:"ACCOUNT_TYPE_WALLET",funding:"ACCOUNT_TYPE_WALLET",spot:"ACCOUNT_TYPE_SPOT"},accounts:{ACCOUNT_TYPE_WALLET:"wallet",ACCOUNT_TYPE_SPOT:"spot"},fetchTradingFee:{method:"fetchPrivateTradingFee"},timeDifference:0,adjustForTimeDifference:!0},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!1,GTD:!1},hedged:!1,selfTradePrevention:!1,trailing:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:1e5,untilDays:void 0,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!0,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:1e3,daysBack:1e5,daysBackCanceled:1,untilDays:void 0,trigger:!0,trailing:!1,symbolRequired:!1},fetchOHLCV:void 0},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}}})}nonce(){let e=this.safeInteger(this.options,"timeDifference");if(void 0===e)throw new a.ExchangeError(this.id+' nonce() requires a numeric options["timeDifference"]');return this.milliseconds()-e}async fetchTime(e={}){let t=await this.publicGetTime(e);return this.safeInteger(t,"serverTime")}async fetchMarkets(e={}){let t=await this.publicGetPair(e);this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference();let i=this.safeDict(this.options,"cachedCurrencies",{}),s=this.indexBy(i,"id"),r=[],a=this.toArray(t);for(let e=0;e<a.length;e++){let t=a[e],i=this.safeString(t,"id"),o=this.safeString(t,"baseCurrency"),n=this.safeString(t,"quoteCurrency"),d=this.safeDict(s,o),h=this.safeDict(s,n),c=this.safeDict(d,"info"),l=this.safeDict(h,"info");if(void 0!==c&&void 0!==l){let e=this.safeCurrencyCode(this.safeString(c,"tag")),s=this.safeCurrencyCode(this.safeString(l,"tag"));if(void 0===e||void 0===s)continue;let a=s.toLowerCase(),d=this.capitalize(a),h=this.safeString(t,"status");r.push({id:i,symbol:e+"/"+s,base:e,quote:s,settle:void 0,baseId:o,quoteId:n,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:"PAIR_STATUS_ACTIVE"===h,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(t,"quantityTick"),price:this.safeNumber(t,"priceTick")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(t,"minOrderQuantity"),max:void 0},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(t,"minOrderCost"+d),max:this.safeNumber(t,"maxOrderCost"+d)}},created:this.safeInteger(t,"created"),info:t})}}return r}async fetchCurrencies(e={}){let t=await this.publicGetCurrency(e);return this.parseCurrencies(t)}parseCurrency(e){let t=this.safeString(e,"id"),i=this.safeString(e,"tag"),s=this.safeCurrencyCode(i),r=this.safeString(e,"type");return this.safeCurrencyStructure({id:t,code:s,info:e,name:this.safeString(e,"name"),type:"CURRENCY_TYPE_CRYPTO"===r||"CURRENCY_TYPE_IEO"===r?"crypto":"other",active:"CURRENCY_STATUS_ACTIVE"===this.safeString(e,"status"),deposit:void 0,withdraw:void 0,fee:this.safeNumber(e,"fee"),precision:this.parseNumber(this.parsePrecision(this.safeString(e,"decimals"))),limits:{amount:{min:this.safeNumber(e,"minTransferAmount"),max:void 0},withdraw:{min:void 0,max:void 0}},networks:{}})}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let i=await this.privateGetAuthAccount(e),s={info:i,timestamp:void 0,datetime:void 0},r=this.safeString2(this.options,"fetchBalance","defaultType","spot"),a=this.safeString(e,"type",r),o=this.safeDict(this.options,"types",{}),n=this.safeString(o,a,a),d=this.groupBy(i,"type"),h=this.safeList(d,n,[]);for(let e=0;e<h.length;e++){let i=this.safeDict(h,e),r=this.safeString(i,"currency"),a=this.safeInteger(i,"timestamp");void 0!==a&&(t=void 0===t?a:Math.max(t,a));let o=this.safeCurrencyCode(r),n=this.account();n.free=this.safeString(i,"available"),n.used=this.safeString(i,"blocked"),void 0!==o&&(s[o]=n)}return s.timestamp=t,s.datetime=this.iso8601(t),this.safeBalance(s)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={currency:s.baseId,quote:s.quoteId};void 0!==t&&(r.limit=t);let a=await this.publicGetBookCurrencyQuote(this.extend(r,i)),n=this.safeList(a,"ask",[]),d=this.safeList(a,"bid",[]),h=[],c=[];for(let e=0;e<n.length;e++){let t=n[e],i=this.safeString(t,"quantity");o.A.stringGt(i,"0")&&h.push(t)}for(let e=0;e<d.length;e++){let t=d[e],i=this.safeString(t,"quantity");o.A.stringGt(i,"0")&&c.push(t)}return this.parseOrderBook({ask:h,bid:c},e,void 0,"bid","ask","price","quantity")}parseTicker(e,t){let i=this.safeString(e,"symbol"),s=this.safeString(e,"lastPrice"),r=this.safeIntegerOmitZero(e,"updateTimestamp");return this.safeTicker({symbol:this.safeSymbol(i,t),timestamp:r,datetime:this.iso8601(r),low:void 0,high:void 0,bid:this.safeString(e,"bestBid"),bidVolume:this.safeString(e,"bestBidQuantity"),ask:this.safeString(e,"bestAsk"),askVolume:this.safeString(e,"bestAskQuantity"),vwap:void 0,open:void 0,close:s,last:s,previousClose:void 0,change:void 0,percentage:this.safeString(e,"change24h"),average:void 0,baseVolume:this.safeString(e,"amount24h"),quoteVolume:this.safeString(e,"volume24h"),info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={base:i.baseId,quote:i.quoteId},r=await this.publicGetTickerBaseQuote(this.extend(s,t));return this.parseTicker(r,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetTicker(t);return this.parseTickers(i,e)}parseTrade(e,t){let i,s,r=this.safeInteger(e,"timestamp"),a=this.safeString(e,"price"),o=this.safeString(e,"quantity"),n=this.safeString(e,"cost"),d=this.safeBool(e,"makerBuyer"),h=this.safeString(e,"direction");void 0===h?h=!0===d?"sell":"buy":"TRADE_DIRECTION_BUY"===h?h="buy":"TRADE_DIRECTION_SELL"===h&&(h="sell");let c="buy"===h,l=this.safeString(e,"baseCurrency"),u=this.safeString(e,"quoteCurrency"),f=this.safeCurrencyCode(l),p=this.safeCurrencyCode(u),m=t;void 0!==f&&void 0!==p&&(i=f+"/"+p,void 0!==this.markets&&i in this.markets&&(m=this.market(i)));let g=this.safeString(e,"id"),v=this.safeString(e,"order"),y=this.safeString(e,"fee");return void 0!==y&&(s={cost:y,currency:p}),this.safeTrade({info:e,timestamp:r,datetime:this.iso8601(r),symbol:i,id:g,order:v,type:void 0,takerOrMaker:!0===d&&c?"maker":"taker",side:h,price:a,amount:o,cost:n,fee:s},m)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={currency:r.baseId,quote:r.quoteId};void 0!==i&&(a.limit=Math.min(i,100));let o=await this.publicGetTradeHistoryCurrencyQuote(this.extend(a,s));return this.parseTrades(o,r,t,i)}async fetchTradingFee(e,t={}){let i=this.safeDict(this.options,"fetchTradingFee",{}),s=this.safeString(i,"method","fetchPrivateTradingFee"),r=this.safeString(t,"method",s),o=this.omit(t,"method");if("fetchPrivateTradingFee"===r)return await this.fetchPrivateTradingFee(e,o);if("fetchPublicTradingFee"===r)return await this.fetchPublicTradingFee(e,o);throw new a.NotSupported(this.id+" not support this method")}async fetchPublicTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={currency:i.baseId,quote:i.quoteId},r=await this.publicGetTradeFeeCurrencyQuote(this.extend(s,t));return{info:r,symbol:i.symbol,maker:this.safeNumber(r,"makerFee"),taker:this.safeNumber(r,"takerFee"),percentage:void 0,tierBased:void 0}}async fetchPrivateTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={currency:i.baseId,quote:i.quoteId},r=await this.privateGetAuthTradeFeeCurrencyQuote(this.extend(s,t));return{info:r,symbol:i.symbol,maker:this.safeNumber(r,"makerFee"),taker:this.safeNumber(r,"takerFee"),percentage:void 0,tierBased:void 0}}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==i&&(a.limit=i);let o=[];return void 0!==e?(a.currency=(r=this.market(e)).baseId,a.quote=r.quoteId,o=await this.privateGetAuthTradePairCurrencyQuote(this.extend(a,s))):o=await this.privateGetAuthTrade(this.extend(a,s)),this.parseTrades(o,r,t,i)}parseOrderStatus(e){return this.safeString({ORDER_STATUS_PLACED:"open",ORDER_STATUS_CLOSED:"closed",ORDER_STATUS_CANCELLED:"canceled"},e,e)}parseOrderType(e){return this.safeString({ORDER_TYPE_MARKET:"market",ORDER_TYPE_LIMIT:"limit"},e,e)}parseTimeInForce(e){return this.safeString({ORDER_CONDITION_GOOD_TILL_CANCELLED:"GTC",ORDER_CONDITION_IMMEDIATE_OR_CANCEL:"IOC",ORDER_CONDITION_FILL_OR_KILL:"FOK"},e,e)}parseOrder(e,t){let i,s,r=this.safeString(e,"id"),a=this.safeInteger(e,"timestamp"),o=this.safeString(e,"baseCurrency"),n=this.safeString(e,"quoteCurrency"),d=this.safeCurrencyCode(o),h=this.safeCurrencyCode(n);void 0!==d&&void 0!==h&&(i=d+"/"+h);let c=void 0!==i&&void 0!==this.markets&&i in this.markets,l=t;c&&(l=this.market(i));let u=this.safeString(e,"side");if(void 0!==u){let e=u.split("_"),t=e.length;s=this.safeStringLower(e,t-1)}let f=this.parseOrderType(this.safeString(e,"type")),p=this.safeString(e,"price"),m=this.safeString(e,"quantity"),g=this.safeString(e,"filled"),v=this.safeString(e,"cost"),y=this.parseOrderStatus(this.safeString(e,"status")),b=this.safeString(e,"message");void 0!==b&&(b.indexOf("cancel")>=0?y="canceled":b.indexOf("accept")>=0&&(y="open"));let w=this.safeString(e,"clientOrderId"),k=this.parseTimeInForce(this.safeString(e,"condition"));return this.safeOrder({id:r,clientOrderId:w,info:e,timestamp:a,datetime:this.iso8601(a),lastTradeTimestamp:void 0,status:y,symbol:i,type:f,timeInForce:k,postOnly:void 0,side:s,price:p,triggerPrice:this.safeString(e,"stopPrice"),cost:v,amount:m,filled:g,average:void 0,remaining:void 0,fee:void 0,trades:void 0},l)}async fetchOpenOrders(e,t,i,s={}){let r;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOpenOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let o=this.safeBool2(s,"trigger","stop"),n=this.omit(s,"stop"),d=this.market(e),h={currency:d.baseId,quote:d.quoteId};return r=!0===o?await this.privateGetAuthStopOrderPairCurrencyQuoteActive(this.extend(h,n)):await this.privateGetAuthOrderPairCurrencyQuoteActive(this.extend(h,n)),this.parseOrders(r,d,t,i)}async fetchOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o={},n=this.safeBool2(s,"trigger","stop"),d=this.omit(s,["stop","trigger"]);return void 0!==i&&(o.limit=i),void 0!==e?(o.currency=(a=this.market(e)).baseId,o.quote=a.quoteId,r=!0===n?await this.privateGetAuthStopOrderPairCurrencyQuote(this.extend(o,d)):await this.privateGetAuthOrderPairCurrencyQuote(this.extend(o,d))):r=!0===n?await this.privateGetAuthStopOrder(this.extend(o,d)):await this.privateGetAuthOrder(this.extend(o,d)),this.parseOrders(r,a,t,i)}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r={id:e},a=this.safeBool2(i,"trigger","stop"),o=this.omit(i,["stop","trigger"]);return s=!0===a?await this.privateGetAuthStopOrderGetOrderId(this.extend(r,o)):await this.privateGetAuthOrderGetOrderId(this.extend(r,o)),this.parseOrder(s)}async createOrder(e,t,i,s,r,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=t.toUpperCase();this.checkRequiredArgument("createOrder",i,"side");let h={baseCurrency:n.baseId,quoteCurrency:n.quoteId,side:i.toUpperCase(),condition:"GTC",type:d,clientOrderId:this.uuid(),quantity:this.amountToPrecision(e,s),timestamp:this.seconds()};"LIMIT"===d&&(h.price=this.priceToPrecision(e,r));let c=this.safeString2(a,"triggerPrice","stopPrice"),l=this.omit(a,["triggerPrice","stopPrice"]);return void 0!==c?(h.stopPrice=this.priceToPrecision(e,c),o=await this.privatePostAuthStopOrderPlace(this.extend(h,l))):o=await this.privatePostAuthOrderPlace(this.extend(h,l)),this.parseOrder(o,n)}async cancelOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r={id:e},a=this.safeBool2(i,"trigger","stop"),o=this.omit(i,["stop","trigger"]);return s=!0===a?await this.privatePostAuthStopOrderCancel(this.extend(r,o)):await this.privatePostAuthOrderCancel(this.extend(r,o)),this.parseOrder(s)}async cancelAllOrders(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r={},a=this.safeBool2(t,"trigger","stop"),o=this.omit(t,["stop","trigger"]);return void 0!==e?(r.currency=(s=this.market(e)).baseId,r.quote=s.quoteId,i=!0===a?await this.privatePostAuthStopOrderCancelAllCurrencyQuote(this.extend(r,o)):await this.privatePostAuthOrderCancelAllCurrencyQuote(this.extend(r,o))):i=!0===a?await this.privatePostAuthStopOrderCancelAll(this.extend(r,o)):await this.privatePostAuthOrderCancelAll(this.extend(r,o)),[this.safeOrder({info:i})]}async fetchTransactions(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=await this.privateGetAuthTransaction(this.extend({},s));void 0!==e&&(r=this.currency(e));let o=this.safeList(a,"content",[]);return this.parseTransactions(o,r,t,i)}parseTransaction(e,t){let i=this.safeString(e,"id"),s=this.safeInteger(e,"timestamp"),r=this.safeString(e,"currency"),a=this.safeCurrencyCode(r,t),o=this.parseTransactionStatus(this.safeString(e,"status")),n=this.safeNumber(e,"amount"),d=this.safeString(e,"senderAddress"),h=this.safeString(e,"recipientAddress"),c=this.safeString(e,"transactionHash"),l=this.safeString(e,"memo"),u={currency:void 0,cost:void 0,rate:void 0},f=this.safeNumber(e,"transactionFee");void 0!==f&&(u.cost=f,u.currency=a);let p=this.parseTransactionType(this.safeString(e,"type"));return{info:e,id:i,txid:c,timestamp:s,datetime:this.iso8601(s),network:void 0,addressFrom:d,addressTo:h,address:h,tagFrom:void 0,tagTo:l,tag:l,type:p,amount:n,currency:a,status:o,updated:void 0,comment:void 0,internal:void 0,fee:u}}parseTransactionStatus(e){return this.safeString({TRANSACTION_STATUS_CONFIRMED:"ok",TRANSACTION_STATUS_EXECUTED:"ok",TRANSACTION_STATUS_CHECKING:"pending",TRANSACTION_STATUS_CANCELLED:"canceled",TRANSACTION_STATUS_FAILED:"failed",TRANSACTION_STATUS_REJECTED:"rejected"},e,e)}parseTransactionType(e){return this.safeString({TRANSACTION_TYPE_DEPOSIT:"deposit",TRANSACTION_TYPE_WITHDRAWAL:"withdrawal"},e,e)}async fetchTransfers(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),a=await this.privateGetAuthTransfer(s),o=this.safeList(a,"content",[]);return this.parseTransfers(o,r,t,i)}async transfer(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o={currency:this.currency(e).id,recipient:s,value:this.currencyToPrecision(e,t)};return a=s.indexOf("@")>=0?await this.privatePostAuthTransferEmail(this.extend(o,r)):36===s.length?await this.privatePostAuthTransferId(this.extend(o,r)):await this.privatePostAuthTransferPhone(this.extend(o,r)),this.parseTransfer(a)}parseTransfer(e,t){let i=this.safeTimestamp(e,"timestamp"),s=this.safeString(e,"currency"),r=this.safeString(e,"status");return{info:e,id:this.safeString(e,"id"),timestamp:this.safeInteger(e,"timestamp"),datetime:this.iso8601(i),currency:this.safeCurrencyCode(s,t),amount:this.safeNumber(e,"transferringFunds"),fromAccount:this.safeString(e,"fromAccount"),toAccount:this.safeString(e,"toAccount"),status:this.parseTransferStatus(r)}}parseTransferStatus(e){return this.safeString({TRANSFER_STATUS_COMPLETED:"ok",TRANSFER_STATUS_PENDING:"pending",TRANSFER_STATUS_REJECTED:"failed",TRANSFER_STATUS_UNVERIFIED:"pending",TRANSFER_STATUS_CANCELLED:"canceled"},e,e)}sign(e,t="public",i="GET",r={},o,n){let d=o,h=n,c="/"+this.version+"/"+this.implodeParams(e,r),l=c,u=this.omit(r,this.extractParams(e)),f=this.urlencode(u);if("GET"===i&&Object.keys(u).length>0&&(l+="?"+f),"private"===t){this.checkRequiredCredentials();let e=this.hmac(this.encode(i+c+f),this.encode(this.secret),s.Zf);d={"X-LA-APIKEY":this.apiKey,"X-LA-SIGNATURE":e,"X-LA-DIGEST":"HMAC-SHA512"},"POST"===i&&(d["Content-Type"]="application/json",h=this.json(u))}let p=this.safeString(this.urls.api,"rest");if(void 0===p)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");return{url:p+l,method:i,body:h,headers:d}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"message"),l=this.id+" "+o;void 0!==c&&(this.throwExactlyMatchedException(this.exceptions.exact,c,l),this.throwBroadlyMatchedException(this.exceptions.broad,c,l));let u=this.safeValue(n,"error"),f=this.safeString(u,"message");if(void 0!==u||void 0!==f)throw this.throwExactlyMatchedException(this.exceptions.exact,u,l),this.throwBroadlyMatchedException(this.exceptions.broad,o,l),new a.ExchangeError(l)}}i.d(t,{A:()=>n})},7162(e,t,i){"use strict";var s=i(8858),r=i(4721),a=i(1713),o=i(1453),n=i(7749),d=i(8748);class h extends a.A{describe(){return this.deepExtend(super.describe(),{id:"lbank",name:"LBank",countries:["CN"],version:"v2",rateLimit:20,pro:!0,has:{CORS:!1,spot:!0,margin:!1,swap:void 0,future:!1,option:!1,addMargin:!1,cancelAllOrders:!0,cancelOrder:!0,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,fetchBalance:!0,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchClosedOrders:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!1,fetchFundingRate:!0,fetchFundingRateHistory:!1,fetchFundingRates:!0,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverageTiers:!1,fetchMarginMode:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTransactionFees:!0,fetchWithdrawals:!0,reduceMargin:!1,setLeverage:!1,setMarginMode:!1,setPositionMode:!1,withdraw:!0},timeframes:{"1m":"minute1","5m":"minute5","15m":"minute15","30m":"minute30","1h":"hour1","2h":"hour2","4h":"hour4","6h":"hour6","8h":"hour8","12h":"hour12","1d":"day1","1w":"week1"},urls:{logo:"https://user-images.githubusercontent.com/1294454/38063602-9605e28a-3302-11e8-81be-64b1e53c4cfb.jpg",api:{rest:"https://api.lbank.info",contract:"https://lbkperp.lbank.com"},api2:"https://api.lbkex.com",www:"https://www.lbank.com",doc:"https://www.lbank.com/en-US/docs/index.html",fees:"https://support.lbank.site/hc/en-gb/articles/900000535703-Trading-Fees-From-14-00-on-April-7-2020-UTC-8-",referral:"https://www.lbank.com/login/?icode=7QCY"},api:{spot:{public:{get:{currencyPairs:{cost:2.5},accuracy:{cost:2.5},usdToCny:{cost:2.5},assetConfigs:{cost:2.5},withdrawConfigs:{cost:3.75},timestamp:{cost:2.5},"ticker/24hr":{cost:2.5},ticker:{cost:2.5},depth:{cost:2.5},incrDepth:{cost:2.5},trades:{cost:2.5},kline:{cost:2.5},"supplement/system_ping":{cost:2.5},"supplement/incrDepth":{cost:2.5},"supplement/trades":{cost:2.5},"supplement/ticker/price":{cost:2.5},"supplement/ticker/bookTicker":{cost:2.5}},post:{"supplement/system_status":{cost:2.5}}},private:{post:{user_info:{cost:2.5},"subscribe/get_key":{cost:2.5},"subscribe/refresh_key":{cost:2.5},"subscribe/destroy_key":{cost:2.5},get_deposit_address:{cost:2.5},deposit_history:{cost:2.5},create_order:{cost:1},batch_create_order:{cost:1},cancel_order:{cost:1},cancel_clientOrders:{cost:1},orders_info:{cost:2.5},orders_info_history:{cost:2.5},order_transaction_detail:{cost:2.5},transaction_history:{cost:2.5},orders_info_no_deal:{cost:2.5},withdraw:{cost:2.5},withdrawCancel:{cost:2.5},withdraws:{cost:2.5},"supplement/user_info":{cost:2.5},"supplement/withdraw":{cost:2.5},"supplement/deposit_history":{cost:2.5},"supplement/withdraws":{cost:2.5},"supplement/get_deposit_address":{cost:2.5},"supplement/add_deposit_address":{cost:2.5},"supplement/asset_detail":{cost:2.5},"supplement/customer_trade_fee":{cost:2.5},"supplement/api_Restrictions":{cost:2.5},"supplement/system_ping":{cost:2.5},"supplement/create_order_test":{cost:1},"supplement/create_order":{cost:1},"supplement/cancel_order":{cost:1},"supplement/cancel_order_by_symbol":{cost:1},"supplement/orders_info":{cost:2.5},"supplement/orders_info_no_deal":{cost:2.5},"supplement/orders_info_history":{cost:2.5},"supplement/user_info_account":{cost:2.5},"supplement/transaction_history":{cost:2.5},"spot/wallet/withdraw":{cost:2.5},"spot/wallet/deposit_history":{cost:2.5},"spot/wallet/withdraws":{cost:2.5},"spot/trade/orders_info":{cost:2.5},"spot/trade/orders_info_history":{cost:2.5}}}},contract:{public:{get:{"cfd/openApi/v1/pub/getTime":{cost:2.5},"cfd/openApi/v1/pub/instrument":{cost:2.5},"cfd/openApi/v1/pub/marketData":{cost:2.5},"cfd/openApi/v1/pub/marketOrder":{cost:2.5}}}}},fees:{trading:{maker:this.parseNumber("0.001"),taker:this.parseNumber("0.001")},funding:{withdraw:{}}},commonCurrencies:{XBT:"XBT",HIT:"Hiver",VET_ERC20:"VEN",PNT:"Penta"},precisionMode:4,options:{cacheSecretAsPem:!0,createMarketBuyOrderRequiresPrice:!0,fetchTrades:{method:"spotPublicGetTrades"},fetchTransactionFees:{method:"fetchPrivateTransactionFees"},fetchDepositWithdrawFees:{method:"fetchPrivateDepositWithdrawFees"},fetchDepositAddress:{method:"fetchDepositAddressDefault"},createOrder:{method:"spotPrivatePostSupplementCreateOrder"},fetchOrder:{method:"fetchOrderSupplement"},fetchBalance:{method:"spotPrivatePostSupplementUserInfo"},networks:{ERC20:"erc20",ETH:"erc20",TRC20:"trc20",TRX:"trc20",OMNI:"omni",ASA:"asa",BEP20:"bep20(bsc)",BSC:"bep20(bsc)",HT:"heco",BNB:"bep2",BTC:"btc",DOGE:"dogecoin",MATIC:"matic",POLYGON:"matic",OEC:"oec",BTCTRON:"btctron",XRP:"xrp"},networksById:{erc20:"ERC20",trc20:"TRC20",TRX:"TRC20","bep20(bsc)":"BEP20",bep20:"BEP20"},defaultNetworks:{USDT:"TRC20"}},features:{default:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!1,GTD:!1},hedged:!1,selfTradePrevention:!1,trailing:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:2,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:200,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:{marginMode:!1,limit:200,daysBack:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:void 0,fetchOHLCV:{limit:2e3}},spot:{extends:"default"},swap:{linear:{extends:"default"},inverse:void 0},future:{linear:void 0,inverse:void 0}}})}async fetchTime(e={}){let t,[i,s]=this.handleMarketTypeAndParams("fetchTime",void 0,e);return t="swap"===i?await this.contractPublicGetCfdOpenApiV1PubGetTime(s):await this.spotPublicGetTimestamp(s),this.safeInteger(t,"data")}async fetchCurrencies(e={}){let t=await this.spotPublicGetWithdrawConfigs(e),i=this.safeList(t,"data",[]),s=Object.values(this.groupBy(i,"assetCode"));return this.parseCurrencies(s)}parseCurrency(e){let t=this.safeString(e[0],"assetCode"),i=this.safeCurrencyCode(t),s={};for(let t=0;t<e.length;t++){let r=this.safeDict(e,t),a=this.safeString(r,"chain");void 0===a&&(a=this.safeString(r,"assetCode"));let o=this.networkIdToCode(a,i);void 0!==o&&(s[o]={id:a,network:o,limits:{withdraw:{min:this.safeNumber(r,"min"),max:void 0},deposit:{min:this.safeNumber(r,"minTransfer"),max:void 0}},active:void 0,deposit:void 0,withdraw:this.safeBool(r,"canWithDraw"),fee:this.safeNumber(r,"fee"),precision:this.parseNumber(this.parsePrecision(this.safeString(r,"transferAmtScale"))),info:r})}return this.safeCurrencyStructure({id:t,code:i,precision:void 0,type:void 0,name:void 0,active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,limits:{withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},networks:s,info:e})}async fetchMarkets(e={}){let t=[this.fetchSpotMarkets(e),this.fetchSwapMarkets(e)],i=await Promise.all(t);return this.arrayConcat(i[0],i[1])}async fetchSpotMarkets(e={}){let t=await this.spotPublicGetAccuracy(e),i=this.safeList(t,"data",[]),s=[];for(let e=0;e<i.length;e++){let t=i[e],r=this.safeString(t,"symbol"),a=r.split("_"),o=a[0],n=a[1],d=this.safeCurrencyCode(o),h=this.safeCurrencyCode(n);if(void 0===d||void 0===h)continue;let c=d+"/"+h;s.push({id:r,symbol:c,base:d,quote:h,baseId:o,quoteId:n,settle:void 0,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:!0,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(t,"quantityAccuracy"))),price:this.parseNumber(this.parsePrecision(this.safeString(t,"priceAccuracy")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(t,"minTranQua"),max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:t})}return s}async fetchSwapMarkets(e={}){let t=await this.contractPublicGetCfdOpenApiV1PubInstrument(this.extend({productGroup:"SwapU"},e)),i=this.safeList(t,"data",[]),s=[];for(let e=0;e<i.length;e++){let t=i[e],r=this.safeString(t,"symbol"),a=this.safeString(t,"baseCurrency"),o=this.safeString(t,"clearCurrency"),n=this.safeCurrencyCode(a),d=this.safeCurrencyCode(o);if(void 0===n||void 0===d)continue;let h=this.safeCurrencyCode(o),c=n+"/"+d+":"+h;s.push({id:r,symbol:c,base:n,quote:d,settle:h,baseId:a,quoteId:o,settleId:o,type:"swap",spot:!1,margin:!1,swap:!0,future:!1,option:!1,active:!0,contract:!0,linear:!0,inverse:!1,contractSize:this.safeNumber(t,"volumeMultiple"),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(t,"volumeTick"),price:this.safeNumber(t,"priceTick")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(t,"minOrderVolume"),max:this.safeNumber(t,"maxOrderVolume")},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(t,"minOrderCost"),max:void 0}},created:void 0,info:t})}return s}parseTicker(e,t){let i=this.safeInteger(e,"timestamp");void 0===i&&(i=this.safeTimestamp(e,"lastTime"));let s=this.safeString(e,"symbol"),r=this.safeSymbol(s,t),a=this.safeDict(e,"ticker",{}),o=this.safeMarket(s,t),n=!0===o.contract?e:a;return this.safeTicker({symbol:r,timestamp:i,datetime:this.iso8601(i),high:this.safeString2(n,"high","highestPrice"),low:this.safeString2(n,"low","lowestPrice"),bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:this.safeString(n,"openPrice"),close:void 0,last:this.safeString2(n,"latest","lastPrice"),previousClose:void 0,change:void 0,percentage:this.safeString(n,"change"),average:void 0,baseVolume:this.safeString2(n,"vol","volume"),quoteVolume:this.safeString(n,"turnover"),info:e},o)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0===i.swap){let e=await this.fetchTickers([i.symbol],t);return this.safeDict(e,i.symbol)}let s={symbol:i.id},r=await this.spotPublicGetTicker24hr(this.extend(s,t)),a=this.safeList(r,"data",[]),o=this.safeDict(a,0,{});return this.parseTicker(o,i)}async fetchTickers(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e);void 0!==r&&r.length>0&&(s=this.market(r[0]));let a={},[o,n]=this.handleMarketTypeAndParams("fetchTickers",s,t);"swap"===o?(a.productGroup="SwapU",i=await this.contractPublicGetCfdOpenApiV1PubMarketData(this.extend(a,n))):(a.symbol="all",i=await this.spotPublicGetTicker24hr(this.extend(a,n)));let d=this.safeList(i,"data",[]);return this.parseTickers(d,r)}async fetchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=void 0===t?60:t,o={symbol:r.id},[n,d]=this.handleMarketTypeAndParams("fetchOrderBook",r,i);"swap"===n?(o.depth=a,s=await this.contractPublicGetCfdOpenApiV1PubMarketOrder(this.extend(o,d))):(o.size=a,s=await this.spotPublicGetDepth(this.extend(o,d)));let h=this.safeDict(s,"data",{}),c=this.milliseconds();return!0===r.swap?this.parseOrderBook(h,r.symbol,c,"bids","asks","price","volume"):this.parseOrderBook(h,r.symbol,c,"bids","asks")}parseTrade(e,t){let i,s,r,a=this.safeInteger2(e,"date_ms","time");void 0===a&&(a=this.safeInteger(e,"dealTime"));let o=this.safeString2(e,"amount","qty");void 0===o&&(o=this.safeString(e,"dealQuantity"));let n=this.safeString(e,"price");void 0===n&&(n=this.safeString(e,"dealPrice"));let d=this.safeString(e,"quoteQty");void 0===d&&(d=this.safeString(e,"dealVolumePrice"));let h=this.safeString2(e,"tradeType","type");if(void 0!==h){let e=h.split("_");h=this.safeString(e,0);let t=this.safeString(e,1);i="limit",s="taker",void 0!==t&&("market"===t?i="market":"maker"===t&&(s="maker"))}let c=this.safeString2(e,"tid","id");void 0===c&&(c=this.safeString(e,"txUuid"));let l=this.safeString(e,"orderUuid"),u=this.safeSymbol(void 0,t),f=this.safeString(e,"tradeFee");return void 0!==f&&(r={cost:f,currency:"buy"===h?this.safeString(t,"base"):this.safeString(t,"quote"),rate:this.safeString(e,"tradeFeeRate")}),this.safeTrade({timestamp:a,datetime:this.iso8601(a),symbol:u,id:c,order:l,type:i,takerOrMaker:s,side:h,price:n,amount:o,cost:d,fee:r,info:e},t)}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={symbol:a.id};void 0!==t&&(o.time=t),void 0!==i?o.size=Math.min(i,600):o.size=600;let n=this.safeDict(this.options,"fetchTrades",{}),d=this.safeString(n,"method","spotPublicGetTrades"),h=this.safeString(s,"method",d),c=this.omit(s,"method");r="spotPublicGetSupplementTrades"===h?await this.spotPublicGetSupplementTrades(this.extend(o,c)):await this.spotPublicGetTrades(this.extend(o,c));let l=this.safeList(r,"data",[]);return this.parseTrades(l,a,t,i)}parseOHLCV(e,t){return[this.safeTimestamp(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=void 0===s?100:Math.min(s,2e3),n=this.parseTimeframe(t),d=void 0===i?this.milliseconds()-1e3*n*o:i,h=this.parseToInt(d/1e3),c=Math.min(o+1,2e3),l={symbol:a.id,type:this.safeString(this.timeframes,t,t),time:h,size:c},u=await this.spotPublicGetKline(this.extend(l,r)),f=this.safeList(u,"data",[]);return this.parseOHLCVs(f,a,t,d,o)}parseBalance(e){let t=this.safeInteger(e,"ts"),i={info:e,timestamp:t,datetime:this.iso8601(t)},s=this.safeDict(e,"data");if(void 0!==this.safeValue(s,"toBtc")){let e=this.safeDict(s,"freeze",{}),t=this.safeDict(s,"free",{}),r=Object.keys(t);for(let s=0;s<r.length;s++){let a=r[s],o=this.safeCurrencyCode(a),n=this.account();n.used=this.safeString(e,a),n.free=this.safeString(t,a),void 0!==o&&(i[o]=n)}return this.safeBalance(i)}let r=this.safeList(s,"balances");if(void 0!==r){for(let e=0;e<r.length;e++){let t=this.safeDict(r,e),s=this.safeString(t,"asset"),a=this.safeCurrencyCode(s),o=this.account();o.free=this.safeString(t,"free"),o.used=this.safeString(t,"locked"),void 0!==a&&(i[a]=o)}return this.safeBalance(i)}if(!0===Array.isArray(s))for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),r=this.safeString(t,"coin"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(t,"usableAmt"),o.used=this.safeString(t,"freezeAmt"),void 0!==a&&(i[a]=o)}return this.safeBalance(i)}parseFundingRate(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeSymbol(s,t),a=this.safeNumber(e,"markedPrice"),o=this.safeNumber(e,"underlyingPrice"),n=this.safeNumber(e,"fundingRate"),d=this.safeInteger(e,"nextFeeTime"),h=this.safeInteger(e,"positionFeeTime");return void 0!==h&&(i=this.parseToInt(h/60/60).toString()+"h"),{info:e,symbol:r,markPrice:a,indexPrice:o,fundingRate:n,fundingTimestamp:d,fundingDatetime:this.iso8601(d),timestamp:void 0,datetime:void 0,nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:i}}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=await this.fetchFundingRates([i.symbol],t);return this.safeDict(s,i.symbol)}async fetchFundingRates(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.contractPublicGetCfdOpenApiV1PubMarketData(this.extend({productGroup:"SwapU"},t)),r=this.safeList(s,"data",[]);return this.parseFundingRates(r,i)}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let i=this.safeDict(this.options,"fetchBalance",{}),s=this.safeString(i,"method","spotPrivatePostSupplementUserInfo"),r=this.safeString(e,"method",s),a=void 0===(t="spotPrivatePostSupplementUserInfoAccount"===r?await this.spotPrivatePostSupplementUserInfoAccount():"spotPrivatePostUserInfo"===r?await this.spotPrivatePostUserInfo():await this.spotPrivatePostSupplementUserInfo())?{}:t,n=this.parseBalance(a);if(void 0===n)throw new o.NullResponse(this.id+" fetchBalance() returned empty response");return n}parseTradingFee(e,t){let i=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(i),maker:this.safeNumber(e,"makerCommission"),taker:this.safeNumber(e,"takerCommission"),percentage:void 0,tierBased:void 0}}async fetchTradingFee(e,t={}){let i=this.market(e),s=await this.fetchTradingFees(this.extend(t,{category:i.id}));return this.safeDict(s,e)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.spotPrivatePostSupplementCustomerTradeFee(this.extend({},e)),i=this.safeList(t,"data",[]),s={};for(let e=0;e<i.length;e++){let t=this.parseTradingFee(i[e]);s[t.symbol]=t}return s}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new o.NotSupported(this.id+" createMarketBuyOrderWithCost() supports spot orders only");return i.createMarketBuyOrderRequiresPrice=!1,await this.createOrder(e,"market","buy",t,void 0,i)}async createOrder(e,t,i,s,r,a={}){let d;void 0===this.markets&&await this.loadMarkets();let h=this.market(e),c=this.safeString2(a,"custom_id","clientOrderId"),l=this.safeBool(a,"postOnly",!1),u=this.safeStringUpper(a,"timeInForce"),f=this.omit(a,["custom_id","clientOrderId","timeInForce","postOnly"]),p={symbol:h.id},m="IOC"===u,g="FOK"===u,v=!0===l||"PO"===u;if("market"===t&&(m||g||v))throw new o.InvalidOrder(this.id+" createOrder () does not allow market FOK, IOC, or postOnly orders. Only limit IOC, FOK, and postOnly orders are allowed");if("limit"===t)p.type=i,p.price=this.priceToPrecision(e,r),p.amount=this.amountToPrecision(e,s),m?p.type=i+"_ioc":g?p.type=i+"_fok":v&&(p.type=i+"_maker");else if("market"===t){if("sell"===i)p.type=i+"_market",p.amount=this.amountToPrecision(e,s);else if("buy"===i){let t;p.type=i+"_market";let a=!0;[a,f]=this.handleOptionBoolAndParams(f,"createOrder","createMarketBuyOrderRequiresPrice",!0);let d=this.safeNumber(f,"cost");if(f=this.omit(f,"cost"),void 0!==d)t=this.costToPrecision(e,d);else if(a)if(void 0===r)throw new o.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument");else{let i=this.numberToString(s),a=this.numberToString(r),o=n.Y.stringMul(i,a);t=this.costToPrecision(e,o)}else t=this.costToPrecision(e,s);p.price=t}}void 0!==c&&(p.custom_id=c);let y=this.safeDict(this.options,"createOrder",{}),b=this.safeString(y,"method","spotPrivatePostSupplementCreateOrder"),w=this.safeString(f,"method",b),k=this.omit(f,"method");d="spotPrivatePostCreateOrder"===w?await this.spotPrivatePostCreateOrder(this.extend(p,k)):await this.spotPrivatePostSupplementCreateOrder(this.extend(p,k));let S=this.safeDict(d,"data",{});return this.safeOrder({id:this.safeString(S,"order_id"),info:S},h)}parseOrderStatus(e){return this.safeString({"-1":"canceled",0:"open",1:"open",2:"closed",3:"canceled",4:"closed"},e,e)}parseOrder(e,t){let i,s,r=this.safeString2(e,"orderId","order_id"),a=this.safeString2(e,"clientOrderId","custom_id"),o=this.safeInteger2(e,"time","create_time"),n=this.safeString(e,"status"),d=this.safeString(e,"symbol"),h=this.safeMarket(d,t),c=!1,l="limit",u=this.safeString2(e,"type","tradeType"),f=u.split("_"),p=this.safeString(f,0),m=this.safeString(f,1);"market"===m&&(l="market"),"maker"===m&&(c=!0,i="PO"),"ioc"===m&&(i="IOC"),"fok"===m&&(i="FOK");let g=this.safeString(e,"price"),v=this.safeString(e,"cummulativeQuoteQty");"buy_market"!==u&&(s=this.safeString2(e,"origQty","amount"));let y=this.safeString2(e,"executedQty","deal_amount");return this.safeOrder({id:r,clientOrderId:a,datetime:this.iso8601(o),timestamp:o,lastTradeTimestamp:void 0,status:this.parseOrderStatus(n),symbol:h.symbol,type:l,timeInForce:i,postOnly:c,side:p,price:g,triggerPrice:void 0,cost:v,amount:s,filled:y,remaining:void 0,trades:void 0,fee:void 0,info:e,average:void 0},h)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.safeString(i,"method");if(void 0===s){let e=this.safeDict(this.options,"fetchOrder",{});s=this.safeString(e,"method","fetchOrderSupplement")}return"fetchOrderSupplement"===s?await this.fetchOrderSupplement(e,t,i):await this.fetchOrderDefault(e,t,i)}async fetchOrderSupplement(e,t,i={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s={symbol:this.market(t).id,orderId:e},r=await this.spotPrivatePostSupplementOrdersInfo(this.extend(s,i)),a=this.safeDict(r,"data",{});return this.parseOrder(a)}async fetchOrderDefault(e,t,i={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s={symbol:this.market(t).id,order_id:e},r=await this.spotPrivatePostOrdersInfo(this.extend(s,i)),a=this.safeList(r,"data",[]);if(1===a.length)return this.parseOrder(a[0]);throw new o.BadRequest(this.id+" fetchOrder() can only fetch one order at a time")}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=this.safeValue(s,"start_date",t),n=this.omit(s,"start_date"),d={symbol:r.id};void 0!==i&&(d.size=i),void 0!==a&&(d.start_date=this.ymd(a,"-"),d.end_date=this.ymd(a+864e5,"-"));let h=await this.spotPrivatePostTransactionHistory(this.extend(d,n)),c=this.safeList(h,"data",[]);return this.parseTrades(c,r,a,i)}async fetchOrders(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=void 0===i?100:i,n={symbol:r.id,current_page:1,page_length:a},d=await this.spotPrivatePostSupplementOrdersInfoHistory(this.extend(n,s)),h=this.safeDict(d,"data",{}),c=this.safeList(h,"orders",[]);return this.parseOrders(c,r,t,a)}async fetchOpenOrders(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchOpenOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=void 0===i?100:i,n={symbol:r.id,current_page:1,page_length:a},d=await this.spotPrivatePostSupplementOrdersInfoNoDeal(this.extend(n,s)),h=this.safeDict(d,"data",{}),c=this.safeList(h,"orders",[]);return this.parseOrders(c,r,t,a)}async cancelOrder(e,t,i={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.safeString2(i,"origClientOrderId","clientOrderId"),r=this.omit(i,["origClientOrderId","clientOrderId"]),a={symbol:this.market(t).id,orderId:e};void 0!==s&&(a.origClientOrderId=s);let n=await this.spotPrivatePostSupplementCancelOrder(this.extend(a,r)),d=this.safeDict(n,"data",{});return this.parseOrder(d)}async cancelAllOrders(e,t={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let i={symbol:this.market(e).id},s=await this.spotPrivatePostSupplementCancelOrderBySymbol(this.extend(i,t)),r=this.safeList(s,"data",[]);return this.parseOrders(r)}getNetworkCodeForCurrency(e,t){let i=this.safeDict(this.options,"defaultNetworks"),s=this.safeStringUpper(i,e),r=this.safeDict(this.options,"networks",{}),a=this.safeStringUpper(t,"network",s);return this.safeString(r,a,a)}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeDict(this.options,"fetchDepositAddress",{}),s=this.safeString(i,"method","fetchDepositAddressDefault"),r=this.safeString(t,"method",s),a=this.omit(t,"method");return"fetchDepositAddressSupplement"===r?await this.fetchDepositAddressSupplement(e,a):await this.fetchDepositAddressDefault(e,a)}async fetchDepositAddressDefault(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={assetCode:this.currency(e).id},s=this.getNetworkCodeForCurrency(e,t),r=void 0!==s?this.omit(t,"network"):t;void 0!==s&&(i.netWork=s);let a=await this.spotPrivatePostGetDepositAddress(this.extend(i,r)),o=this.safeDict(a,"data"),n=this.safeString(o,"address"),d=this.safeString(o,"memo");return{info:a,currency:e,network:this.networkIdToCode(this.safeString(o,"netWork"),e),address:n,tag:d}}async fetchDepositAddressSupplement(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={coin:this.currency(e).id},s=this.safeDict(this.options,"networks"),r=this.safeStringUpper(t,"network"),a=void 0!==(r=this.safeString(s,r,r))?this.omit(t,"network"):t;void 0!==r&&(i.networkName=r);let o=await this.spotPrivatePostSupplementGetDepositAddress(this.extend(i,a)),n=this.safeDict(o,"data");return{info:o,currency:e,network:void 0,address:this.safeString(n,"address"),tag:this.safeString(n,"memo")}}async withdraw(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let n=this.safeString(o,"fee"),d=this.omit(o,"fee");this.checkRequiredArgument("withdraw",n,"fee");let h={address:i,coin:this.currency(e).id,amount:t,fee:n};void 0!==a&&(h.memo=a);let c=this.safeStringUpper2(d,"network","networkName"),l=this.omit(d,["network","networkName"]),u=this.safeDict(this.options,"networks"),f=this.safeString(u,c,c);void 0!==f&&(h.networkName=f);let p=await this.spotPrivatePostSupplementWithdraw(this.extend(h,l)),m=this.safeDict(p,"data",{});return{info:m,id:this.safeString(m,"withdrawId")}}parseTransactionStatus(e,t){return this.safeString(this.safeDict({deposit:{1:"pending",2:"ok",3:"failed",4:"canceled",5:"transfer"},withdrawal:{1:"pending",2:"canceled",3:"failed",4:"ok"}},t,{}),e,e)}parseTransaction(e,t){let i,s,r,a,o=this.safeString(e,"id");i=void 0===o?"deposit":"withdrawal";let n=this.safeString(e,"txId"),d=this.safeInteger2(e,"insertTime","applyTime"),h=this.safeString(e,"address");"deposit"===i?s=h:r=h;let c=this.safeNumber(e,"amount"),l=this.safeString2(e,"coin","coid"),u=this.safeCurrencyCode(l,t),f=this.parseTransactionStatus(this.safeString(e,"status"),i),p=this.safeNumber(e,"fee");return void 0!==p&&(a={cost:p,currency:u}),{info:e,id:o,txid:n,timestamp:d,datetime:this.iso8601(d),network:this.networkIdToCode(this.safeString(e,"networkName"),u),address:h,addressTo:r,addressFrom:s,tag:void 0,tagTo:void 0,tagFrom:void 0,type:i,amount:c,currency:u,status:f,updated:void 0,comment:void 0,internal:"transfer"===f,fee:a}}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.coin=(r=this.currency(e)).id),void 0!==t&&(a.startTime=t);let o=await this.spotPrivatePostSupplementDepositHistory(this.extend(a,s)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"depositOrders",[]);return this.parseTransactions(d,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.coin=(r=this.currency(e)).id),void 0!==t&&(a.startTime=t);let o=await this.spotPrivatePostSupplementWithdraws(this.extend(a,s)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"withdraws",[]);return this.parseTransactions(d,r,t,i)}async fetchTransactionFees(e,t={}){let i;if(void 0===this.markets&&await this.loadMarkets(),!0===this.checkRequiredCredentials(!1)){let e=this.safeDict(this.options,"fetchTransactionFees",{}),s=this.safeString(e,"method","fetchPrivateTransactionFees"),r=this.safeString(t,"method",s),a=this.omit(t,"method");i="fetchPublicTransactionFees"===r?await this.fetchPublicTransactionFees(a):await this.fetchPrivateTransactionFees(a)}else i=await this.fetchPublicTransactionFees(t);return i}async fetchPrivateTransactionFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.spotPrivatePostSupplementUserInfo(),i=this.safeList(t,"data",[]),s={};for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),r=this.safeString(t,"coin"),a=this.safeCurrencyCode(r),o=this.safeList(t,"networkList",[]);void 0!==a&&(s[a]={});for(let e=0;e<o.length;e++){let t=this.safeDict(o,e),i=this.safeNumber(t,"withdrawFee");if(void 0!==i){let e=this.networkIdToCode(this.safeString(t,"name"),a);void 0!==e&&void 0!==a&&void 0!==e&&(s[a][e]=i)}}}return{withdraw:s,deposit:{},info:t}}async fetchPublicTransactionFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=this.safeString2(e,"coin","assetCode"),i=this.omit(e,["coin","assetCode"]),s={};void 0!==t&&(s.assetCode=this.currency(t).id);let r=await this.spotPublicGetWithdrawConfigs(this.extend(s,i)),a=this.safeList(r,"data",[]),o={};for(let e=0;e<a.length;e++){let t=this.safeDict(a,e);if("true"===this.safeString(t,"canWithDraw")){let e=this.safeString(t,"assetCode"),i=this.safeCurrencyCode(e),s=this.networkIdToCode(this.safeString(t,"chain"),i);void 0===s&&(s=i);let r=this.safeString(t,"fee");void 0===this.safeValue(o,i)&&void 0!==i&&(o[i]={}),void 0!==i&&void 0!==s&&(o[i][s]=this.parseNumber(r))}}return{withdraw:o,deposit:{},info:r}}async fetchDepositWithdrawFees(e,t={}){let i;if(void 0===this.markets&&await this.loadMarkets(),!0===this.checkRequiredCredentials(!1)){let s=this.safeDict(this.options,"fetchDepositWithdrawFees",{}),r=this.safeString(s,"method","fetchPrivateDepositWithdrawFees"),a=this.safeString(t,"method",r),o=this.omit(t,"method");i="fetchPublicDepositWithdrawFees"===a?await this.fetchPublicDepositWithdrawFees(e,o):await this.fetchPrivateDepositWithdrawFees(e,o)}else i=await this.fetchPublicDepositWithdrawFees(e,t);return i}async fetchPrivateDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.spotPrivatePostSupplementUserInfo(t),s=this.safeList(i,"data",[]);return this.parseDepositWithdrawFees(s,e,"coin")}async fetchPublicDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.spotPublicGetWithdrawConfigs(this.extend({},t)),s=this.safeList(i,"data",[]);return this.parsePublicDepositWithdrawFees(s,e)}parsePublicDepositWithdrawFees(e,t){let i={};for(let s=0;s<e.length;s++){let r=e[s];if(!0===this.safeBool(r,"canWithDraw")){let e=this.safeString(r,"assetCode"),s=this.safeCurrencyCode(e);if(void 0!==s&&(void 0===t||this.inArray(s,t))){let e=this.safeNumber(r,"fee");if(void 0!==e){void 0===this.safeDict(i,s)?i[s]=this.depositWithdrawFee([r]):i[s].info.push(r);let t=this.networkIdToCode(this.safeString(r,"chain"),s);void 0!==t?i[s].networks[t]={withdraw:{fee:e,percentage:void 0},deposit:{fee:void 0,percentage:void 0}}:i[s].withdraw={fee:e,percentage:void 0}}}}}return i}parseDepositWithdrawFee(e,t){let i=this.depositWithdrawFee(e),s=this.safeString(t,"code"),r=this.safeList(e,"networkList",[]);for(let e=0;e<r.length;e++){let t=this.safeDict(r,e),a=this.networkIdToCode(this.safeString(t,"name"),s),o=this.safeNumber(t,"withdrawFee"),n=this.safeBool(t,"isDefault");void 0!==o&&(!0===n&&(i.withdraw={fee:o,percentage:void 0}),void 0!==a&&(i.networks[a]={withdraw:{fee:o,percentage:void 0},deposit:{fee:void 0,percentage:void 0}}))}return i}sign(e,t="public",i="GET",a={},n,h){let c=this.omit(a,this.extractParams(e)),l=this.safeString(this.urls.api,"rest");if(void 0===l)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");let u=l+"/"+this.version+"/"+this.implodeParams(e,a);if("spot"===t[0])u+=".do";else{let t=this.safeString(this.urls.api,"contract");if(void 0===t)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");u=t+"/"+this.implodeParams(e,a)}if("public"===t[1])Object.keys(c).length>0&&(u+="?"+this.urlencode(this.keysort(c)));else{let e,t;this.checkRequiredCredentials();let a=this.milliseconds().toString(),o=this.uuid22()+this.uuid16();c=this.extend({api_key:this.apiKey},c);let n=e=this.secret.length>32?"RSA":"HmacSHA256",h=this.rawencode(this.keysort(this.extend({echostr:o,signature_method:n,timestamp:a},c))),l=this.encode(h),f=this.hash(l,s.Fx).toUpperCase();if("RSA"===e){let e;!0===this.safeBool(this.options,"cacheSecretAsPem",!0)?void 0===(e=this.safeString(this.options,"pem"))&&(e=this.convertSecretToPem(this.encode(this.secret)),this.options.pem=e):e=this.convertSecretToPem(this.encode(this.secret)),t=(0,d.n)(f,e,r.sc)}else"HmacSHA256"===e&&(t=this.hmac(this.encode(f),this.encode(this.secret),r.sc));return c.sign=t,{url:u,method:i,body:this.urlencode(this.keysort(c)),headers:{"Content-Type":"application/x-www-form-urlencoded",timestamp:a,signature_method:e,echostr:o}}}return{url:u,method:i,body:h,headers:n}}convertSecretToPem(e){let t=e.length-0,i=this.parseToInt(t/64);i=this.sum(i,1);let s="-----BEGIN PRIVATE KEY-----\n";for(let e=0;e<i;e++){let t=64*e,i=this.sum(t,64);s+=this.secret.slice(t,i)+"\n"}return s+"-----END PRIVATE KEY-----"}handleErrors(e,t,i,s,r,a,n,d,h){if(void 0===n)throw new o.NullResponse(this.id+" parseBalance() returned empty response");let c=this.safeValue(n,"result");if("false"===c||null==c||!1===c){let e=this.safeString(n,"error_code"),t=this.safeString({1e4:"Internal error",10001:"The required parameters can not be empty",10002:"Validation failed",10003:"Invalid parameter",10004:"Request too frequent",10005:"Secret key does not exist",10006:"User does not exist",10007:"Invalid signature",10008:"Invalid Trading Pair",10009:"Price and/or Amount are required for limit order",10010:"Price and/or Amount must be less than minimum requirement",10013:"The amount is too small",10014:"Insufficient amount of money in the account",10015:"Invalid order type",10016:"Insufficient account balance",10017:"Server Error",10018:"Page size should be between 1 and 50",10019:"Cancel NO more than 3 orders in one request",10020:"Volume < 0.001",10021:"Price < 0.01",10022:"Invalid authorization",10023:"Market Order is not supported yet",10024:"User cannot trade on this pair",10025:"Order has been filled",10026:"Order has been cancelld",10027:"Order is cancelling",10028:"Wrong query time",10029:"from is not in the query time",10030:"from do not match the transaction type of inqury",10031:"echostr length must be valid and length must be from 30 to 40",10033:"Failed to create order",10036:"customID duplicated",10100:"Has no privilege to withdraw",10101:"Invalid fee rate to withdraw",10102:"Too little to withdraw",10103:"Exceed daily limitation of withdraw",10104:"Cancel was rejected",10105:"Request has been cancelled",10106:"None trade time",10107:"Start price exception",10108:"can not create order",10109:"wallet address is not mapping",10110:"transfer fee is not mapping",10111:"mount > 0",10112:"fee is too lower",10113:"transfer fee is 0",10600:"intercepted by replay attacks filter, check timestamp",10601:"Interface closed unavailable",10701:"invalid asset code",10702:"not allowed deposit"},e,this.json(n));throw new(this.safeValue({10001:o.BadRequest,10002:o.AuthenticationError,10003:o.BadRequest,10004:o.RateLimitExceeded,10005:o.AuthenticationError,10006:o.AuthenticationError,10007:o.AuthenticationError,10008:o.BadSymbol,10009:o.InvalidOrder,10010:o.InvalidOrder,10013:o.InvalidOrder,10014:o.InsufficientFunds,10015:o.InvalidOrder,10016:o.InsufficientFunds,10017:o.ExchangeError,10018:o.BadRequest,10019:o.BadRequest,10020:o.BadRequest,10021:o.InvalidOrder,10022:o.PermissionDenied,10023:o.InvalidOrder,10024:o.PermissionDenied,10025:o.InvalidOrder,10026:o.InvalidOrder,10027:o.InvalidOrder,10028:o.BadRequest,10029:o.BadRequest,10030:o.BadRequest,10031:o.InvalidNonce,10033:o.ExchangeError,10036:o.DuplicateOrderId,10100:o.PermissionDenied,10101:o.BadRequest,10102:o.InsufficientFunds,10103:o.ExchangeError,10104:o.ExchangeError,10105:o.ExchangeError,10106:o.BadRequest,10107:o.BadRequest,10108:o.ExchangeError,10109:o.InvalidAddress,10110:o.ExchangeError,10111:o.BadRequest,10112:o.BadRequest,10113:o.BadRequest,10600:o.BadRequest,10601:o.ExchangeError,10701:o.BadSymbol,10702:o.PermissionDenied},e,o.ExchangeError))(t)}}}i.d(t,{A:()=>h})},1723(e,t,i){"use strict";var s=i(6834),r=i(6885),a=i(4748),o=i(1453),n=i(7749),d=i(1093);class h extends a.A{describe(){return this.deepExtend(super.describe(),{id:"lighter",name:"Lighter",countries:[],version:"v1",rateLimit:1e3,certified:!1,pro:!0,dex:!0,quoteJsonNumbers:!1,has:{CORS:void 0,spot:!0,margin:!1,swap:!0,future:!1,option:!1,addMargin:!0,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelAllOrdersAfter:!0,cancelOrder:!0,cancelOrders:!1,cancelOrdersForSymbols:!1,closeAllPositions:!1,closePosition:!1,createMarketBuyOrderWithCost:!1,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,createStopOrder:!1,createTriggerOrder:!1,editOrder:!0,fetchAccounts:!0,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCanceledAndClosedOrders:!1,fetchCanceledOrders:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDeposits:!0,fetchDepositWithdrawFee:!1,fetchDepositWithdrawFees:!1,fetchFundingHistory:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!0,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLedger:!1,fetchLeverage:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchMarginMode:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyLiquidations:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!1,fetchOrderBook:!0,fetchOrders:!1,fetchOrderTrades:!1,fetchPosition:!0,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!1,fetchTradingFee:!1,fetchTradingFees:!1,fetchTransfer:!1,fetchTransfers:!0,fetchVolatilityHistory:!1,fetchWithdrawal:!1,fetchWithdrawals:!0,reduceMargin:!0,repayCrossMargin:!1,repayIsolatedMargin:!1,sandbox:!0,setLeverage:!0,setMargin:!0,setMarginMode:!0,setPositionMode:!1,transfer:!0,withdraw:!0},timeframes:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","4h":"4h","12h":"12h","1d":"1d"},hostname:"zklighter.elliot.ai",urls:{logo:"https://github.com/user-attachments/assets/5aa1158d-0734-49fc-9155-501d94b76a0b",api:{root:"https://mainnet.{hostname}",public:"https://mainnet.{hostname}",private:"https://mainnet.{hostname}"},test:{root:"https://testnet.{hostname}",public:"https://testnet.{hostname}",private:"https://testnet.{hostname}"},www:"https://lighter.xyz/",doc:"https://apidocs.lighter.xyz/",fees:"https://docs.lighter.xyz/perpetual-futures/fees",referral:{url:"https://app.lighter.xyz/?referral=715955W9",discount:.1}},api:{root:{get:{"":{cost:1},info:{cost:1}}},public:{get:{account:{cost:1},accountsByL1Address:{cost:1},apikeys:{cost:1},exchangeStats:{cost:1},assetDetails:{cost:1},orderBookDetails:{cost:1},orderBookOrders:{cost:1},orderBooks:{cost:1},recentTrades:{cost:1},blockTxs:{cost:1},nextNonce:{cost:1},tx:{cost:1},txFromL1TxHash:{cost:1},txs:{cost:1},announcement:{cost:1},block:{cost:1},blocks:{cost:1},currentHeight:{cost:1},candles:{cost:1},markPriceCandles:{cost:1},fundings:{cost:1},"fastbridge/info":{cost:1},"funding-rates":{cost:1},withdrawalDelay:{cost:1},partnerStats:{cost:1},syntheticSpotInfo:{cost:1},tokenlist:{cost:1}},post:{sendTx:{cost:1},sendTxBatch:{cost:1}}},private:{get:{accountLimits:{cost:1},accountMetadata:{cost:1},pnl:{cost:1},l1Metadata:{cost:1},liquidations:{cost:1},positionFunding:{cost:1},publicPoolsMetadata:{cost:1},getMakerOnlyApiKeys:{cost:1},accountActiveOrders:{cost:1},accountInactiveOrders:{cost:1},accountOrders:{cost:1},export:{cost:1},"export/historicalTrades":{cost:1},trades:{cost:1},accountTxs:{cost:1},"deposit/history":{cost:1},"transfer/history":{cost:1},"withdraw/history":{cost:1},"referral/points":{cost:1},transferFeeInfo:{cost:1},"rfq/get":{cost:1},"rfq/list":{cost:1}},post:{changeAccountTier:{cost:1},setMakerOnlyApiKeys:{cost:1},"notification/ack":{cost:1},"rfq/create":{cost:1},"rfq/respond":{cost:1},"rfq/update":{cost:1}}}},httpExceptions:{},exceptions:{exact:{21146:o.ExchangeError,21500:o.ExchangeError,21501:o.ExchangeError,21502:o.ExchangeError,21503:o.ExchangeError,21504:o.ExchangeError,21505:o.ExchangeError,21506:o.ExchangeError,21507:o.ExchangeError,21508:o.ExchangeError,21511:o.ExchangeError,21512:o.ExchangeError,21600:o.InvalidOrder,21601:o.InvalidOrder,21602:o.InvalidOrder,21603:o.InvalidOrder,21604:o.InvalidOrder,21605:o.InvalidOrder,21606:o.InvalidOrder,21607:o.InvalidOrder,21608:o.InvalidOrder,21611:o.InvalidOrder,21612:o.InvalidOrder,21613:o.InvalidOrder,21614:o.InvalidOrder,21700:o.InvalidOrder,21701:o.InvalidOrder,21702:o.InvalidOrder,21703:o.InvalidOrder,21704:o.InvalidOrder,21705:o.InvalidOrder,21706:o.InvalidOrder,21707:o.InvalidOrder,21708:o.InvalidOrder,21709:o.InvalidOrder,21710:o.InvalidOrder,21711:o.InvalidOrder,21712:o.InvalidOrder,21713:o.InvalidOrder,21714:o.InvalidOrder,21715:o.InvalidOrder,21716:o.InvalidOrder,21717:o.InvalidOrder,21718:o.InvalidOrder,21719:o.InvalidOrder,21720:o.InvalidOrder,21721:o.InvalidOrder,21722:o.InvalidOrder,21723:o.InvalidOrder,21724:o.InvalidOrder,21725:o.InvalidOrder,21726:o.InvalidOrder,21727:o.InvalidOrder,21728:o.InvalidOrder,21729:o.InvalidOrder,21730:o.InvalidOrder,21731:o.InvalidOrder,21732:o.InvalidOrder,21733:o.InvalidOrder,21734:o.InvalidOrder,21735:o.InvalidOrder,21736:o.InvalidOrder,21737:o.InvalidOrder,21738:o.InvalidOrder,21739:o.InvalidOrder,21740:o.InvalidOrder,21901:o.InvalidOrder,21902:o.InvalidOrder,21903:o.InvalidOrder,21904:o.InvalidOrder,21905:o.InvalidOrder,21906:o.InvalidOrder,23e3:o.RateLimitExceeded,23001:o.RateLimitExceeded,23002:o.RateLimitExceeded,23003:o.RateLimitExceeded},broad:{}},fees:{taker:0,maker:0},requiredCredentials:{apiKey:!1,secret:!1,walletAddress:!1,privateKey:!0,password:!1},precisionMode:4,commonCurrencies:{},options:{defaultType:"swap",builderFee:!0,chainId:304,accountIndex:void 0,apiKeyIndex:void 0,lighterPrivateKey:void 0,wasmExecPath:void 0,libraryPath:void 0,integratorAccountIndex:718718,integratorMakerFee:1e3,integratorTakerFee:1e3,authDeadlineExpiry:28800,authDeadlineMinimumRemaining:60,tiersForAccountIndexes:{}},features:{default:{sandbox:!0,createOrder:{timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},leverage:!1,marketBuyRequiresPrice:!1,marketBuyByCost:!1,selfTradePrevention:!1,trailing:!1,iceberg:!1}}}})}async loadAccount(e,t,i,s,r={}){this.initAuthObject(s,i);let a=this.safeDict(this.options.auths[s],i),n=this.safeValue(a,"signer");if(void 0!==n)return n;let d=this.handleOptionStringAndParams(r,"loadAccount","libraryPath")[0];if(void 0!==t&&""!==t&&void 0!==d&&void 0!==i&&void 0!==s)return n=await this.loadLighterLibrary(d,e,t,this.parseToInt(i),this.parseToInt(s),!0),this.options.auths[s][i].signer=n,n;if(void 0!==this.privateKey&&""!==this.privateKey&&void 0!==i&&void 0!==s){if(this.privateKey.length>66)throw new o.NotSupported(this.id+" after the latest update (v4.5.50), CCXT now expects the l1 private key to be provided in the credentials. Please check for more details: https://github.com/ccxt/ccxt/wiki/FAQ#how-to-use-the-lighter-exchange-in-ccxt");n=await this.loadLighterLibrary(d,e,"",this.parseToInt(i),this.parseToInt(s),!1),this.options.auths[s][i].signer=n;let t=await this.changeApiKey();return await this.handleBuilderFeeApproval(this.parseToInt(s),this.parseToInt(i)),t}return n}initAuthObject(e,t){"auths"in this.options||(this.options.auths={}),e in this.options.auths||(this.options.auths[e]={}),t in this.options.auths[e]||(this.options.auths[e][t]={signer:void 0,lighterPrivateKey:void 0,deadline:void 0,token:void 0})}getLighterPrivateKey(e,t){if("auths"in this.options&&e in this.options.auths&&t in this.options.auths[e]&&"lighterPrivateKey"in this.options.auths[e][t])return this.options.auths[e][t].lighterPrivateKey}async preLoadLighterLibrary(e={}){let[t,i]=this.handleApiKeyIndex(e,"loadAccount","apiKeyIndex","api_key_index"),s=(await this.handleAccountIndex(i,"loadAccount","accountIndex","account_index"))[0];if(void 0===s)throw new o.ArgumentsRequired(this.id+" requires accountIndex or account_index");let r=this.numberToString(s),a=this.numberToString(t);this.initAuthObject(r,a);let n=this.safeDict(this.options.auths[r][a],"signer");return void 0!==n||(n=await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(r,a),a,r),await this.handleBuilderFeeApproval(s,t),void 0!==n)}handleApiKeyIndex(e,t,i,s,r){let[a,o]=this.handleOptionAndParams2(e,t,i,s,r),n=a;return(void 0===n||n<4||n>254)&&(n=254,this.options.apiKeyIndex=n),[this.parseToInt(n),o]}async handleAccountIndex(e,t,i,s,r){let[a,n]=this.handleOptionAndParams2(e,t,i,s,r),d=a;if(void 0===d){let e=this.walletAddress;if(void 0!==this.privateKey){if(this.privateKey.length>66)throw new o.NotSupported(this.id+" after the latest update (v4.5.50), CCXT now expects the l1 private key to be provided in the credentials. Please check for more details: https://github.com/ccxt/ccxt/wiki/FAQ#how-to-use-the-lighter-exchange-in-ccxt");e=this.ethGetAddressFromPrivateKey(this.privateKey)}if(void 0===e||""===e)throw new o.ArgumentsRequired(this.id+" "+t+"() requires an "+i+"/"+s+" parameter or walletAddress to fetch accountIndex. Alternatively set privateKey in credentials to enable automatic walletAddress detection.");let r=await this.publicGetAccountsByL1Address({l1_address:e}),a=this.safeList(r,"sub_accounts");if(Array.isArray(a)){let e=this.safeDict(a,0);if(void 0===e)throw new o.ArgumentsRequired(this.id+" "+t+"() requires an "+i+" or "+s+" parameter");d=e.index,this.options.accountIndex=d}}return[this.parseToInt(d),n]}async createSubAccount(e,t={}){let[i,s]=this.handleApiKeyIndex(t,"createSubAccount","apiKeyIndex","api_key_index"),[r,a]=await this.handleAccountIndex(s,"createSubAccount","accountIndex","account_index"),o=await this.fetchNonce(r,i,a),n=this.numberToString(r),d=this.numberToString(i),h=await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(n,d),d,n,a),[c,l]=this.lighterSignCreateSubAccount(h,this.extend({nonce:o,api_key_index:i,account_index:r},a));return await this.publicPostSendTx({tx_type:c,tx_info:l})}createAuth(e={}){let t=this.safeString2(e,"apiKeyIndex","api_key_index");if(void 0===t){let e=this.handleOptionAndParams2({},"createAuth","apiKeyIndex","api_key_index");t=this.safeString(e,0)}let i=this.safeString2(e,"accountIndex","account_index");if(void 0===i){let e=this.handleOptionAndParams2({},"createAuth","accountIndex","account_index");i=this.safeString(e,0)}let s=this.safeDict(this.options,"auths"),r=this.safeDict(s,i),a=this.safeDict(r,t),o=this.safeInteger(a,"deadline");if(void 0!==o&&o>=this.seconds()+this.safeInteger(this.options,"authDeadlineMinimumRemaining",60))return this.safeString(a,"token");let n=this.seconds()+this.safeInteger(this.options,"authDeadlineExpiry",28800),d={deadline:n,api_key_index:this.parseToInt(t),account_index:this.parseToInt(i)},h=this.lighterCreateAuthToken(this.options.auths[i][t].signer,d);return this.options.auths[i][t].deadline=n,this.options.auths[i][t].token=h,h}pow(e,t){let i=n.A.stringMul(e,"1"),s=this.parseToInt(t);if(s<0)throw new o.BadRequest(this.id+" pow() requires m > 0.");if(0===s)return"1";if(s>100)throw new o.BadRequest(this.id+" pow() requires m < 100.");for(let t=1;t<s;t++)i=n.A.stringMul(i,e);return i}hashMessage(e){let t=this.encode(e),i=this.binaryLength(t),r=this.base16ToBinary("19"),a=this.base16ToBinary("0a"),o=this.binaryConcat(r,this.encode("Ethereum Signed Message:"),a,this.encode(this.numberToString(i)));return"0x"+this.hash(this.binaryConcat(o,t),s.lY,"hex")}signHash(e,t){this.checkRequiredCredentials();let i=(0,d.h1)(e.slice(-64),t.slice(-64),r.bI,void 0),s=i.r,a=i.s,o=this.intToBase16(this.sum(27,i.v));return"0x"+s.padStart(64,"0")+a.padStart(64,"0")+o}signL1AndPrepareTxInfo(e,t,i){let s=this.hashMessage(t),r=this.signHash(s,i),a=this.parseJson(e);return a.L1Sig=r,this.json(a)}async handleBuilderFeeApproval(e,t){if(!0!==this.safeBool(this.options,"builderFee",!0))return!1;if(!0===this.safeBool(this.options,"approvedBuilderFee",!1))return!0;let i=!1;try{if(await this.checkIfStandardTier(this.parseToInt(e)))i=!0,this.options.builderFee=!1;else{let i=this.safeInteger(this.options,"integratorAccountIndex",718718),s=this.safeInteger(this.options,"integratorTakerFee",1e3),r=this.safeInteger(this.options,"integratorMakerFee",1e3);await this.approveBuilderFee(i,s,r,e,t),this.options.approvedBuilderFee=!0}}catch(e){this.options.builderFee=!1}return!i}async checkIfStandardTier(e){let t=this.safeDict(this.options,"tiersForAccountIndexes",{}),i=e.toString(),s=this.safeBool(t,i);if(void 0!==s)return s;let r=await this.privateGetAccountLimits({account_index:e}),a="standard"===this.safeString(r,"user_tier");return t[i]=a,this.options.tiersForAccountIndexes=t,a}async approveBuilderFee(e,t,i,s,r,a={}){let o=this.numberToString(s),n=this.numberToString(r),d=await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(o,n),n,o,a),h=await this.fetchNonce(s,r,this.extend(a,{skipNonce:!1})),c=this.milliseconds()+31536e4,[l,u,f]=this.lighterSignApproveIntegrator(d,this.extend({integrator_account_index:e,integrator_taker_fee:t,integrator_maker_fee:i,approval_expiry:c,nonce:h,api_key_index:r,account_index:s},a)),p=this.signL1AndPrepareTxInfo(u,f,this.privateKey);return await this.publicPostSendTx({tx_type:l,tx_info:p})}async changeApiKey(e={}){let[t,i]=this.handleApiKeyIndex(e,"changeApiKey","apiKeyIndex","api_key_index"),[s,r]=await this.handleAccountIndex(i,"changeApiKey","accountIndex","account_index"),a=this.numberToString(s),o=this.numberToString(t),n=this.options.auths[a][o].signer,[d,h]=this.lighterGenerateApiKey(n),c=await this.fetchNonce(s,t,this.extend(r,{skipNonce:!1})),l={pubkey:this.encode(h),nonce:c,api_key_index:t,account_index:s},u=this.lighterCreateClient(n,this.options.chainId,d,t,s),[f,p,m]=this.lighterSignChangePubkey(u,this.extend(l,r)),g=this.signL1AndPrepareTxInfo(p,m,this.privateKey);return await this.publicPostSendTx({tx_type:f,tx_info:g}),this.options.auths[a][o].lighterPrivateKey=d,this.options.auths[a][o].signer=u,await this.handleBuilderFeeApproval(s,t),u}setSandboxMode(e){super.setSandboxMode(e),this.options.sandboxMode=e,this.options.chainId=e?300:304}createOrderRequest(e,t,i,s,r,a={}){let d,h,c;if(void 0===t)throw new o.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new o.ArgumentsRequired(this.id+" requires a side argument");if(void 0===r)throw new o.ArgumentsRequired(this.id+" createOrder() requires a price argument");let l=this.safeBool2(a,"reduceOnly","reduce_only",!1),u=t.toUpperCase(),f=this.market(e),p=i.toUpperCase(),m={market_index:this.parseToInt(f.id)},[g,v]=this.handleApiKeyIndex(a,"createOrder","apiKeyIndex","api_key_index"),[y,b]=this.handleOptionAndParams2(v,"createOrder","accountIndex","account_index"),[w,k]=this.handleOptionAndParams(b,"createOrder","nonce"),[S,O]=this.handleOptionIntegerAndParams(k,"createOrder","orderExpiry",0),T=S;void 0!==w&&(m.nonce=w),m.api_key_index=g,m.account_index=this.parseToInt(y);let P=this.safeString2(O,"triggerPrice","stopPrice"),I=this.safeValue(O,"stopLossPrice",P),A=this.safeValue(O,"takeProfitPrice"),x=this.safeDict(O,"stopLoss"),M=this.safeDict(O,"takeProfit"),_=void 0!==x,C=void 0!==M,B=void 0!==I||void 0!==A,E="MARKET"===u,R=this.safeStringLower(O,"timeInForce","gtt"),L=this.isPostOnly(E,void 0,O),N=this.omit(O,["stopLoss","takeProfit","timeInForce"]);E?(d=1,h=0):d=0,"BUY"===p?m.is_ask=0:m.is_ask=1,L?(h=2,T=-1):E||("ioc"===R?(h=0,T=0):"gtt"===R&&(h=1,T=-1));let D=this.safeDict(f,"info",{}),q=this.priceToPrecision(e,r),F=this.pow("10",D.size_decimals),V=this.pow("10",D.price_decimals),G="0",H=this.randNumber(9),U=this.safeInteger2(N,"client_order_index","clientOrderId",H),W=this.omit(N,["reduceOnly","reduce_only","timeInForce","postOnly","nonce","apiKeyIndex","stopPrice","triggerPrice","stopLossPrice","takeProfitPrice","client_order_index","clientOrderId"]);B?(c=this.numberToString(s),void 0!==I?(d=E?2:3,G=this.priceToPrecision(e,I)):void 0!==A&&(d=E?4:5,G=this.priceToPrecision(e,A))):c=this.amountToPrecision(e,s),m.order_expiry=T,m.order_type=d,m.time_in_force=h,m.reduce_only=+(!0===l),m.client_order_index=U,m.base_amount=this.parseToInt(n.A.stringMul(c,F)),m.avg_execution_price=this.parseToInt(n.A.stringMul(q,V)),m.trigger_price=this.parseToInt(n.A.stringMul(G,V)),this.safeBool(this.options,"builderFee",!0)&&(m.integrator_account_index=this.options.integratorAccountIndex,m.integrator_taker_fee=this.options.integratorTakerFee,m.integrator_maker_fee=this.options.integratorMakerFee);let j=[];if(j.push(this.extend(m,W)),_||C){j[0].client_order_index=0;let t="";t="BUY"===p?"sell":"buy";let i=this.safeNumber2(x,"triggerPrice","stopPrice"),s=this.safeString(x,"type","limit"),r=this.safeNumber2(x,"price","stopLossPrice",i),a=this.safeNumber2(M,"triggerPrice","stopPrice"),o=this.safeString(M,"type","limit"),n=this.safeNumber2(M,"price","takeProfitPrice",a);if(void 0!==x){let a=this.createOrderRequest(e,s,t,0,r,this.extend(W,{stopLossPrice:i,reduceOnly:!0}))[0];a.client_order_index=0,j.push(a)}if(void 0!==M){let i=this.createOrderRequest(e,o,t,0,n,this.extend(W,{takeProfitPrice:a,reduceOnly:!0}))[0];i.client_order_index=0,j.push(i)}}return j}async fetchNonce(e,t,i={}){if(void 0===e||void 0===t)throw new o.ArgumentsRequired(this.id+" fetchNonce() requires accountIndex and apiKeyIndex.");if("nonce"in i)return this.safeInteger(i,"nonce");let s=this.safeInteger(this.options,"nonce");if(void 0!==s)return s;if(this.handleOptionBoolAndParams(i,"fetchNonce","skipNonce",!0)[0])return this.milliseconds();let r=await this.publicGetNextNonce({account_index:e,api_key_index:t});return this.safeInteger(r,"nonce")}async signAndCreateOrder(e,t,i,s,r,a,o={}){let n,d,h;void 0===this.markets&&await this.loadMarkets();let c=(await this.handleAccountIndex(o,e,"accountIndex","account_index"))[0],l=this.handleApiKeyIndex(o,e,"apiKeyIndex","api_key_index")[0],u=this.numberToString(c),f=this.numberToString(l),p=await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(u,f),f,u,o);try{await this.checkIfStandardTier(c)&&(this.options.builderFee=!1)}catch(e){this.options.builderFee=!1}let[m,g]=this.handleOptionIntegerAndParams(o,e,"groupingType",3),v=this.createOrderRequest(t,i,s,r,a,g),y=v.length;if(y>0&&(d=v[0]),void 0===this.safeInteger(d,"nonce")&&(d.nonce=await this.fetchNonce(c,l)),y<2)[h,n]=this.lighterSignCreateOrder(p,d);else{let e={grouping_type:m,orders:v,nonce:d.nonce,api_key_index:l,account_index:c};this.safeBool(this.options,"builderFee",!0)&&(e.integrator_account_index=d.integrator_account_index,e.integrator_taker_fee=d.integrator_taker_fee,e.integrator_maker_fee=d.integrator_maker_fee),[h,n]=this.lighterSignCreateGroupedOrders(p,e)}return[h,n,d]}async createOrder(e,t,i,s,r,a={}){let[o,n,d]=await this.signAndCreateOrder("createOrder",e,t,i,s,r,a),h=this.market(e),c=await this.publicPostSendTx({tx_type:o,tx_info:n});return this.parseOrder(this.deepExtend(c,d),h)}async editOrder(e,t,i,s,r,a,o={}){let d;void 0===this.markets&&await this.loadMarkets();let[h,c]=this.handleApiKeyIndex(o,"editOrder","apiKeyIndex","api_key_index"),[l,u]=await this.handleAccountIndex(c,"editOrder","accountIndex","account_index"),f=this.numberToString(l),p=this.numberToString(h),m=await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(f,p),p,f,u),g=this.market(t),v=this.safeDict(g,"info",{}),y=this.pow("10",v.size_decimals),b=this.pow("10",v.price_decimals),w=this.safeStringN(u,["stopPrice","triggerPrice","stopLossPrice","takeProfitPrice"]),k=this.omit(u,["stopPrice","triggerPrice","stopLossPrice","takeProfitPrice"]),S=this.priceToPrecision(t,a),O="0";void 0!==w?(d=this.numberToString(r),O=this.priceToPrecision(t,w)):d=this.amountToPrecision(t,r);let T=await this.fetchNonce(l,h,k),P={market_index:this.parseToInt(g.id),index:this.parseToInt(e),base_amount:this.parseToInt(n.A.stringMul(d,y)),price:this.parseToInt(n.A.stringMul(S,b)),trigger_price:this.parseToInt(n.A.stringMul(O,b)),nonce:T,api_key_index:h,account_index:l};this.safeBool(this.options,"builderFee",!0)&&(P.integrator_account_index=this.options.integratorAccountIndex,P.integrator_taker_fee=this.options.integratorTakerFee,P.integrator_maker_fee=this.options.integratorMakerFee);let[I,A]=this.lighterSignModifyOrder(m,this.extend(P,k)),x=await this.publicPostSendTx({tx_type:I,tx_info:A});return this.parseOrder(x,g)}async fetchStatus(e={}){let t=await this.rootGet(e);return{status:"200"===this.safeString(t,"status")?"ok":"error",updated:void 0,eta:void 0,url:void 0,info:t}}async fetchTime(e={}){let t=await this.rootGet(e);return this.safeTimestamp(t,"timestamp")}async fetchMarkets(e={}){let t=await this.publicGetOrderBookDetails(e),i=this.safeList(t,"spot_order_book_details",[]),s=this.safeList(t,"order_book_details",[]),r=this.arrayConcat(i,s),a=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.safeString(t,"market_id"),s=this.safeString(t,"market_type");"perp"===s&&(s="swap");let o=this.safeString(t,"symbol");void 0!==o&&-1!==o.indexOf("/")&&(o=o.split("/")[0]);let n="USDC",d="swap"===s?"USDC":void 0,h=this.safeCurrencyCode(o),c=this.safeCurrencyCode(n);if(void 0===h||void 0===c)continue;let l=this.safeCurrencyCode(d),u=h+"/"+c;void 0!==l&&(u=u+":"+l);let f=this.safeString2(t,"size_decimals","supported_size_decimals"),p=this.safeString2(t,"price_decimals","supported_price_decimals"),m=void 0===f?void 0:this.parseNumber(this.parsePrecision(f)),g=void 0===p?void 0:this.parseNumber(this.parsePrecision(p)),v=this.safeNumber(t,"quote_multiplier");a.push({id:i,symbol:u,base:h,quote:c,settle:l,baseId:o,quoteId:n,settleId:d,type:s,spot:"spot"===s,margin:!1,swap:"swap"===s,future:!1,option:!1,active:"active"===this.safeString(t,"status"),contract:"swap"===s,linear:"swap"===s||void 0,inverse:"swap"!==s&&void 0,taker:this.safeNumber(t,"taker_fee"),maker:this.safeNumber(t,"maker_fee"),contractSize:v,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:m,price:g},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(t,"min_base_amount"),max:void 0},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(t,"min_quote_amount"),max:this.safeNumber(t,"order_quote_limit")}},created:void 0,info:t})}return a}async fetchCurrencies(e={}){let t=await this.publicGetAssetDetails(e);this.checkRequiredCredentials(!1)&&await this.preLoadLighterLibrary();let i=this.safeList(t,"asset_details",[]);return this.parseCurrencies(i)}parseCurrency(e){let t,i,s=this.safeString(e,"asset_id"),r=this.safeCurrencyCode(this.safeString(e,"symbol")),a=this.safeString(e,"decimals"),o="USDC"===r;return o&&(t=this.safeNumber(e,"min_transfer_amount"),i=this.safeNumber(e,"min_withdrawal_amount")),this.safeCurrencyStructure({id:s,name:r,code:r,precision:this.parseNumber("1e-"+a),active:!0,fee:void 0,networks:{},deposit:o,withdraw:o,type:"crypto",limits:{deposit:{min:t,max:void 0},withdraw:{min:i,max:void 0}},info:e})}async fetchOrderBook(e,t,i={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchOrderBook() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={market_id:s.id,limit:100};void 0!==t&&(r.limit=Math.min(t,100));let a=await this.publicGetOrderBookOrders(this.extend(r,i));return this.parseOrderBook(a,s.symbol,void 0,"bids","asks","price","remaining_base_amount")}parseTicker(e,t){let i=this.safeString(e,"market_id"),s=this.safeMarket(i,t),r=s.symbol,a=this.safeString(e,"last_trade_price"),o=this.safeString(e,"daily_price_high"),n=this.safeString(e,"daily_price_low"),d=this.safeString(e,"daily_base_token_volume"),h=this.safeString(e,"daily_quote_token_volume"),c=this.safeString(e,"daily_price_change");return this.safeTicker({symbol:r,timestamp:void 0,datetime:void 0,high:o,low:n,bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:void 0,close:a,last:a,previousClose:void 0,change:void 0,percentage:c,average:void 0,baseVolume:d,quoteVolume:h,markPrice:this.safeString(e,"mark_price"),indexPrice:this.safeString(e,"index_price"),info:e},s)}async fetchTicker(e,t={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchTicker() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={market_id:i.id},r=await this.publicGetOrderBookDetails(this.extend(s,t)),a=this.safeList(r,"spot_order_book_details",[]),n=this.safeList(r,"order_book_details",[]),d=this.arrayConcat(a,n),h=this.safeDict(d,0,{});return this.parseTicker(h,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetOrderBookDetails(t),r=this.safeList(s,"spot_order_book_details",[]),a=this.safeList(s,"order_book_details",[]),o=this.arrayConcat(r,a);return this.parseTickers(o,i)}parseOHLCV(e,t){return[this.safeInteger(e,"t"),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}async fetchOHLCV(e,t="1h",i,s,r={}){let a,n;if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchOHLCV() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h=this.safeInteger(r,"until"),c=this.omit(r,["until"]),l=this.milliseconds();if(void 0!==i)if(a=i,void 0!==h)n=h;else if(void 0!==s){let e=this.parseTimeframe(t);n=this.sum(i,e*s*1e3)}else n=l;else n=void 0!==h?h:l,a=void 0!==s?n-1e3*this.parseTimeframe(t)*s:n-1e3*this.parseTimeframe(t)*100;let u={market_id:d.id,count_back:0,resolution:this.safeString(this.timeframes,t,t),start_timestamp:a,end_timestamp:n},f=await this.publicGetCandles(this.extend(u,c)),p=this.safeList(f,"c",[]);return this.parseOHLCVs(p,d,t,i,s)}parseFundingRate(e,t){let i=this.safeString(e,"market_id");return{info:e,symbol:this.safeSymbol(i,t),markPrice:void 0,indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:this.safeNumber(e,"rate"),fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:void 0}}async fetchFundingRates(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetFundingRates(this.extend(t)),s=this.safeList(i,"funding_rates",[]),r=[];for(let e=0;e<s.length;e++)"lighter"===this.safeString(s[e],"exchange")&&r.push(s[e]);return this.parseFundingRates(r,e)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=await this.handleAccountIndex(e,"fetchBalance","accountIndex","account_index"),s=this.safeString2(this.options,"fetchBalance","defaultType","spot"),r=this.safeString(i,"type",s),a={by:this.safeString(i,"by","index"),value:t},o=await this.publicGetAccount(this.extend(a,i)),d={info:o},h=this.safeList(o,"accounts",[]);for(let e=0;e<h.length;e++){let t=this.safeDict(h,e);if("spot"===r){let e=this.safeList(t,"assets",[]);for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s=this.safeString(i,"symbol"),r=this.safeCurrencyCode(s),a=this.safeDict(d,r,this.account());a.total=n.A.stringAdd(a.total,this.safeString(i,"balance")),a.used=n.A.stringAdd(a.used,this.safeString(i,"locked_balance")),void 0!==r&&(d[r]=a)}}else{let e=this.safeDict(d,"USDC",this.account()),i=this.safeString(e,"total","0"),s=this.safeString(e,"free","0"),r=this.safeString(t,"collateral","0"),a=this.safeString(t,"available_balance","0");e.total=n.A.stringAdd(i,r),e.free=n.A.stringAdd(s,a),d.USDC=e}}return this.safeBalance(d)}async fetchPosition(e,t={}){let i=await this.fetchPositions([e],t);return this.safeDict(i,0,{})}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=await this.handleAccountIndex(t,"fetchPositions","accountIndex","account_index"),r={by:this.safeString(s,"by","index"),value:i},a=await this.publicGetAccount(this.extend(r,s)),o=[],n=this.safeList(a,"accounts",[]);for(let e=0;e<n.length;e++){let t=this.safeDict(n,e),i=this.safeList(t,"positions",[]);for(let e=0;e<i.length;e++)o.push(i[e])}return this.parsePositions(o,e)}parsePosition(e,t){let i,s,r,a=this.safeString(e,"market_id"),o=this.safeMarket(a,t),n=this.safeInteger(e,"sign");void 0!==n&&(i=1===n?"long":"short");let d=this.safeInteger(e,"margin_mode");void 0!==d&&(s=0===d?"cross":"isolated");let h=this.safeString(e,"initial_margin_fraction");if(void 0!==h){let e=this.parseToInt(h);e>0&&(r=100/e)}return this.safePosition({info:e,id:void 0,symbol:o.symbol,timestamp:void 0,datetime:void 0,isolated:"isolated"===s,hedged:void 0,side:i,contracts:this.safeNumber(e,"position"),contractSize:void 0,entryPrice:this.safeNumber(e,"avg_entry_price"),markPrice:void 0,notional:this.safeNumber(e,"position_value"),leverage:r,collateral:this.safeNumber(e,"allocated_margin"),initialMargin:void 0,maintenanceMargin:void 0,initialMarginPercentage:void 0,maintenanceMarginPercentage:void 0,unrealizedPnl:this.safeNumber(e,"unrealized_pnl"),liquidationPrice:this.safeNumber(e,"liquidation_price"),marginMode:s,percentage:void 0})}async fetchAccounts(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=await this.handleAccountIndex(e,"fetchAccounts","accountIndex","account_index"),s={by:this.safeString(i,"by","index"),value:t},r=await this.publicGetAccount(this.extend(s,i)),a=this.safeList(r,"accounts",[]);return this.parseAccounts(a,i)}parseAccount(e){let t=this.safeString(e,"account_type");return{id:this.safeString(e,"account_index"),type:"0"===t?"main":"subaccount",code:void 0,info:e}}async fetchOpenOrders(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchOpenOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let[r,a]=await this.handleAccountIndex(s,"fetchOpenOrders","accountIndex","account_index"),[n,d]=this.handleApiKeyIndex(a,"fetchOpenOrders","apiKeyIndex","api_key_index"),h=this.numberToString(r),c=this.numberToString(n);await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(h,c),c,h,d);let l=this.market(e),u={market_id:l.id,account_index:r},f=await this.privateGetAccountActiveOrders(this.extend(u,d)),p=this.safeList(f,"orders",[]);return this.parseOrders(p,l,t,i)}async fetchClosedOrders(e,t,i,s={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchClosedOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let[r,a]=await this.handleAccountIndex(s,"fetchClosedOrders","accountIndex","account_index"),[n,d]=this.handleApiKeyIndex(a,"fetchClosedOrders","apiKeyIndex","api_key_index"),h=this.numberToString(r),c=this.numberToString(n);await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(h,c),c,h,d);let l=this.market(e),u={market_id:l.id,account_index:r,limit:100};void 0!==i&&(u.limit=Math.min(i,100));let f=await this.privateGetAccountInactiveOrders(this.extend(u,d)),p=this.safeList(f,"orders",[]);return this.parseOrders(p,l,t,i)}parseOrder(e,t){let i,s,r,a,o=this.safeString(e,"market_index"),n=this.safeMarket(o,t),d=this.safeTimestamp(e,"timestamp"),h=this.safeBool(e,"is_ask");if(void 0===h){let t=this.safeInteger(e,"is_ask");void 0!==t&&(h=1===t)}void 0!==h&&(i=h?"sell":"buy");let c=this.safeString(e,"type");if(void 0===c){let t=this.safeInteger(e,"order_type");c=this.parseOrderTypeInteger(t)}let l=this.parseNumber(this.omitZero(this.safeString(e,"trigger_price")));void 0!==c&&(c.indexOf("stop-loss")>=0&&(s=l),c.indexOf("take-profit")>=0&&(r=l));let u=this.safeInteger(e,"time_in_force");a=void 0!==u?this.parseOrderTimeInForceInteger(u):this.safeString(e,"time_in_force");let f=this.safeBool(e,"reduce_only");if(void 0===f){let t=this.safeInteger(e,"reduce_only");void 0!==t&&(f=1===t)}let p=this.safeString(e,"status");return this.safeOrder({info:e,id:this.safeString(e,"order_id"),clientOrderId:this.omitZero(this.safeString2(e,"client_order_id","client_order_index")),timestamp:d,datetime:this.iso8601(d),lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeTimestamp(e,"updated_at"),symbol:n.symbol,type:this.parseOrderType(c),timeInForce:this.parseOrderTimeInForce(a),postOnly:"post-only"===a,reduceOnly:f,side:i,price:this.safeString(e,"price"),triggerPrice:l,stopLossPrice:s,takeProfitPrice:r,amount:this.safeString(e,"initial_base_amount"),cost:this.safeString(e,"filled_quote_amount"),average:void 0,filled:this.safeString(e,"filled_base_amount"),remaining:this.safeString(e,"remaining_base_amount"),status:this.parseOrderStatus(p),fee:void 0,trades:void 0},n)}parseOrderStatus(e){return this.safeString({"in-progress":"open",pending:"open",open:"open",filled:"closed",canceled:"canceled","canceled-post-only":"canceled","canceled-reduce-only":"canceled","canceled-position-not-allowed":"rejected","canceled-margin-not-allowed":"rejected","canceled-too-much-slippage":"canceled","canceled-not-enough-liquidity":"canceled","canceled-self-trade":"canceled","canceled-expired":"expired","canceled-oco":"canceled","canceled-child":"canceled","canceled-liquidation":"canceled"},e,e)}parseOrderType(e){return this.safeString({limit:"limit",market:"market","stop-loss":"market","stop-loss-limit":"limit","take-profit":"market","take-profit-limit":"limit",twap:"twap","twap-sub":"twap",liquidation:"market"},e,e)}parseOrderTypeInteger(e){if(void 0!==e)return this.safeString({0:"limit",1:"market",2:"stop-loss",3:"stop-loss-limit",4:"take-profit",5:"take-profit-limit",6:"twap",7:"twap-sub",8:"liquidation"},e.toString())}parseOrderTimeInForce(e){return this.safeString({"immediate-or-cancel":"IOC","good-till-time":"GTC","post-only":"PO",Unknown:void 0},e,e)}parseOrderTimeInForceInteger(e){return this.safeString({0:"immediate-or-cancel",1:"good-till-time",2:"post-only"},e.toString())}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let[a,d]=this.handleApiKeyIndex(r,"transfer","apiKeyIndex","api_key_index"),[h,c]=await this.handleAccountIndex(d,"transfer","accountIndex","account_index"),[l,u]=this.handleOptionAndParams2(c,"transfer","toAccountIndex","to_account_index",h),f=this.numberToString(h),p=this.numberToString(a),m=await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(f,p),p,f,u),g=this.currency(e),v=g.code;if("USDC"!==v&&"ETH"!==v)throw new o.ExchangeError(this.id+" transfer() only supports USDC and ETH transfers");let y=this.parseToInt(n.A.stringMul(this.pow("10","USDC"===v?"6":"8"),this.currencyToPrecision(e,t))),b=this.safeString(u,"memo","0x000000000000000000000000000000"),w=this.omit(u,["memo"]),k=await this.fetchNonce(h,a,w),S={to_account_index:l,asset_index:this.parseToInt(g.id),from_route_type:+("perp"!==i),to_route_type:+("perp"!==s),amount:y,usdc_fee:0,memo:b,nonce:k,api_key_index:a,account_index:h},[O,T]=this.lighterSignTransfer(m,this.extend(S,w)),P=await this.publicPostSendTx({tx_type:O,tx_info:T});return this.parseTransfer(P)}async fetchTransfers(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchTransfers","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchTransfers",e,t,i,o,"cursor","cursor",void 0,50);let[n,d]=await this.handleAccountIndex(o,"fetchTransfers","accountIndex","account_index"),[h,c]=this.handleApiKeyIndex(d,"fetchTransfers","apiKeyIndex","api_key_index"),l=this.numberToString(n),u=this.numberToString(h);await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(l,u),u,l,c),void 0!==e&&(r=this.currency(e));let f=await this.privateGetTransferHistory(this.extend({account_index:n},c)),p=this.safeList(f,"transfers",[]),m=this.safeString(f,"cursor");return void 0!==this.safeDict(p,0)&&void 0!==m&&(p[0].cursor=m),this.parseTransfers(p,r,t,i,c)}parseTransfer(e,t){let i=this.safeString(e,"asset_id"),s=this.safeCurrencyCode(i,t),r=this.safeInteger(e,"timestamp"),a=this.safeDict(e,"from",{}),o=this.safeDict(e,"to",{});return{id:this.safeString(e,"id"),timestamp:r,datetime:this.iso8601(r),currency:s,amount:this.safeNumber(e,"amount"),fromAccount:this.safeString(a,"from_account_index"),toAccount:this.safeString(o,"to_account_index"),status:void 0,info:e}}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,n]=this.handleOptionBoolAndParams(s,"fetchDeposits","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchDeposits",e,t,i,n,"cursor","cursor",void 0,50);let[d,h]=this.handleOptionStringAndParams2(n,"fetchDeposits","address","l1_address");if(void 0===d)throw new o.ArgumentsRequired(this.id+" fetchDeposits() requires an address parameter");let[c,l]=await this.handleAccountIndex(h,"fetchDeposits","accountIndex","account_index"),u={account_index:c,l1_address:d},[f,p]=this.handleApiKeyIndex(l,"fetchDeposits","apiKeyIndex","api_key_index"),m=this.numberToString(c),g=this.numberToString(f);await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(m,g),g,m,p),void 0!==e&&(u.coin=(r=this.currency(e)).id);let v=await this.privateGetDepositHistory(this.extend(u,p)),y=this.safeList(v,"deposits",[]),b=this.safeString(v,"cursor");return void 0!==this.safeDict(y,0)&&void 0!==b&&(y[0].cursor=b),this.parseTransactions(y,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r,[a,o]=this.handleOptionBoolAndParams(s,"fetchWithdrawals","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchWithdrawals",e,t,i,o,"cursor","cursor",void 0,50);let[n,d]=await this.handleAccountIndex(o,"fetchWithdrawals","accountIndex","account_index");void 0===this.markets&&await this.loadMarkets();let h={account_index:n},[c,l]=this.handleApiKeyIndex(d,"fetchWithdrawals","apiKeyIndex","api_key_index"),u=this.numberToString(n),f=this.numberToString(c);await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(u,f),f,u,l),void 0!==e&&(h.coin=(r=this.currency(e)).id);let p=await this.privateGetWithdrawHistory(this.extend(h,l)),m=this.safeList(p,"withdraws",[]),g=this.safeString(p,"cursor");return void 0!==this.safeDict(m,0)&&void 0!==g&&(m[0].cursor=g),this.parseTransactions(m,r,t,i)}parseTransaction(e,t){let i=this.safeString(e,"type");i=void 0===i?"deposit":"withdrawal";let s=this.safeInteger(e,"timestamp"),r=this.safeString(e,"status");return{info:e,id:this.safeString(e,"id"),txid:this.safeString(e,"l1_tx_hash"),type:i,currency:this.safeCurrencyCode(this.safeString(e,"asset_id"),t),network:void 0,amount:this.safeNumber(e,"amount"),status:this.parseTransactionStatus(r),timestamp:s,datetime:this.iso8601(s),address:void 0,addressFrom:void 0,addressTo:void 0,tag:void 0,tagFrom:void 0,tagTo:void 0,updated:void 0,comment:void 0,fee:void 0,internal:void 0}}parseTransactionStatus(e){return this.safeString({failed:"failed",pending:"pending",completed:"ok",claimable:"ok"},e,e)}async withdraw(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let[a,d]=this.handleApiKeyIndex(r,"withdraw","apiKeyIndex","api_key_index"),[h,c]=await this.handleAccountIndex(d,"withdraw","accountIndex","account_index"),l=this.numberToString(h),u=this.numberToString(a),f=await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(l,u),u,l,c),p=this.currency(e),m=p.code;if("USDC"!==m&&"ETH"!==m)throw new o.ExchangeError(this.id+" withdraw() only supports USDC and ETH transfers");let g=this.parseToInt(n.A.stringMul(this.pow("10","USDC"===m?"6":"8"),this.currencyToPrecision(e,t))),v=this.safeInteger(c,"routeType",0),y=this.omit(c,"routeType"),b=await this.fetchNonce(h,a,y),w={asset_index:this.parseToInt(p.id),route_type:v,amount:g,nonce:b,api_key_index:a,account_index:h},[k,S]=this.lighterSignWithdraw(f,this.extend(w,y)),O=await this.publicPostSendTx({tx_type:k,tx_info:S});return this.parseTransaction(O)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchMyTrades",e,t,i,o,"next_cursor","cursor",void 0,50);let[n,d]=await this.handleAccountIndex(o,"fetchMyTrades","accountIndex","account_index"),[h,c]=this.handleApiKeyIndex(d,"fetchMyTrades","apiKeyIndex","api_key_index"),l=this.numberToString(n),u=this.numberToString(h);await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(l,u),u,l,c);let f={sort_by:"timestamp",limit:100,account_index:n};void 0!==i&&(f.limit=Math.min(i,100));let[p,m]=this.handleOptionIntegerAndParams2(c,"fetchMyTrades","until","from");void 0!==p&&(f.from=p),void 0!==e&&(f.market_id=(r=this.market(e)).id);let g=await this.privateGetTrades(this.extend(f,m)),v=this.safeList(g,"trades",[]);for(let e=0;e<v.length;e++)v[e].account_index=n;let y=this.safeString(g,"next_cursor");return void 0!==this.safeDict(v,0)&&void 0!==y&&(v[0].next_cursor=y),this.parseTrades(v,r,t,i,m)}parseTrade(e,t){let i,s,r,a=this.safeString(e,"market_id"),o=this.safeMarket(a,t),n=this.safeInteger(e,"timestamp"),d=this.safeString(e,"account_index"),h=this.safeString(e,"ask_account_id"),c=this.safeString(e,"bid_account_id"),l=this.safeBool(e,"is_maker_ask");return void 0!==d&&(d===h?(i="sell",s=this.safeString(e,"ask_id")):d===c&&(i="buy",s=this.safeString(e,"bid_id"))),void 0!==i&&void 0!==l&&(r=("sell"===i?l:!l)?"maker":"taker"),this.safeTrade({info:e,id:this.safeString(e,"trade_id"),timestamp:n,datetime:this.iso8601(n),symbol:o.symbol,order:s,type:this.safeString(e,"type"),side:i,takerOrMaker:r,price:this.safeString(e,"price"),amount:this.safeString(e,"size"),cost:this.safeString(e,"usd_amount"),fee:void 0},o)}async setLeverage(e,t,i={}){if(void 0===t)throw new o.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");let[s,r]=this.handleOptionStringAndParams2(i,"setLeverage","marginMode","margin_mode");if(void 0===s)throw new o.ArgumentsRequired(this.id+" setLeverage() requires an marginMode parameter");return await this.modifyLeverageAndMarginMode(e,s,t,r)}async setMarginMode(e,t,i={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" setMarginMode() requires an marginMode parameter");let[s,r]=this.handleOptionAndParams(i,"setMarginMode","leverage");if(void 0===s)throw new o.ArgumentsRequired(this.id+" setMarginMode() requires an leverage parameter");return await this.modifyLeverageAndMarginMode(s,e,t,r)}async modifyLeverageAndMarginMode(e,t,i,s={}){if(void 0===this.markets&&await this.loadMarkets(),"cross"!==t&&"isolated"!==t)throw new o.BadRequest(this.id+" modifyLeverageAndMarginMode() requires a marginMode parameter that must be either cross or isolated");let[r,a]=this.handleApiKeyIndex(s,"modifyLeverageAndMarginMode","apiKeyIndex","api_key_index");if(void 0===i)throw new o.ArgumentsRequired(this.id+" modifyLeverageAndMarginMode() requires a symbol argument");let[n,d]=await this.handleAccountIndex(a,"modifyLeverageAndMarginMode","accountIndex","account_index"),h=this.numberToString(n),c=this.numberToString(r),l=await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(h,c),c,h,d),u=this.market(i),f=await this.fetchNonce(n,r,d),p={market_index:this.parseToInt(u.id),initial_margin_fraction:this.parseToInt(1e4/e),margin_mode:+("cross"!==t),nonce:f,api_key_index:r,account_index:n},[m,g]=this.lighterSignUpdateLeverage(l,this.extend(p,d));return await this.publicPostSendTx({tx_type:m,tx_info:g})}async signAndCancelOrder(e,t,i,s={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===i)throw new o.ArgumentsRequired(this.id+" "+e+" requires a symbol argument");let[r,a]=this.handleApiKeyIndex(s,e,"apiKeyIndex","api_key_index"),[n,d]=await this.handleAccountIndex(a,e,"accountIndex","account_index"),h=this.market(i),c=this.safeString2(d,"client_order_index","clientOrderId"),l=this.omit(d,["client_order_index","clientOrderId"]),u=this.numberToString(n),f=this.numberToString(r),p=await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(u,f),f,u,l),m=await this.fetchNonce(n,r,l),g={market_index:this.parseToInt(h.id),nonce:m,api_key_index:r,account_index:n};if(void 0!==c)g.order_index=this.parseToInt(c);else if(void 0!==t)g.order_index=this.parseToInt(t);else throw new o.ArgumentsRequired(this.id+" "+e+" requires order id or client order id");let[v,y]=this.lighterSignCancelOrder(p,this.extend(g,l));return[v,y]}async cancelOrder(e,t,i={}){let[s,r]=await this.signAndCancelOrder("cancelOrder",e,t,i),a=this.market(t),o=await this.publicPostSendTx({tx_type:s,tx_info:r});return this.parseOrder(o,a)}async signAndCancelAllOrders(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleApiKeyIndex(i,e,"apiKeyIndex","api_key_index"),[a,o]=await this.handleAccountIndex(r,e,"accountIndex","account_index"),n=this.numberToString(a),d=this.numberToString(s),h=await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(n,d),d,n,o),c=await this.fetchNonce(a,s,o),[l,u]=this.lighterSignCancelAllOrders(h,this.extend({time_in_force:0,time:0,nonce:c,api_key_index:s,account_index:a},o));return[l,u]}async cancelAllOrders(e,t={}){let[i,s]=await this.signAndCancelAllOrders("cancelAllOrdersWs",e,t),r=await this.publicPostSendTx({tx_type:i,tx_info:s});return this.parseOrders([r])}async cancelAllOrdersAfter(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),e<3e5||e>1296e6)throw new o.BadRequest(this.id+" timeout should be between 5 minutes and 15 days.");let[i,s]=this.handleApiKeyIndex(t,"cancelOrder","apiKeyIndex","api_key_index"),[r,a]=await this.handleAccountIndex(s,"cancelAllOrdersAfter","accountIndex","account_index"),n=this.numberToString(r),d=this.numberToString(i),h=await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(n,d),d,n,a),c=await this.fetchNonce(r,i,a),l={time_in_force:1,time:this.milliseconds()+e,nonce:c,api_key_index:i,account_index:r},[u,f]=this.lighterSignCancelAllOrders(h,this.extend(l,a));return await this.publicPostSendTx({tx_type:u,tx_info:f})}async addMargin(e,t,i={}){return await this.setMargin(e,t,this.extend({direction:1},i))}async reduceMargin(e,t,i={}){return await this.setMargin(e,t,this.extend({direction:0},i))}async setMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleApiKeyIndex(i,"setMargin","apiKeyIndex","api_key_index"),a=this.safeInteger(r,"direction");if(void 0===a||!this.inArray(a,[0,1]))throw new o.ArgumentsRequired(this.id+" setMargin() requires a direction parameter either 1 (increase margin) or 0 (decrease margin)");if(void 0===e)throw new o.ArgumentsRequired(this.id+" setMargin() requires a symbol argument");let[d,h]=await this.handleAccountIndex(r,"setMargin","accountIndex","account_index"),c=this.numberToString(d),l=this.numberToString(s),u=await this.loadAccount(this.options.chainId,this.getLighterPrivateKey(c,l),l,c,h),f=this.market(e),p=await this.fetchNonce(d,s,h),m={market_index:this.parseToInt(f.id),usdc_amount:this.parseToInt(n.A.stringMul(this.pow("10","6"),this.currencyToPrecision("USDC",t))),direction:a,nonce:p,api_key_index:s,account_index:d},[g,v]=this.lighterSignUpdateMargin(u,this.extend(m,h)),y=await this.publicPostSendTx({tx_type:g,tx_info:v});return this.parseMarginModification(y,f)}parseMarginModification(e,t){let i=this.safeInteger(e,"predicted_execution_time_ms");return{info:e,symbol:this.safeString(t,"symbol"),type:void 0,marginMode:void 0,amount:void 0,total:void 0,code:"USDC",status:void 0,timestamp:i,datetime:this.iso8601(i)}}sign(e,t="public",i="GET",s={},r,a){let n,d;if("root"===t){let e=this.safeString(this.urls.api,"public");if(void 0===e)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");n=this.implodeHostname(e)}else{let i=this.safeString(this.urls.api,t);if(void 0===i)throw new o.ExchangeError(this.id+" sign() has no API URL for this endpoint");n=this.implodeHostname(i)+"/api/"+this.version+"/"+e}if("private"===t&&(d={Authorization:this.createAuth(s)}),Object.keys(s).length>0){if("POST"===i)return{url:n,method:i,body:s,headers:{"Content-Type":"multipart/form-data"}};n+="?"+this.rawencode(s)}return"private"===t?{url:n,method:i,body:a,headers:d}:{url:n,method:i,body:a,headers:r}}handleErrors(e,t,i,s,r,a,n,d,h){if(null==n)return;let c=this.safeString(n,"code"),l=this.safeString(n,"msg");if(void 0!==c&&"0"!==c&&"200"!==c){let e=this.id+" "+a;throw this.throwBroadlyMatchedException(this.exceptions.broad,l,e),this.throwExactlyMatchedException(this.exceptions.exact,c,e),new o.ExchangeError(e)}}}i.d(t,{A:()=>h})},5642(e,t,i){"use strict";var s=i(7527),r=i(1453),a=i(7749);class o extends s.A{describe(){return this.deepExtend(super.describe(),{id:"luno",name:"Luno",countries:["GB","SG","ZA"],rateLimit:200,version:"1",pro:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createDepositAddress:!0,createOrder:!0,createReduceOnlyOrder:!1,fetchAccounts:!0,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositWithdrawFee:!0,fetchDepositWithdrawFees:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLedger:!0,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrice:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!1,fetchPositionForSymbolWs:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsForSymbolWs:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!1,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1},urls:{referral:"https://www.luno.com/invite/44893A",logo:"https://user-images.githubusercontent.com/1294454/27766607-8c1a69d8-5ede-11e7-930c-540b5eb9be24.jpg",api:{public:"https://api.luno.com/api",private:"https://api.luno.com/api",exchange:"https://api.luno.com/api/exchange",exchangePrivate:"https://api.luno.com/api/exchange"},www:"https://www.luno.com",doc:["https://www.luno.com/en/developers/api","https://npmjs.org/package/bitx","https://github.com/bausmeier/node-bitx"]},api:{exchange:{get:{markets:{cost:1}}},exchangePrivate:{get:{candles:{cost:1},move:{cost:1},"move/list_moves":{cost:1},transfers:{cost:1}},post:{convert:{cost:1},move:{cost:1}}},public:{get:{orderbook:{cost:1},orderbook_top:{cost:1},ticker:{cost:1},tickers:{cost:1},trades:{cost:1}}},private:{get:{"accounts/{id}/pending":{cost:1},"accounts/{id}/transactions":{cost:1},balance:{cost:1},beneficiaries:{cost:1},"send/networks":{cost:1},fee_info:{cost:1},funding_address:{cost:1},listorders:{cost:1},listtrades:{cost:1},send_fee:{cost:1},"orders/{id}":{cost:1},withdrawals:{cost:1},"withdrawals/{id}":{cost:1},transfers:{cost:1},"users/linked":{cost:1}},post:{accounts:{cost:1},"address/validate":{cost:1},postorder:{cost:1},marketorder:{cost:1},stoporder:{cost:1},funding_address:{cost:1},withdrawals:{cost:1},send:{cost:1},"oauth2/grant":{cost:1},beneficiaries:{cost:1}},put:{"accounts/{id}/name":{cost:1}},delete:{"withdrawals/{id}":{cost:1},"beneficiaries/{id}":{cost:1}}}},timeframes:{"1m":60,"5m":300,"15m":900,"30m":1800,"1h":3600,"3h":10800,"4h":14400,"1d":86400,"3d":259200,"1w":604800},fees:{trading:{tierBased:!0,percentage:!0,taker:this.parseNumber("0.006"),maker:this.parseNumber("0.004"),tiers:{taker:[[this.parseNumber("0"),this.parseNumber("0.006")],[this.parseNumber("20000"),this.parseNumber("0.005")],[this.parseNumber("200000"),this.parseNumber("0.004")],[this.parseNumber("1000000"),this.parseNumber("0.003")],[this.parseNumber("2000000"),this.parseNumber("0.002")],[this.parseNumber("5000000"),this.parseNumber("0.0015")],[this.parseNumber("10000000"),this.parseNumber("0.001")],[this.parseNumber("20000000"),this.parseNumber("0.0009")],[this.parseNumber("40000000"),this.parseNumber("0.0008")],[this.parseNumber("80000000"),this.parseNumber("0.0007")],[this.parseNumber("120000000"),this.parseNumber("0.0006")],[this.parseNumber("160000000"),this.parseNumber("0.0005")],[this.parseNumber("300000000"),this.parseNumber("0.0005")]],maker:[[this.parseNumber("0"),this.parseNumber("0.004")],[this.parseNumber("20000"),this.parseNumber("0.003")],[this.parseNumber("200000"),this.parseNumber("0.002")],[this.parseNumber("1000000"),this.parseNumber("0.001")],[this.parseNumber("2000000"),this.parseNumber("0.0008")],[this.parseNumber("5000000"),this.parseNumber("0.0006")],[this.parseNumber("10000000"),this.parseNumber("0")],[this.parseNumber("20000000"),this.parseNumber("0")],[this.parseNumber("40000000"),this.parseNumber("-0.0001")],[this.parseNumber("80000000"),this.parseNumber("-0.0001")],[this.parseNumber("120000000"),this.parseNumber("-0.0002")],[this.parseNumber("160000000"),this.parseNumber("-0.0002")],[this.parseNumber("300000000"),this.parseNumber("-0.0002")]]}}},exceptions:{exact:{ErrAccountIsMigrating:r.OperationRejected,ErrAccountLimit:r.OperationRejected,ErrAccountNotFound:r.ExchangeError,ErrAccountsNotDifferent:r.BadRequest,ErrActiveCryptoRequestExists:r.OperationRejected,ErrAddressCreateRateLimitReached:r.RateLimitExceeded,ErrAddressLimitReached:r.OperationRejected,ErrAmountTooBig:r.BadRequest,ErrAmountTooSmall:r.BadRequest,ErrApiKeyRevoked:r.AuthenticationError,ErrBeneficiaryNotFound:r.ExchangeError,ErrBlockedSendsCurrency:r.OperationRejected,ErrCannotStopUnknownOrNonPendingOrder:r.InvalidOrder,ErrCannotTradeWhileQuoteActive:r.OperationRejected,ErrConvertPairNotSupported:r.BadRequest,ErrConvertRateLimited:r.RateLimitExceeded,ErrCounterDenominationNotAllowed:r.InvalidOrder,ErrCreditAccountNotTransactional:r.BadRequest,ErrCustomRefNotAllowed:r.BadRequest,ErrDeadlineExceeded:r.RequestTimeout,ErrDebitAccountNotTransactional:r.BadRequest,ErrDescriptionTooLong:r.BadRequest,ErrDifferentCurrencies:r.BadRequest,ErrDisallowedTarget:r.InvalidAddress,ErrDuplicateClientMoveID:r.OperationRejected,ErrDuplicateClientOrderID:r.DuplicateOrderId,ErrDuplicateExternalID:r.OperationRejected,ErrERC20AddressAlreadyAssigned:r.OperationRejected,ErrERC20AssignNonDefault:r.BadRequest,ErrFundsMoveNotFound:r.ExchangeError,ErrIdempotencyKeyConflict:r.OperationRejected,ErrIdempotencyKeyRequestMismatch:r.BadRequest,ErrIncompatibleBeneficiary:r.BadRequest,ErrIncorrectPin:r.AuthenticationError,ErrInsufficientBalance:r.InsufficientFunds,ErrInsufficientFunds:r.InsufficientFunds,ErrInsufficientPerms:r.PermissionDenied,ErrInternal:r.ExchangeNotAvailable,ErrInvalidAccount:r.BadRequest,ErrInvalidAccountID:r.BadRequest,ErrInvalidAccountNumber:r.BadRequest,ErrInvalidAmount:r.BadRequest,ErrInvalidArguments:r.BadRequest,ErrInvalidBaseVolume:r.InvalidOrder,ErrInvalidBranchCode:r.BadRequest,ErrInvalidClientOrderId:r.InvalidOrder,ErrInvalidCounterVolume:r.InvalidOrder,ErrInvalidCurrency:r.BadRequest,ErrInvalidDetails:r.BadRequest,ErrInvalidMarketPair:r.BadSymbol,ErrInvalidOrderRef:r.InvalidOrder,ErrInvalidOrderSide:r.InvalidOrder,ErrInvalidParameters:r.BadRequest,ErrInvalidPrice:r.InvalidOrder,ErrInvalidRequestType:r.BadRequest,ErrInvalidSourceAccount:r.BadRequest,ErrInvalidStopDirection:r.InvalidOrder,ErrInvalidStopPrice:r.InvalidOrder,ErrInvalidVolume:r.InvalidOrder,ErrLimitOutOfRange:r.BadRequest,ErrMarketNotAllowed:r.PermissionDenied,ErrMarketUnavailable:r.ExchangeError,ErrMaxActiveFiatRequestsExists:r.OperationRejected,ErrMissingIdempotencyKey:r.BadRequest,ErrNoAddressesAssigned:r.InvalidAddress,ErrNoTradesToInferStopDirection:r.InvalidOrder,ErrNotEnoughLiquidity:r.InvalidOrder,ErrNotFound:r.ExchangeError,ErrOrderCanceled:r.InvalidOrder,ErrOrderNotFound:r.OrderNotFound,ErrPostOnlyMode:r.InvalidOrder,ErrPostOnlyNotAllowed:r.InvalidOrder,ErrPriceDenominationNotAllowed:r.InvalidOrder,ErrPriceTooHigh:r.InvalidOrder,ErrPriceTooLow:r.InvalidOrder,ErrRejectedBeneficiary:r.OperationRejected,ErrRequestTypeDoesNotSupportFastWithdrawals:r.BadRequest,ErrStopPriceTooHigh:r.InvalidOrder,ErrStopPriceTooLow:r.InvalidOrder,ErrTooManyRequests:r.RateLimitExceeded,ErrTooManyRowsRequested:r.BadRequest,ErrTravelRule:r.ManualInteractionNeeded,ErrUnauthorised:r.AuthenticationError,ErrUnderMaintenance:r.OnMaintenance,ErrUpdateRequired:r.ExchangeError,ErrUserBlockedForCancelWithdrawal:r.PermissionDenied,ErrUserNotVerifiedForCurrency:r.AccountNotEnabled,ErrValueTooHigh:r.InvalidOrder,ErrVerificationLevelTooLow:r.AccountNotEnabled,ErrVolumeDenominationNotAllowed:r.InvalidOrder,ErrVolumeTooHigh:r.InvalidOrder,ErrVolumeTooLow:r.InvalidOrder,ErrWithdrawalBlocked:r.PermissionDenied,ErrWithdrawalNotFound:r.ExchangeError}},precisionMode:4,features:{spot:{sandbox:!1,fetchCurrencies:{private:!0},createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!0,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:1e5,untilDays:1e5,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:1e3,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:1e3,daysBack:1e5,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:1e3,daysBack:1e5,daysBackCanceled:1,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:void 0}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},rollingWindowSize:6e4})}async fetchCurrencies(e={}){if(!this.checkRequiredCredentials(!1))return{};let t=await this.privateGetSendNetworks(e),i=this.safeList(t,"data",[]),s=Object.values(this.groupBy(i,"native_currency"));return this.parseCurrencies(s)}parseCurrency(e){let t=this.safeString(e[0],"native_currency"),i=this.safeCurrencyCode(t),s={};for(let t=0;t<e.length;t++){let r=this.safeDict(e,t),a=this.safeString(r,"name"),o=this.networkIdToCode(a,i);void 0!==o&&(s[o]={id:a,network:o,limits:{withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,precision:void 0,info:r})}return this.safeCurrencyStructure({id:t,code:i,precision:void 0,type:void 0,name:void 0,active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,limits:{withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},networks:s,info:e})}async fetchMarkets(e={}){let t=await this.exchangeGetMarkets(e),i=[],s=this.safeList(t,"markets",[]);for(let e=0;e<s.length;e++){let t,r,a=s[e],o=this.safeString(a,"market_id"),n=this.safeString(a,"base_currency"),d=this.safeString(a,"counter_currency"),h=this.safeCurrencyCode(n),c=this.safeCurrencyCode(d);if(void 0===h||void 0===c)continue;let l=this.safeString(a,"trading_status"),u=["ZAR"],f=["MYR","NGN","IDR","KES","UGX","AUD","GBP","EUR","USD","ZARU"],p=["USDT","USDC"];this.inArray(c,u)?this.inArray(h,p)?(t=this.parseNumber("0.002"),r=this.parseNumber("-0.0001")):(t=this.parseNumber("0.006"),r=this.parseNumber("0.004")):this.inArray(c,f)||(t=this.parseNumber("0.001"),r=this.parseNumber("0.0008")),i.push({id:o,symbol:h+"/"+c,taker:t,maker:r,base:h,quote:c,settle:void 0,baseId:n,quoteId:d,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:"ACTIVE"===l,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(a,"volume_scale"))),price:this.parseNumber(this.parsePrecision(this.safeString(a,"price_scale")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(a,"min_volume"),max:this.safeNumber(a,"max_volume")},price:{min:this.safeNumber(a,"min_price"),max:this.safeNumber(a,"max_price")},cost:{min:void 0,max:void 0}},created:void 0,info:a})}return i}async fetchAccounts(e={}){let t=await this.privateGetBalance(e),i=this.safeList(t,"balance",[]),s=[];for(let e=0;e<i.length;e++){let t=i[e],r=this.safeString(t,"account_id"),a=this.safeString(t,"asset"),o=this.safeCurrencyCode(a);s.push({id:r,type:void 0,code:o,info:t})}return s}parseBalance(e){let t=this.safeList(e,"balance",[]),i={info:e,timestamp:void 0,datetime:void 0};for(let e=0;e<t.length;e++){let s=this.safeDict(t,e),r=this.safeString(s,"asset"),o=this.safeCurrencyCode(r),n=this.safeString(s,"reserved"),d=this.safeString(s,"unconfirmed"),h=this.safeString(s,"balance"),c=a.Y.stringAdd(n,d),l=a.Y.stringAdd(h,d);if(void 0!==o&&o in i)i[o].used=a.Y.stringAdd(i[o].used,c),i[o].total=a.Y.stringAdd(i[o].total,l);else if(void 0!==o){let e=this.account();e.used=c,e.total=l,i[o]=e}}return this.safeBalance(i)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetBalance(e);return this.parseBalance(t)}async fetchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={pair:r.id};s=void 0!==t&&t<=100?await this.publicGetOrderbookTop(this.extend(a,i)):await this.publicGetOrderbook(this.extend(a,i));let o=this.safeInteger(s,"timestamp");return this.parseOrderBook(s,r.symbol,o,"bids","asks","price","volume")}parseOrderStatus(e){return this.safeString({PENDING:"open"},e,e)}parseOrder(e,t){let i,s,r=this.safeInteger(e,"creation_timestamp"),a=this.parseOrderStatus(this.safeString(e,"state")),o=this.safeString(e,"type");"ASK"===o||"SELL"===o?i="sell":("BID"===o||"BUY"===o)&&(i="buy");let n=this.safeString(e,"pair"),d=this.safeMarket(n,t),h=this.safeString(e,"limit_price"),c=this.safeString(e,"limit_volume"),l=this.safeNumber(e,"fee_counter"),u=this.safeNumber(e,"fee_base"),f=this.safeString(e,"base"),p=this.safeString(e,"counter");void 0!==l?s={cost:l,currency:d.quote}:void 0!==u&&(s={cost:u,currency:d.base});let m=this.safeString(e,"order_id");return this.safeOrder({id:m,clientOrderId:void 0,datetime:this.iso8601(r),timestamp:r,lastTradeTimestamp:void 0,status:a,symbol:d.symbol,type:void 0,timeInForce:void 0,postOnly:void 0,side:i,price:h,triggerPrice:void 0,amount:c,filled:f,cost:p,remaining:void 0,trades:void 0,fee:s,info:e,average:void 0},d)}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateGetOrdersId(this.extend({id:e},i));return this.parseOrder(s)}async fetchOrdersByState(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o={};void 0!==e&&(o.state=e),void 0!==t&&(o.pair=(a=this.market(t)).id);let n=await this.privateGetListorders(this.extend(o,r)),d=this.safeList(n,"orders",[]);return this.parseOrders(d,a,i,s)}async fetchOrders(e,t,i,s={}){return await this.fetchOrdersByState(void 0,e,t,i,s)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrdersByState("PENDING",e,t,i,s)}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrdersByState("COMPLETE",e,t,i,s)}parseTicker(e,t){let i=this.safeInteger(e,"timestamp"),s=this.safeString(e,"pair"),r=this.safeSymbol(s,t),a=this.safeString(e,"last_trade");return this.safeTicker({symbol:r,timestamp:i,datetime:this.iso8601(i),high:void 0,low:void 0,bid:this.safeString(e,"bid"),bidVolume:void 0,ask:this.safeString(e,"ask"),askVolume:void 0,vwap:void 0,open:void 0,close:a,last:a,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"rolling_24_hour_volume"),quoteVolume:void 0,info:e},t)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetTickers(t),r=this.safeList(s,"tickers",[]),a=this.indexBy(r,"pair"),o=Object.keys(a),n={};for(let e=0;e<o.length;e++){let t=o[e],i=this.safeMarket(t),s=i.symbol,r=a[t];n[s]=this.parseTicker(r,i)}return this.filterByArrayTickers(n,"symbol",i)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={pair:i.id},r=await this.publicGetTicker(this.extend(s,t));return this.parseTicker(r,i)}parseTrade(e,t){let i,s,r,o,n=this.safeString(e,"order_id"),d=this.safeString(e,"sequence");if(void 0!==n){let t=this.safeString(e,"type");"ASK"===t||"SELL"===t?s="sell":("BID"===t||"BUY"===t)&&(s="buy"),i="sell"===s&&this.safeBool(e,"is_buy",!1)?"maker":"buy"!==s||this.safeBool(e,"is_buy",!1)?"taker":"maker"}else s=this.safeBool(e,"is_buy",!1)?"buy":"sell";let h=this.safeString(e,"fee_base"),c=this.safeString(e,"fee_counter");void 0!==h?a.Y.stringEquals(h,"0.0")||(r=this.safeString(t,"base"),o=h):void 0===c||a.Y.stringEquals(c,"0.0")||(r=this.safeString(t,"quote"),o=c);let l=this.safeInteger(e,"timestamp");return this.safeTrade({info:e,id:d,timestamp:l,datetime:this.iso8601(l),symbol:this.safeString(t,"symbol"),order:n,type:void 0,side:s,takerOrMaker:i,price:this.safeString(e,"price"),amount:this.safeString2(e,"volume","base"),cost:this.safeString(e,"counter"),fee:{cost:o,currency:r}},t)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={pair:r.id};void 0!==t&&(a.since=t);let o=await this.publicGetTrades(this.extend(a,s)),n=this.safeList(o,"trades",[]);return this.parseTrades(n,r,t,i)}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={duration:this.safeValue(this.timeframes,t,t),pair:a.id};if(void 0!==i)o.since=this.parseToInt(i);else{let e=1e6*this.parseTimeframe(t);o.since=this.milliseconds()-e}let n=await this.exchangePrivateGetCandles(this.extend(o,r)),d=this.safeList(n,"candles",[]);return this.parseOHLCVs(d,a,t,i,s)}parseOHLCV(e,t){return[this.safeInteger(e,"timestamp"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new r.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={pair:a.id};void 0!==t&&(o.since=t),void 0!==i&&(o.limit=i);let n=await this.privateGetListtrades(this.extend(o,s)),d=this.safeList(n,"trades",[]);return this.parseTrades(d,a,t,i)}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={pair:this.market(e).id},s=await this.privateGetFeeInfo(this.extend(i,t));return{info:s,symbol:e,maker:this.safeNumber(s,"maker_fee"),taker:this.safeNumber(s,"taker_fee"),percentage:void 0,tierBased:void 0}}async createOrder(e,t,i,s,a,o={}){let n;void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h={pair:d.id};if(this.checkRequiredArgument("createOrder",i,"side"),"market"===t?(h.type=i.toUpperCase(),"buy"===i?h.counter_volume=this.amountToPrecision(d.symbol,s):h.base_volume=this.amountToPrecision(d.symbol,s),n=await this.privatePostMarketorder(this.extend(h,o))):(h.volume=this.amountToPrecision(d.symbol,s),h.price=this.priceToPrecision(d.symbol,a),h.type="buy"===i?"BID":"ASK",n=await this.privatePostPostorder(this.extend(h,o))),void 0===n)throw new r.NullResponse(this.id+" createOrder() returned empty response");return this.safeOrder({info:n,id:n.order_id},d)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privatePostStoporder(this.extend({order_id:e},i));return this.safeOrder({info:s})}async fetchLedgerByEntries(e,t,i,s={}){let r=void 0===t?-1:t,a=void 0===i?1:i,o={min_row:r,max_row:this.sum(r,a)};return await this.fetchLedger(e,void 0,a,this.extend(o,s))}async fetchLedger(e,t,i,s={}){let a;void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let o=this.safeString(s,"id"),n=this.safeValue(s,"min_row"),d=this.safeValue(s,"max_row");if(void 0===o){if(void 0===e)throw new r.ArgumentsRequired(this.id+" fetchLedger() requires a currency code argument if no account id specified in params");a=this.currency(e);let t=this.indexBy(this.accounts,"currency"),i=this.safeDict(t,e);if(void 0===i)throw new r.ExchangeError(this.id+" fetchLedger() could not find account id for "+e);o=this.safeString(i,"id")}if(void 0===n&&void 0===d)d=0,n=-1e3;else if(void 0===n||void 0===d)throw new r.ExchangeError(this.id+" fetchLedger() require both params 'max_row' and 'min_row' or neither to be defined");if(void 0!==i&&d-n>i&&(d<=0?n=d-i:n>0&&(d=n+i)),d-n>1e3)throw new r.ExchangeError(this.id+" fetchLedger() requires the params 'max_row' - 'min_row' <= 1000");let h={id:o,min_row:n,max_row:d},c=await this.privateGetAccountsIdTransactions(this.extend(s,h)),l=this.safeList(c,"transactions",[]);return this.parseLedger(l,a,t,i)}parseLedgerComment(e){let t,i=e.split(" "),s=this.safeString(i,0),r=this.safeString(i,2),a=this.safeString(i,3),o=this.safeString({Withdrawal:"fee",Trading:"fee",Payment:"transaction",Sent:"transaction",Deposit:"transaction",Received:"transaction",Released:"released",Reserved:"reserved",Sold:"trade",Bought:"trade",Failure:"failed"},s);return void 0===o&&"fee"===r&&(o="fee"),"reserved"===o&&"order"===a&&(t=this.safeString(i,4)),{type:o,referenceId:t}}parseLedgerEntry(e,t){let i,s,r=this.safeString(e,"row_index"),o=this.safeString(e,"account_id"),n=this.safeInteger(e,"timestamp"),d=this.safeString(e,"currency"),h=this.safeCurrencyCode(d,t),c=this.safeCurrency(d,t),l=this.safeString(e,"available_delta"),u=this.safeString(e,"balance_delta"),f=this.safeString(e,"balance"),p=this.safeString(e,"description"),m=f,g="0.0",v=this.parseLedgerComment(p),y=v.type,b=v.referenceId;return a.Y.stringEquals(u,"0.0")?a.Y.stringLt(l,"0.0")?(s="pending",g=a.Y.stringAbs(l)):a.Y.stringGt(l,"0.0")&&(s="canceled",g=a.Y.stringAbs(l)):(m=a.Y.stringSub(f,u),s="ok",g=a.Y.stringAbs(u)),a.Y.stringGt(u,"0")||a.Y.stringGt(l,"0")?i="in":(a.Y.stringLt(u,"0")||a.Y.stringLt(l,"0"))&&(i="out"),this.safeLedgerEntry({info:e,id:r,direction:i,account:o,referenceId:b,referenceAccount:void 0,type:y,currency:h,amount:this.parseToNumeric(g),timestamp:n,datetime:this.iso8601(n),before:this.parseToNumeric(m),after:this.parseToNumeric(f),status:s,fee:void 0},c)}async createDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={asset:i.id},r=await this.privatePostFundingAddress(this.extend(s,t));return this.parseDepositAddress(r,i)}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={asset:i.id},r=await this.privateGetFundingAddress(this.extend(s,t));return this.parseDepositAddress(r,i)}parseDepositAddress(e,t){let i=this.safeStringUpper(e,"currency");return{info:e,currency:this.safeCurrencyCode(i,t),network:void 0,address:this.safeString(e,"address"),tag:this.safeString(e,"name")}}async fetchDepositWithdrawFee(e,t={}){if(void 0===this.safeString(t,"address"))throw new r.ArgumentsRequired(this.id+' fetchDepositWithdrawFee() requires an "address" parameter - luno quotes the send fee per destination address');await this.loadMarkets();let i=this.currency(e),s={currency:i.id},a=await this.privateGetSendFee(this.extend(s,t)),o=this.depositWithdrawFee(a);return o.withdraw.fee=this.safeNumber(a,"fee"),o.withdraw.percentage=!1,this.assignDefaultDepositWithdrawFees(o,i)}sign(e,t="public",i="GET",s={},a,o){let n,d=this.safeString(this.urls.api,t);if(void 0===d)throw new r.ExchangeError(this.id+" sign() has no API URL for this endpoint");let h=d+"/"+this.version+"/"+this.implodeParams(e,s),c=this.omit(s,this.extractParams(e));return Object.keys(c).length>0&&(h+="?"+this.urlencode(c)),("private"===t||"exchangePrivate"===t)&&(this.checkRequiredCredentials(),n={Authorization:"Basic "+this.stringToBase64(this.apiKey+":"+this.secret)}),{url:h,method:i,body:o,headers:void 0===n?a:n}}handleErrors(e,t,i,s,a,o,n,d,h){if(void 0!==n&&void 0!==this.safeValue(n,"error")){let e=this.id+" "+this.json(n),t=this.safeString(n,"error_code");throw this.throwExactlyMatchedException(this.exceptions.exact,t,e),new r.ExchangeError(e)}}}i.d(t,{A:()=>o})},6981(e,t,i){"use strict";var s=i(4721),r=i(4930),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"mercado",name:"Mercado Bitcoin",countries:["BR"],rateLimit:1e3,version:"v3",has:{CORS:!0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createMarketOrder:!0,createOrder:!0,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrice:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:"emulated",fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!1,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,withdraw:!0},timeframes:{"15m":"15m","1h":"1h","3h":"3h","1d":"1d","1w":"1w","1M":"1M"},urls:{logo:"https://user-images.githubusercontent.com/1294454/27837060-e7c58714-60ea-11e7-9192-f05e86adb83f.jpg",api:{public:"https://www.mercadobitcoin.net/api",private:"https://www.mercadobitcoin.net/tapi",v4Public:"https://www.mercadobitcoin.com.br/v4",v4PublicNet:"https://api.mercadobitcoin.net/api/v4",v4Private:"https://api.mercadobitcoin.net/api/v4"},www:"https://www.mercadobitcoin.com.br",doc:["https://www.mercadobitcoin.com.br/api-doc","https://www.mercadobitcoin.com.br/trade-api"]},api:{public:{get:{coins:{cost:1},"{coin}/orderbook/":{cost:1},"{coin}/ticker/":{cost:1},"{coin}/trades/":{cost:1},"{coin}/trades/{from}/":{cost:1},"{coin}/trades/{from}/{to}":{cost:1},"{coin}/day-summary/{year}/{month}/{day}/":{cost:1}}},private:{post:{cancel_order:{cost:1},get_account_info:{cost:1},get_order:{cost:1},get_withdrawal:{cost:1},list_system_messages:{cost:1},list_orders:{cost:1},list_orderbook:{cost:1},place_buy_order:{cost:1},place_sell_order:{cost:1},place_market_buy_order:{cost:1},place_market_sell_order:{cost:1},withdraw_coin:{cost:1}}},v4Public:{get:{"{coin}/candle/":{cost:1}}},v4PublicNet:{get:{candles:{cost:1}}},v4Private:{post:{accounts:{cost:1},"accounts/{accountId}/{symbol}/transfers/internal":{cost:1},"oauth2/token":{cost:1}},patch:{"accounts/{accountId}/wallet/{symbol}/deposits/{depositId}":{cost:1}}}},fees:{trading:{maker:.003,taker:.007}},options:{limits:{BTC:.001,BCH:.001,ETH:.01,LTC:.01,XRP:.1}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!0,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:void 0,daysBack:1e5,untilDays:1e5,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:{marginMode:!1,limit:500,daysBack:1e5,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:void 0,fetchOHLCV:{limit:1e3}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},precisionMode:4})}async fetchMarkets(e={}){let t=await this.publicGetCoins(e),i=[],s=this.safeDict(this.options,"limits",{}),r=this.toArray(t);for(let e=0;e<r.length;e++){let t=r[e],a=this.safeCurrencyCode(t),o=this.safeCurrencyCode("BRL");if(void 0===a||void 0===o)continue;let n=o+a;i.push({id:n,symbol:a+"/"+o,base:a,quote:o,settle:void 0,baseId:t,quoteId:"BRL",settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:void 0,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber("1e-8"),price:this.parseNumber("1e-5")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(s,t),max:void 0},price:{min:this.parseNumber("1e-5"),max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:t})}return i}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={coin:s.base},a=await this.publicGetCoinOrderbook(this.extend(r,i));return this.parseOrderBook(a,s.symbol)}parseTicker(e,t){let i=this.safeSymbol(void 0,t),s=this.safeTimestamp(e,"date"),r=this.safeString(e,"last");return this.safeTicker({symbol:i,timestamp:s,datetime:this.iso8601(s),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"buy"),bidVolume:void 0,ask:this.safeString(e,"sell"),askVolume:void 0,vwap:void 0,open:void 0,close:r,last:r,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"vol"),quoteVolume:void 0,info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={coin:i.base},r=await this.publicGetCoinTicker(this.extend(s,t)),a=this.safeDict(r,"ticker",{});return this.parseTicker(a,i)}parseTrade(e,t){let i,s=this.safeTimestamp2(e,"date","executed_timestamp"),r=this.safeMarket(void 0,t),a=this.safeString2(e,"tid","operation_id"),o=this.safeString(e,"type"),n=this.safeString(e,"price"),d=this.safeString2(e,"amount","quantity"),h=this.safeString(e,"fee_rate");return void 0!==h&&(i={cost:h,currency:void 0}),this.safeTrade({id:a,info:e,timestamp:s,datetime:this.iso8601(s),symbol:r.symbol,order:void 0,type:void 0,side:o,takerOrMaker:void 0,price:n,amount:d,cost:void 0,fee:i},r)}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={coin:a.base};void 0!==t&&(o.from=this.parseToInt(t/1e3));let n=this.safeInteger(s,"to");return r=void 0!==t&&void 0!==n?await this.publicGetCoinTradesFromTo(this.extend(o,s)):void 0!==t?await this.publicGetCoinTradesFrom(this.extend(o,s)):await this.publicGetCoinTrades(this.extend(o,s)),this.parseTrades(r,a,t,i)}parseBalance(e){let t=this.safeDict(e,"response_data",{}),i=this.safeDict(t,"balance",{}),s={info:e},r=Object.keys(i);for(let e=0;e<r.length;e++){let t=r[e],a=this.safeCurrencyCode(t);if(t in i){let e=this.safeDict(i,t,{}),r=this.account();r.free=this.safeString(e,"available"),r.total=this.safeString(e,"total"),void 0!==a&&(s[a]=r)}}return this.safeBalance(s)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostGetAccountInfo(e);return this.parseBalance(t)}async createOrder(e,t,i,s,r,n={}){let d;void 0===this.markets&&await this.loadMarkets();let h=this.market(e),c={coin_pair:h.id};if("limit"===t)c.limit_price=this.priceToPrecision(h.symbol,r),c.quantity=this.amountToPrecision(h.symbol,s),d="buy"===i?await this.privatePostPlaceBuyOrder(this.extend(c,n)):await this.privatePostPlaceSellOrder(this.extend(c,n));else if("buy"===i){if(void 0===r)throw new a.InvalidOrder(this.id+" createOrder() requires the price argument with market buy orders to calculate total order cost (amount to spend), where cost = amount * price. Supply a price argument to createOrder() call if you want the cost to be calculated for you from price and amount");let e=this.numberToString(s),t=this.numberToString(r),i=this.parseToNumeric(o.Y.stringMul(e,t));c.cost=this.priceToPrecision(h.symbol,i),d=await this.privatePostPlaceMarketBuyOrder(this.extend(c,n))}else c.quantity=this.amountToPrecision(h.symbol,s),d=await this.privatePostPlaceMarketSellOrder(this.extend(c,n));return this.safeOrder({info:d,id:d.response_data.order.order_id.toString()},h)}async cancelOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r={coin_pair:s.id,order_id:e},o=await this.privatePostCancelOrder(this.extend(r,i)),n=this.safeDict(o,"response_data",{}),d=this.safeDict(n,"order",{});return this.parseOrder(d,s)}parseOrderStatus(e){return this.safeString({2:"open",3:"canceled",4:"closed"},e,e)}parseOrder(e,t){let i,s=this.safeString(e,"order_id"),r=this.safeString(e,"order_type");"order_type"in e&&(i="1"===r?"buy":"sell");let a=this.parseOrderStatus(this.safeString(e,"status")),o=this.safeString(e,"coin_pair"),n=this.safeMarket(o,t),d=this.safeTimestamp(e,"created_timestamp"),h={cost:this.safeString(e,"fee"),currency:n.quote},c=this.safeString(e,"limit_price"),l=this.safeString(e,"executed_price_avg"),u=this.safeString(e,"quantity"),f=this.safeString(e,"executed_quantity"),p=this.safeTimestamp(e,"updated_timestamp"),m=this.safeList(e,"operations",[]),g=n.symbol;return this.safeOrder({info:e,id:s,clientOrderId:void 0,timestamp:d,datetime:this.iso8601(d),lastTradeTimestamp:p,symbol:g,type:"limit",timeInForce:void 0,postOnly:void 0,side:i,price:c,triggerPrice:void 0,cost:void 0,average:l,amount:u,filled:f,remaining:void 0,status:a,fee:h,trades:m},n)}async fetchOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r={coin_pair:s.id,order_id:parseInt(e)},o=await this.privatePostGetOrder(this.extend(r,i)),n=this.safeDict(o,"response_data",{}),d=this.safeDict(n,"order");return this.parseOrder(d,s)}async withdraw(e,t,i,s,r={}){let[o,n]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let d=this.currency(e),h={coin:d.id,quantity:t.toFixed(10),address:i};if("BRL"===e){if(!("account_ref"in n))throw new a.ArgumentsRequired(this.id+" withdraw() requires account_ref parameter to withdraw "+e)}else if("LTC"!==e){if(!("tx_fee"in n))throw new a.ArgumentsRequired(this.id+" withdraw() requires tx_fee parameter to withdraw "+e);if("XRP"===e)if(void 0===o){if(!("destination_tag"in n))throw new a.ArgumentsRequired(this.id+" withdraw() requires a tag argument or destination_tag parameter to withdraw "+e)}else h.destination_tag=o}let c=await this.privatePostWithdrawCoin(this.extend(h,n)),l=this.safeDict(c,"response_data",{}),u=this.safeDict(l,"withdrawal");return this.parseTransaction(u,d)}parseTransaction(e,t){let i=this.safeCurrency(void 0,t);return{id:this.safeString(e,"id"),txid:void 0,timestamp:void 0,datetime:void 0,network:void 0,addressFrom:void 0,address:void 0,addressTo:void 0,amount:void 0,type:void 0,currency:i.code,status:void 0,updated:void 0,tagFrom:void 0,tag:void 0,tagTo:void 0,comment:void 0,internal:void 0,fee:void 0,info:e}}parseOHLCV(e,t){return[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]}async fetchOHLCV(e,t="15m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={resolution:this.safeString(this.timeframes,t,t),symbol:a.base+"-"+a.quote},n=void 0===s?100:s;if(void 0!==i)o.from=this.parseToInt(i/1e3),o.to=this.sum(o.from,n*this.parseTimeframe(t));else{let e=this.seconds();o.to=e,o.from=e-n*this.parseTimeframe(t)}let d=await this.v4PublicNetGetCandles(this.extend(o,r));return this.parseTradingViewOHLCV(d,a,t,i,n)}async fetchOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={coin_pair:r.id},n=await this.privatePostListOrders(this.extend(o,s)),d=this.safeDict(n,"response_data",{}),h=this.safeList(d,"orders",[]);return this.parseOrders(h,r,t,i)}async fetchOpenOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOpenOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={coin_pair:r.id,status_list:"[2]"},n=await this.privatePostListOrders(this.extend(o,s)),d=this.safeDict(n,"response_data",{}),h=this.safeList(d,"orders",[]);return this.parseOrders(h,r,t,i)}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={coin_pair:r.id,has_fills:!0},n=await this.privatePostListOrders(this.extend(o,s)),d=this.safeDict(n,"response_data",{}),h=this.safeList(d,"orders",[]),c=this.parseOrders(h,r,t,i),l=this.ordersToTrades(c);return this.filterBySymbolSinceLimit(l,this.safeString(r,"symbol"),t,i)}ordersToTrades(e){let t=[];for(let i=0;i<e.length;i++){let s=this.safeList(e[i],"trades",[]);for(let e=0;e<s.length;e++)t.push(s[e])}return t}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},o,n){let d,h,c=this.safeString(this.urls.api,t);if(void 0===c)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let l=c+"/",u=this.omit(r,this.extractParams(e)),f="public"===t||"v4Public"===t||"v4PublicNet"===t;if(f)l+=this.implodeParams(e,r),Object.keys(u).length>0&&(l+="?"+this.urlencode(u));else{this.checkRequiredCredentials(),l+=this.version+"/";let t=this.incrementingNonce();d=this.urlencode(this.extend({tapi_method:e,tapi_nonce:t},r));let i="/tapi/"+this.version+"/?"+d;h={"Content-Type":"application/x-www-form-urlencoded","TAPI-ID":this.apiKey,"TAPI-MAC":this.hmac(this.encode(i),this.encode(this.secret),s.Zf)}}let p=d;f&&(p=n);let m=h;return f&&(m=o),{url:l,method:i,body:p,headers:m}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0!==n&&void 0!==this.safeValue(n,"error_message"))throw new a.ExchangeError(this.id+" "+this.json(n))}}i.d(t,{A:()=>n})},2641(e,t,i){"use strict";var s=i(4721),r=i(1852),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"mexc",name:"MEXC Global",countries:["SC"],rateLimit:50,version:"v3",certified:!0,pro:!0,has:{CORS:void 0,spot:!0,margin:!0,swap:!0,future:!1,option:!1,addMargin:!0,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!0,closePosition:!1,createDepositAddress:!0,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!0,createMarketSellOrderWithCost:!0,createOrder:!0,createOrders:!0,createPostOnlyOrder:!0,createReduceOnlyOrder:!0,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,createTriggerOrder:!0,deposit:void 0,editOrder:void 0,fetchAccounts:!0,fetchBalance:!0,fetchBidsAsks:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCanceledOrders:!0,fetchClosedOrder:void 0,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:void 0,fetchDepositAddress:!0,fetchDepositAddresses:void 0,fetchDepositAddressesByNetwork:!0,fetchDeposits:!0,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!0,fetchFundingInterval:!0,fetchFundingIntervals:!1,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchIndexOHLCV:!0,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchL2OrderBook:!0,fetchLedger:void 0,fetchLedgerEntry:void 0,fetchLeverage:!0,fetchLeverages:!1,fetchLeverageTiers:!0,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarketLeverageTiers:"emulated",fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenOrder:void 0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:void 0,fetchOrders:!0,fetchOrderTrades:!0,fetchPosition:"emulated",fetchPositionHistory:"emulated",fetchPositionMode:!0,fetchPositions:!0,fetchPositionsHistory:!0,fetchPositionsRisk:void 0,fetchPremiumIndexOHLCV:!1,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!1,fetchTradingLimits:void 0,fetchTransactionFee:"emulated",fetchTransactionFees:!0,fetchTransactions:void 0,fetchTransfer:!0,fetchTransfers:!0,fetchWithdrawal:void 0,fetchWithdrawals:!0,reduceMargin:!0,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!0,setMarginMode:!0,setPositionMode:!0,signIn:void 0,transfer:!0,withdraw:!0},urls:{logo:"https://user-images.githubusercontent.com/1294454/137283979-8b2a818d-8633-461b-bfca-de89e8c446b2.jpg",api:{spot:{public:"https://api.mexc.com",private:"https://api.mexc.com"},spot2:{public:"https://www.mexc.com/open/api/v2",private:"https://www.mexc.com/open/api/v2"},contract:{public:"https://api.mexc.com/api/v1/contract",private:"https://api.mexc.com/api/v1/private"},broker:{private:"https://api.mexc.com/api/v3/broker"}},www:"https://www.mexc.com/",doc:["https://www.mexc.com/api-docs/spot-v3/introduction","https://www.mexc.com/api-docs/futures/integration-guide"],fees:["https://www.mexc.com/fee"],referral:"https://www.mexc.com/register?inviteCode=mexc-1FQ1GNu1"},api:{spot:{public:{get:{announcements:{cost:8},ping:{cost:1},time:{cost:1},defaultSymbols:{cost:1},"symbol/offline":{cost:10},exchangeInfo:{cost:25},depth:{cost:3},trades:{cost:5},historicalTrades:{cost:1},aggTrades:{cost:1},klines:{cost:1},avgPrice:{cost:1},"ticker/24hr":{cost:25},"ticker/price":{cost:10},"ticker/bookTicker":{cost:10},"etf/info":{cost:1}}},private:{get:{"kyc/status":{cost:1},uid:{cost:1},apiKeyInfo:{cost:1},order:{cost:2},openOrders:{cost:3},allOrders:{cost:10},account:{cost:10},myTrades:{cost:10},"strategy/group":{cost:20},"strategy/group/uid":{cost:20},tradeFee:{cost:20},"sub-account/list":{cost:1},"sub-account/apiKey":{cost:1},"sub-account/asset":{cost:1},"capital/config/getall":{cost:10},"capital/deposit/hisrec":{cost:10},"capital/withdraw/history":{cost:1},"capital/withdraw/address":{cost:10},"capital/deposit/address":{cost:10},"capital/transfer":{cost:1},"capital/transfer/tranId":{cost:1},"capital/transfer/internal":{cost:1},"capital/sub-account/universalTransfer":{cost:1},"capital/convert":{cost:1},"capital/convert/list":{cost:1},"margin/loan":{cost:1},"margin/allOrders":{cost:1},"margin/myTrades":{cost:1},"margin/openOrders":{cost:1},"margin/maxTransferable":{cost:1},"margin/priceIndex":{cost:1},"margin/order":{cost:1},"margin/isolated/account":{cost:1},"margin/maxBorrowable":{cost:1},"margin/repay":{cost:1},"margin/isolated/pair":{cost:1},"margin/forceLiquidationRec":{cost:1},"margin/isolatedMarginData":{cost:1},"margin/isolatedMarginTier":{cost:1},"rebate/taxQuery":{cost:1},"rebate/detail":{cost:1},"rebate/detail/kickback":{cost:1},"rebate/referCode":{cost:1},"rebate/affiliate/commission":{cost:1},"rebate/affiliate/withdraw":{cost:1},"rebate/affiliate/commission/detail":{cost:1},"rebate/affiliate/campaign":{cost:1},"rebate/affiliate/referral":{cost:1},"rebate/affiliate/subaffiliates":{cost:1},"rebate/affiliate/list":{cost:1},"mxDeduct/enable":{cost:1},userDataStream:{cost:1},selfSymbols:{cost:1},"asset/internal/transfer/record":{cost:10}},post:{order:{cost:1},"order/test":{cost:1},apiKeyInfo:{cost:1},"sub-account/virtualSubAccount":{cost:1},"sub-account/apiKey":{cost:1},"sub-account/futures":{cost:1},"sub-account/margin":{cost:1},batchOrders:{cost:10},"strategy/group":{cost:20},"strategy/group/uid":{cost:20},"capital/withdraw/apply":{cost:1},"capital/withdraw":{cost:1},"capital/transfer":{cost:50},"capital/transfer/internal":{cost:1},"capital/deposit/address":{cost:1},"capital/sub-account/universalTransfer":{cost:1},"capital/convert":{cost:10},"mxDeduct/enable":{cost:1},userDataStream:{cost:1}},put:{userDataStream:{cost:1}},delete:{order:{cost:1},openOrders:{cost:1},"order/all":{cost:1},"sub-account/apiKey":{cost:1},"strategy/group":{cost:1},"strategy/group/uid":{cost:1},"margin/order":{cost:1},"margin/openOrders":{cost:1},userDataStream:{cost:1},"capital/withdraw":{cost:1}}}},contract:{public:{get:{ping:{cost:2},detail:{cost:100},support_currencies:{cost:2},"depth/{symbol}":{cost:2},"depth_commits/{symbol}/{limit}":{cost:2},"index_price/{symbol}":{cost:2},"fair_price/{symbol}":{cost:2},"funding_rate/{symbol}":{cost:2},"kline/{symbol}":{cost:2},"kline/index_price/{symbol}":{cost:2},"kline/fair_price/{symbol}":{cost:2},"deals/{symbol}":{cost:2},ticker:{cost:2},risk_reverse:{cost:2},"risk_reverse/history":{cost:2},"funding_rate/history":{cost:2}}},private:{get:{"account/assets":{cost:2},"account/asset/{currency}":{cost:2},"account/transfer_record":{cost:2},"account/profit_rate/{type}":{cost:2},"account/asset/analysis/{type}":{cost:2},"account/feeDeductConfigs":{cost:2},"account/asset/analysis/yesterday_pnl":{cost:2},"account/asset/analysis/today_pnl":{cost:2},"account/config/contractFeeDiscountConfig":{cost:2},"order/fee_details":{cost:2},"account/discountType":{cost:2},"account/asset/analysis/export":{cost:2},"account/asset_book/order_deal_fee/total":{cost:2},"account/contract/fee_rate":{cost:2},"account/contract/zero_fee_rate":{cost:2},"position/list/history_positions":{cost:2},"position/open_positions":{cost:2},"position/funding_records":{cost:2},"position/position_mode":{cost:2},"order/list/open_orders/{symbol}":{cost:2},"order/list/open_orders":{cost:2},"order/list/history_orders":{cost:2},"order/list/order_deals/v3":{cost:2},"order/external/{symbol}/{external_oid}":{cost:2},"order/get/{order_id}":{cost:2},"order/batch_query":{cost:8},"order/deal_details/{order_id}":{cost:2},"order/list/order_deals":{cost:2},"order/list/close_orders":{cost:2},"planorder/list/orders":{cost:2},"stoporder/list/orders":{cost:2},"stoporder/open_orders":{cost:2},"stoporder/order_details/{stop_order_id}":{cost:2},"account/risk_limit":{cost:2},"account/tiered_fee_rate":{cost:2},"position/leverage":{cost:2},"account/tiered_fee_rate/v2":{cost:2},"trackorder/list/orders":{cost:2},"market_maker/self_trade/blacklist":{cost:2},"market_maker/self_trade/blacklist/search":{cost:2}},post:{"account/asset/analysis/v3":{cost:2},"account/asset/analysis/calendar/daily/v3":{cost:2},"account/asset/analysis/calendar/monthly/v3":{cost:2},"account/asset/analysis/recent/v3":{cost:2},"position/change_margin":{cost:2},"position/change_auto_add_im":{cost:2},"position/change_leverage":{cost:2},"position/change_position_mode":{cost:2},"position/reverse":{cost:2},"position/close_all":{cost:10},"order/create":{cost:2},"order/submit":{cost:2},"order/submit_batch":{cost:40},"order/chase_limit_order":{cost:40},"order/change_limit_order":{cost:40},"order/cancel":{cost:2},"order/batch_cancel_with_external":{cost:2},"order/cancel_with_external":{cost:2},"order/cancel_all":{cost:2},"order/open_order_total_count":{cost:2},"order/batch_query_with_external":{cost:2},"account/change_risk_level":{cost:2},"planorder/place":{cost:2},"planorder/place/v2":{cost:2},"planorder/cancel":{cost:2},"planorder/cancel_all":{cost:2},"planorder/change_stop_order":{cost:2},"stoporder/place":{cost:2},"stoporder/cancel":{cost:2},"stoporder/cancel_all":{cost:2},"stoporder/change_price":{cost:2},"stoporder/change_plan_price":{cost:2},"trackorder/place":{cost:2},"trackorder/cancel":{cost:2},"trackorder/change_order":{cost:2},"market_maker/self_trade/blacklist/create":{cost:2},"market_maker/self_trade/blacklist/update":{cost:2},"market_maker/self_trade/blacklist/delete":{cost:2}}}},spot2:{public:{get:{"market/symbols":{cost:1},"market/coin/list":{cost:2},"common/timestamp":{cost:1},"common/ping":{cost:2},"market/ticker":{cost:1},"market/depth":{cost:1},"market/deals":{cost:1},"market/kline":{cost:1},"market/api_default_symbols":{cost:2}}},private:{get:{"account/info":{cost:1},"order/open_orders":{cost:1},"order/list":{cost:1},"order/query":{cost:1},"order/deals":{cost:1},"order/deal_detail":{cost:1},"asset/deposit/address/list":{cost:2},"asset/deposit/list":{cost:2},"asset/address/list":{cost:2},"asset/withdraw/list":{cost:2},"asset/internal/transfer/record":{cost:10},"account/balance":{cost:10},"asset/internal/transfer/info":{cost:10},"market/api_symbols":{cost:2}},post:{"order/place":{cost:1},"order/place_batch":{cost:1},"order/advanced/place_batch":{cost:1},"asset/withdraw":{cost:2},"asset/internal/transfer":{cost:10}},delete:{"order/cancel":{cost:1},"order/cancel_by_symbol":{cost:1},"asset/withdraw":{cost:2}}}},broker:{private:{get:{"sub-account/universalTransfer":{cost:1},"sub-account/list":{cost:1},"sub-account/status":{cost:1},"sub-account/apiKey":{cost:1},"capital/deposit/subAddress":{cost:1},"capital/deposit/subHisrec":{cost:1},"capital/deposit/subHisrec/getall":{cost:1},"rebate/taxQuery":{cost:1}},post:{"sub-account/virtualSubAccount":{cost:1},"sub-account/apiKey":{cost:1},"capital/deposit/subAddress":{cost:1},"capital/withdraw/apply":{cost:1},"sub-account/universalTransfer":{cost:1},"sub-account/futures":{cost:1}},delete:{"sub-account/apiKey":{cost:1}}}}},precisionMode:4,timeframes:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","4h":"4h","8h":"8h","1d":"1d","1w":"1w","1M":"1M"},fees:{trading:{tierBased:!1,percentage:!0,maker:this.parseNumber("0.00"),taker:this.parseNumber("0.0005")}},options:{adjustForTimeDifference:!1,timeDifference:0,fetchMarkets:{types:{spot:!0,swap:{linear:!0,inverse:!1}}},useCcxtTradeId:!0,timeframes:{spot:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"60m","4h":"4h","1d":"1d","1w":"1W","1M":"1M"},swap:{"1m":"Min1","5m":"Min5","15m":"Min15","30m":"Min30","1h":"Min60","4h":"Hour4","8h":"Hour8","1d":"Day1","1w":"Week1","1M":"Month1"}},defaultType:"spot",defaultNetwork:"ETH",defaultNetworks:{ETH:"ETH",USDT:"ERC20",USDC:"ERC20",BTC:"BTC",LTC:"LTC"},networks:{ZKSYNC:"ZKSYNCERA",TRC20:"TRX",TON:"TONCOIN",ARBITRUM:"ARB",STX:"STACKS",LUNC:"LUNA",STARK:"STARKNET",APT:"APTOS",PEAQ:"PEAQEVM",AVAXC:"AVAX_CCHAIN",ERC20:"ETH",ACA:"ACALA",BEP20:"BSC",OPTIMISM:"OP",ASTR:"ASTAR",BTM:"BTM2",CRC20:"CRONOS",DOT:"DOTASSETHUB",ETHF:"ETF",HRC20:"HECO",OASIS:"ROSE",OKC:"OKT",RSK:"RBTC"},networksById:{"BNB Smart Chain(BEP20-RACAV1)":"BSC","BNB Smart Chain(BEP20-RACAV2)":"BSC","BNB Smart Chain(BEP20)":"BSC","Ethereum(ERC20)":"ERC20"},recvWindow:5e3,maxTimeTillEnd:0x1cf7c57ff,broker:"CCXT"},features:{default:{sandbox:!1,createOrder:{marginMode:!0,triggerPrice:!1,triggerDirection:!1,triggerPriceType:{last:!1,mark:!1,index:!1},stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!0,trailing:!1,leverage:!0,marketBuyByCost:!0,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:{max:20},fetchMyTrades:{marginMode:!1,limit:100,daysBack:30,untilDays:void 0,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!0,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:{marginMode:!0,limit:1e3,daysBack:7,untilDays:7,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:{marginMode:!0,limit:1e3,daysBack:7,daysBackCanceled:7,untilDays:7,trigger:!1,trailing:!1,symbolRequired:!0},fetchOHLCV:{limit:1e3}},spot:{extends:"default",fetchCurrencies:{private:!0}},forDerivs:{extends:"default",createOrder:{triggerPrice:!0,triggerPriceType:{last:!0,mark:!0,index:!0},triggerDirection:!0,stopLossPrice:!1,takeProfitPrice:!1,hedged:!0,leverage:!0,marketBuyByCost:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:90,untilDays:90},fetchOrder:{marginMode:!1},fetchOpenOrders:{marginMode:!1,limit:100,trigger:!0,trailing:!1},fetchOrders:{marginMode:!1,limit:100,daysBack:90,untilDays:90,trigger:!0,trailing:!1},fetchClosedOrders:{marginMode:!1,limit:100,daysBack:90,daysBackCanceled:void 0,untilDays:90,trigger:!0,trailing:!1},fetchOHLCV:{limit:2e3}},swap:{linear:{extends:"forDerivs"},inverse:{extends:"forDerivs"}},future:{linear:void 0,inverse:void 0}},commonCurrencies:{BEYONDPROTOCOL:"BEYOND",BIFI:"BIFIF",BYN:"BEYONDFI",COFI:"COFIX",DFI:"DFISTARTER",DFT:"DFUTURE",DRK:"DRK",EGC:"EGORASCREDIT",FLUX1:"FLUX",FLUX:"FLUX1",FREE:"FREEROSSDAO",GAS:"GASDAO",GASNEO:"GAS",GMT:"GMTTOKEN",STEPN:"GMT",HERO:"STEPHERO",MIMO:"MIMOSA",PROS:"PROSFINANCE",SIN:"SINCITYTOKEN",SOUL:"SOULSWAP",XBT:"XBT"},exceptions:{exact:{"-1128":a.BadRequest,"-2011":a.BadRequest,"-1121":a.BadSymbol,401:a.AuthenticationError,402:a.AuthenticationError,403:a.PermissionDenied,406:a.PermissionDenied,429:a.RateLimitExceeded,500:a.ExchangeError,501:a.ExchangeNotAvailable,503:a.ExchangeNotAvailable,504:a.RequestTimeout,510:a.RateLimitExceeded,511:a.PermissionDenied,513:a.BadRequest,601:a.BadRequest,603:a.BadRequest,604:a.OnMaintenance,701:a.PermissionDenied,702:a.PermissionDenied,703:a.PermissionDenied,704:a.PermissionDenied,801:a.OnMaintenance,1e3:a.AuthenticationError,1001:a.BadSymbol,10101:a.InsufficientFunds,2009:a.InvalidOrder,2011:a.BadRequest,30004:a.InsufficientFunds,33333:a.BadRequest,44444:a.BadRequest,1002:a.InvalidOrder,30019:a.BadRequest,30005:a.InvalidOrder,2003:a.InvalidOrder,2005:a.InsufficientFunds,400:a.BadRequest,600:a.BadRequest,70011:a.PermissionDenied,88004:a.InsufficientFunds,88009:a.ExchangeError,88013:a.InvalidOrder,88015:a.InsufficientFunds,700003:a.InvalidNonce,26:a.ExchangeError,602:a.AuthenticationError,10001:a.AuthenticationError,10007:a.BadSymbol,10015:a.BadRequest,10072:a.BadRequest,10073:a.BadRequest,10095:a.InvalidOrder,10096:a.InvalidOrder,10097:a.InvalidOrder,10098:a.InvalidOrder,10099:a.BadRequest,10100:a.BadRequest,10102:a.InvalidOrder,10103:a.ExchangeError,10200:a.BadRequest,10201:a.BadRequest,10202:a.BadRequest,10206:a.BadRequest,10211:a.BadRequest,10212:a.BadRequest,10216:a.ExchangeError,10219:a.ExchangeError,10222:a.BadRequest,10232:a.BadRequest,10259:a.ExchangeError,10265:a.ExchangeError,10268:a.BadRequest,11444:a.OnMaintenance,20001:a.ExchangeError,20002:a.ExchangeError,22222:a.BadRequest,3e4:a.ExchangeError,30001:a.InvalidOrder,30002:a.InvalidOrder,30003:a.InvalidOrder,30010:a.InvalidOrder,30014:a.InvalidOrder,30016:a.InvalidOrder,30018:a.AccountSuspended,30020:a.AuthenticationError,30021:a.BadRequest,30025:a.InvalidOrder,30026:a.BadRequest,30027:a.InvalidOrder,30028:a.InvalidOrder,30029:a.InvalidOrder,30032:a.InvalidOrder,30041:a.InvalidOrder,30087:a.InvalidOrder,60005:a.ExchangeError,700001:a.AuthenticationError,700002:a.AuthenticationError,700004:a.BadRequest,700005:a.InvalidNonce,700006:a.BadRequest,700007:a.AuthenticationError,700008:a.BadRequest,700013:a.AuthenticationError,730001:a.BadRequest,730002:a.BadRequest,73e4:a.ExchangeError,730003:a.ExchangeError,730100:a.ExchangeError,730600:a.BadRequest,730601:a.BadRequest,730602:a.BadRequest,730700:a.BadRequest,730701:a.BadRequest,730702:a.BadRequest,730703:a.BadRequest,730704:a.BadRequest,730705:a.BadRequest,730706:a.BadRequest,730707:a.BadRequest,730101:a.BadRequest,140001:a.BadRequest,140002:a.AuthenticationError},broad:{"Order quantity error, please try to modify.":a.BadRequest,"Combination of optional parameters invalid":a.BadRequest,"api market order is disabled":a.BadRequest,"Contract not allow place order!":a.InvalidOrder,Oversold:a.InsufficientFunds,"Insufficient position":a.InsufficientFunds,"Insufficient balance!":a.InsufficientFunds,"Bid price is great than max allow price":a.InvalidOrder,"Invalid symbol.":a.BadSymbol,"Param error!":a.BadRequest,maintenance:a.OnMaintenance}}})}async fetchStatus(e={}){let t,i,[s,r]=this.handleMarketTypeAndParams("fetchStatus",void 0,e),a={};return"spot"===s?t=Object.keys(a=await this.spotPublicGetPing(r)).length>0?this.json(a):"ok":"swap"===s&&(a=await this.contractPublicGetPing(r),t=this.safeBool(a,"success",!1)?"ok":this.json(a),i=this.safeInteger(a,"data")),{status:t,updated:i,url:void 0,eta:void 0,info:a}}async fetchTime(e={}){let t,[i,s]=this.handleMarketTypeAndParams("fetchTime",void 0,e);return"spot"===i?(t=await this.spotPublicGetTime(s),this.safeInteger(t,"serverTime")):"swap"===i?(t=await this.contractPublicGetPing(s),this.safeInteger(t,"data")):void 0}async fetchCurrencies(e={}){if(!this.checkRequiredCredentials(!1))return{};let t=await this.spotPrivateGetCapitalConfigGetall(e);return this.parseCurrencies(t)}parseCurrency(e){let t=this.safeString(e,"coin"),i=this.safeCurrencyCode(t),s={},r=this.safeList(e,"networkList",[]);for(let e=0;e<r.length;e++){let t=r[e],a=this.safeString2(t,"netWork","network"),o=this.networkIdToCode(a,i);void 0!==o&&(s[o]={info:t,id:a,network:o,active:void 0,deposit:this.safeBool(t,"depositEnable",!1),withdraw:this.safeBool(t,"withdrawEnable",!1),fee:this.safeNumber(t,"withdrawFee"),precision:void 0,limits:{withdraw:{min:this.safeString(t,"withdrawMin"),max:this.safeString(t,"withdrawMax")}},contract:this.safeString(t,"contract")})}return this.safeCurrencyStructure({info:e,id:t,code:i,name:this.safeString(e,"name"),active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,precision:void 0,limits:{amount:{min:void 0,max:void 0}},type:"crypto",networks:s})}async fetchMarkets(e={}){this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference();let t=this.fetchSpotMarkets(e),i=this.fetchSwapMarkets(e),[s,r]=await Promise.all([t,i]);return this.arrayConcat(s,r)}async fetchSpotMarkets(e={}){let t=await this.spotPublicGetExchangeInfo(e),i=this.safeList(t,"symbols",[]),s=[];for(let e=0;e<i.length;e++){let t=i[e],r=this.safeString(t,"symbol"),a=this.safeString(t,"baseAsset"),o=this.safeString(t,"quoteAsset"),n=this.safeCurrencyCode(a),d=this.safeCurrencyCode(o);if(void 0===n||void 0===d)continue;let h=this.safeString(t,"status"),c=this.safeBool(t,"isSpotTradingAllowed"),l=!1;"1"===h&&!0===c&&(l=!0);let u=this.safeBool(t,"isMarginTradingAllowed"),f=this.safeNumber(t,"makerCommission"),p=this.safeNumber(t,"takerCommission"),m=this.safeNumber(t,"maxQuoteAmount");s.push({id:r,symbol:n+"/"+d,base:n,quote:d,settle:void 0,baseId:a,quoteId:o,settleId:void 0,type:"spot",spot:!0,margin:u,swap:!1,future:!1,option:!1,active:l,contract:!1,linear:void 0,inverse:void 0,taker:p,maker:f,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(t,"baseAssetPrecision"))),price:this.parseNumber(this.parsePrecision(this.safeString(t,"quoteAssetPrecision")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(t,"baseSizePrecision"),max:void 0},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(t,"quoteAmountPrecision"),max:m}},created:void 0,info:t})}return s}async fetchSwapMarkets(e={}){let t=this.rateLimit;this.setProperty(this,"rateLimit",10);let i=await this.contractPublicGetDetail(e);this.setProperty(this,"rateLimit",t);let s=this.safeList(i,"data",[]),r=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.safeString(t,"symbol"),a=this.safeString(t,"baseCoin"),o=this.safeString(t,"quoteCoin"),n=this.safeString(t,"settleCoin"),d=this.safeCurrencyCode(a),h=this.safeCurrencyCode(o);if(void 0===d||void 0===h)continue;let c=this.safeCurrencyCode(n),l=this.safeString(t,"state"),u=h===c;r.push({id:i,symbol:d+"/"+h+":"+c,base:d,quote:h,settle:c,baseId:a,quoteId:o,settleId:n,type:"swap",spot:!1,margin:!1,swap:!0,future:!1,option:!1,active:"0"===l,contract:!0,linear:u,inverse:!u,taker:this.safeNumber(t,"takerFeeRate"),maker:this.safeNumber(t,"makerFeeRate"),contractSize:this.safeNumber(t,"contractSize"),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(t,"volUnit"),price:this.safeNumber(t,"priceUnit")},limits:{leverage:{min:this.safeNumber(t,"minLeverage"),max:this.safeNumber(t,"maxLeverage")},amount:{min:this.safeNumber(t,"minVol"),max:this.safeNumber(t,"maxVol")},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:t})}return r}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};if(void 0!==t&&(r.limit=t),!0===s.spot){let t=await this.spotPublicGetDepth(this.extend(r,i)),s=this.safeInteger(t,"timestamp"),a=this.parseOrderBook(t,e,s);return a.nonce=this.safeInteger(t,"lastUpdateId"),a}if(!0===s.swap){let t=await this.contractPublicGetDepthSymbol(this.extend(r,i)),s=this.safeDict(t,"data"),a=this.safeInteger(s,"timestamp"),o=this.parseOrderBook(s,e,a);return o.nonce=this.safeInteger(s,"version"),o}throw new a.NotSupported(this.id+" fetchOrderBook() does not support "+s.type+" markets")}parseOrderBookBidAsk(e,t=0,i=1,s=2){let r=this.safeNumber(e,t),a=this.safeNumber(e,i),o=this.safeNumber(e,2);return void 0!==o?[r,a,o]:[r,a]}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={symbol:r.id};void 0!==i&&(o.limit=i);let n=[];if(!0===r.spot){let e=this.safeInteger2(s,"endTime","until");if(void 0!==t&&(o.startTime=t,void 0===e))throw new a.ArgumentsRequired(this.id+" fetchTrades() requires an until parameter when since is provided");if(void 0!==e){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchTrades() requires a since parameter when until is provided");o.endTime=e}let i=this.safeString(this.options,"fetchTradesMethod","spotPublicGetAggTrades");i=this.safeString(s,"method",i);let r=this.omit(s,["method"]);if("spotPublicGetAggTrades"===i)n=await this.spotPublicGetAggTrades(this.extend(o,r));else if("spotPublicGetHistoricalTrades"===i)n=await this.spotPublicGetHistoricalTrades(this.extend(o,r));else if("spotPublicGetTrades"===i)n=await this.spotPublicGetTrades(this.extend(o,r));else throw new a.NotSupported(this.id+" fetchTrades() not support this method")}else if(!0===r.swap){let e=await this.contractPublicGetDealsSymbol(this.extend(o,s));n=this.safeList(e,"data",[])}return this.parseTrades(n,r,t,i)}parseTrade(e,t){let i,s,r,a,o,n,d,h,c,l,u;if("v"in e)s=this.safeInteger(e,"t"),a=(u=this.safeMarket(void 0,t)).symbol,h=this.safeString(e,"p"),c=this.safeString(e,"v"),n=this.parseOrderSide(this.safeString(e,"T")),d="taker";else{let f=this.safeString(e,"symbol");if(a=(u=this.safeMarket(f,t)).symbol,i=this.safeString2(e,"id","a"),h=this.safeString2(e,"price","p"),r=this.safeString(e,"orderId"),"positionMode"in e)s=this.safeInteger(e,"timestamp"),c=this.safeString(e,"vol"),n=this.parseOrderSide(this.safeString(e,"side")),o={cost:this.safeString(e,"fee"),currency:this.safeCurrencyCode(this.safeString(e,"feeCurrency"))},d=this.safeBool2(e,"isTaker","taker",!1)?"taker":"maker";else{s=this.safeInteger2(e,"time","T"),c=this.safeString2(e,"qty","q"),l=this.safeString(e,"quoteQty");let t=this.safeBool(e,"isBuyer"),i=this.safeBool(e,"isMaker"),r=this.safeBool2(e,"isBuyerMaker","m");void 0!==i&&(d=!0===i?"maker":"taker"),void 0!==t&&(n=!0===t?"buy":"sell"),void 0!==r&&(n=!0===r?"sell":"buy",d="taker");let a=this.safeString(e,"commissionAsset");void 0!==a&&(o={cost:this.safeString(e,"commission"),currency:this.safeCurrencyCode(a)})}}return void 0===i&&this.safeBool(this.options,"useCcxtTradeId",!0)&&(i=this.createCcxtTradeId(s,n,c,h,d)),this.safeTrade({id:i,order:r,timestamp:s,datetime:this.iso8601(s),symbol:a,type:void 0,side:n,takerOrMaker:d,price:h,amount:c,cost:l,fee:o,info:e},u)}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=!0===o.spot?500:2e3,[d,h]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(d)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,h,n);let c=this.safeDict(this.options,"timeframes",{}),l=this.safeDict(c,o.type,{}),u=this.safeString(l,t),f=1e3*this.parseTimeframe(t),p={symbol:o.id,interval:u},m=[],g=this.safeInteger2(h,"until","endTime"),v=void 0!==g&&void 0===i,y=h;v&&(y=this.omit(h,["until"]));let b=i;if(v&&(b=g-(null!=s&&0!==s?s:n)*f),!0===o.spot){void 0!==b&&(p.startTime=b,void 0===g)&&(p.endTime=Math.min(this.sum(i,n*f),this.milliseconds())),void 0!==s&&(p.limit=s),void 0!==g&&(p.endTime=g+1);let e=await this.spotPublicGetKlines(this.extend(p,y));m=this.toArray(e)}else if(!0===o.swap){let e;void 0!==i&&(p.start=this.parseToInt(i/1e3)),void 0!==g&&(p.end=this.parseToInt(g/1e3),void 0===i&&(p.start=this.parseToInt(b/1e3)));let t=this.safeString(y,"price","default"),s=this.omit(y,"price");if("default"===t)e=await this.contractPublicGetKlineSymbol(this.extend(p,s));else if("index"===t)e=await this.contractPublicGetKlineIndexPriceSymbol(this.extend(p,s));else if("mark"===t)e=await this.contractPublicGetKlineFairPriceSymbol(this.extend(p,s));else throw new a.NotSupported(this.id+" fetchOHLCV() not support this price type, [default, index, mark]");let r=this.safeDict(e,"data");m=this.convertTradingViewToOHLCV(r,"time","open","high","low","close","vol")}return this.parseOHLCVs(m,o,t,i,s)}parseOHLCV(e,t){return[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]}async fetchTickers(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r={},a=!1;if(void 0!==e){a=1===e.length;let t=this.safeString(e,0);i=this.market(t)}let[o,n]=this.handleMarketTypeAndParams("fetchTickers",i,t);if(a&&(r.symbol=this.safeString(i,"id")),"spot"===o)s=await this.spotPublicGetTicker24hr(this.extend(r,n));else if("swap"===o){let e=await this.contractPublicGetTicker(this.extend(r,n));s=this.safeList(e,"data",[])}return a&&(s=[s]),this.parseTickers(s,e)}async fetchTicker(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),[r,a]=this.handleMarketTypeAndParams("fetchTicker",s,t),o={symbol:s.id};if("spot"===r)i=await this.spotPublicGetTicker24hr(this.extend(o,a));else if("swap"===r){let e=await this.contractPublicGetTicker(this.extend(o,a));i=this.safeDict(e,"data",{})}return this.parseTicker(i,s)}parseTicker(e,t){let i,s,r,a,n,d,h,c,l,u,f,p,m,g=this.safeString(e,"symbol"),v=this.safeMarket(g,t);return!0===this.safeBool(v,"swap")||"timestamp"in e?(i=this.safeInteger(e,"timestamp"),s=this.safeString(e,"bid1"),r=this.safeString(e,"ask1"),d=this.safeString(e,"volume24"),h=this.safeString(e,"amount24"),l=this.safeString(e,"high24Price"),u=this.safeString(e,"lower24Price"),p=this.safeString(e,"riseFallValue"),f=this.safeString(e,"riseFallRate")):(i=this.safeInteger(e,"closeTime"),s=this.safeString(e,"bidPrice"),r=this.safeString(e,"askPrice"),a=this.safeString(e,"bidQty"),n=this.safeString(e,"askQty"),o.Y.stringEq(a,"0")&&(a=void 0),o.Y.stringEq(n,"0")&&(n=void 0),d=this.safeString(e,"volume"),h=this.safeString(e,"quoteVolume"),c=this.safeString(e,"openPrice"),l=this.safeString(e,"highPrice"),u=this.safeString(e,"lowPrice"),m=this.safeString(e,"prevClosePrice"),p=this.safeString(e,"priceChange"),f=this.safeString(e,"priceChangePercent")),f=o.Y.stringMul(f,"100"),this.safeTicker({symbol:v.symbol,timestamp:i,datetime:this.iso8601(i),open:c,high:l,low:u,close:this.safeString(e,"lastPrice"),bid:s,bidVolume:a,ask:r,askVolume:n,vwap:void 0,previousClose:m,change:p,percentage:f,average:void 0,baseVolume:d,quoteVolume:h,info:e},v)}async fetchBidsAsks(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=!1;void 0!==e&&(r=1===e.length,i=this.market(e[0]));let[o,n]=this.handleMarketTypeAndParams("fetchBidsAsks",i,t);if("spot"===o)s=await this.spotPublicGetTickerBookTicker(n);else if("swap"===o)throw new a.NotSupported(this.id+" fetchBidsAsks() is not available for "+o+" markets");return r&&(s=[s]),this.parseTickers(s,e)}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new a.NotSupported(this.id+" createMarketBuyOrderWithCost() supports spot orders only");return await this.createOrder(e,"market","buy",0,void 0,this.extend({cost:t},i))}async createMarketSellOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new a.NotSupported(this.id+" createMarketBuyOrderWithCost() supports spot orders only");return await this.createOrder(e,"market","sell",0,void 0,this.extend({cost:t},i))}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),[n,d]=this.handleMarginModeAndParams("createOrder",a);return!0===o.spot?await this.createSpotOrder(o,t,i,s,r,n,d):await this.createSwapOrder(o,t,i,s,r,n,d)}createSpotOrderRequest(e,t,i,s,r,n,d={}){let h=e.symbol;if(void 0===t||void 0===i)throw new a.ArgumentsRequired(this.id+" createOrder() requires a type and a side argument");let c=i.toUpperCase(),l={symbol:e.id,side:c,type:t.toUpperCase()};if("market"===t){let e=this.safeNumber2(d,"cost","quoteOrderQty");if(void 0!==e)l.quoteOrderQty=this.costToPrecision(h,e);else if(void 0===r)l.quantity=this.amountToPrecision(h,s);else{let e=this.numberToString(s),t=this.numberToString(r),i=o.Y.stringMul(e,t);l.quoteOrderQty=this.costToPrecision(h,i)}}else l.quantity=this.amountToPrecision(h,s);void 0!==r&&(l.price=this.priceToPrecision(h,r));let u="market"===t?this.omit(d,"cost"):d,f=this.safeString(u,"clientOrderId");void 0!==f&&(l.newClientOrderId=f);let p=void 0!==f?this.omit(u,["type","clientOrderId"]):u;if(void 0!==n&&"isolated"!==n)throw new a.BadRequest(this.id+" createOrder() does not support marginMode "+n+" for spot-margin trading");let[m,g]=this.handlePostOnly("market"===t,"LIMIT_MAKER"===t,p);!0===m&&(l.type="LIMIT_MAKER");let v=this.safeString(g,"timeInForce"),y=void 0!==v?this.omit(g,"timeInForce"):g;return void 0!==v&&("IOC"===v?l.type="IMMEDIATE_OR_CANCEL":"FOK"===v&&(l.type="FILL_OR_KILL")),this.extend(l,y)}async createSpotOrder(e,t,i,s,r,a,o={}){let n;void 0===this.markets&&await this.loadMarkets();let d=this.safeBool(o,"test",!1),h=this.omit(o,"test"),c=this.createSpotOrderRequest(e,t,i,s,r,a,h);n=!0===d?await this.spotPrivatePostOrderTest(c):await this.spotPrivatePostOrder(c);let l=this.parseOrder(n,e);return l.side=i,l.type=t,void 0===this.safeString(l,"price")&&(l.price=r),void 0===this.safeString(l,"amount")&&(l.amount=s),l}async createSwapOrder(e,t,i,s,r,o,n={}){let d,h,c,l;void 0===this.markets&&await this.loadMarkets();let u=e.symbol;if(void 0!==o)if("cross"===o)h=2;else if("isolated"===o)h=1;else throw new a.ArgumentsRequired(this.id+' createSwapOrder() marginMode parameter should be either "cross" or "isolated"');else h=this.safeInteger(n,"openType",2);if("limit"!==t&&"market"!==t&&1!==t&&2!==t&&3!==t&&4!==t&&5!==t&&6!==t)throw new a.InvalidOrder(this.id+" createSwapOrder() order type must either limit, market, or 1 for limit orders, 2 for post-only orders, 3 for IOC orders, 4 for FOK orders, 5 for market orders or 6 to convert market price to current price");let[f,p]=this.handlePostOnly("market"===t,2===t,n);c=!0===f?2:"limit"===t?1:"market"===t?6:t;let m=this.amountToPrecision(u,s);void 0===m&&(m="0");let g={symbol:e.id,vol:parseFloat(m),type:c,openType:h};if(5!==c&&6!==c&&"market"!==c){let e=this.priceToPrecision(u,r);void 0===e&&(e="0"),g.price=parseFloat(e)}if(1===h&&void 0===this.safeInteger(p,"leverage"))throw new a.ArgumentsRequired(this.id+" createSwapOrder() requires a leverage parameter for isolated margin orders");let v=this.safeBool(p,"reduceOnly",!1);!0===this.safeBool(p,"hedged",!1)?(l=!0===v?"buy"===i?4:2:"buy"===i?1:3,g.positionMode=1):l=!0===v?"buy"===i?2:4:"buy"===i?1:3,g.side=l;let y=!0===v?this.omit(p,"reduceOnly"):p,b=this.safeString2(y,"clientOrderId","externalOid");void 0!==b&&(g.externalOid=b);let w=this.safeNumber2(y,"triggerPrice","stopPrice"),k=this.omit(y,["clientOrderId","externalOid","postOnly","stopPrice","triggerPrice","hedged"]);void 0!==w&&0!==w?(g.triggerPrice=this.priceToPrecision(u,w),g.triggerType=this.safeInteger(k,"triggerType",1),g.executeCycle=this.safeInteger(k,"executeCycle",1),g.trend=this.safeInteger(k,"trend",1),g.orderType=this.safeInteger(k,"orderType",1),d=await this.contractPrivatePostPlanorderPlace(this.extend(g,k))):d=await this.contractPrivatePostOrderCreate(this.extend(g,k));let S=this.safeDict(d,"data");return this.safeOrder({id:this.safeString(S,"orderId"),timestamp:this.safeInteger(S,"ts")},e)}async createOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=[],r=t;for(let t=0;t<e.length;t++){let o,n=this.safeDict(e,t),d=this.safeString(n,"symbol"),h=this.market(d);if(!0!==h.spot)throw new a.NotSupported(this.id+" createOrders() is only supported for spot markets");if(void 0===i)i=d;else if(i!==d)throw new a.BadRequest(this.id+" createOrders() requires all orders to have the same symbol");let c=this.safeString(n,"type"),l=this.safeString(n,"side"),u=this.safeValue(n,"amount"),f=this.safeValue(n,"price"),p=this.safeDict(n,"params",{});[o,r]=this.handleMarginModeAndParams("createOrder",r);let m=this.createSpotOrderRequest(h,c,l,u,f,o,p);s.push(m)}let o={batchOrders:this.json(s)},n=await this.spotPrivatePostBatchOrders(o);return this.parseOrders(n)}async fetchOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r={symbol:s.id},o={};if(!0===s.spot){let t=this.safeString(i,"clientOrderId");void 0!==t?r.origClientOrderId=t:r.orderId=e;let s=void 0!==t?this.omit(i,"clientOrderId"):i,[n,d]=this.handleMarginModeAndParams("fetchOrder",s);if(void 0!==n){if("isolated"!==n)throw new a.BadRequest(this.id+" fetchOrder() does not support marginMode "+n+" for spot-margin trading");o=await this.spotPrivateGetMarginOrder(this.extend(r,d))}else o=await this.spotPrivateGetOrder(this.extend(r,d))}else if(!0===s.swap){r.order_id=e;let t=await this.contractPrivateGetOrderGetOrderId(this.extend(r,i));o=this.safeValue(t,"data")}return this.parseOrder(o,s)}async fetchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o={};void 0!==e&&(o.symbol=(r=this.market(e)).id);let n=this.safeInteger(s,"until"),d=this.omit(s,"until"),[h,c]=this.handleMarketTypeAndParams("fetchOrders",r,d);if("spot"===h){let s;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrders() requires a symbol argument for spot market");let[h,c]=this.handleMarginModeAndParams("fetchOrders",d);if(void 0!==t&&(o.startTime=t),void 0!==n&&(o.endTime=n),void 0!==i&&(o.limit=i),void 0!==h){if("isolated"!==h)throw new a.BadRequest(this.id+" fetchOrders() does not support marginMode "+h+" for spot-margin trading");s=await this.spotPrivateGetMarginAllOrders(this.extend(o,c))}else s=await this.spotPrivateGetAllOrders(this.extend(o,c));return this.parseOrders(s,r,t,i)}{if(void 0!==t){o.start_time=t;let e=this.safeInteger(this.options,"maxTimeTillEnd");if(void 0===e)throw new a.ExchangeError(this.id+' fetchOrders() requires a numeric options["maxTimeTillEnd"]');let i=this.safeInteger(d,"end_time",n);if(void 0===i)o.end_time=this.sum(t,e);else if(i-t>e)throw new a.BadRequest(this.id+" end is invalid, i.e. exceeds allowed 90 days.");else o.end_time=n}else if(void 0!==n){let e=this.safeInteger(this.options,"maxTimeTillEnd");if(void 0===e)throw new a.ExchangeError(this.id+' fetchOrders() requires a numeric options["maxTimeTillEnd"]');o.start_time=this.sum(n,-1*e),o.end_time=n}void 0!==i&&(o.page_size=i);let e=this.safeString(this.options,"fetchOrders","contractPrivateGetOrderListHistoryOrders");e=this.safeString(c,"method",e);let s=[],h=[];if("contractPrivateGetOrderListHistoryOrders"===e){let e=await this.contractPrivateGetOrderListHistoryOrders(this.extend(o,c));s=this.safeValue(e,"data")}else{let e=await this.contractPrivateGetPlanorderListOrders(this.extend(o,c));h=this.safeValue(e,"data")}let l=this.arrayConcat(h,s);return this.parseOrders(l,r,t,i,d)}}async fetchOrdersByIds(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r={};void 0!==t&&(r.symbol=(s=this.market(t)).id);let[o,n]=this.handleMarketTypeAndParams("fetchOrdersByIds",s,i);if("spot"===o)throw new a.BadRequest(this.id+" fetchOrdersByIds() is not supported for "+o);{r.order_ids=e.join(",");let t=await this.contractPrivateGetOrderBatchQuery(this.extend(r,n)),i=this.safeList(t,"data");return this.parseOrders(i,s)}}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o={};void 0!==e&&(r=this.market(e));let[n,d]=this.handleMarketTypeAndParams("fetchOpenOrders",r,s);if("spot"===n){let s;void 0!==e&&(o.symbol=this.safeString(r,"id"));let[n,h]=this.handleMarginModeAndParams("fetchOpenOrders",d);if(void 0!==n){if("isolated"!==n)throw new a.BadRequest(this.id+" fetchOpenOrders() does not support marginMode "+n+" for spot-margin trading");s=await this.spotPrivateGetMarginOpenOrders(this.extend(o,h))}else s=await this.spotPrivateGetOpenOrders(this.extend(o,h));return this.parseOrders(s,r,t,i)}{void 0===i&&(o.page_size=100);let e=await this.contractPrivateGetOrderListOpenOrders(this.extend(o,d)),s=this.safeList(e,"data",[]);return this.parseOrders(s,r,t,i,d)}}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrdersByState(3,e,t,i,s)}async fetchCanceledOrders(e,t,i,s={}){return await this.fetchOrdersByState(4,e,t,i,s)}async fetchOrdersByState(e,t,i,s,r={}){let o;void 0===this.markets&&await this.loadMarkets();let n={};void 0!==t&&(o=this.market(t));let[d]=this.handleMarketTypeAndParams("fetchOrdersByState",o,r);if("spot"!==d)return n.states=e,await this.fetchOrders(t,i,s,this.extend(n,r));throw new a.NotSupported(this.id+" fetchOrdersByState() is not supported for "+d)}async cancelOrder(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(r=this.market(t)).id;let[o,n]=this.handleMarketTypeAndParams("cancelOrder",r,i),[d,h]=this.handleMarginModeAndParams("cancelOrder",n);if("spot"===o){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");let i={symbol:this.safeString(r,"id")},o=this.safeString(n,"clientOrderId");if(void 0!==o?i.origClientOrderId=o:i.orderId=e,void 0!==d){if("isolated"!==d)throw new a.BadRequest(this.id+" cancelOrder() does not support marginMode "+d+" for spot-margin trading");s=await this.spotPrivateDeleteMarginOrder(this.extend(i,h))}else s=await this.spotPrivateDeleteOrder(this.extend(i,h))}else{let t,i=this.safeString(this.options,"cancelOrder","contractPrivatePostOrderCancel");if("contractPrivatePostOrderCancel"===(i=this.safeString(h,"method",i)))t=await this.contractPrivatePostOrderCancel([e]);else if("contractPrivatePostPlanorderCancel"===i)t=await this.contractPrivatePostPlanorderCancel([e]);else throw new a.NotSupported(this.id+" cancelOrder() not support this method");s=this.safeValue(t,"data");let r=this.safeDict(s,0),o=this.safeString(r,"errorMsg","");if("success"!==o)throw new a.InvalidOrder(this.id+" cancelOrder() the order with id "+e+" cannot be cancelled: "+o)}return this.parseOrder(s,r)}async cancelOrders(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=void 0!==t?this.market(t):void 0,[r]=this.handleMarketTypeAndParams("cancelOrders",s,i);if("spot"===r)throw new a.BadRequest(this.id+" cancelOrders() is not supported for "+r);{let t=await this.contractPrivatePostOrderCancel(e),i=this.safeList(t,"data");return this.parseOrders(i,s)}}async cancelAllOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(i=this.market(e));let s={},[r,a]=this.handleMarketTypeAndParams("cancelAllOrders",i,t);if("spot"===r){if(void 0===e)return await this.spotPrivateDeleteOrderAll(a),[];s.symbol=this.safeString(i,"id");let t=await this.spotPrivateDeleteOpenOrders(this.extend(s,a));return this.parseOrders(t,i)}{void 0!==e&&(s.symbol=this.safeString(i,"id"));let t=this.safeString(this.options,"cancelAllOrders","contractPrivatePostOrderCancelAll");t=this.safeString(a,"method",t);let r={};"contractPrivatePostOrderCancelAll"===t?r=await this.contractPrivatePostOrderCancelAll(this.extend(s,a)):"contractPrivatePostPlanorderCancelAll"===t&&(r=await this.contractPrivatePostPlanorderCancelAll(this.extend(s,a)));let o=this.safeList(r,"data",[]);return this.parseOrders(o,i)}}parseOrder(e,t){let i,s;if(void 0!==this.safeInteger(e,"code"))return this.safeOrder({info:e,status:"rejected",clientOrderId:this.safeString(e,"newClientOrderId")});i="string"==typeof e?e:this.safeString2(e,"orderId","id");let r=this.parseOrderTimeInForce(this.safeString(e,"timeInForce")),a=this.safeString(e,"type");void 0===r&&(r=this.getTifFromRawOrderType(a));let n=this.safeString(e,"symbol"),d=this.safeMarket(n,t),h=this.safeIntegerN(e,["time","createTime","transactTime"]),c=this.safeString(e,"feeCurrency");if(void 0!==c){let t=this.safeString(e,"takerFee"),i=this.safeString(e,"makerFee"),r=o.Y.stringAdd(t,i);s={currency:c,cost:this.parseNumber(r)}}return this.safeOrder({id:i,clientOrderId:this.safeString(e,"clientOrderId"),timestamp:h,datetime:this.iso8601(h),lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeInteger(e,"updateTime"),status:this.parseOrderStatus(this.safeString2(e,"status","state")),symbol:d.symbol,type:this.parseOrderType(a),timeInForce:r,side:this.parseOrderSide(this.safeString(e,"side")),price:this.safeNumber(e,"price"),triggerPrice:this.safeNumber2(e,"stopPrice","triggerPrice"),average:this.safeNumber(e,"dealAvgPrice"),amount:this.safeNumber2(e,"origQty","vol"),cost:this.safeNumber(e,"cummulativeQuoteQty"),filled:this.safeNumber2(e,"executedQty","dealVol"),remaining:void 0,fee:s,trades:void 0,info:e},d)}parseOrderSide(e){return this.safeString({BUY:"buy",SELL:"sell",1:"buy",2:"sell"},e,e)}parseOrderType(e){return this.safeString({MARKET:"market",LIMIT:"limit",LIMIT_MAKER:"limit",IMMEDIATE_OR_CANCEL:"limit",FILL_OR_KILL:"limit"},e,e)}parseOrderStatus(e){return this.safeString({NEW:"open",FILLED:"closed",CANCELED:"canceled",PARTIALLY_FILLED:"open",PARTIALLY_CANCELED:"canceled",2:"open",3:"closed",4:"canceled"},e,e)}parseOrderTimeInForce(e){return this.safeString({GTC:"GTC",FOK:"FOK",IOC:"IOC"},e,e)}getTifFromRawOrderType(e){return this.safeString({LIMIT:"GTC",LIMIT_MAKER:"POST_ONLY",IMMEDIATE_OR_CANCEL:"IOC",FILL_OR_KILL:"FOK",MARKET:"IOC"},e,e)}async fetchAccountHelper(e,t){if("spot"===e)return await this.spotPrivateGetAccount(t);if("swap"===e){let e=await this.contractPrivateGetAccountAssets(t);return{balances:this.safeList(e,"data",[])}}}async fetchAccounts(e={}){let[t,i]=this.handleMarketTypeAndParams("fetchAccounts",void 0,e);void 0===this.markets&&await this.loadMarkets();let s=await this.fetchAccountHelper(t,i),r=this.safeList(s,"balances",[]),a=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.safeString2(t,"asset","currency"),s=this.safeCurrencyCode(i);a.push({id:this.safeString(t,"id"),type:this.safeString(t,"type"),code:s,info:t})}return a}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.spot)throw new a.BadRequest(this.id+" fetchTradingFee() supports spot markets only");let s={symbol:i.id},r=await this.spotPrivateGetTradeFee(this.extend(s,t)),o=this.safeDict(r,"data",{});return{info:o,symbol:e,maker:this.safeNumber(o,"makerCommission"),taker:this.safeNumber(o,"takerCommission"),percentage:void 0,tierBased:void 0}}customParseBalance(e,t){let i;i="margin"===t?this.safeList(e,"assets",[]):"swap"===t?this.safeList(e,"data",[]):this.safeList(e,"balances",[]);let s={info:e};if("margin"===t){for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),r=this.safeDict(t,"baseAsset",{}),a=this.safeDict(t,"quoteAsset",{}),o=this.safeCurrencyCode(this.safeString(r,"asset")),n=this.safeCurrencyCode(this.safeString(a,"asset"));void 0!==o&&(s=this.mergeBalanceAccount(s,o,this.parseBalanceHelper(r))),void 0!==n&&(s=this.mergeBalanceAccount(s,n,this.parseBalanceHelper(a)))}return this.safeBalance(s)}if("swap"===t){for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),r=this.safeString(t,"currency"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(t,"availableBalance"),o.used=this.safeString(t,"frozenBalance"),void 0!==a&&(s[a]=o)}return this.safeBalance(s)}for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),r=this.safeString(t,"asset"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(t,"free"),o.used=this.safeString(t,"locked"),void 0!==a&&(s[a]=o)}return this.safeBalance(s)}parseBalanceHelper(e){let t=this.account();t.used=this.safeString(e,"locked"),t.free=this.safeString(e,"free"),t.total=this.safeString(e,"totalAsset");let i=this.safeString(e,"borrowed"),s=this.safeString(e,"interest");return t.debt=o.Y.stringAdd(i,s),t}async fetchBalance(e={}){let t,i,s;void 0===this.markets&&await this.loadMarkets();let r={};[i,s]=this.handleMarketTypeAndParams("fetchBalance",void 0,e);let o=this.safeString(s,"marginMode"),n=this.safeBool(s,"margin",!1),d=this.omit(s,["margin","marginMode"]);if(void 0!==o||!0===n||"margin"===i){let e,s=this.safeString(d,"symbol");if(void 0===s){let t=this.safeList(d,"symbols");if(void 0!==t){let i=this.marketIds(t);void 0!==i&&(e=i.join(","))}}else e=this.market(s).id;this.checkRequiredArgument("fetchBalance",e,"symbol or symbols"),i="margin",r.symbols=e;let a=this.omit(d,["symbol","symbols"]);t=await this.spotPrivateGetMarginIsolatedAccount(this.extend(r,a))}else if("spot"===i)t=await this.spotPrivateGetAccount(this.extend(r,d));else if("swap"===i)t=await this.contractPrivateGetAccountAssets(this.extend(r,d));else throw new a.NotSupported(this.id+" fetchBalance() not support this method");return this.customParseBalance(t,i)}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),[o,n]=this.handleMarketTypeAndParams("fetchMyTrades",r,s),d={symbol:r.id},h=[];if("spot"===o){void 0!==t&&(d.startTime=t),void 0!==i&&(d.limit=i);let e=this.safeInteger(n,"until");void 0!==e&&(d.endTime=e);let s=void 0!==e?this.omit(n,"until"):n;h=await this.spotPrivateGetMyTrades(this.extend(d,s))}else{void 0!==t&&(d.start_time=t,void 0===this.safeInteger(n,"end_time")&&(d.end_time=this.sum(t,this.options.maxTimeTillEnd))),void 0!==i&&(d.page_size=i);let e=await this.contractPrivateGetOrderListOrderDeals(this.extend(d,n));h=this.safeList(e,"data",[])}return this.parseTrades(h,r,t,i)}async fetchOrderTrades(e,t,i,s,r={}){let o;void 0===this.markets&&await this.loadMarkets();let n={};void 0!==t&&(o=this.market(t));let[d,h]=this.handleMarketTypeAndParams("fetchOrderTrades",o,r),c=[];if("spot"===d){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrderTrades() requires a symbol argument");n.symbol=this.safeString(o,"id"),n.orderId=e,c=await this.spotPrivateGetMyTrades(this.extend(n,h))}else{n.order_id=e;let t=await this.contractPrivateGetOrderDealDetailsOrderId(this.extend(n,h));c=this.safeList(t,"data",[])}return this.parseTrades(c,o,i,s,h)}async modifyMarginHelper(e,t,i,s={}){let r=this.safeInteger(s,"positionId");if(void 0===r)throw new a.ArgumentsRequired(this.id+" modifyMarginHelper() requires a positionId parameter");return void 0===this.markets&&await this.loadMarkets(),await this.contractPrivatePostPositionChangeMargin(this.extend({positionId:r,amount:t,type:i},s))}async reduceMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,"SUB",i)}async addMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,"ADD",i)}async setLeverage(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={leverage:e},r=this.safeInteger(i,"positionId");if(void 0===r){let e=this.safeNumber(i,"openType"),r=this.safeNumber(i,"positionType"),o=void 0!==t?this.market(t):void 0;if(void 0===e||void 0===r||void 0===o)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a positionId parameter or a symbol argument with openType and positionType parameters, use openType 1 or 2 for isolated or cross margin respectively, use positionType 1 or 2 for long or short positions");s.openType=e,s.symbol=o.id,s.positionType=r}else s.positionId=r;return await this.contractPrivatePostPositionChangeLeverage(this.extend(s,i))}async fetchFundingHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={};void 0!==e&&(r.symbol=this.market(e).id),void 0!==i&&(r.page_size=i);let a=await this.contractPrivateGetPositionFundingRecords(this.extend(r,s)),o=this.safeDict(a,"data",{}),n=this.safeList(o,"resultList",[]),d=[];for(let t=0;t<n.length;t++){let i=n[t],s=this.safeInteger(i,"settleTime");d.push({info:i,symbol:e,code:void 0,timestamp:s,datetime:this.iso8601(s),id:this.safeNumber(i,"id"),amount:this.safeNumber(i,"funding")})}return d}parseFundingRate(e,t){let i,s=this.safeNumber2(e,"fundingRate","rate"),r=this.safeInteger(e,"nextSettleTime"),a=this.safeString(e,"symbol"),o=this.safeSymbol(a,t,void 0,"contract"),n=this.safeInteger(e,"timestamp"),d=this.safeString(e,"collectCycle");return void 0!==d&&(i=d+"h"),{info:e,symbol:o,markPrice:void 0,indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:n,datetime:this.iso8601(n),fundingRate:s,fundingTimestamp:r,fundingDatetime:this.iso8601(r),nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:i}}async fetchFundingInterval(e,t={}){return await this.fetchFundingRate(e,t)}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.contractPublicGetFundingRateSymbol(this.extend(s,t)),a=this.safeDict(r,"data",{});return this.parseFundingRate(a,i)}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={symbol:r.id};void 0!==i&&(o.page_size=i);let n=await this.contractPublicGetFundingRateHistory(this.extend(o,s)),d=this.safeDict(n,"data"),h=this.safeList(d,"resultList",[]),c=[];for(let e=0;e<h.length;e++){let t=h[e],i=this.safeString(t,"symbol"),s=this.safeSymbol(i),r=this.safeInteger(t,"settleTime");c.push({info:t,symbol:s,fundingRate:this.safeNumber(t,"fundingRate"),timestamp:r,datetime:this.iso8601(r)})}let l=this.sortBy(c,"timestamp");return this.filterBySymbolSinceLimit(l,this.safeString(r,"symbol"),t,i)}async fetchLeverageTiers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,"swap",!0,!0),s=await this.contractPublicGetDetail(t),r=this.safeList(s,"data");return this.parseLeverageTiers(r,i,"symbol")}parseMarketLeverageTiers(e,t){let i=this.safeString(e,"symbol"),s=this.safeString(e,"maintenanceMarginRate"),r=this.safeString(e,"initialMarginRate"),a=this.safeString(e,"maxVol"),n=this.safeString(e,"riskIncrVol"),d=this.safeString(e,"riskIncrMmr"),h=this.safeString(e,"riskIncrImr"),c="0",l=[],u=this.safeString(e,"quoteCoin");if("0"===n)return[{tier:0,symbol:this.safeSymbol(i,t,void 0,"contract"),currency:this.safeCurrencyCode(u),minNotional:void 0,maxNotional:void 0,maintenanceMarginRate:void 0,maxLeverage:this.safeNumber(e,"maxLeverage"),info:e}];for(;o.Y.stringLt(c,a);){let a=o.Y.stringAdd(c,n),f=this.parseNumber(c),p=this.parseNumber(s),m=this.parseNumber(o.Y.stringDiv("1",r));l.push({tier:this.parseNumber(o.Y.stringDiv(a,n)),symbol:this.safeSymbol(i,t,void 0,"contract"),currency:this.safeCurrencyCode(u),minNotional:f,maxNotional:this.parseNumber(a),maintenanceMarginRate:p,maxLeverage:m,info:e}),r=o.Y.stringAdd(r,h),s=o.Y.stringAdd(s,d),c=a}return l}parseDepositAddress(e,t){let i=this.safeString(e,"address"),s=this.safeString(e,"coin"),r=this.safeCurrencyCode(s,t),a=this.safeString(e,"netWork");return{info:e,currency:r,network:this.networkIdToCode(a,r),address:i,tag:this.safeString(e,"memo")}}async fetchDepositAddressesByNetwork(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.currency(e),r={coin:s.id},a=this.safeString(t,"network");if(void 0!==a){let t=this.networkIdToCode(a,e),r=this.safeDict(s,"networks",{});if(void 0!==t&&t in r){let e=void 0===t?{}:this.safeDict(r,t,{}),s=this.safeDict(e,"info",{});i=this.safeString(s,"network")}else i=this.networkCodeToId(a,e)}void 0!==i&&(r.network=i);let o=this.omit(t,"network"),n=await this.spotPrivateGetCapitalDepositAddress(this.extend(r,o)),d=this.parseDepositAddresses(n,void 0,!1);return this.indexBy(d,"network")}async createDepositAddress(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.currency(e),r={coin:s.id},o=this.safeString(t,"network");if(void 0===o)throw new a.ArgumentsRequired(this.id+" createDepositAddress requires a `network` parameter");let n=this.networkIdToCode(o,e),d=this.safeDict(s,"networks",{});if(void 0!==n&&n in d){let e=void 0===n?{}:this.safeDict(d,n,{}),t=this.safeDict(e,"info",{});i=this.safeString(t,"network")}else i=this.networkCodeToId(o,e);void 0!==i&&(r.network=i);let h=this.omit(t,"network"),c=await this.spotPrivatePostCapitalDepositAddress(this.extend(r,h));return this.parseDepositAddress(c,s)}async fetchDepositAddress(e,t={}){let i,s=this.safeString(t,"network"),r=await this.fetchDepositAddressesByNetwork(e,t);if(void 0!==s){let t=this.networkIdToCode(s,e);i=void 0===t?void 0:this.safeDict(r,t)}else{let t=this.safeDict(this.options,"defaultNetworks"),s=this.safeString(t,e);if(void 0!==s)i=this.safeDict(r,s);else{let e=Object.keys(r),t=this.safeString(e,0);i=this.safeDict(r,t)}}if(void 0===i)throw new a.InvalidAddress(this.id+" fetchDepositAddress() cannot find a deposit address for "+e+", and network"+s+"consider creating one using .createDepositAddress() method or in MEXC website");return i}async fetchDeposits(e,t,i,s={}){let r,o;void 0===this.markets&&await this.loadMarkets();let n={};if(void 0!==e&&(o=this.safeString(s,"network")),void 0!==e&&(n.coin=(r=this.currency(e)).id,void 0!==o&&(n.coin=r.id+"-"+o)),void 0!==t&&(n.startTime=t),void 0!==i){if(i>1e3)throw new a.ExchangeError("This exchange supports a maximum limit of 1000");n.limit=i}let d=void 0!==o?this.omit(s,"network"):s,h=await this.spotPrivateGetCapitalDepositHisrec(this.extend(n,d));return this.parseTransactions(h,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o={};if(void 0!==e&&(o.coin=(r=this.currency(e)).id),void 0!==t&&(o.startTime=t),void 0!==i){if(i>1e3)throw new a.ExchangeError("This exchange supports a maximum limit of 1000");o.limit=i}let n=await this.spotPrivateGetCapitalWithdrawHistory(this.extend(o,s));return this.parseTransactions(n,r,t,i)}parseTransaction(e,t){let i,s,r,a=this.safeString2(e,"id","tranId"),n=void 0===a?"deposit":"withdrawal",d=this.safeInteger2(e,"insertTime","applyTime"),h=this.safeInteger(e,"updateTime"),c=this.safeString(e,"coin");void 0!==c&&(i=c.split("-")[0]);let l=this.safeCurrencyCode(i,t),u=this.safeString(e,"network");void 0!==u&&(s=this.networkIdToCode(u,l));let f=this.parseTransactionStatusByType(this.safeString(e,"status"),n),p=this.safeString(e,"amount"),m=this.safeString(e,"address"),g=this.safeString2(e,"transHash","txId"),v=this.safeString(e,"transactionFee");return void 0!==v&&(r={cost:this.parseNumber(v),currency:l}),"withdrawal"===n&&(p=o.Y.stringSub(p,v)),{info:e,id:a,txid:g,timestamp:d,datetime:this.iso8601(d),network:s,address:m,addressTo:m,addressFrom:void 0,tag:this.safeString(e,"memo"),tagTo:void 0,tagFrom:void 0,type:n,amount:this.parseNumber(p),currency:l,status:f,updated:h,comment:this.safeString(e,"remark"),internal:void 0,fee:r}}parseTransactionStatusByType(e,t){let i=this.safeDict({deposit:{1:"failed",2:"pending",3:"pending",4:"pending",5:"ok",6:"pending",7:"failed"},withdrawal:{1:"pending",2:"pending",3:"pending",4:"pending",5:"pending",6:"pending",7:"ok",8:"failed",9:"canceled",10:"pending"}},t,{});return this.safeString(i,e,e)}async closeAllPositions(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.contractPrivatePostPositionCloseAll(e),i=this.safeList(t,"data",[]);return this.parsePositions(i)}async fetchPosition(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={symbol:this.market(e).id},s=await this.fetchPositions(void 0,this.extend(i,t));return this.safeDict(s,0)}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.contractPrivateGetPositionOpenPositions(t),s=this.safeList(i,"data",[]);return this.parsePositions(s,e)}parsePosition(e,t){let i=this.safeMarket(this.safeString(e,"symbol"),t,void 0,"swap").symbol,s=this.safeString(e,"holdVol"),r=this.safeNumber(e,"openAvgPrice"),a=this.safeString(e,"im"),o=this.safeString(e,"positionType"),n=this.safeString(e,"margin_mode"),d=this.safeNumber(e,"leverage"),h=this.safeNumber(e,"liquidatePrice"),c=this.safeInteger(e,"updateTime");return this.safePosition({info:e,id:void 0,symbol:i,contracts:this.parseNumber(s),contractSize:void 0,entryPrice:r,collateral:void 0,side:"1"===o?"long":"short",unrealizedPnl:void 0,leverage:this.parseNumber(d),percentage:void 0,marginMode:"1"===n?"isolated":"cross",notional:void 0,markPrice:void 0,lastPrice:void 0,liquidationPrice:h,initialMargin:this.parseNumber(a),initialMarginPercentage:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,marginRatio:void 0,timestamp:c,datetime:this.iso8601(c),hedged:void 0,stopLossPrice:void 0,takeProfitPrice:void 0,lastUpdateTimestamp:void 0})}async fetchTransfer(e,t,i={}){let[s,r]=this.handleMarketTypeAndParams("fetchTransfer",void 0,i);if(void 0===this.markets&&await this.loadMarkets(),"spot"===s){let t=await this.spotPrivateGetAssetInternalTransferRecord(this.extend({transact_id:e},r)),i=this.safeDict(t,"data",{});return this.parseTransfer(i)}throw new a.BadRequest(this.id+" fetchTransfer() is not supported for "+s)}async fetchTransfers(e,t,i,s={}){let r,[o,n]=this.handleMarketTypeAndParams("fetchTransfers",void 0,s);void 0===this.markets&&await this.loadMarkets();let d={};void 0!==e&&(r=this.currency(e));let[h,c]=this.handleOptionStringAndParams(n,"fetchTransfers","fromAccountType"),l={spot:"SPOT",swap:"FUTURES",futures:"FUTURES",future:"FUTURES",margin:"SPOT"};if(void 0!==h)d.fromAccountType=this.safeString(l,h,h);else throw new a.ArgumentsRequired(this.id+' fetchTransfers() requires a fromAccountType parameter, one of "SPOT", "FUTURES"');let[u,f]=this.handleOptionStringAndParams(c,"fetchTransfers","toAccountType");if(void 0!==u)d.toAccountType=this.safeString(l,u,u);else throw new a.ArgumentsRequired(this.id+' fetchTransfers() requires a toAccountType parameter, one of "SPOT", "FUTURES"');let p=[];if("spot"===o){if(void 0!==t&&(d.startTime=t),void 0!==i){if(i>100)throw new a.ExchangeError("This exchange supports a maximum limit of 50");d.size=i}let e=await this.spotPrivateGetCapitalTransfer(this.extend(d,f));p=this.safeList(e,"rows",[])}else if("swap"===o){void 0!==i&&(d.page_size=i);let e=await this.contractPrivateGetAccountTransferRecord(this.extend(d,f)),t=this.safeDict(e,"data");p=this.safeValue(t,"resultList")}return this.parseTransfers(p,r,t,i)}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let o=this.currency(e),n={spot:"SPOT",swap:"FUTURES",future:"FUTURES"},d=this.safeString(n,i,i),h=this.safeString(n,s,s);if(void 0===d){let e=Object.keys(n);throw new a.ExchangeError(this.id+" fromAccount must be one of "+e.join(", "))}if(void 0===h){let e=Object.keys(n);throw new a.ExchangeError(this.id+" toAccount must be one of "+e.join(", "))}let c={asset:o.id,amount:t,fromAccountType:d,toAccountType:h},l="ISOLATED_MARGIN"===d||"ISOLATED_MARGIN"===h;if(l){let e=this.safeString(r,"symbol");if(void 0===e)throw new a.ArgumentsRequired(this.id+" transfer() requires a symbol argument for isolated margin");c.symbol=this.market(e).id}let u=r;l&&(u=this.omit(r,"symbol"));let f=await this.spotPrivatePostCapitalTransfer(this.extend(c,u)),p=this.parseTransfer(f,o);return this.extend(p,{amount:t,fromAccount:i,toAccount:s})}parseTransfer(e,t){let i,s,r=this.safeString2(e,"currency","asset"),a=this.safeStringN(e,["transact_id","txid","tranId"]),o=this.safeInteger2(e,"createTime","timestamp"),n=void 0!==o?this.iso8601(o):void 0,d=this.safeString(e,"type"),h=this.safeString(e,"fromAccountType"),c=this.safeString(e,"toAccountType");return void 0!==h&&void 0!==c?(i=h,s=c):void 0!==d?(i="IN"===d?"MAIN":"CONTRACT",s="IN"===d?"CONTRACT":"MAIN"):(i=this.safeString(e,"from"),s=this.safeString(e,"to")),{info:e,id:a,timestamp:o,datetime:n,currency:this.safeCurrencyCode(r,t),amount:this.safeNumber(e,"amount"),fromAccount:this.parseAccountId(i),toAccount:this.parseAccountId(s),status:this.parseTransferStatus(this.safeStringN(e,["transact_state","state","status"]))}}parseAccountId(e){return this.safeString({SPOT:"spot",FUTURES:"swap",MAIN:"spot",CONTRACT:"swap"},e,e)}parseTransferStatus(e){return this.safeString({SUCCESS:"ok",FAILED:"failed",WAIT:"pending"},e,e)}async withdraw(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let o=this.currency(e),[n,d]=this.handleWithdrawTagAndParams(s,r);if(!0===this.safeBool(d,"internal",!1)){let e=this.omit(d,"internal"),s={asset:o.id,amount:t,toAccount:i};if(void 0===this.safeString(e,"toAccountType"))throw new a.ArgumentsRequired(this.id+" withdraw() requires a toAccountType parameter for internal transfer to be of: EMAIL | UID | MOBILE");let r=await this.spotPrivatePostCapitalTransferInternal(this.extend(s,e));return this.parseTransaction(r,o)}let h=this.safeDict(this.options,"networks",{}),c=this.safeString2(d,"network","netWork");c=this.safeString(h,c,c),c=this.networkCodeToId(c,this.safeString(o,"code")),this.checkAddress(i);let l={coin:o.id,address:i,amount:t};void 0!==n&&(l.memo=n),void 0!==c&&(l.netWork=c);let u=void 0!==c?this.omit(d,["network","netWork"]):d,f=await this.spotPrivatePostCapitalWithdraw(this.extend(l,u));return this.parseTransaction(f,o)}async setPositionMode(e,t,i={}){return await this.contractPrivatePostPositionChangePositionMode(this.extend({positionMode:e?1:2},i))}async fetchPositionMode(e,t={}){let i=await this.contractPrivateGetPositionPositionMode(t),s=this.safeInteger(i,"data");return{info:i,hedged:1===s}}async fetchTransactionFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.spotPrivateGetCapitalConfigGetall(t);return this.parseTransactionFees(i,e)}parseTransactionFees(e,t){let i={};for(let s=0;s<e.length;s++){let r=e[s],a=this.safeString(r,"coin"),o=this.safeCurrency(a),n=this.safeString(o,"code");(void 0===t||this.inArray(n,t))&&(i[n]=this.parseTransactionFee(r,o))}return{withdraw:i,deposit:{},info:e}}parseTransactionFee(e,t){let i=this.safeList(e,"networkList",[]),s={};for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),r=this.safeString(t,"network"),a=this.safeString(this.options.networks,r,r),o=this.safeNumber(t,"withdrawFee");s[a]=o}return s}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.spotPrivateGetCapitalConfigGetall(t);return this.parseDepositWithdrawFees(i,e,"coin")}parseDepositWithdrawFee(e,t){let i=this.safeList(e,"networkList",[]),s=this.depositWithdrawFee(e);for(let e=0;e<i.length;e++){let r=this.safeDict(i,e),a=this.safeString(r,"network"),o=this.networkIdToCode(a,this.safeString(t,"code"));void 0!==o&&(s.networks[o]={withdraw:{fee:this.safeNumber(r,"withdrawFee"),percentage:void 0},deposit:{fee:void 0,percentage:void 0}})}return this.assignDefaultDepositWithdrawFees(s)}async fetchLeverage(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.contractPrivateGetPositionLeverage(this.extend(s,t)),a=this.safeList(r,"data",[]);return this.parseLeverage(a,i)}parseLeverage(e,t){let i,s,r;for(let t=0;t<e.length;t++){let a=this.safeDict(e,t),o=this.safeInteger(a,"openType"),n=this.safeInteger(a,"positionType");1===n?s=this.safeInteger(a,"leverage"):2===n&&(r=this.safeInteger(a,"leverage")),i=1===o?"isolated":"cross"}return{info:e,symbol:this.safeString(t,"symbol"),marginMode:i,longLeverage:s,shortLeverage:r}}handleMarginModeAndParams(e,t={},i){let s=this.safeString(this.options,"defaultType"),r=this.safeBool(t,"margin",!1),[a,o]=super.handleMarginModeAndParams(e,t,i);return"margin"===s||!0===r?["isolated",o]:[a,o]}async fetchPositionsHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={};void 0!==e&&1===e.length&&(r.symbol=this.market(e[0]).id),void 0!==i&&(r.page_size=i);let a=await this.contractPrivateGetPositionListHistoryPositions(this.extend(r,s)),o=this.safeList(a,"data",[]),n=this.parsePositions(o,e,s);return this.filterBySinceLimit(n,t,i)}async setMarginMode(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(t);if(!0===s.spot)throw new a.BadSymbol(this.id+" setMarginMode() supports contract markets only");let r=e.toLowerCase();if("isolated"!==r&&"cross"!==r)throw new a.BadRequest(this.id+" setMarginMode() marginMode argument should be isolated or cross");let o=this.safeInteger(i,"leverage");if(void 0===o)throw new a.ArgumentsRequired(this.id+" setMarginMode() requires a leverage parameter");let n=this.safeStringLower2(i,"direction","positionId"),d={leverage:o,openType:"isolated"===r?1:2};void 0!==t&&(d.symbol=s.id),void 0!==n&&(d.positionType="short"===n?2:1);let h=this.omit(i,"direction"),c=await this.contractPrivatePostPositionChangeLeverage(this.extend(d,h));return this.parseLeverage(c,s)}nonce(){return this.milliseconds()-this.safeInteger(this.options,"timeDifference",0)}sign(e,t="public",i="GET",r={},o,n){let d,h=o,c=n,l=this.safeString(t,0),u=this.safeString(t,1),f=this.implodeParams(e,r),p=this.omit(r,this.extractParams(e));if("spot"===l||"broker"===l){if("broker"===l){let e=this.safeString(this.urls.api[l],u);if(void 0===e)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");d=e+"/"+f}else{let e=this.safeString(this.urls.api[l],u);if(void 0===e)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");d=e+"/api/"+this.version+"/"+f}let e=p;"private"===u&&("broker"===l&&("POST"===i||"PUT"===i||"DELETE"===i)?(e={timestamp:this.nonce(),recvWindow:this.safeInteger(this.options,"recvWindow",5e3)},c=this.json(p)):(e.timestamp=this.nonce(),e.recvWindow=this.safeInteger(this.options,"recvWindow",5e3)));let t="";Object.keys(e).length>0&&(d+="?"+(t=this.urlencode(e))),"private"===u&&(this.checkRequiredCredentials(),d+="&signature="+this.hmac(this.encode(t),this.encode(this.secret),s.sc),h={"X-MEXC-APIKEY":this.apiKey,source:this.safeString(this.options,"broker","CCXT")}),("POST"===i||"PUT"===i||"DELETE"===i)&&((h=void 0===h?{}:h)["Content-Type"]="application/json")}else if("contract"===l||"spot2"===l){let e=this.safeString(this.urls.api[l],u);if(void 0===e)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");d=e+"/"+this.implodeParams(f,p);let t=this.omit(p,this.extractParams(f));if("public"===u)Object.keys(t).length>0&&(d+="?"+this.urlencode(t));else{this.checkRequiredCredentials();let e=this.nonce().toString(),r="";if(h={ApiKey:this.apiKey,"Request-Time":e,"Content-Type":"application/json",source:this.safeString(this.options,"broker","CCXT")},"POST"===i)c=r=this.json(t);else{let e=this.keysort(t);Object.keys(e).length>0&&(r+=this.urlencode(e),d+="?"+r)}r=this.apiKey+e+r;let a=this.hmac(this.encode(r),this.encode(this.secret),s.sc);h.Signature=a}}return{url:d,method:i,body:c,headers:h}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n||!0===this.safeBool(n,"success",!1))return;let c=this.safeString(n,"code");if(void 0!==c&&"200"!==c&&"0"!==c){let e=this.id+" "+o;throw this.throwBroadlyMatchedException(this.exceptions.broad,o,e),this.throwExactlyMatchedException(this.exceptions.exact,c,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>n})},6479(e,t,i){"use strict";var s=i(7468),r=i(6834),a=i(6885),o=i(4496),n=i(1453),d=i(7749),h=i(1093);class c extends o.A{describe(){return this.deepExtend(super.describe(),{id:"modetrade",name:"Mode Trade",countries:["KY"],rateLimit:100,version:"v1",certified:!1,pro:!0,dex:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!1,option:!1,addMargin:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,cancelWithdraw:!1,closeAllPositions:!1,closePosition:!1,createConvertTrade:!1,createDepositAddress:!1,createMarketBuyOrderWithCost:!1,createMarketOrder:!0,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!0,createReduceOnlyOrder:!0,createStopLimitOrder:!0,createStopLossOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,createTakeProfitOrder:!0,createTrailingAmountOrder:!1,createTrailingPercentOrder:!1,createTriggerOrder:!0,editOrder:!0,fetchAccounts:!1,fetchBalance:!0,fetchCanceledOrders:!1,fetchClosedOrder:!1,fetchClosedOrders:!0,fetchConvertCurrencies:!1,fetchConvertQuote:!1,fetchCurrencies:!0,fetchDepositAddress:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!0,fetchFundingHistory:!0,fetchFundingInterval:!0,fetchFundingIntervals:!1,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchIndexOHLCV:!1,fetchLedger:!0,fetchLeverage:!0,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterestHistory:!1,fetchOpenOrder:!1,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchOrderTrades:!0,fetchPosition:!0,fetchPositionMode:!1,fetchPositions:!0,fetchPremiumIndexOHLCV:!1,fetchStatus:!0,fetchTicker:!1,fetchTickers:!1,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchTransactions:"emulated",fetchTransfers:!1,fetchWithdrawals:!0,reduceMargin:!1,setLeverage:!0,setMargin:!1,setPositionMode:!1,transfer:!1,withdraw:!0},timeframes:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","4h":"4h","12h":"12h","1d":"1d","1w":"1w","1M":"1mon","1y":"1y"},urls:{logo:"https://github.com/user-attachments/assets/bbde7d00-6e40-404f-8f34-8fb15893eb24",api:{public:"https://api-evm.orderly.org",private:"https://api-evm.orderly.org"},test:{public:"https://testnet-api-evm.orderly.org",private:"https://testnet-api-evm.orderly.org"},www:"https://trade.mode.network",doc:["https://orderly.network/docs/build-on-omnichain/building-on-omnichain"],referral:{url:"https://trade.mode.network?ref=MODETRADE",discount:.2}},api:{v1:{public:{get:{"public/volume/stats":{cost:1},"public/broker/name":{cost:1},"public/chain_info/{broker_id}":{cost:1},"public/system_info":{cost:1},"public/vault_balance":{cost:1},"public/insurancefund":{cost:1},"public/chain_info":{cost:1},"faucet/usdc":{cost:1},"public/account":{cost:1},get_account:{cost:1},registration_nonce:{cost:1},get_orderly_key:{cost:1},"public/liquidation":{cost:1},"public/liquidated_positions":{cost:1},"public/config":{cost:1},"public/campaign/ranking":{cost:10},"public/campaign/stats":{cost:10},"public/campaign/user":{cost:10},"public/campaign/stats/details":{cost:10},"public/campaigns":{cost:10},"public/points/leaderboard":{cost:1},"client/points":{cost:1},"public/points/epoch":{cost:1},"public/points/epoch_dates":{cost:1},"public/referral/check_ref_code":{cost:1},"public/referral/verify_ref_code":{cost:1},"referral/admin_info":{cost:1},"referral/info":{cost:1},"referral/referee_info":{cost:1},"referral/referee_rebate_summary":{cost:1},"referral/referee_history":{cost:1},"referral/referral_history":{cost:1},"referral/rebate_summary":{cost:1},"client/distribution_history":{cost:1},"tv/config":{cost:1},"tv/history":{cost:1},"tv/symbol_info":{cost:1},"tv/kline_history":{cost:20},"public/funding_rate_history":{cost:1},"public/funding_rate/{symbol}":{cost:.33},"public/funding_rates":{cost:1},"public/info":{cost:1},"public/info/{symbol}":{cost:1},"public/market_trades":{cost:1},"public/token":{cost:1},"public/futures":{cost:1},"public/futures/{symbol}":{cost:1}},post:{register_account:{cost:1},"public/query":{cost:1}}},private:{get:{"client/key_info":{cost:6},"client/orderly_key_ip_restriction":{cost:6},"order/{oid}":{cost:1},"client/order/{client_order_id}":{cost:1},"algo/order/{oid}":{cost:1},"algo/client/order/{client_order_id}":{cost:1},orders:{cost:1},"algo/orders":{cost:1},"trade/{tid}":{cost:1},trades:{cost:1},"order/{oid}/trades":{cost:1},"client/liquidator_liquidations":{cost:1},liquidations:{cost:1},"asset/history":{cost:60},"client/holding":{cost:1},withdraw_nonce:{cost:1},settle_nonce:{cost:1},"pnl_settlement/history":{cost:1},internal_transfer_history:{cost:1},"volume/user/daily":{cost:60},"volume/user/stats":{cost:60},"client/statistics":{cost:60},"client/info":{cost:60},"client/statistics/daily":{cost:60},positions:{cost:3.33},"position/{symbol}":{cost:3.33},"funding_fee/history":{cost:30},"notification/inbox/notifications":{cost:60},"notification/inbox/unread":{cost:60},"volume/broker/daily":{cost:60},"broker/fee_rate/default":{cost:10},"broker/user_info":{cost:10},"broker/daily_fee_revenue":{cost:1},"orderbook/{symbol}":{cost:1},kline:{cost:1},"client/leverages":{cost:1},"client/margin_modes":{cost:1},"referral/multi_level/admin":{cost:10},"referral/multi_level/admin/info":{cost:1},"referral/multi_level/admin/referee_list":{cost:1},"referral/multi_level/admin/summary":{cost:1},"referral/multi_level/max_rebate_rate":{cost:10},"referral/multi_level/rebate_info":{cost:10},"referral/multi_level/referee_list":{cost:1},"referral/multi_level/statistics":{cost:1},"referral/multi_level/volume_prerequisite":{cost:1}},post:{orderly_key:{cost:1},"client/set_orderly_key_ip_restriction":{cost:6},"client/reset_orderly_key_ip_restriction":{cost:6},order:{cost:1},"batch-order":{cost:10},"algo/order":{cost:1},liquidation:{cost:1},claim_insurance_fund:{cost:1},withdraw_request:{cost:1},settle_pnl:{cost:1},internal_transfer:{cost:1},"notification/inbox/mark_read":{cost:60},"notification/inbox/mark_read_all":{cost:60},"client/leverage":{cost:120},"client/leverages":{cost:120},"client/margin_mode":{cost:1},position_margin:{cost:1},"client/maintenance_config":{cost:60},delegate_signer:{cost:10},delegate_orderly_key:{cost:10},delegate_settle_pnl:{cost:10},delegate_withdraw_request:{cost:10},"broker/fee_rate/set":{cost:10},"broker/fee_rate/set_default":{cost:10},"broker/fee_rate/default":{cost:10},"referral/create":{cost:10},"referral/update":{cost:10},"referral/bind":{cost:10},"referral/edit_split":{cost:10},"referral/edit_referee_description":{cost:1},"referral/multi_level/admin":{cost:10},"referral/multi_level/admin/update":{cost:10},"referral/multi_level/admin/create/affiliate":{cost:1},"referral/multi_level/admin/reset/affiliate":{cost:10},"referral/multi_level/admin/update/affiliate":{cost:10},"referral/multi_level/claim_code":{cost:10},"referral/multi_level/rebate_rate/set_default":{cost:10},"referral/multi_level/rebate_rate/update":{cost:10}},put:{order:{cost:1},"algo/order":{cost:1}},delete:{order:{cost:1},"algo/order":{cost:1},"client/order":{cost:1},"algo/client/order":{cost:1},"algo/orders":{cost:1},orders:{cost:1},"batch-order":{cost:1},"client/batch-order":{cost:1}}}}},requiredCredentials:{apiKey:!0,secret:!0,accountId:!0,privateKey:!1},fees:{trading:{tierBased:!0,percentage:!0,maker:this.parseNumber("0.0002"),taker:this.parseNumber("0.0005")}},options:{sandboxMode:!1,brokerId:"CCXTMODE",verifyingContractAddress:"0x6F7a338F2aA472838dEFD3283eB360d4Dff5D203"},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:{max:10},fetchMyTrades:{marginMode:!1,limit:500,daysBack:void 0,untilDays:1e5,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!0,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:500,trigger:!0,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:500,daysBack:void 0,untilDays:1e5,trigger:!0,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:500,daysBack:void 0,daysBackCanceled:void 0,untilDays:1e5,trigger:!0,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:1e3}},spot:void 0,forDerivatives:{extends:"default",createOrder:{triggerPriceType:void 0,attachedStopLossTakeProfit:{triggerPriceType:void 0,price:!1}}},swap:{linear:{extends:"forDerivatives"},inverse:void 0},future:{linear:void 0,inverse:void 0}},commonCurrencies:{},exceptions:{exact:{"-1000":n.ExchangeError,"-1001":n.AuthenticationError,"-1002":n.AuthenticationError,"-1003":n.RateLimitExceeded,"-1004":n.BadRequest,"-1005":n.BadRequest,"-1006":n.InvalidOrder,"-1007":n.BadRequest,"-1008":n.InvalidOrder,"-1009":n.InsufficientFunds,"-1011":n.NetworkError,"-1012":n.BadRequest,"-1101":n.InsufficientFunds,"-1102":n.InvalidOrder,"-1103":n.InvalidOrder,"-1104":n.InvalidOrder,"-1105":n.InvalidOrder,"-1201":n.BadRequest,"-1202":n.BadRequest,29:n.BadRequest,9:n.AuthenticationError,3:n.AuthenticationError,2:n.BadRequest,15:n.BadRequest},broad:{}},precisionMode:4})}setSandboxMode(e){super.setSandboxMode(e),this.options.sandboxMode=e}async fetchStatus(e={}){let t=await this.v1PublicGetPublicSystemInfo(e),i=this.safeDict(t,"data",{}),s=this.safeString(i,"status");return{status:s=void 0===s?"error":"0"===s?"ok":"maintenance",updated:void 0,eta:void 0,url:void 0,info:t}}async fetchTime(e={}){let t=await this.v1PublicGetPublicSystemInfo(e);return this.safeInteger(t,"timestamp")}parseMarket(e){let t=this.safeString(e,"symbol",""),i=t.split("_"),s=this.safeString(i,1),r=this.safeString(i,2),a=this.safeCurrencyCode(s),o=this.safeCurrencyCode(r);if(void 0===a||void 0===o)return;let n=this.safeString(i,2),d=this.safeCurrencyCode(n);return this.safeMarketStructure({id:t,symbol:a+"/"+o+":"+d,base:a,quote:o,settle:d,baseId:s,quoteId:r,settleId:n,type:"swap",spot:!1,margin:!1,swap:!0,future:!1,option:!1,active:void 0,contract:!0,linear:!0,inverse:!1,contractSize:this.parseNumber("1"),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(e,"base_tick"),price:this.safeNumber(e,"quote_tick")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(e,"base_min"),max:this.safeNumber(e,"base_max")},price:{min:this.safeNumber(e,"quote_min"),max:this.safeNumber(e,"quote_max")},cost:{min:this.safeNumber(e,"min_notional"),max:void 0}},created:this.safeInteger(e,"created_time"),info:e})}async fetchMarkets(e={}){let t=await this.v1PublicGetPublicInfo(e),i=this.safeDict(t,"data",{}),s=this.safeList(i,"rows",[]);return this.parseMarkets(s)}async fetchCurrencies(e={}){let t=await this.v1PublicGetPublicToken(e),i=this.safeDict(t,"data",{}),s=this.safeList(i,"rows",[]);return this.parseCurrencies(s)}parseCurrency(e){let t,i=this.safeString(e,"token"),s=this.safeList(e,"chain_details",[]),r=this.safeCurrencyCode(i),a={};for(let e=0;e<s.length;e++){let i=s[e],r=this.safeString(i,"chain_id",""),o=this.parsePrecision(this.safeString(i,"decimals"));void 0!==o&&(t=void 0===t?o:d.Y.stringMin(o,t)),a[r]={id:r,network:r,limits:{withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},active:void 0,deposit:void 0,withdraw:void 0,fee:this.safeNumber(i,"withdrawal_fee"),precision:this.parseNumber(o),info:i}}return this.safeCurrencyStructure({id:i,name:i,code:r,precision:this.parseNumber(t),active:void 0,fee:void 0,networks:a,deposit:void 0,withdraw:void 0,limits:{deposit:{min:void 0,max:void 0},withdraw:{min:this.safeNumber(e,"minimum_withdraw_amount"),max:void 0}},info:e})}parseTokenAndFeeTemp(e,t,i){let s,r=this.safeString(e,i);if(void 0!==r){let i=this.safeString(e,t);s={cost:r,currency:this.safeCurrencyCode(i)}}return s}parseTrade(e,t){let i,s="id"in e,r=this.safeInteger(e,"executed_timestamp"),a=this.safeString(e,"symbol"),o=this.safeMarket(a,t),n=o.symbol,h=this.safeString(e,"executed_price"),c=this.safeString(e,"executed_quantity"),l=this.safeString(e,"order_id"),u=this.parseTokenAndFeeTemp(e,"fee_asset","fee"),f=this.safeString(u,"cost");void 0!==f&&void 0!==u&&(u.cost=f);let p=d.Y.stringMul(h,c),m=this.safeStringLower(e,"side"),g=this.safeString(e,"id");return s&&(i="1"===this.safeString(e,"is_maker")?"maker":"taker"),this.safeTrade({id:g,timestamp:r,datetime:this.iso8601(r),symbol:n,side:m,price:h,amount:c,cost:p,order:l,takerOrMaker:i,type:void 0,fee:u,info:e},o)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id};void 0!==i&&(a.limit=i);let o=await this.v1PublicGetPublicMarketTrades(this.extend(a,s)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"rows",[]);return this.parseTrades(d,r,t,i)}parseFundingRate(e,t){let i=this.safeString(e,"symbol"),s=void 0===i?t:this.market(i),r=this.safeInteger(e,"next_funding_time"),a=this.safeInteger(e,"est_funding_rate_timestamp"),o=this.safeInteger(e,"last_funding_rate_timestamp"),n=this.safeString(e,"last_funding_rate_timestamp"),h=this.safeString(e,"next_funding_time"),c=d.Y.stringSub(h,n);return{info:e,symbol:void 0!==s?s.symbol:void 0,markPrice:void 0,indexPrice:void 0,interestRate:this.parseNumber("0"),estimatedSettlePrice:void 0,timestamp:a,datetime:this.iso8601(a),fundingRate:this.safeNumber(e,"est_funding_rate"),fundingTimestamp:r,fundingDatetime:this.iso8601(r),nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:this.safeNumber(e,"last_funding_rate"),previousFundingTimestamp:o,previousFundingDatetime:this.iso8601(o),interval:this.parseFundingInterval(c)}}parseFundingInterval(e){return this.safeString({36e5:"1h",144e5:"4h",288e5:"8h",576e5:"16h",864e5:"24h"},e,e)}async fetchFundingInterval(e,t={}){return await this.fetchFundingRate(e,t)}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=await this.v1PublicGetPublicFundingRateSymbol(this.extend(s,t)),a=this.safeDict(r,"data",{});return this.parseFundingRate(a,i)}async fetchFundingRates(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.v1PublicGetPublicFundingRates(t),r=this.safeDict(s,"data",{}),a=this.safeList(r,"rows",[]);return this.parseFundingRates(a,i)}async fetchFundingRateHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(a)return await this.fetchPaginatedCallIncremental("fetchFundingRateHistory",e,t,i,o,"page",25);let n={};if(void 0!==e){let t=this.market(e);r=this.safeString(t,"symbol"),n.symbol=t.id}void 0!==t&&(n.start_t=t);let[d,h]=this.handleUntilOption("end_t",n,o,.001),c=await this.v1PublicGetPublicFundingRateHistory(this.extend(d,h)),l=this.safeDict(c,"data",{}),u=this.safeList(l,"rows",[]),f=[];for(let e=0;e<u.length;e++){let t=u[e],i=this.safeString(t,"symbol"),s=this.safeInteger(t,"funding_rate_timestamp");f.push({info:t,symbol:this.safeSymbol(i),fundingRate:this.safeNumber(t,"funding_rate"),timestamp:s,datetime:this.iso8601(s)})}let p=this.sortBy(f,"timestamp");return this.filterBySymbolSinceLimit(p,r,t,i)}parseIncome(e,t){let i=this.safeString(e,"symbol"),s=this.safeSymbol(i,t),r=this.safeString(e,"funding_fee"),a=this.safeCurrencyCode("USDC"),o=this.safeInteger(e,"updated_time"),n=this.safeNumber(e,"funding_rate");return r="Pay"===this.safeString(e,"payment_type")?d.Y.stringNeg(r):r,{info:e,symbol:s,code:a,timestamp:o,datetime:this.iso8601(o),id:void 0,amount:this.parseNumber(r),rate:n}}async fetchFundingHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchFundingHistory","paginate",!1);if(a)return await this.fetchPaginatedCallIncremental("fetchFundingHistory",e,t,i,o,"page",500);let n={};void 0!==e&&(n.symbol=(r=this.market(e)).id),void 0!==t&&(n.start_t=t);let d=this.safeInteger(o,"until"),h=this.omit(o,["until"]);void 0!==d&&(n.end_t=d),void 0!==i&&(n.size=Math.min(i,500));let c=await this.v1PrivateGetFundingFeeHistory(this.extend(n,h)),l=this.safeDict(c,"data",{}),u=this.safeList(l,"rows",[]);return this.parseIncomes(u,r,t,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v1PrivateGetClientInfo(e),i=this.safeDict(t,"data",{}),s=this.safeString(i,"futures_maker_fee_rate"),r=this.safeString(i,"futures_taker_fee_rate"),a={},o=this.symbols;if(void 0!==o)for(let e=0;e<o.length;e++){let i=o[e];a[i]={info:t,symbol:i,maker:this.parseNumber(d.Y.stringDiv(s,"10000")),taker:this.parseNumber(d.Y.stringDiv(r,"10000")),percentage:!0,tierBased:!0}}return a}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={symbol:this.market(e).id};void 0!==t&&(s.max_level=Math.min(t,1e3));let r=await this.v1PrivateGetOrderbookSymbol(this.extend(s,i)),a=this.safeDict(r,"data",{}),o=this.safeInteger(a,"timestamp");return this.parseOrderBook(a,e,o,"bids","asks","price","quantity")}parseOHLCV(e,t){return[this.safeInteger(e,"start_timestamp"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={symbol:a.id,type:this.safeString(this.timeframes,t,t)};void 0!==s&&(o.limit=Math.min(s,1e3));let n=await this.v1PrivateGetKline(this.extend(o,r)),d=this.safeDict(n,"data",{}),h=this.safeList(d,"rows",[]);return this.parseOHLCVs(h,a,t,i,s)}parseOrder(e,t){let i,s,r=this.safeIntegerN(e,["timestamp","created_time","createdTime"]),a=this.safeStringN(e,["order_id","orderId","algoOrderId"]),o=this.omitZero(this.safeString2(e,"client_order_id","clientOrderId")),n=this.safeString(e,"symbol"),h=this.safeMarket(n,t),c=h.symbol,l=this.safeString2(e,"order_price","price"),u=this.safeString2(e,"order_quantity","quantity"),f=this.safeString2(e,"order_amount","amount"),p=this.safeStringLower2(e,"order_type","type"),m=this.safeString2(e,"status","algoStatus"),g=this.safeBool(e,"success");void 0!==g&&(m=g?"NEW":"REJECTED");let v=this.safeStringLower(e,"side"),y=this.omitZero(this.safeString2(e,"executed","totalExecutedQuantity")),b=this.omitZero(this.safeString2(e,"average_executed_price","averageExecutedPrice")),w=d.Y.stringSub(f,y),k=this.safeNumber2(e,"total_fee","totalFee"),S=this.safeString2(e,"fee_asset","feeAsset"),O=this.safeList(e,"Transactions"),T=this.safeNumber(e,"triggerPrice"),P=this.safeList(e,"childOrders");if(void 0!==P){let e=this.safeDict(P,0),t=this.safeList(e,"childOrders",[]);if(t.length>0){let e=this.safeDict(t,0),r=this.safeDict(t,1);i=this.safeNumber(e,"triggerPrice"),s=this.safeNumber(r,"triggerPrice")}}let I=this.safeInteger2(e,"updatedTime","updated_time");return this.safeOrder({id:a,clientOrderId:o,timestamp:r,datetime:this.iso8601(r),lastTradeTimestamp:void 0,lastUpdateTimestamp:I,status:this.parseOrderStatus(m),symbol:c,type:this.parseOrderType(p),timeInForce:this.parseTimeInForce(p),postOnly:void 0,reduceOnly:this.safeBool(e,"reduce_only"),side:v,price:l,triggerPrice:T,takeProfitPrice:i,stopLossPrice:s,average:b,amount:u,filled:y,remaining:w,cost:f,trades:O,fee:{cost:k,currency:S},info:e},h)}parseTimeInForce(e){if(void 0!==e)return this.safeString({ioc:"IOC",fok:"FOK",post_only:"PO"},e)}parseOrderStatus(e){if(void 0!==e&&void 0!==e)return this.safeString({NEW:"open",FILLED:"closed",CANCEL_SENT:"canceled",CANCEL_ALL_SENT:"canceled",CANCELLED:"canceled",PARTIAL_FILLED:"open",REJECTED:"rejected",INCOMPLETE:"open",COMPLETED:"closed"},e,e)}parseOrderType(e){if(void 0!==e)return this.safeStringLower({LIMIT:"limit",MARKET:"market",POST_ONLY:"limit"},e,e)}createOrderRequest(e,t,i,s,r,a={}){if(void 0===i)throw new n.ArgumentsRequired(this.id+" requires a side argument");if(void 0===t)throw new n.ArgumentsRequired(this.id+" requires a type argument");let o=this.safeBool2(a,"reduceOnly","reduce_only"),d=t.toUpperCase(),h=this.market(e);if(void 0===i)throw new n.ArgumentsRequired(this.id+" createOrder() requires a side argument");let c=i.toUpperCase(),l={symbol:h.id,side:c},u=this.safeString2(a,"triggerPrice","stopPrice"),f=this.safeValue(a,"stopLoss"),p=this.safeValue(a,"takeProfit"),m=void 0!==f,g=void 0!==p,v=this.safeString(a,"algoType"),y=void 0!==u||m||g||void 0!==this.safeValue(a,"childOrders"),b="MARKET"===d,w=this.safeStringLower(a,"timeInForce"),k=this.isPostOnly(b,void 0,a),S="order_quantity";y&&(S="quantity");let O="order_price";y&&(O="price");let T="order_type";y&&(T="type"),l[T]=d,y||(k?l.order_type="POST_ONLY":"fok"===w?l.order_type="FOK":"ioc"===w&&(l.order_type="IOC")),!0===o&&(l.reduce_only=o),void 0!==r&&(l[O]=this.priceToPrecision(e,r)),b&&!y?l[S]=this.amountToPrecision(e,s):"POSITIONAL_TP_SL"!==v&&(l[S]=this.amountToPrecision(e,s));let P=this.safeStringN(a,["clOrdID","clientOrderId","client_order_id"]);if(void 0!==P&&(l.client_order_id=P),void 0!==u)l.trigger_price=this.priceToPrecision(e,u),l.algo_type="STOP";else if(m||g){l.algo_type="TP_SL";let t={symbol:h.id,reduce_only:!1,algo_type:"POSITIONAL_TP_SL",child_orders:[]},i=t.child_orders,s="BUY";if("BUY"===c&&(s="SELL"),m){let t=this.safeNumber2(f,"triggerPrice","price",f),r={side:s,algo_type:"TP_SL",trigger_price:this.priceToPrecision(e,t),type:"LIMIT",reduce_only:!0};i.push(r)}if(g){let t=this.safeNumber2(p,"triggerPrice","price",p),r={side:s,algo_type:"TP_SL",trigger_price:this.priceToPrecision(e,t),type:"LIMIT",reduce_only:!0};i.push(r)}l.child_orders=[t]}let I=this.omit(a,["reduceOnly","reduce_only","clOrdID","clientOrderId","client_order_id","postOnly","timeInForce","stopPrice","triggerPrice","stopLoss","takeProfit"]);return this.extend(l,I)}async createOrder(e,t,i,s,r,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=this.createOrderRequest(e,t,i,s,r,a),h=this.safeString2(a,"triggerPrice","stopPrice"),c=this.safeValue(a,"stopLoss"),l=this.safeValue(a,"takeProfit");o=void 0!==h||void 0!==c||void 0!==l||void 0!==this.safeValue(a,"childOrders")?await this.v1PrivatePostAlgoOrder(d):await this.v1PrivatePostOrder(d);let u=this.safeDict(o,"data",{});u.timestamp=this.safeInteger(o,"timestamp");let f=this.parseOrder(u,n);return f.type=t,f}async createOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=[];for(let t=0;t<e.length;t++){let s=this.safeDict(e,t),r=this.safeString(s,"symbol");if(void 0===r)throw new n.ArgumentsRequired(this.id+" createOrders() requires a symbol for each order");let a=this.safeString(s,"type",""),o=this.safeString(s,"side"),d=this.safeValue(s,"amount"),h=this.safeValue(s,"price"),c=this.safeDict(s,"params",{}),l=this.safeString2(c,"triggerPrice","stopPrice"),u=this.safeDict(c,"stopLoss"),f=this.safeDict(c,"takeProfit");if(void 0!==l||void 0!==u||void 0!==f||void 0!==this.safeValue(c,"childOrders"))throw new n.NotSupported(this.id+" createOrders() only support non-stop order");let p=this.createOrderRequest(r,a,o,d,h,c);i.push(p)}let s=await this.v1PrivatePostBatchOrder(this.extend({orders:i},t)),r=this.safeDict(s,"data",{}),a=this.safeList(r,"rows",[]);return this.parseOrders(a)}async editOrder(e,t,i,s,r,a,o={}){let n;void 0===this.markets&&await this.loadMarkets();let d=this.market(t),h={order_id:e},c=this.safeStringN(o,["triggerPrice","stopPrice","takeProfitPrice","stopLossPrice"]);void 0!==c&&(h.triggerPrice=this.priceToPrecision(t,c));let l=void 0!==c||void 0!==this.safeValue(o,"childOrders"),u="order_quantity";l&&(u="quantity");let f="order_price";l&&(f="price"),void 0!==a&&(h[f]=this.priceToPrecision(t,a)),void 0!==r&&(h[u]=this.amountToPrecision(t,r));let p=this.omit(o,["stopPrice","triggerPrice","takeProfitPrice","stopLossPrice","trailingTriggerPrice","trailingAmount","trailingPercent"]);if(l)n=await this.v1PrivatePutAlgoOrder(this.extend(h,p));else{h.symbol=d.id,void 0!==s&&(h.side=s.toUpperCase());let e=i.toUpperCase(),t=this.safeStringLower(p,"timeInForce"),r="MARKET"===e;this.isPostOnly(r,void 0,p)?h.order_type="POST_ONLY":"fok"===t?h.order_type="FOK":"ioc"===t?h.order_type="IOC":h.order_type=e;let a=this.safeStringN(p,["clOrdID","clientOrderId","client_order_id"]),o=this.omit(p,["clOrdID","clientOrderId","client_order_id","postOnly","timeInForce"]);void 0!==a&&(h.client_order_id=a),n=await this.v1PrivatePutOrder(this.extend(h,o))}let m=this.safeDict(n,"data",{});return m.timestamp=this.safeInteger(n,"timestamp"),this.parseOrder(m,d)}async cancelOrder(e,t,i={}){let s,r,a=this.safeBool2(i,"stop","trigger",!1),o=this.omit(i,["stop","trigger"]);if(!0!==a&&void 0===t)throw new n.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(r=this.market(t));let d={symbol:this.safeString(r,"id")},h=this.safeString2(o,"clOrdID","clientOrderId"),c=this.safeString(o,"client_order_id",h),l=void 0!==c,u=this.omit(o,["clOrdID","clientOrderId","client_order_id"]);!0===a?l?(d.client_order_id=c,s=await this.v1PrivateDeleteAlgoClientOrder(this.extend(d,u))):(d.order_id=e,s=await this.v1PrivateDeleteAlgoOrder(this.extend(d,o))):l?(d.client_order_id=c,s=await this.v1PrivateDeleteClientOrder(this.extend(d,u))):(d.order_id=e,s=await this.v1PrivateDeleteOrder(this.extend(d,o)));let f={symbol:t};if(l?f.client_order_id=c:f.id=e,!0===a)return this.extend(this.parseOrder(s),f);let p=this.safeDict(s,"data",{});return this.extend(this.parseOrder(p),f)}async cancelOrders(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.safeListN(i,["clOrdIDs","clientOrderIds","client_order_ids"]),a=this.omit(i,["clOrdIDs","clientOrderIds","client_order_ids"]),o={};return void 0!==r?(o.client_order_ids=r.join(","),s=await this.v1PrivateDeleteClientBatchOrder(this.extend(o,a))):(o.order_ids=e.join(","),s=await this.v1PrivateDeleteBatchOrder(this.extend(o,a))),[this.safeOrder({info:s})]}async cancelAllOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.safeBool2(t,"stop","trigger"),r=this.omit(t,["stop","trigger"]),a={};return void 0!==e&&(a.symbol=this.market(e).id),i=!0===s?await this.v1PrivateDeleteAlgoOrders(this.extend(a,r)):await this.v1PrivateDeleteOrders(this.extend(a,r)),[this.safeOrder({info:i})]}async fetchOrder(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(r=this.market(t));let a=this.safeBool2(i,"stop","trigger",!1),o={},n=this.safeStringN(i,["clOrdID","clientOrderId","client_order_id"]),d=this.omit(i,["stop","trigger","clOrdID","clientOrderId","client_order_id"]);!0===a?void 0!==n&&""!==n?(o.client_order_id=n,s=await this.v1PrivateGetAlgoClientOrderClientOrderId(this.extend(o,d))):(o.oid=e,s=await this.v1PrivateGetAlgoOrderOid(this.extend(o,d))):void 0!==n&&""!==n?(o.client_order_id=n,s=await this.v1PrivateGetClientOrderClientOrderId(this.extend(o,d))):(o.oid=e,s=await this.v1PrivateGetOrderOid(this.extend(o,d)));let h=this.safeDict(s,"data",s);return this.parseOrder(h,r)}async fetchOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o=this.safeBool2(s,"stop","trigger",!1),n=!0===o?100:500,[d,h]=this.handleOptionBoolAndParams(s,"fetchOrders","paginate",!1);if(d)return await this.fetchPaginatedCallIncremental("fetchOrders",e,t,i,h,"page",n);let c={},l=this.omit(h,["stop","trigger"]);void 0!==e&&(c.symbol=(a=this.market(e)).id),void 0!==t&&(c.start_t=t),void 0!==i?c.size=Math.min(i,n):c.size=n,!0===o&&(c.algo_type="STOP");let[u,f]=this.handleUntilOption("end_t",c,l);r=!0===o?await this.v1PrivateGetAlgoOrders(this.extend(u,f)):await this.v1PrivateGetOrders(this.extend(u,f));let p=this.safeDict(r,"data",r),m=this.safeList(p,"rows",[]);return this.parseOrders(m,a,t,i)}async fetchOpenOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.extend(s,{status:"INCOMPLETE"});return await this.fetchOrders(e,t,i,r)}async fetchClosedOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.extend(s,{status:"COMPLETED"});return await this.fetchOrders(e,t,i,r)}async fetchOrderTrades(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(a=this.market(t));let o=await this.v1PrivateGetOrderOidTrades(this.extend({oid:e},r)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"rows",[]);return this.parseTrades(d,a,i,s,r)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(a)return await this.fetchPaginatedCallIncremental("fetchMyTrades",e,t,i,o,"page",500);let n={};void 0!==e&&(n.symbol=(r=this.market(e)).id),void 0!==t&&(n.start_t=t),void 0!==i?n.size=i:n.size=500;let[d,h]=this.handleUntilOption("end_t",n,o),c=await this.v1PrivateGetTrades(this.extend(d,h)),l=this.safeDict(c,"data",{}),u=this.safeList(l,"rows",[]);return this.parseTrades(u,r,t,i,h)}parseBalance(e){let t={info:e},i=this.safeList(e,"holding",[]);for(let e=0;e<i.length;e++){let s=this.safeDict(i,e),r=this.safeCurrencyCode(this.safeString(s,"token")),a=this.account();a.total=this.safeString(s,"holding"),a.used=this.safeString(s,"frozen"),void 0!==r&&(t[r]=a)}return this.safeBalance(t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.v1PrivateGetClientHolding(e),i=this.safeDict(t,"data");return this.parseBalance(i)}async getAssetHistoryRows(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.token=(r=this.currency(e)).id),void 0!==t&&(a.start_t=t),void 0!==i&&(a.size=i);let o=this.safeString(s,"type"),n=this.omit(s,"type");void 0!==o&&(a.type=o);let d=await this.v1PrivateGetAssetHistory(this.extend(a,n)),h=this.safeDict(d,"data",{});return[r,this.safeList(h,"rows",[])]}parseLedgerEntry(e,t){let i,s,r=this.safeString(e,"token"),a=this.safeCurrencyCode(r,t),o=this.safeCurrency(r,t),n=this.safeNumber(e,"amount"),d=this.safeString(e,"side");void 0!==d&&(i="DEPOSIT"===d?"in":"out");let h=this.safeInteger(e,"created_time"),c=this.parseNumber(this.safeString(e,"fee"));return void 0!==c&&(s={currency:a,cost:c}),this.safeLedgerEntry({id:this.safeString(e,"id"),currency:a,account:void 0,referenceAccount:void 0,referenceId:this.safeString(e,"tx_id"),status:this.parseTransactionStatus(this.safeString(e,"trans_status")),amount:n,before:void 0,after:void 0,fee:s,direction:i,timestamp:h,datetime:this.iso8601(h),type:this.parseLedgerEntryType(this.safeString2(e,"type","side")),info:e},o)}parseLedgerEntryType(e){return this.safeString({BALANCE:"transaction",COLLATERAL:"transfer",DEPOSIT:"transaction",WITHDRAW:"transaction"},e,e)}async fetchLedger(e,t,i,s={}){let r=await this.getAssetHistoryRows(e,t,i,s),a=this.safeValue(r,0),o=this.safeList(r,1);return this.parseLedger(o,a,t,i,s)}parseTransaction(e,t){let i,s=this.safeString(e,"token"),r=this.safeCurrencyCode(s,t),a=this.safeStringLower(e,"side");"withdraw"===a&&(a="withdrawal");let o=this.parseNumber(this.safeString(e,"fee"));void 0!==o&&(i={currency:r,cost:o});let n=this.safeInteger(e,"created_time");return{info:e,id:this.safeString2(e,"id","withdraw_id"),txid:this.safeString(e,"tx_id"),timestamp:n,datetime:this.iso8601(n),address:void 0,addressFrom:void 0,addressTo:void 0,tag:void 0,tagFrom:void 0,tagTo:void 0,type:a,amount:this.safeNumber(e,"amount"),currency:r,status:this.parseTransactionStatus(this.safeString(e,"trans_status")),updated:this.safeInteger(e,"updated_time"),comment:void 0,internal:void 0,fee:i,network:void 0}}parseTransactionStatus(e){if(void 0!==e)return this.safeString({NEW:"pending",CONFIRMING:"pending",PENDING:"pending",PENDING_REBALANCE:"pending",PROCESSING:"pending",COMPLETED:"ok",FAILED:"failed",CANCELED:"canceled"},e,e)}async fetchDeposits(e,t,i,s={}){return await this.fetchDepositsWithdrawals(e,t,i,this.extend({side:"DEPOSIT"},s))}async fetchWithdrawals(e,t,i,s={}){return await this.fetchDepositsWithdrawals(e,t,i,this.extend({side:"WITHDRAW"},s))}async fetchDepositsWithdrawals(e,t,i,s={}){let r=await this.getAssetHistoryRows(e,t,i,this.extend({},s)),a=this.safeValue(r,0),o=this.safeList(r,1,[]),n=this.omit(s,"side");return this.parseTransactions(o,a,t,i,n)}async getWithdrawNonce(e={}){let t=await this.v1PrivateGetWithdrawNonce(e),i=this.safeDict(t,"data",{});return this.safeNumber(i,"withdraw_nonce")}hashMessage(e){return"0x"+this.hash(e,r.lY,"hex")}signHash(e,t){let i=(0,h.h1)(e.slice(-64),t.slice(-64),a.bI,void 0),s=i.r,r=i.s,o=this.intToBase16(this.sum(27,i.v));return"0x"+s.padStart(64,"0")+r.padStart(64,"0")+o}signMessage(e,t){return this.signHash(this.hashMessage(e),t.slice(-64))}async withdraw(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets(),this.checkAddress(i);let a=e.toUpperCase();if("USDC"!==a)throw new n.NotSupported(this.id+" withdraw() only support USDC");let o=this.currency(a),d=this.safeString(this.options,"verifyingContractAddress"),h=this.safeString(r,"chainId"),c=this.safeDict(o,"networks",{}),l=void 0===h?{}:this.safeDict(c,h,{});if(void 0===this.safeNumber(l,"id"))throw new n.BadRequest(this.id+" withdraw() require chainId parameter");let u=await this.getWithdrawNonce(r),f=this.nonce(),p={brokerId:this.safeString(this.options,"keyBrokerId","mode"),chainId:this.parseToInt(h),receiver:i,token:a,amount:t.toString(),withdrawNonce:u,timestamp:f},m=this.ethEncodeStructuredData({chainId:h,name:"Orderly",verifyingContract:d,version:"1"},{Withdraw:[{name:"brokerId",type:"string"},{name:"chainId",type:"uint256"},{name:"receiver",type:"address"},{name:"token",type:"string"},{name:"amount",type:"uint256"},{name:"withdrawNonce",type:"uint64"},{name:"timestamp",type:"uint64"}]},p),g=this.signMessage(m,this.privateKey),v=this.omit(r,"chainId"),y=await this.v1PrivatePostWithdrawRequest(this.extend({signature:g,userAddress:i,verifyingContract:d,message:p},v)),b=this.safeDict(y,"data",{});return this.parseTransaction(b,o)}parseLeverage(e,t){let i=this.safeInteger(e,"max_leverage");return{info:e,symbol:this.safeString(t,"symbol"),marginMode:void 0,longLeverage:i,shortLeverage:i}}async fetchLeverage(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=await this.v1PrivateGetClientInfo(t),r=this.safeDict(s,"data",{});return this.parseLeverage(r,i)}async setLeverage(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=e<1,r=e>50;if(s||r)throw new n.BadRequest(this.id+" leverage should be between 1 and 50");return await this.v1PrivatePostClientLeverage(this.extend({leverage:e},i))}parsePosition(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=this.safeString(e,"position_qty");i=d.Y.stringGt(a,"0")?"long":"short";let o=this.safeString(r,"contractSize"),n=this.safeString(e,"mark_price"),h=this.safeInteger(e,"timestamp"),c=this.safeString(e,"average_open_price"),l=this.safeString(e,"unsettled_pnl");a=d.Y.stringAbs(a);let u=d.Y.stringMul(a,n);return this.safePosition({info:e,id:void 0,symbol:this.safeString(r,"symbol"),timestamp:h,datetime:this.iso8601(h),lastUpdateTimestamp:void 0,initialMargin:void 0,initialMarginPercentage:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,entryPrice:this.parseNumber(c),notional:this.parseNumber(u),leverage:void 0,unrealizedPnl:this.parseNumber(l),contracts:this.parseNumber(a),contractSize:this.parseNumber(o),marginRatio:void 0,liquidationPrice:this.safeNumber(e,"est_liq_price"),markPrice:this.parseNumber(n),lastPrice:void 0,collateral:void 0,marginMode:"cross",side:i,percentage:void 0,hedged:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}async fetchPosition(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new n.ArgumentsRequired(this.id+" fetchPosition() requires a symbol argument");let i=this.market(e),s={symbol:i.id},r=await this.v1PrivateGetPositionSymbol(this.extend(s,t)),a=this.safeDict(r,"data",{});return this.parsePosition(a,i)}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.v1PrivateGetPositions(t),s=this.safeDict(i,"data",{}),r=this.safeList(s,"rows",[]);return this.parsePositions(r,e)}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},a,o){let d=t[0],c=t[1],l=this.implodeParams(e,r),u=this.safeString(this.urls.api,c);if(void 0===u)throw new n.ExchangeError(this.id+" sign() has no API URL for this endpoint");let f=u+"/"+d+"/",p=this.keysort(this.omit(r,this.extractParams(e)));if("public"===c)f+=l,Object.keys(p).length>0&&(f+="?"+this.urlencode(p));else{let t;this.checkRequiredCredentials();let r="POST"===i||"PUT"===i,a="algo/order"===e||"order"===e||"batch-order"===e;if(r&&a&&!0!==this.safeBool(this.options,"sandboxMode",!1)){let t=this.safeString(this.options,"brokerId","CCXTMODE");if("batch-order"===e){let e=this.safeList(p,"orders",[]);for(let i=0;i<e.length;i++)p.orders[i].order_tag=t}else p.order_tag=t}let n=p;r&&a&&(n=this.keysort(p));let c="",u=this.nonce().toString();f+=l;let m=this.apiKey;0>m.indexOf("ed25519:")&&(m="ed25519:"+m);let g={"orderly-account-id":this.accountId,"orderly-key":m,"orderly-timestamp":u};c=u+i+"/"+d+"/"+l,"POST"===i||"PUT"===i?(c+=t=this.json(n),g["content-type"]="application/json"):(Object.keys(n).length>0&&(f+="?"+this.urlencode(n),c+="?"+this.rawencode(n)),g["content-type"]="application/x-www-form-urlencoded",t="DELETE"===i?"":o);let v=this.secret;v.indexOf("ed25519:")>=0&&(v=v.split("ed25519:")[1]);let y=(0,h.q4)(this.encode(c),this.base58ToBinary(v),s.ev);return g["orderly-signature"]=this.urlencodeBase64(this.base64ToBinary(y)),{url:f,method:i,body:t,headers:g}}return{url:f,method:i,body:o,headers:a}}handleErrors(e,t,i,s,r,a,o,d,h){if(null==o)return;let c=this.safeBool(o,"success"),l=this.safeString(o,"code");if(!0!==c){let e=this.id+" "+this.json(o);throw this.throwBroadlyMatchedException(this.exceptions.broad,a,e),this.throwExactlyMatchedException(this.exceptions.exact,l,e),new n.ExchangeError(e)}}}i.d(t,{A:()=>c})},6555(e,t,i){"use strict";var s=i(2202),r=i(1453),a=i(7749);class o extends s.A{describe(){return this.deepExtend(super.describe(),{id:"mudrex",name:"Mudrex",countries:["IN"],rateLimit:100,version:"v1",pro:!0,certified:!1,dex:!1,hostname:"trade.mudrex.com",has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!1,option:!1,addMargin:!0,cancelOrder:!0,closePosition:!0,createMarketOrder:!0,createOrder:!0,createOrderWithTakeProfitAndStopLoss:!0,createReduceOnlyOrder:!0,editOrder:!0,fetchBalance:!0,fetchClosedOrders:!0,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchIndexOHLCV:!1,fetchLeverage:!0,fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!1,fetchOrders:!0,fetchPositions:!0,fetchPositionsHistory:!0,fetchTicker:!0,fetchTickers:!0,fetchTrades:!1,reduceMargin:!0,setLeverage:!0,transfer:!0,watchOHLCV:!0,watchTicker:!0,watchTickers:!0},timeframes:{"1m":"1m","3m":"3t","5m":"5t","10m":"10t","15m":"15t","30m":"30t","1h":"1h","4h":"4h","6h":"6h","12h":"12h","1d":"1d","1w":"1w","1M":"1mth"},urls:{logo:"https://github.com/user-attachments/assets/72368864-84ed-43eb-8c75-d4fb77023b42",api:{public:"https://trade.mudrex.com/fapi/v1",private:"https://trade.mudrex.com/fapi/v1",market:"https://trade.mudrex.com/fapi/v1"},www:"https://mudrex.com",doc:"https://docs.trade.mudrex.com/docs",fees:"https://docs.trade.mudrex.com"},api:{market:{get:{"price/kline":{cost:1},"price/mark-kline":{cost:1}}},public:{get:{}},private:{get:{futures:{cost:1},"futures/{asset_id}":{cost:1},"wallet/funds":{cost:5},"futures/funds":{cost:5},"futures/transactions":{cost:1},"futures/orders":{cost:1},"futures/orders/history":{cost:1},"futures/orders/{order_id}":{cost:1},"futures/positions":{cost:1},"futures/positions/history":{cost:1},"futures/fee/history":{cost:1},"futures/{asset_id}/leverage":{cost:2},"futures/positions/{position_id}/liq-price":{cost:1}},post:{"wallet/futures/transfer":{cost:5},"futures/transfers/inr":{cost:5},"futures/{asset_id}/order":{cost:2},"futures/positions/{position_id}/close":{cost:2},"futures/positions/{position_id}/close/partial":{cost:2},"futures/positions/{position_id}/reverse":{cost:2},"futures/positions/{position_id}/add-margin":{cost:2},"futures/positions/{position_id}/riskorder":{cost:2},"futures/{asset_id}/leverage":{cost:2}},patch:{"futures/orders/{order_id}":{cost:1},"futures/positions/{position_id}/riskorder":{cost:2}},delete:{"futures/orders/{order_id}":{cost:2}}}},requiredCredentials:{apiKey:!1,secret:!0},fees:{trading:{tierBased:!1,percentage:!0,taker:this.parseNumber("0.00059"),maker:this.parseNumber("0.00023")}},options:{defaultType:"swap",broker:"42ce8902-8585-448c-a1e8-0371a6ca7ca8"},exceptions:{exact:{"400 Invalid trade currency":r.BadRequest},broad:{"Invalid trade currency":r.BadRequest,"Params error":r.BadRequest,"invalid trigger type":r.BadRequest,"invalid order type":r.BadRequest,"order price out of permissible range":r.BadRequest,"quantity not a multiple of the quantity step":r.BadRequest,"leverage out of permissible range":r.BadRequest,"insufficient balance":r.InsufficientFunds,"asset not found":r.BadSymbol,"leverage not found":r.OrderNotFound,"order not found":r.OrderNotFound,"Rate limit exceeded":r.RateLimitExceeded}}})}sign(e,t="public",i="GET",s={},a,o){let n=this.safeDict(this.urls,"api",{}),d=this.safeString(n,t);if(void 0===d)throw new r.ExchangeError(this.id+" unknown API namespace: "+t);let h=d+"/"+this.implodeParams(e,s),c=this.omit(s,this.extractParams(e)),l={};void 0!==a&&(l=this.extend({},a));let u=this.safeString(this.options,"broker");void 0!==u&&(l["Partner-Id"]=u);let f=i.toUpperCase();if("private"===t&&(this.checkRequiredCredentials(),l["X-Authentication"]=this.secret,"POST"===f||"PATCH"===f||"DELETE"===f)){l["Content-Type"]="application/json";let e=this.safeString(c,"is_symbol");return(void 0!==e&&(c=this.omit(c,"is_symbol"),h+="?"+this.urlencode({is_symbol:e})),"DELETE"===f&&this.isEmpty(c))?{url:h,method:f,body:void 0,headers:l}:{url:h,method:f,body:this.json(c),headers:l}}return Object.keys(c).length>0&&(h+="?"+this.urlencode(c)),{url:h,method:f,body:void 0,headers:l}}handleErrors(e,t,i,s,a,o,n,d,h){if(void 0!==n&&"object"==typeof n&&!0!==this.safeBool(n,"success",!0)){let t=this.safeList(n,"errors",[]),i=this.safeDict(t,0,{}),s=this.safeString(i,"text",this.json(n)),a=this.safeString(i,"code");this.throwExactlyMatchedException(this.exceptions.exact,s,this.id+" "+s),this.throwExactlyMatchedException(this.exceptions.exact,a,this.id+" "+s),this.throwBroadlyMatchedException(this.exceptions.broad,s,this.id+" "+s);let o=this.id+" "+s,d=s.toLowerCase();if(401===e||d.indexOf("auth")>=0)throw new r.AuthenticationError(o);if(429===e||d.indexOf("rate")>=0)throw new r.RateLimitExceeded(o);if(d.indexOf("insufficient")>=0)throw new r.InsufficientFunds(o);if(400===e)throw new r.BadRequest(o);throw new r.ExchangeError(o)}}parseOHLCV(e,t){return[this.safeTimestamp(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]}async fetchOHLCV(e,t="1m",i,s,a={}){let o,n;void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h=this.safeString(a,"price"),c=d.baseId+"/"+d.quoteId,l={assets:c,aggregation:this.safeString(this.timeframes,t,t)},u=this.parseTimeframe(t),f=s;void 0===f&&(f=500);let p=this.seconds();if(void 0===(n=void 0!==i?this.parseToInt(i/1e3):p-u*f))throw new r.ExchangeError(this.id+" fetchOHLCV() missing startTime");let m=n+u*f,g=this.safeInteger(a,"until"),v=this.omit(a,["price","until"]);void 0!==g?m=this.parseToInt(g/1e3):m>p&&(m=p),l.start_time=n,l.end_time=m,o="mark"===h?await this.marketGetPriceMarkKline(this.extend(l,v)):await this.marketGetPriceKline(this.extend(l,v));let y=this.safeDict(o,"data",{}),b=this.safeDict(y,"asset_ticks",{}),w=this.safeList(b,c.toLowerCase(),[]);return this.parseOHLCVs(w,d,t,i,s)}async fetchMarkOHLCV(e,t="1m",i,s,r={}){return await this.fetchOHLCV(e,t,i,s,this.extend(r,{price:"mark"}))}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={asset_id:i.id,is_symbol:1},r=await this.privateGetFuturesAssetId(this.extend(s,t)),a=this.safeDict(r,"data",{});return this.parseTicker(a,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privateGetFutures(this.extend({},t)),s=this.safeValue(i,"data",[]),r=Array.isArray(s)?s:this.safeList(s,"items",[]),a={};for(let t=0;t<r.length;t++){let i=r[t],s=this.safeString(i,"symbol");if(void 0===s)continue;let o=this.safeMarket(s),n=o.symbol;(void 0===e||this.inArray(n,e))&&(a[n]=this.parseTicker(i,o))}return this.filterByArrayTickers(a,"symbol",e)}parseTicker(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=s.symbol,a=this.safeNumber(e,"change_perc");return this.safeTicker({symbol:r,timestamp:void 0,datetime:void 0,high:void 0,low:void 0,bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:this.safeNumber(e,"last_day_price"),close:this.safeNumber(e,"price"),last:this.safeNumber(e,"price"),previousClose:void 0,change:void 0,percentage:a,average:void 0,baseVolume:void 0,quoteVolume:this.safeNumber(e,"volume"),info:e},s)}async fetchMarkets(e={}){let t=[],i=0,s=!0;for(;!0===s;){let r=this.extend({limit:100,offset:i},e),a=await this.privateGetFutures(r),o=this.safeValue(a,"data",[]),n=[];if("object"!=typeof o||Array.isArray(o))n=this.toArray(o);else{let e=(n=this.safeList(o,"items",[])).length;0===e&&(e=(n=this.safeList(o,"results",[])).length),0===e&&"symbol"in o&&(n=[o])}let d=n.length;if(0===d){s=!1;break}for(let e=0;e<d;e++)t.push(n[e]);d<100?s=!1:i=this.sum(i,100)}let r=[];for(let e=0;e<t.length;e++)r.push(this.parseMarket(t[e]));return r}parseMarket(e){let t,i=this.safeString(e,"symbol"),s=i;void 0!==i&&i.endsWith("USDT")&&(s=i.slice(0,-4));let r="USDT",a="USDT";void 0!==s&&(t=s+"/"+r+":"+a);let o=this.safeString(e,"price_step","0.01"),n=this.safeString(e,"quantity_step","0.001");return this.safeMarketStructure({id:i,lowercaseId:void 0,symbol:t,base:s,quote:r,settle:a,baseId:s,quoteId:"USDT",settleId:"USDT",type:"swap",spot:!1,margin:!1,swap:!0,future:!1,option:!1,active:!0,contract:!0,linear:!0,inverse:!1,taker:this.safeNumber(this.fees.trading,"taker"),maker:this.safeNumber(this.fees.trading,"maker"),contractSize:this.safeNumber(e,"contract_size",1),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(n),price:this.parseNumber(o)},limits:{amount:{min:this.safeNumber(e,"min_contract"),max:this.safeNumber(e,"max_contract")},price:{min:this.safeNumber(e,"min_price"),max:this.safeNumber(e,"max_price")},cost:{min:this.safeNumber(e,"min_notional_value"),max:void 0}},info:e,created:void 0})}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleMarketTypeAndParams("fetchBalance",void 0,e,"swap"),a=this.safeStringN(s,["trade_currency","tradeCurrency","currency"]),o=this.omit(s,["trade_currency","tradeCurrency","currency"]),n={};"spot"===i?(void 0!==a&&(n.currency=a),t=await this.privateGetWalletFunds(this.extend(n,o))):(void 0!==a&&(n.trade_currency=a),t=await this.privateGetFuturesFunds(this.extend(n,o)));let d=a;if(void 0===d&&(d="USDT"),void 0===t)throw new r.NullResponse(this.id+" fetchBalance() returned empty response");return t.currency=d,this.parseBalance(t)}parseBalance(e){let t=this.safeDict(e,"data",{}),i=this.safeString(e,"currency","USDT"),s={info:e},r=this.account(),a=this.safeString(t,"balance");return void 0!==a?(r.free=a,r.used=this.safeString(t,"locked_amount")):(r.total=this.safeString(t,"total"),r.free=this.safeString(t,"withdrawable")),s[i]=r,this.safeBalance(s)}async fetchLeverage(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={asset_id:this.market(e).id,is_symbol:1},s=await this.privateGetFuturesAssetIdLeverage(this.extend(i,t)),r=this.safeDict(s,"data",{});return{info:s,symbol:e,marginMode:this.safeStringLower(r,"margin_type"),longLeverage:this.safeNumber(r,"leverage"),shortLeverage:this.safeNumber(r,"leverage")}}async setLeverage(e,t,i={}){if(void 0===t)throw new r.ArgumentsRequired(this.id+" setLeverage() requires a symbol");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),a=this.safeString(i,"marginType","ISOLATED"),o={asset_id:s.id,is_symbol:1,margin_type:a,leverage:e},n=this.omit(i,["marginType"]);return await this.privatePostFuturesAssetIdLeverage(this.extend(o,n))}async createOrder(e,t,i,s,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=this.safeString(o,"stopLossPrice"),h=this.safeString(o,"takeProfitPrice");if(void 0!==d||void 0!==h){let t=this.safeString2(o,"positionId","position_id");if(void 0===t)throw new r.ArgumentsRequired(this.id+" createOrder() requires a positionId parameter to place a stopLossPrice or takeProfitPrice order");let i=this.omit(o,["stopLossPrice","takeProfitPrice","positionId","position_id"]),s={position_id:t};void 0!==h&&(s.is_takeprofit=!0,s.takeprofit_price=this.priceToPrecision(e,h)),void 0!==d&&(s.is_stoploss=!0,s.stoploss_price=this.priceToPrecision(e,d));let a=await this.privatePostFuturesPositionsPositionIdRiskorder(this.extend(s,i)),c=this.safeDict(a,"data",a);return this.parseOrder(c,n)}let c=this.safeInteger(o,"leverage",1);if("market"===t&&void 0===a)throw new r.ArgumentsRequired(this.id+" createOrder() requires a price argument for market orders");let l={asset_id:n.id,is_symbol:1,leverage:this.numberToString(c),quantity:this.amountToPrecision(e,s),order_price:this.priceToPrecision(e,a),order_type:"buy"===i?"LONG":"SHORT",trigger_type:"market"===t?"MARKET":"LIMIT",reduce_only:this.safeBool(o,"reduceOnly",!1)},u=this.safeDict(o,"takeProfit"),f=this.safeDict(o,"stopLoss");void 0!==u&&(l.is_takeprofit=!0,l.takeprofit_price=this.priceToPrecision(e,this.safeStringN(u,["triggerPrice","stopPrice","price"]))),void 0!==f&&(l.is_stoploss=!0,l.stoploss_price=this.priceToPrecision(e,this.safeStringN(f,["triggerPrice","stopPrice","price"])));let p=this.omit(o,["leverage","reduceOnly","takeProfit","stopLoss"]),m=await this.privatePostFuturesAssetIdOrder(this.extend(l,p)),g=this.safeDict(m,"data",m),v=this.extend(g,{order_type:l.order_type,trigger_type:l.trigger_type}),y=this.parseOrder(v,n);return y.info=g,y}async editOrder(e,t,i,s,r,a,o={}){let n;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(n=this.market(t));let d={order_id:e};void 0!==r&&(d.quantity=this.amountToPrecision(t,r)),void 0!==a&&(d.order_price=this.priceToPrecision(t,a));let h=await this.privatePatchFuturesOrdersOrderId(this.extend(d,o)),c=this.safeDict(h,"data",h);return this.parseOrder(c,n)}parseOrderStatus(e){return this.safeString({open:"open",created:"open",new:"open",pending:"open",partially_filled:"open",filled:"closed",completed:"closed",cancelled:"canceled",canceled:"canceled",rejected:"rejected",expired:"expired"},e,e)}parseOrder(e,t){let i,s,r,a,o,n=this.safeString(e,"symbol"),d=this.safeMarket(n,t),h=this.safeString2(e,"order_id","id"),c=this.safeStringUpper(e,"order_type");"LONG"===c?i="buy":"SHORT"===c&&(i="sell");let l=this.safeString2(e,"price","order_price"),u=l;("STOPLOSS"===c||"TAKEPROFIT"===c)&&(s=l,u=void 0,"STOPLOSS"===c?r=l:a=l);let f=this.safeStringUpper(e,"trigger_type");"MARKET"===f?o="market":"LIMIT"===f&&(o="limit");let p=this.parse8601(this.safeString(e,"created_at")),m=this.parseOrderStatus(this.safeStringLower(e,"status")),g=d.symbol;return this.safeOrder({info:e,id:h,clientOrderId:void 0,timestamp:p,datetime:this.iso8601(p),lastTradeTimestamp:void 0,symbol:g,type:o,timeInForce:void 0,postOnly:void 0,side:i,price:u,triggerPrice:s,stopLossPrice:r,takeProfitPrice:a,amount:this.safeString2(e,"quantity","amount"),cost:void 0,average:this.safeString(e,"filled_price"),filled:this.safeString(e,"filled_quantity"),remaining:void 0,status:m,fee:void 0,trades:[],fees:[],lastUpdateTimestamp:this.parse8601(this.safeString(e,"updated_at")),reduceOnly:this.safeBool(e,"reduce_only")},d)}async cancelOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let r=await this.privateDeleteFuturesOrdersOrderId(this.extend({order_id:e},i)),a=this.safeDict(r,"data",r);return this.parseOrder(a,s)}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let r=await this.privateGetFuturesOrdersOrderId(this.extend({order_id:e},i)),a=this.safeDict(r,"data",r);return this.parseOrder(a,s)}async fetchOrdersByState(e,t,i,s,r={}){let a,o;void 0===this.markets&&await this.loadMarkets();let n={};void 0!==s&&(n.limit=s);let d=this.extend(n,r);a="closed"===e?await this.privateGetFuturesOrdersHistory(d):await this.privateGetFuturesOrders(d);let h=this.safeValue(a,"data",[]),c=this.toArray(h);void 0!==t&&(o=this.market(t));let l=[];for(let e=0;e<c.length;e++)l.push(this.parseOrder(c[e],o));return this.filterBySymbolSinceLimit(l,t,i,s)}async fetchOrders(e,t,i,s={}){return await this.fetchOrdersByState("closed",e,t,i,s)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrdersByState("open",e,t,i,s)}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrdersByState("closed",e,t,i,s)}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privateGetFuturesPositions(this.extend({},t)),s=this.safeValue(i,"data",[]);if(void 0===s)return[];let r=this.toArray(s),a=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.safeString(t,"symbol"),s=this.safeMarket(i),o=this.parsePosition(t,s);a.push(o)}return this.filterByArrayPositions(a,"symbol",e)}async fetchPositionsHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e),a={};void 0!==i&&(a.limit=i);let o=await this.privateGetFuturesPositionsHistory(this.extend(a,s)),n=this.safeList(o,"data",[]),d=this.parsePositions(n,r);return this.filterBySinceLimit(d,t,i)}parsePosition(e,t){let i,s,r=this.safeMarket(void 0,t),o=this.safeString(e,"symbol"),n=this.safeSymbol(o,r),d=this.safeStringUpper2(e,"order_type","position_type");"LONG"===d?i="long":"SHORT"===d&&(i="short");let h=this.parse8601(this.safeString(e,"updated_at"));void 0===h&&(h=this.parse8601(this.safeString(e,"created_at")));let c=this.safeString(e,"quantity"),l=this.safeString(e,"entry_price"),u=this.safeString(r,"contractSize","1");void 0!==c&&void 0!==l&&(s=this.parseNumber(a.Y.stringMul(a.Y.stringMul(c,l),u)));let f=this.safeString(e,"initial_margin");return{info:e,id:this.safeString(e,"id"),symbol:n,timestamp:h,datetime:this.iso8601(h),isolated:!0,hedged:!1,side:i,contracts:this.safeNumber(e,"quantity"),contractSize:this.safeNumber(r,"contractSize"),entryPrice:this.safeNumber(e,"entry_price"),markPrice:void 0,lastPrice:this.safeNumber(e,"closed_price"),notional:s,leverage:this.safeInteger(e,"leverage"),collateral:this.parseNumber(f),initialMargin:this.parseNumber(f),initialMarginPercentage:void 0,maintenanceMargin:this.safeNumber(e,"maintenance_margin"),maintenanceMarginPercentage:void 0,unrealizedPnl:void 0,realizedPnl:this.safeNumber(e,"pnl"),liquidationPrice:this.safeNumber(e,"liquidation_price"),marginMode:"isolated",percentage:void 0}}async closePosition(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.safeString(i,"position_id"),a=this.safeValue(i,"amount");if(void 0===s){let r=this.market(e),a=await this.fetchPositions([e],i);for(let e=0;e<a.length;e++){let i=a[e];if((void 0===t||i.side===t)&&i.symbol===r.symbol){s=this.safeString(i,"id");break}}}if(void 0===s)throw new r.OrderNotFound(this.id+" closePosition() could not resolve position_id");let o={position_id:s};if(void 0!==a){let t=this.safeStringUpper(i,"order_type","LIMIT");o.order_type=t,o.quantity=this.amountToPrecision(e,a);let s=this.safeString(i,"limit_price");"LIMIT"===t&&void 0!==s&&(o.limit_price=s);let r=this.omit(i,["order_type","limit_price","amount","position_id"]);return await this.privatePostFuturesPositionsPositionIdClosePartial(this.extend(o,r))}let n=this.omit(i,["position_id"]);return await this.privatePostFuturesPositionsPositionIdClose(this.extend(o,n))}async addMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.safeString(i,"position_id");if(void 0===s){let t=await this.fetchPositions([e],i);for(let i=0;i<t.length;i++){let r=t[i];if(r.symbol===e){s=this.safeString(r,"id");break}}}if(void 0===s)throw new r.OrderNotFound(this.id+" addMargin() could not resolve position_id");let a={position_id:s,margin:this.costToPrecision(e,t)},o=this.omit(i,["position_id"]),n=await this.privatePostFuturesPositionsPositionIdAddMargin(this.extend(a,o));return this.extend(n,{})}async reduceMargin(e,t,i={}){return await this.addMargin(e,-t,i)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let[a,o]=this.handleOptionIntegerAndParams(s,"fetchMyTrades","paginationCalls",10),n=0;void 0!==i&&(n=2*i);let d=[],h=0,c=0,l=0,u=!0;for(;!0===u;){let e={};n>0&&(e.limit=n,e.offset=l);let t=await this.privateGetFuturesFeeHistory(this.extend(e,o)),s=this.safeList(t,"data",[]),f=s.length;for(let e=0;e<f;e++){let t=s[e];d.push(t),"TRANSACTION"===this.safeString(t,"fee_type")&&(void 0===r||this.safeString(t,"symbol")===r.id)&&(h=this.sum(h,1))}c=this.sum(c,1),u=!1,void 0!==i&&f===n&&h<i&&c<a&&(l=this.sum(l,n),u=!0)}let f=[],p=[],m=[],g=[];for(let e=0;e<d.length;e++){let t=d[e],i=this.safeString(t,"fee_type"),s=this.safeString(t,"symbol","")+":"+this.safeString(t,"created_at","")+":"+this.safeString(t,"transaction_amount","");"TRANSACTION"===i?(m.push(t),g.push(s)):"REBATE"===i&&(f.push(s),p.push(this.safeString(t,"fee_amount","0")))}let v=[];for(let e=0;e<m.length;e++){let t;for(let i=0;i<f.length;i++)if(f[i]===g[e]){t=this.safeString(p,i),f[i]=void 0;break}void 0===t?v.push(m[e]):v.push(this.extend(m[e],{rebate_amount:t}))}return this.parseTrades(v,r,t,i)}parseTrade(e,t){let i,s,r,o=this.safeString(e,"symbol"),n=this.safeMarket(o,t),d=n.symbol,h=this.parse8601(this.safeString(e,"created_at")),c=this.safeStringLower(e,"order_type");"long"===c?i="buy":"short"===c&&(i="sell"),"MARKET"===this.safeStringUpper(e,"trigger_type")&&(s="taker");let l=this.safeString(e,"fee_amount"),u=this.safeString(e,"rebate_amount");return void 0!==l&&void 0!==u&&(l=a.Y.stringSub(l,u)),void 0!==l&&(r={cost:l,currency:this.safeString(e,"trade_currency")}),this.safeTrade({info:e,timestamp:h,datetime:this.iso8601(h),symbol:d,id:this.safeString(e,"id"),order:void 0,type:this.safeStringLower(e,"trigger_type"),side:i,takerOrMaker:s,price:void 0,amount:void 0,cost:this.safeString(e,"transaction_amount"),fee:r},n)}async transfer(e,t,i,s,r={}){let a,o={spot:"SPOT",SPOT:"SPOT",futures:"FUTURES",future:"FUTURES",FUTURES:"FUTURES"},n=this.safeString(o,i,i.toUpperCase()),d=this.safeString(o,s,s.toUpperCase()),h={from_wallet_type:n,to_wallet_type:d,amount:this.numberToString(t)},c=!1;"INR"===e?c=!0:"INR"===this.safeString2(r,"trade_currency","tradeCurrency")&&(c=!0),a=c?await this.privatePostFuturesTransfersInr(this.extend(h,r)):await this.privatePostWalletFuturesTransfer(this.extend(h,r));let l=this.safeDict(a,"data",a);return{info:a,id:this.safeString(l,"id"),timestamp:void 0,datetime:void 0,currency:e,amount:t,fromAccount:n,toAccount:d,status:"ok"}}}i.d(t,{A:()=>o})},3700(e,t,i){"use strict";var s=i(5058);class r extends s.A{describe(){return this.deepExtend(super.describe(),{id:"myokx",name:"MyOKX (EEA)",certified:!1,pro:!0,hostname:"eea.okx.com",urls:{logo:"https://user-images.githubusercontent.com/1294454/152485636-38b19e4a-bece-4dec-979a-5982859ffc04.jpg",api:{rest:"https://{hostname}"},www:"https://my.okx.com",doc:"https://my.okx.com/docs-v5/en/#overview",fees:"https://my.okx.com/pages/products/fees.html",referral:{url:"https://www.my.okx.com/join/CCXT2023",discount:.2},test:{rest:"https://{hostname}"}},has:{CORS:void 0,spot:!0,margin:void 0,swap:!0,future:!1,option:!1},features:{swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},options:{mica:!0,fetchMarkets:{types:["spot","swap"]}}})}}i.d(t,{A:()=>r})},1586(e,t,i){"use strict";var s=i(5287),r=i(7749),a=i(1093),o=i(6834),n=i(6885),d=i(1453);class h extends s.A{describe(){return this.deepExtend(super.describe(),{id:"nado",name:"Nado",countries:["KY"],rateLimit:25,version:"v1",precisionMode:4,certified:!1,pro:!0,dex:!0,has:{CORS:void 0,spot:!0,margin:!0,swap:!0,future:!1,option:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,createOrder:!0,editOrder:!0,fetchBalance:!0,fetchCanceledAndClosedOrders:!0,fetchCanceledOrders:!0,fetchClosedOrders:!0,fetchCurrencies:!0,fetchDeposits:!0,fetchFundingHistory:!0,fetchFundingRate:!0,fetchFundingRates:!0,fetchMarkets:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterests:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPositions:!0,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchWithdrawals:!0,withdraw:!1},urls:{logo:"https://github.com/user-attachments/assets/811f4e1a-a8b5-4b9e-84c2-0f88997bd274",api:{gateway:"https://gateway.prod.nado.xyz/v1",gatewayV2:"https://gateway.prod.nado.xyz/v2",archive:"https://archive.prod.nado.xyz/v1",archiveV2:"https://archive.prod.nado.xyz/v2",trigger:"https://trigger.prod.nado.xyz/v1"},test:{gateway:"https://gateway.test.nado.xyz/v1",gatewayV2:"https://gateway.test.nado.xyz/v2",archive:"https://archive.test.nado.xyz/v1",archiveV2:"https://archive.test.nado.xyz/v2",trigger:"https://trigger.test.nado.xyz/v1"},www:"https://nado.xyz",doc:"https://docs.nado.xyz/"},api:{gateway:{public:{get:{symbols:{cost:2},query:{cost:1},"edge/query":{cost:1}},post:{query:{cost:1},"edge/query":{cost:1}}},private:{post:{execute:{cost:1}}}},gatewayV2:{public:{get:{assets:{cost:2},pairs:{cost:1},orderbook:{cost:1}}}},archive:{post:{"":{cost:1}}},archiveV2:{public:{get:{tickers:{cost:1},contracts:{cost:1},trades:{cost:1},symbols:{cost:1}}}},trigger:{private:{post:{execute:{cost:1},query:{cost:1}}}}},requiredCredentials:{apiKey:!1,secret:!1,walletAddress:!0,privateKey:!0},fees:{trading:{tierBased:!0,percentage:!0,maker:this.parseNumber("0.0001"),taker:this.parseNumber("0.00035")}},options:{defaultType:"swap",recvWindow:5e3,expiration:"4294967295",subaccount:"default",editOrder:{placeRequiresUnfilled:!0},builderFee:!0,builder:"4500",feeRate:"10"},timeframes:{"1m":60,"5m":300,"15m":900,"1h":3600,"2h":7200,"4h":14400,"1d":86400,"1w":604800,"4w":2419200},features:{},exceptions:{exact:{1e3:d.RateLimitExceeded,1015:d.RateLimitExceeded,1001:d.PermissionDenied,1002:d.RestrictedLocation,1003:d.RestrictedLocation,1004:d.OnMaintenance,1005:d.BadRequest,2e3:d.InvalidOrder,2001:d.InvalidOrder,2002:d.InvalidOrder,2003:d.InvalidOrder,2004:d.InvalidOrder,2005:d.OperationRejected,2006:d.InsufficientFunds,2007:d.InvalidOrder,2008:d.OrderImmediatelyFillable,2009:d.InvalidOrder,2010:d.InvalidOrder,2011:d.InvalidNonce,2012:d.InvalidNonce,2013:d.DuplicateOrderId,2014:d.PermissionDenied,2015:d.BadSymbol,2016:d.BadSymbol,2017:d.InsufficientFunds,2019:d.InvalidOrder,2020:d.OrderNotFound,2021:d.PermissionDenied,2022:d.InvalidNonce,2023:d.OperationRejected,2024:d.InvalidAddress,2025:d.InsufficientFunds,2026:d.BadRequest,2027:d.BadRequest,2028:d.AuthenticationError,2029:d.BadRequest,2030:d.RateLimitExceeded,2031:d.OrderNotFillable,2033:d.InvalidNonce,2034:d.AuthenticationError,2035:d.AuthenticationError,2036:d.InsufficientFunds,2037:d.InsufficientFunds,2038:d.BadRequest,2039:d.BadRequest,2040:d.BadRequest,2041:d.BadRequest,2042:d.OperationRejected,2043:d.InsufficientFunds,2044:d.OperationRejected,2045:d.InvalidOrder,2046:d.InvalidOrder,2047:d.InvalidOrder,2048:d.InvalidOrder,2049:d.OperationFailed,2050:d.PermissionDenied,2051:d.OperationRejected,2052:d.InvalidOrder,2053:d.OperationFailed,2054:d.InvalidOrder,2055:d.InvalidOrder,2056:d.OrderNotFillable,2057:d.OperationRejected,2058:d.OrderNotFound,2059:d.InvalidOrder,2060:d.BadSymbol,2061:d.BadRequest,2062:d.ArgumentsRequired,2063:d.BadResponse,2064:d.InvalidOrder,2065:d.InvalidOrder,2066:d.InvalidOrder,2067:d.InvalidOrder,2068:d.OnMaintenance,2069:d.OperationRejected,2070:d.OperationRejected,2071:d.OperationRejected,2072:d.InvalidOrder,2073:d.InvalidOrder,2074:d.BadRequest,2075:d.InvalidOrder,2076:d.InvalidOrder,2077:d.BadRequest,2078:d.RateLimitExceeded,2079:d.BadRequest,2080:d.BadRequest,2081:d.InvalidOrder,2082:d.BadSymbol,2083:d.InvalidOrder,2084:d.InvalidOrder,2085:d.InvalidOrder,2086:d.BadRequest,2087:d.OperationFailed,2088:d.InvalidOrder,2089:d.BadRequest,2090:d.BadRequest,2091:d.BadRequest,2092:d.InsufficientFunds,2093:d.OperationRejected,2094:d.InvalidOrder,2095:d.InvalidOrder,2096:d.InsufficientFunds,2097:d.InvalidOrder,2098:d.InvalidOrder,2099:d.InvalidOrder,2100:d.InvalidOrder,2101:d.InvalidOrder,2102:d.InvalidOrder,2103:d.InvalidOrder,2104:d.InvalidOrder,2105:d.InvalidOrder,2106:d.InvalidOrder,2107:d.InvalidOrder,2108:d.InvalidOrder,2109:d.InvalidOrder,2110:d.InvalidOrder,2111:d.InvalidOrder,2112:d.InvalidOrder,2113:d.InvalidOrder,2114:d.InvalidOrder,2115:d.OperationFailed,2117:d.InvalidOrder,2118:d.BadRequest,2119:d.InvalidOrder,2120:d.OperationFailed,2121:d.OperationFailed,2122:d.InvalidOrder,2123:d.BadRequest,2124:d.InvalidOrder,2125:d.OperationRejected,2126:d.OrderNotFound,3e3:d.BadRequest,3001:d.BadRequest,3002:d.ArgumentsRequired,3003:d.BadRequest,3004:d.BadRequest,3005:d.OperationFailed,4e3:d.BadRequest,4001:d.NotSupported,4002:d.ExchangeNotAvailable,4003:d.OperationFailed,4004:d.OperationRejected,5e3:d.ExchangeNotAvailable},broad:{}}})}async createOrder(e,t,i,s,r,a={}){let o;this.checkRequiredCredentials(),await this.loadMarkets();let n=this.market(e),d=await this.createOrderRequest(e,t,i,s,r,a),h=this.safeDict(d,"place_order",{});return o="trigger"in h?await this.triggerPrivatePostExecute(d):await this.gatewayPrivatePostExecute(d),this.parseOrder(this.extend({place_order:h},o),n)}async createOrderRequest(e,t,i,s,a,o={}){let n=this.market(e);if("limit"!==t)throw new d.InvalidOrder(this.id+" createOrder() supports limit orders only");if(void 0===a)throw new d.ArgumentsRequired(this.id+" createOrder() requires a price argument");let h=this.parseToInt(n.id),c=this.priceToPrecision(e,a),l=this.amountToPrecision(e,s),u=this.convertToX18(c),f=this.convertToX18(l);"sell"===i&&(f=r.Y.stringMul(f,"-1"));let[p,m]=this.handleOptionStringAndParams(o,"createOrder","subaccount","default"),[g,v]=this.handleOptionStringAndParams(m,"createOrder","expiration","4294967295"),[y,b]=this.handleOptionIntegerAndParams(v,"createOrder","recvWindow",5e3),w=this.createOrderNonce(y),k=this.safeInteger(b,"id"),S=this.safeBool2(b,"spotLeverage","spot_leverage"),O={sender:this.createSubaccount(this.walletAddress,p),priceX18:u,amount:f,expiration:g,nonce:w},T={product_id:h};void 0!==k&&(T.id=k),void 0!==S&&(T.spot_leverage=S);let P=this.safeString2(b,"triggerPrice","stopPrice"),I=this.safeString(b,"stopLossPrice"),A=this.safeString(b,"takeProfitPrice"),x=void 0!==I,M=void 0!==A,_=void 0!==P;if(_){let e=this.handleTriggerDirectionAndParams(b)[0],t="below";"ascending"===e&&(t="above");let i=this.convertToX18(P),s={};s["oracle_price_"+t]=i,T.trigger={price_trigger:{price_requirement:s}}}else if(x||M){let e="";e="buy"===i?x?"above":"below":x?"below":"above",P=x?I:A;let t=this.convertToX18(P),s={};s["oracle_price_"+e]=t,T.trigger={price_trigger:{price_requirement:s}}}let C=this.safeString(b,"appendix");void 0===C&&(C=this.createOrderAppendix(_||x||M,b)),O.appendix=C;let B=await this.queryContracts(),E=this.safeString(B,"chain_id"),R=this.signOrder(O,h,E);T.order=O,T.signature=R;let L=this.omit(b,["expiration","nonce","appendix","reduceOnly","postOnly","timeInForce","id","spotLeverage","spot_leverage","triggerPrice","stopPrice","triggerDirection","stopLossPrice","takeProfitPrice"]);return this.extend({place_order:T},L)}async editOrder(e,t,i,s,r,a,o={}){this.checkRequiredCredentials(),await this.loadMarkets();let n=this.market(t),d=await this.editOrderRequest(e,t,i,s,r,a,o),h=await this.gatewayPrivatePostExecute(d),c=this.safeDict(d,"cancel_and_place",{}),l=this.safeDict(c,"place_order",{});return this.parseOrder(this.extend({place_order:l},h),n)}async editOrderRequest(e,t,i,s,a,o,n={}){let h=this.market(t);if("limit"!==i)throw new d.InvalidOrder(this.id+" editOrder() supports limit orders only");if(void 0!==this.safeStringN(n,["triggerPrice","stopPrice","stopLossPrice","takeProfitPrice"]))throw new d.NotSupported(this.id+" editOrder() and editOrderWs() do not support trigger orders, cancel the trigger order and create a new one instead");if(void 0===a)throw new d.ArgumentsRequired(this.id+" editOrder() requires an amount argument");if(void 0===o)throw new d.ArgumentsRequired(this.id+" editOrder() requires a price argument");let c=this.parseToInt(h.id),l=this.priceToPrecision(t,o),u=this.amountToPrecision(t,a),f=this.convertToX18(l),p=this.convertToX18(u);"sell"===s&&(p=r.Y.stringMul(p,"-1"));let m=this.safeDict(this.options,"editOrder",{}),[g,v]=this.handleOptionStringAndParams(n,"editOrder","subaccount","default"),[y,b]=this.handleOptionStringAndParams(v,"editOrder","expiration","4294967295"),[w,k]=this.handleOptionIntegerAndParams(b,"editOrder","recvWindow",5e3),S=this.createOrderNonce(w),O=r.Y.stringAdd(S,"1"),T=this.safeString(k,"appendix");void 0===T&&(T=this.createOrderAppendix(!1,k));let P=this.safeInteger(k,"id"),I=this.safeBool2(k,"spotLeverage","spot_leverage"),A=this.safeBool2(k,"placeRequiresUnfilled","place_requires_unfilled",this.safeBool(m,"placeRequiresUnfilled",!0)),x=this.omit(k,["expiration","nonce","appendix","reduceOnly","postOnly","timeInForce","id","spotLeverage","spot_leverage","placeRequiresUnfilled","place_requires_unfilled"]),M=this.createSubaccount(this.walletAddress,g),_={sender:M,productIds:[c],digests:[e],nonce:S},C={sender:M,priceX18:f,amount:p,expiration:y,nonce:O,appendix:T},B=await this.queryContracts(),E=this.safeString(B,"chain_id"),R=this.safeString(B,"endpoint_addr");if(void 0===R)throw new d.ExchangeError(this.id+" editOrder() requires endpoint_addr from contracts query");let L=this.signCancellation(_,E,R),N=this.signOrder(C,c,E),D={product_id:c,order:C,signature:N};return void 0!==P&&(D.id=P),void 0!==I&&(D.spot_leverage=I),this.extend({cancel_and_place:{cancel_tx:_,cancel_signature:L,place_order:D,place_requires_unfilled:A}},x)}async cancelOrder(e,t,i={}){let s=await this.cancelOrders([e],t,i);return this.safeDict(s,0)}async cancelAllOrders(e,t={}){let i,s;this.checkRequiredCredentials(),await this.loadMarkets(),void 0!==e&&(i=this.market(e));let r=this.safeBool2(t,"stop","trigger"),a=this.omit(t,["stop","trigger"]),o=await this.cancelAllOrdersRequest(e,a);s=!0===r?await this.triggerPrivatePostExecute(o):await this.gatewayPrivatePostExecute(o);let n=this.safeDict(s,"data",{}),d=this.safeList(n,"cancelled_orders",[]),h=[];for(let e=0;e<d.length;e++)h.push(this.parseOrder(this.extend({status:"canceled"},d[e]),i));return h}async cancelAllOrdersRequest(e,t={}){let i=[];if(void 0!==e){let t=this.market(e);i.push(this.parseToInt(t.id))}let[s,r]=this.handleOptionStringAndParams(t,"cancelAllOrders","subaccount","default"),a=this.createSubaccount(this.walletAddress,s),[o,n]=this.handleOptionIntegerAndParams(r,"cancelAllOrders","recvWindow",5e3),h={sender:a,productIds:i,nonce:this.createOrderNonce(o)},c=await this.queryContracts(),l=this.safeString(c,"chain_id"),u=this.safeString(c,"endpoint_addr");if(void 0===u)throw new d.ExchangeError(this.id+" cancelAllOrders() requires endpoint_addr from contracts query");let f=this.signCancellationProducts(h,l,u),p=this.safeInteger(n,"id"),m=this.omit(n,["id"]),g={tx:h,signature:f};return void 0!==p&&(g.id=p),this.extend({cancel_product_orders:g},m)}async cancelOrders(e,t,i={}){let s;if(this.checkRequiredCredentials(),void 0===t)throw new d.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument");await this.loadMarkets();let r=this.market(t),a=this.safeBool2(i,"stop","trigger"),o=this.omit(i,["stop","trigger"]),n=await this.cancelOrdersRequest(e,t,o);s=!0===a?await this.triggerPrivatePostExecute(n):await this.gatewayPrivatePostExecute(n);let h=this.safeDict(s,"data",{}),c=this.safeList(h,"cancelled_orders",[]),l=[];for(let e=0;e<c.length;e++)l.push(this.parseOrder(this.extend({status:"canceled"},c[e]),r));return l}async cancelOrdersRequest(e,t,i={}){let s=this.market(t),r=this.parseToInt(s.id),[a,o]=this.handleOptionStringAndParams(i,"cancelOrders","subaccount","default"),n=this.createSubaccount(this.walletAddress,a),h=[];for(let t=0;t<e.length;t++)h.push(r);let[c,l]=this.handleOptionIntegerAndParams(o,"cancelOrders","recvWindow",5e3),u={sender:n,productIds:h,digests:e,nonce:this.createOrderNonce(c)},f=await this.queryContracts(),p=this.safeString(f,"chain_id"),m=this.safeString(f,"endpoint_addr");if(void 0===m)throw new d.ExchangeError(this.id+" cancelOrders() requires endpoint_addr from contracts query");let g=this.signCancellation(u,p,m),v=this.safeInteger(l,"id"),y=this.safeString(l,"required_unfilled_amount"),b=this.safeString(l,"requiredUnfilledAmount"),w=this.omit(l,["id","requiredUnfilledAmount","required_unfilled_amount"]),k={tx:u,signature:g};return void 0!==y?k.required_unfilled_amount=y:void 0!==b&&(k.required_unfilled_amount=this.convertToX18(b)),void 0!==v&&(k.id=v),this.extend({cancel_orders:k},w)}async fetchOrder(e,t,i={}){if(void 0===t)throw new d.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");await this.loadMarkets();let s=this.market(t),r={type:"order",product_id:this.parseToInt(s.id),digest:e},a=await this.gatewayPublicGetQuery(this.extend(r,i)),o=this.safeDict(a,"data",{});return this.parseOrder(o,s)}async fetchOrders(e,t,i,s={}){let r;await this.loadMarkets();let a=[];void 0!==e&&(r=this.market(e),a.push(this.parseToInt(r.id)));let[o,n]=this.handleOptionStringAndParams(s,"fetchOrders","subaccount","default"),h=this.createSubaccount(this.walletAddress,o),c=this.safeBool2(n,"stop","trigger"),l=this.omit(n,["stop","trigger"]);if(!0!==c)throw new d.NotSupported(this.id+" fetchOrders only support trigger");let[u,f]=this.handleOptionIntegerAndParams(l,"fetchOrders","recvWindow",5e3),p={sender:h,recvTime:this.numberToString(this.milliseconds()+u)},m={tx:p,type:"list_trigger_orders",product_ids:a};void 0!==i&&(m.limit=Math.min(i,500));let g=await this.queryContracts(),v=this.safeString(g,"chain_id"),y=this.safeString(g,"endpoint_addr");m.signature=this.signFetchTriggerOrders(p,v,y);let b=await this.triggerPrivatePostQuery(this.extend(m,f)),w=this.safeDict(b,"data",{}),k=this.safeList(w,"orders",[]);return this.parseOrders(k,r,t,i)}async fetchOpenOrders(e,t,i,s={}){if(void 0===this.walletAddress)throw new d.ArgumentsRequired(this.id+" fetchOpenOrders() requires walletAddress");await this.loadMarkets();let[r,a]=this.handleOptionStringAndParams(s,"fetchOpenOrders","subaccount","default"),o=this.createSubaccount(this.walletAddress,r);if(!0===this.safeBool2(a,"stop","trigger"))return await this.fetchOrders(e,t,i,this.extend(a,{status_types:["waiting_price","waiting_dependency"]}));if(void 0===e)throw new d.ArgumentsRequired(this.id+" fetchOpenOrders() requires a symbol argument");let n=this.market(e),h={sender:o,type:"subaccount_orders",product_id:this.parseToInt(n.id)},c=await this.gatewayPublicGetQuery(this.extend(h,a)),l=this.safeDict(c,"data",{}),u=this.safeList(l,"orders",[]);return this.parseOrders(u,n,t,i,{status:"open"})}async fetchClosedOrders(e,t,i,s={}){let r;if(void 0===this.walletAddress)throw new d.ArgumentsRequired(this.id+" fetchClosedOrders() requires walletAddress");await this.loadMarkets(),void 0!==e&&(r=this.market(e));let[a,o]=this.handleOptionStringAndParams(s,"fetchClosedOrders","subaccount","default"),n=this.createSubaccount(this.walletAddress,a);if(!0===this.safeBool2(o,"stop","trigger"))return await this.fetchOrders(e,t,i,this.extend(o,{status_types:["triggered","triggering","twap_executing","twap_completed"]}));let h={subaccounts:[n]};void 0!==r&&(h.product_ids=[this.parseToInt(r.id)]);let[c,l]=this.handleUntilOption("max_time",h,o,.001);void 0!==i&&(c.limit=Math.min(i,500));let u=await this.archivePost(this.deepExtend({orders:c},l)),f=[],p=this.safeList(u,"orders",[]);for(let e=0;e<p.length;e++){let t=p[e];this.isArchiveOrderClosed(t)&&f.push(this.extend({status:"closed"},t))}return this.parseOrders(f,r,t,i)}async fetchCanceledOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend(s,{trigger:!0,status_types:["cancelled","internal_error"]}))}async fetchCanceledAndClosedOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend(s,{trigger:!0,status_types:["cancelled","internal_error","triggered","triggering","twap_executing","twap_completed"]}))}async fetchMyTrades(e,t,i,s={}){let r;if(void 0===this.walletAddress)throw new d.ArgumentsRequired(this.id+" fetchMyTrades() requires walletAddress");await this.loadMarkets(),void 0!==e&&(r=this.market(e));let[a,o]=this.handleOptionStringAndParams(s,"fetchMyTrades","subaccount","default"),n={subaccounts:[this.createSubaccount(this.walletAddress,a)]};void 0!==r&&(n.product_ids=[this.parseToInt(r.id)]);let[h,c]=this.handleUntilOption("max_time",n,o,.001);void 0!==i&&(h.limit=Math.min(i,500));let l=await this.archivePost(this.deepExtend({matches:h},c)),u=this.safeList(l,"matches",[]),f=this.safeList(l,"txs",[]),p=this.indexBy(f,"submission_idx"),m=[];for(let e=0;e<u.length;e++){let t=u[e],i=this.safeString(t,"submission_idx"),s=this.safeDict(p,i,{});m.push(this.extend(s,t))}return this.parseTrades(m,r,t,i)}async fetchBalance(e={}){if(void 0===this.walletAddress)throw new d.ArgumentsRequired(this.id+" fetchBalance() requires walletAddress");await this.loadMarkets();let[t,i]=this.handleOptionStringAndParams(e,"fetchBalance","subaccount","default"),s={type:"subaccount_info",subaccount:this.createSubaccount(this.walletAddress,t)},r=await this.gatewayPublicGetQuery(this.extend(s,i)),a=this.safeDict(r,"data",{});return this.parseBalance(a)}async fetchDeposits(e,t,i,s={}){return await this.queryTransactionsByEventType("deposit_collateral","deposit","fetchDeposits",e,t,i,s)}async fetchWithdrawals(e,t,i,s={}){return await this.queryTransactionsByEventType("withdraw_collateral","withdrawal","fetchWithdrawals",e,t,i,s)}async queryTransactionsByEventType(e,t,i,s,r,a,o={}){let n;if(void 0===this.walletAddress)throw new d.ArgumentsRequired(this.id+" "+i+"() requires walletAddress");await this.loadMarkets(),void 0!==s&&(n=this.currency(s));let[h,c]=this.handleOptionStringAndParams(o,i,"subaccount","default"),l={subaccounts:[this.createSubaccount(this.walletAddress,h)],event_types:[e],limit:{raw:void 0===a?100:Math.min(a,500)}};void 0!==n&&(l.product_ids=[this.parseToInt(n.id)]);let[u,f]=this.handleUntilOption("max_time",l,c,.001),p=await this.archivePost(this.deepExtend({events:u},f)),m=this.safeList(p,"events",[]),g=this.safeList(p,"txs",[]),v=[];for(let e=0;e<m.length;e++){let i=m[e],s=this.safeString(i,"submission_idx"),r={};for(let e=0;e<g.length;e++){let t=g[e];if(this.safeString(t,"submission_idx")===s){r=t;break}}let a=this.extend({},r);(a=this.extend(a,i)).transaction_type=t,v.push(this.parseTransaction(a,n))}return this.filterByCurrencySinceLimit(v,s,r,a)}async fetchPositions(e,t={}){if(void 0===this.walletAddress)throw new d.ArgumentsRequired(this.id+" fetchPositions() requires walletAddress");await this.loadMarkets();let i=this.marketSymbols(e),[s,a]=this.handleOptionStringAndParams(t,"fetchPositions","subaccount","default"),o={type:"subaccount_info",subaccount:this.createSubaccount(this.walletAddress,s)},n=await this.gatewayPublicGetQuery(this.extend(o,a)),h=this.safeDict(n,"data",{}),c=this.safeList(h,"perp_balances",[]),l=this.safeList(h,"perp_products",[]),u=[];for(let e=0;e<c.length;e++){let t=c[e],i=this.safeDict(t,"balance",{}),s=this.safeString(i,"amount");if(void 0===s||r.Y.stringEquals(s,"0"))continue;let a=this.safeString(t,"product_id"),o={};for(let e=0;e<l.length;e++){let t=l[e];if(this.safeString(t,"product_id")===a){o=t;break}}u.push(this.parsePosition(this.extend({product:o},t)))}return this.filterByArrayPositions(u,"symbol",i)}async fetchTime(e={}){let t=await this.gatewayPublicGetEdgeQuery(this.extend({type:"time"},e));return this.safeInteger(t,"server_time")}async fetchStatus(e={}){let t=await this.gatewayPublicGetQuery(this.extend({type:"status"},e));return{status:"active"===this.safeString(t,"data")?"ok":"error",updated:void 0,eta:void 0,url:void 0,info:t}}async fetchMarkets(e={}){let t=this.gatewayPublicGetSymbols(e),i=this.gatewayV2PublicGetPairs(e),s=this.gatewayV2PublicGetAssets(e),r=await Promise.all([t,i,s]),a=this.safeList(r,0,[]),o=this.safeList(r,1,[]),n=this.safeList(r,2,[]),d={};for(let e=0;e<o.length;e++){let t=o[e],i=this.safeString(t,"product_id");void 0!==i&&(d[i]=t)}let h={};for(let e=0;e<n.length;e++){let t=n[e],i=this.safeString(t,"product_id");void 0!==i&&(h[i]=t)}let c={};for(let e=0;e<n.length;e++){let t=n[e],i=this.safeString(t,"symbol"),s=this.safeCurrencyCode(this.removeMarketSuffix(i));if(void 0===s)continue;let r=this.safeDict(c,s);if(void 0===r)c[s]=t;else{let e=this.safeBool(r,"can_deposit",!1),i=this.safeBool(r,"can_withdraw",!1),a=this.safeBool(t,"can_deposit",!1),o=this.safeBool(t,"can_withdraw",!1);!0!==e&&!0!==i&&(!0===a||!0===o)&&(c[s]=t)}}let l=[];for(let e=0;e<a.length;e++){let t=a[e],i=this.safeString(t,"product_id"),s=this.safeDict(d,i,{}),r=this.safeDict(h,i,{}),o=this.safeString(t,"type"),n=o;"perp"===o&&(n="swap");let u="swap"===n,f=this.safeString2(s,"ticker_id","tickerId");if(void 0===f)continue;let p=this.safeString(t,"symbol"),m=this.safeString(s,"quote","USDT0"),g=this.safeCurrencyCode(this.removeMarketSuffix(p)),v=this.safeCurrencyCode(m);if(void 0===g||void 0===v)continue;let y=this.safeDict(c,g,r),b=this.safeDict(c,v),w=this.safeString(y,"product_id",p),k=this.safeString(b,"product_id",m),S=u?k:void 0,O=u?v:void 0,T=g+"/"+v;u&&(T+=":"+O);let P="not_tradable"!==this.safeString(t,"trading_status"),I=this.parseX18(this.safeString(t,"price_increment_x18")),A=this.parseX18(this.safeString(t,"size_increment")),x=this.parseX18(this.safeString(t,"min_size"));l.push(this.safeMarketStructure({id:i,lowercaseId:void 0,symbol:T,base:g,quote:v,settle:O,baseId:w,quoteId:k,settleId:S,type:n,spot:"spot"===n,margin:void 0,swap:u,future:!1,option:!1,active:P,contract:u,linear:!!u||void 0,inverse:!u&&void 0,taker:this.parseX18(this.safeString(t,"taker_fee_rate_x18")),maker:this.parseX18(this.safeString(t,"maker_fee_rate_x18")),contractSize:u?1:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:A,price:I},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:x,max:void 0}},created:void 0,info:this.extend(t,{ticker_id:f,name:this.safeString(r,"name"),v2Pair:s,v2Asset:r})}))}return l}async fetchCurrencies(e={}){let t=await this.gatewayV2PublicGetAssets(e),i={},s=this.toArray(t);for(let e=0;e<s.length;e++){let t=s[e],r=this.parseCurrency(t),a=this.safeString(r,"code");if(void 0===a)continue;let o=this.safeDict(i,a),n=this.safeBool(t,"can_deposit",!1),d=this.safeBool(t,"can_withdraw",!1);if(void 0===o)i[a]=r;else{let e=this.safeBool(o,"deposit",!1),t=this.safeBool(o,"withdraw",!1);!0!==e&&!0!==t&&(!0===n||!0===d)&&(i[a]=r)}}return i}async fetchTickers(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e),s=await this.archiveV2PublicGetTickers(t),r=this.toArray(s);return this.parseTickers(r,i)}async fetchTicker(e,t={}){await this.loadMarkets();let i=this.market(e).symbol,s=await this.fetchTickers([i],t),r=this.safeDict(s,i);if(void 0===r)throw new d.BadSymbol(this.id+" fetchTicker() ticker not found for "+i);return r}async fetchFundingRate(e,t={}){await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new d.BadSymbol(this.id+" fetchFundingRate() supports swap contracts only");let s=this.safeString(i.info,"ticker_id"),r=await this.archiveV2PublicGetContracts(t),a=this.safeDict(r,s,{});return this.parseFundingRate(a,i)}async fetchFundingHistory(e,t,i,s={}){if(void 0===e)throw new d.ArgumentsRequired(this.id+" fetchFundingHistory() requires a symbol argument");if(void 0===this.walletAddress)throw new d.ArgumentsRequired(this.id+" fetchFundingHistory() requires walletAddress");await this.loadMarkets();let r=this.market(e);if(!0!==r.swap)throw new d.BadSymbol(this.id+" fetchFundingHistory() supports swap contracts only");let[a,o]=this.handleOptionStringAndParams(s,"fetchFundingHistory","subaccount","default"),n={interest_and_funding:{subaccount:this.createSubaccount(this.walletAddress,a),product_ids:[this.parseToInt(r.id)],limit:void 0===i?100:Math.min(i,100)}},h=await this.archivePost(this.deepExtend(n,o)),c=this.safeList(h,"funding_payments",[]),l=[];for(let e=0;e<c.length;e++)l.push(this.parseFundingHistory(c[e],r));let u=this.sortBy(l,"timestamp");return this.filterBySymbolSinceLimit(u,e,t,i)}async fetchFundingRates(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e,"swap",!0),s=await this.archiveV2PublicGetContracts(t),r=Object.keys(s),a=[];for(let e=0;e<r.length;e++){let t=r[e];a.push(this.safeDict(s,t,{}))}return this.parseFundingRates(a,i)}async fetchOpenInterest(e,t={}){await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new d.BadSymbol(this.id+" fetchOpenInterest() supports swap contracts only");let s=this.safeString(i.info,"ticker_id"),r=await this.archiveV2PublicGetContracts(t),a=this.safeDict(r,s,{});return this.parseOpenInterest(a,i)}async fetchOpenInterests(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e,"swap",!0),s=await this.archiveV2PublicGetContracts(t),r=Object.keys(s),a=[];for(let e=0;e<r.length;e++){let t=r[e];a.push(this.safeDict(s,t,{}))}return this.parseOpenInterests(a,i)}async fetchOrderBook(e,t,i={}){await this.loadMarkets();let s=this.market(e),r=this.safeString(s.info,"ticker_id"),a=await this.gatewayV2PublicGetOrderbook(this.extend({ticker_id:r,depth:void 0===t?100:t},i)),o=this.safeInteger(a,"timestamp");return this.parseOrderBook(a,s.symbol,o)}async fetchTrades(e,t,i,s={}){await this.loadMarkets();let r=this.market(e),a={ticker_id:this.safeString(r.info,"ticker_id")};void 0!==i&&(a.limit=Math.min(i,500));let o=await this.archiveV2PublicGetTrades(this.extend(a,s));return this.parseTrades(o,r,t,i)}async fetchOHLCV(e,t="1m",i,s,r={}){await this.loadMarkets();let a=this.market(e),o=this.safeInteger(r,"until"),n=this.omit(r,"until"),d={candlesticks:{product_id:this.parseToInt(a.id),granularity:this.safeInteger(this.timeframes,t,this.parseTimeframe(t))}};void 0!==s&&(d.candlesticks.limit=Math.min(s,500)),void 0!==o&&(d.candlesticks.max_time=this.parseToInt(o/1e3));let h=await this.archivePost(this.deepExtend(d,n)),c=this.safeList(h,"candlesticks",[]);return this.parseOHLCVs(c,a,t,i,s)}parseOHLCV(e,t){return[this.safeTimestamp(e,"timestamp"),this.parseX18(this.safeString(e,"open_x18")),this.parseX18(this.safeString(e,"high_x18")),this.parseX18(this.safeString(e,"low_x18")),this.parseX18(this.safeString(e,"close_x18")),this.parseX18(this.safeString(e,"volume"))]}parseTrade(e,t){let i,s,a,o,n,d=this.safeString(e,"product_id"),h=this.safeMarket(d,t),c=this.safeTimestamp(e,"timestamp"),l=this.safeDict(e,"order"),u=void 0!==l,f=void 0===l?{}:l,p=this.safeString(e,"base_filled"),m=this.safeString(e,"quote_filled"),g=this.safeString(f,"amount"),v=this.safeString(e,"trade_type");void 0===v&&void 0!==g&&(v=r.Y.stringLt(g,"0")?"sell":"buy");let y=this.safeString(e,"price");if(void 0===y){let e=this.parseX18(this.safeString(f,"priceX18"));y=void 0===e?void 0:this.numberToString(e)}let b=this.safeBool(e,"is_taker");void 0!==b&&(i=b?"taker":"maker");let w=this.safeString(e,"fee");if(void 0!==(s=u?this.parseX18(w):this.parseNumber(w))&&(a={cost:s,currency:h.quote}),void 0!==p){let e=r.Y.stringAbs(p);o=u?this.parseX18(e):e}if(void 0!==m){let e=r.Y.stringAbs(m);n=u?this.parseX18(e):e}return this.safeTrade({info:e,timestamp:c,datetime:this.iso8601(c),symbol:h.symbol,id:this.safeString2(e,"trade_id","submission_idx"),order:this.safeString(e,"digest"),type:void 0,side:v,takerOrMaker:i,price:y,amount:o,cost:n,fee:a},h)}parseFundingRate(e,t){let i=this.safeString(e,"product_id"),s=this.safeMarket(i,t),r=this.safeTimestamp(e,"next_funding_rate_timestamp");return{info:e,symbol:s.symbol,markPrice:this.safeNumber(e,"mark_price"),indexPrice:this.safeNumber(e,"index_price"),interestRate:void 0,estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:this.safeNumber(e,"funding_rate"),fundingTimestamp:r,fundingDatetime:this.iso8601(r),nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:"24h"}}parseFundingHistory(e,t){let i=this.safeString(e,"product_id"),s=this.safeMarket(i,t),r=this.safeTimestamp(e,"timestamp");return{info:e,symbol:s.symbol,code:this.safeString(s,"settle"),timestamp:r,datetime:this.iso8601(r),id:this.safeString(e,"idx"),amount:this.parseX18(this.safeString(e,"amount"))}}parseOpenInterest(e,t){let i=this.safeString(e,"product_id"),s=this.safeMarket(i,t);return this.safeOpenInterest({symbol:s.symbol,openInterestAmount:this.safeNumber(e,"open_interest"),openInterestValue:this.safeNumber(e,"open_interest_usd"),timestamp:void 0,datetime:void 0,info:e},s)}parseTicker(e,t){let i=this.safeString(e,"product_id"),s=this.safeMarket(i,t),r,a=this.safeString(e,"last_price");return this.safeTicker({symbol:s.symbol,timestamp:r,datetime:this.iso8601(r),high:void 0,low:void 0,bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:void 0,close:a,last:a,previousClose:void 0,change:void 0,percentage:this.safeString(e,"price_change_percent_24h"),average:void 0,baseVolume:this.safeString(e,"base_volume"),quoteVolume:this.safeString(e,"quote_volume"),info:e},s)}parseCurrency(e){let t=this.safeBool(e,"can_deposit",!1),i=this.safeBool(e,"can_withdraw",!1),s=this.safeString(e,"product_id"),r=this.safeString(e,"symbol"),a=this.safeCurrencyCode(this.removeMarketSuffix(r));return this.safeCurrencyStructure({id:s,name:this.safeString(e,"name"),code:a,precision:void 0,active:void 0,fee:void 0,networks:{},deposit:t,withdraw:i,type:"crypto",limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}},info:e})}parseBalance(e){let t={info:e},i=this.safeList(e,"spot_balances",[]);for(let e=0;e<i.length;e++){let s=this.safeDict(i,e),a=this.safeString(s,"product_id"),o=this.safeCurrencyCode(a);if("0"===o)o="USDT0";else if(o===a){let e=this.safeMarket(a,void 0,void 0,"spot");this.safeBool(e,"spot",!1)&&(o=this.safeString(e,"base",o))}let n=this.safeDict(s,"balance",{}),d=r.Y.stringDiv(this.safeString(n,"amount"),"1000000000000000000"),h=this.account();h.total=d,h.free=d,void 0!==o&&(t[o]=h)}return this.safeBalance(t)}parseTransaction(e,t){let i=this.safeString(e,"product_id"),s=this.safeCurrencyCode(i,t),a=this.safeTimestamp(e,"timestamp"),o=this.safeDict(e,"pre_balance",{}),n=this.safeDict(e,"post_balance",{}),d=this.safeDict(o,"spot",{}),h=this.safeDict(n,"spot",{}),c=this.safeDict(d,"balance",{}),l=this.safeDict(h,"balance",{}),u=this.safeString(c,"amount","0"),f=this.safeString(l,"amount","0"),p=this.parseX18(r.Y.stringAbs(r.Y.stringSub(f,u)));return{info:e,id:this.safeString(e,"submission_idx"),txid:void 0,timestamp:a,datetime:this.iso8601(a),address:void 0,addressFrom:void 0,addressTo:void 0,tag:void 0,tagFrom:void 0,tagTo:void 0,type:this.safeString(e,"transaction_type"),amount:p,currency:s,status:"ok",updated:void 0,fee:void 0,network:void 0,comment:void 0,internal:void 0}}parsePosition(e,t){let i,s,a,o,n,d=this.safeString(e,"product_id"),h=this.safeMarket(d,t),c=this.safeDict(e,"balance",{}),l=this.safeString(c,"amount"),u=this.safeDict(e,"product",{}),f=this.safeDict(u,"risk",{}),p=this.safeString2(f,"price_x18","oracle_price_x18"),m=this.safeString(c,"v_quote_balance");if(void 0!==l){r.Y.stringGt(l,"0")?i="long":r.Y.stringLt(l,"0")&&(i="short");let e=r.Y.stringAbs(l);if(s=this.parseX18(e),void 0===m||r.Y.stringEquals(e,"0")||(a=this.parseNumber(r.Y.stringDiv(r.Y.stringAbs(m),e))),void 0!==p){o=this.parseX18(p);let t=r.Y.stringMul(e,p);n=this.parseNumber(r.Y.stringDiv(t,"1000000000000000000000000000000000000"))}}return this.safePosition({info:e,id:void 0,symbol:h.symbol,timestamp:void 0,datetime:void 0,isolated:void 0,hedged:!1,side:i,contracts:s,contractSize:this.safeNumber(h,"contractSize"),entryPrice:a,markPrice:o,notional:n,leverage:void 0,collateral:void 0,initialMargin:void 0,initialMarginPercentage:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,unrealizedPnl:void 0,liquidationPrice:void 0,marginMode:void 0,marginRatio:void 0,percentage:void 0})}isArchiveOrderClosed(e){let t=this.safeString(e,"amount"),i=this.safeString(e,"base_filled");return void 0!==t&&void 0!==i&&r.Y.stringGe(r.Y.stringAbs(i),r.Y.stringAbs(t))}parseOrder(e,t){let i,s,a,o,n,d,h,c,l,u,f,p,m,g,v,y,b=this.safeString(e,"digest"),w=this.safeString(e,"base_filled");if(void 0!==w){i=b;let a=this.safeString(e,"product_id");y=this.safeMarket(a,t);let o=this.safeString(e,"amount");void 0!==o&&(n=r.Y.stringLt(o,"0")?"sell":"buy",h=this.parseX18(r.Y.stringAbs(o))),c=this.parseX18(r.Y.stringAbs(w));let g=this.safeString(e,"quote_filled");u=void 0===g?void 0:this.parseX18(r.Y.stringAbs(g)),void 0!==c&&void 0!==u&&(f=r.Y.stringDiv(this.numberToString(u),this.numberToString(c))),void 0!==o&&void 0!==w&&(l=this.parseX18(r.Y.stringMax(r.Y.stringSub(r.Y.stringAbs(o),r.Y.stringAbs(w)),"0"))),s=this.safeTimestamp(e,"first_fill_timestamp"),m=this.safeTimestamp(e,"last_fill_timestamp"),d=this.parseX18(this.safeString(e,"price_x18")),void 0===(v=this.safeString(e,"status"))&&this.isArchiveOrderClosed(e)&&(v="closed");let k=this.parseX18(this.safeString(e,"fee"));void 0!==k&&(p={cost:k,currency:this.safeString(y,"quote")})}else if(void 0!==b){i=b;let c=this.safeString(e,"product_id");y=this.safeMarket(c,t);let u=this.safeString(e,"amount");void 0!==u&&(n=r.Y.stringLt(u,"0")?"sell":"buy",h=this.parseX18(r.Y.stringAbs(u)));let f=this.safeString(e,"unfilled_amount");void 0!==f&&(l=this.parseX18(r.Y.stringAbs(f))),s=this.safeTimestamp(e,"placed_at");let p=this.safeString(e,"order_type");a=this.parseOrderTimeInForce(p),o="post_only"===p,d=this.parseX18(this.safeString(e,"price_x18")),v=this.safeString(e,"status","open")}else{let a=this.safeDict2(e,"place_order","order",{}),o=this.safeDict(a,"order",{}),c=this.safeString(a,"product_id");y=this.safeMarket(c,t);let l=this.safeDict(e,"data",{});void 0===(i=this.safeString(l,"digest"))&&(i=this.safeString(a,"digest"),s=this.safeTimestamp(e,"placed_at"),g=this.safeTimestamp(e,"updated_at"));let u=this.safeString(o,"amount");void 0!==u&&(n=r.Y.stringLt(u,"0")?"sell":"buy",h=this.parseX18(r.Y.stringAbs(u)));let f=this.safeDict(e,"status");void 0!==f?v=void 0!==this.safeDict(f,"triggered")?"closed":"canceled":("success"===(v=this.safeString(e,"status","rejected"))||v.indexOf("waiting")>=0)&&(v="open"),d=this.parseX18(this.safeString(o,"priceX18"))}return this.safeOrder({info:e,id:i,clientOrderId:void 0,timestamp:s,datetime:this.iso8601(s),lastTradeTimestamp:m,lastUpdateTimestamp:g,symbol:y.symbol,type:"limit",timeInForce:a,postOnly:o,side:n,price:d,stopPrice:void 0,triggerPrice:void 0,amount:h,cost:u,average:f,filled:c,remaining:l,status:v,fee:p,trades:void 0},y)}parseOrderTimeInForce(e){return this.safeString({default:"GTC",ioc:"IOC",fok:"FOK",post_only:"PO"},e,e)}convertToX18(e){if(void 0===e)throw new d.ArgumentsRequired(this.id+" convertToX18() requires a value");return r.Y.stringDiv(r.Y.stringMul(e,"1000000000000000000"),"1",0)}parseX18(e){if(void 0!==e)return this.parseNumber(r.Y.stringDiv(e,"1000000000000000000"))}createOrderNonce(e){let t=this.sum(this.milliseconds(),e),i=r.Y.stringMul(this.numberToString(t),"1048576"),s=this.randNumber(6);return r.Y.stringAdd(i,this.numberToString(s))}createOrderAppendix(e,t={}){let i=this.safeBool(t,"reduceOnly",!1),s=this.isPostOnly(!1,void 0,t),a=this.safeStringUpper(t,"timeInForce"),o=0;if("IOC"===a)o=1;else if("FOK"===a)o=2;else if(s||"PO"===a)o=3;else if(void 0!==a&&"GTC"!==a)throw new d.BadRequest(this.id+" createOrder() only supports timeInForce values GTC, IOC, FOK, or PO");let n="1";if(0!==o&&(n=r.Y.stringAdd(n,r.Y.stringMul(this.numberToString(o),"512"))),!0===i&&(n=r.Y.stringAdd(n,"2048")),!0===this.safeBool(this.options,"builderFee",!0)){let e=this.safeString(this.options,"builder","4500"),t=this.safeString(this.options,"feeRate","10");n=r.Y.stringAdd(n,r.Y.stringMul(e,"281474976710656")),n=r.Y.stringAdd(n,r.Y.stringMul(t,"274877906944"))}return!0===e&&(n=r.Y.stringAdd(n,"4096")),n}createSubaccount(e,t="default"){if(void 0===e)throw new d.ArgumentsRequired(this.id+" createSubaccount() requires walletAddress");let i=this.remove0xPrefix(e).toLowerCase();if(40!==i.length)throw new d.BadRequest(this.id+" createOrder() requires a 20-byte walletAddress");let s=this.remove0xPrefix(this.stringToBase16(void 0===t?"default":t));if(s.length>24)throw new d.BadRequest(this.id+" createOrder() subaccount must fit in 12 bytes");return"0x"+i+this.padHex(s,24,!1)}async queryContracts(e={}){let t=this.safeDict(this.options,"gatewayContracts");if(void 0!==t)return t;let i=await this.gatewayPublicGetQuery(this.extend({type:"contracts"},e)),s=this.safeDict(i,"data",{});return this.options.gatewayContracts=s,s}orderVerifyingContract(e){return"0x"+this.padHex(this.intToBase16(e),40)}padHex(e,t,i=!0){let s;if(void 0===t)throw new d.ArgumentsRequired(this.id+" padHex() requires length");let r="00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";if(s=i?r+e:e+r,i){let e=s.length-t;return s.slice(e,s.length)}return s.slice(0,t)}signOrder(e,t,i){let s={name:"Nado",version:"0.0.1",chainId:i,verifyingContract:this.orderVerifyingContract(t)},r=this.ethEncodeStructuredData(s,{Order:[{name:"sender",type:"bytes32"},{name:"priceX18",type:"int128"},{name:"amount",type:"int128"},{name:"expiration",type:"uint64"},{name:"nonce",type:"uint64"},{name:"appendix",type:"uint128"}]},e),a="0x"+this.hash(r,o.lY,"hex");return this.signHash(a,this.privateKey)}signCancellation(e,t,i){let s=this.ethEncodeStructuredData({name:"Nado",version:"0.0.1",chainId:t,verifyingContract:i},{Cancellation:[{name:"sender",type:"bytes32"},{name:"productIds",type:"uint32[]"},{name:"digests",type:"bytes32[]"},{name:"nonce",type:"uint64"}]},e),r="0x"+this.hash(s,o.lY,"hex");return this.signHash(r,this.privateKey)}signCancellationProducts(e,t,i){let s=this.ethEncodeStructuredData({name:"Nado",version:"0.0.1",chainId:t,verifyingContract:i},{CancellationProducts:[{name:"sender",type:"bytes32"},{name:"productIds",type:"uint32[]"},{name:"nonce",type:"uint64"}]},e),r="0x"+this.hash(s,o.lY,"hex");return this.signHash(r,this.privateKey)}signFetchTriggerOrders(e,t,i){let s=this.ethEncodeStructuredData({name:"Nado",version:"0.0.1",chainId:t,verifyingContract:i},{ListTriggerOrders:[{name:"sender",type:"bytes32"},{name:"recvTime",type:"uint64"}]},e),r="0x"+this.hash(s,o.lY,"hex");return this.signHash(r,this.privateKey)}signHash(e,t){if(void 0===t)throw new d.ArgumentsRequired(this.id+" signHash() requires privateKey");let i=(0,a.h1)(e.slice(-64),t.slice(-64),n.bI,void 0),s=i.r,r=i.s,o=this.intToBase16(this.sum(27,i.v)).toLowerCase();return"0x"+this.padHex(s,64)+this.padHex(r,64)+o}removeMarketSuffix(e){if(void 0!==e)return e.endsWith("-PERP")?e.slice(0,-5):e}sign(e,t=[],i="GET",s={},r,a){let o,n=t[0];"string"==typeof t&&(n=t);let h=this.safeString(this.urls.api,n);if(void 0===h)throw new d.ExchangeError(this.id+" sign() has no API URL for this endpoint");let c=h;""!==e&&(c+="/"+this.implodeParams(e,s));let l=this.omit(s,this.extractParams(e)),u={};return("gateway"===n||"archive"===n)&&(u["Accept-Encoding"]="gzip, br, deflate"),"GET"===i?Object.keys(l).length>0&&(c+="?"+this.urlencode(l)):(u["Content-Type"]="application/json",o=this.json(l)),{url:c,method:i,body:void 0!==o?o:a,headers:u}}handleErrors(e,t,i,s,r,a,o,n,h){if(null==o)return;let c=this.safeString(o,"status"),l=this.safeString(o,"error_code"),u=this.safeString(o,"error");if("failure"===c||void 0!==l||void 0!==u){let e=this.id+" "+a;throw this.throwExactlyMatchedException(this.exceptions.exact,l,e),this.throwBroadlyMatchedException(this.exceptions.broad,u,e),new d.ExchangeError(e)}}}i.d(t,{A:()=>h})},8573(e,t,i){"use strict";var s=i(4721),r=i(2356),a=i(1453),o=i(7749),n=i(6637);class d extends r.A{describe(){return this.deepExtend(super.describe(),{id:"ndax",name:"NDAX",countries:["CA"],rateLimit:1e3,pro:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,closeAllPositions:!1,closePosition:!1,createDepositAddress:!0,createOrder:!0,createReduceOnlyOrder:!1,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,editOrder:!0,fetchAccounts:!0,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLedger:!0,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrice:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchOrderTrades:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!1,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,sandbox:!0,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,signIn:!0,transfer:!1,withdraw:!0},timeframes:{"1m":"60","5m":"300","15m":"900","30m":"1800","1h":"3600","2h":"7200","4h":"14400","6h":"21600","12h":"43200","1d":"86400","1w":"604800","1M":"2419200","4M":"9676800"},urls:{logo:"https://user-images.githubusercontent.com/1294454/108623144-67a3ef00-744e-11eb-8140-75c6b851e945.jpg",test:{public:"https://ndaxmarginstaging.cdnhop.net:8443/AP",private:"https://ndaxmarginstaging.cdnhop.net:8443/AP"},api:{public:"https://api.ndax.io:8443/AP",private:"https://api.ndax.io:8443/AP"},www:"https://ndax.io",doc:["https://apidoc.ndax.io/"],fees:"https://ndax.io/fees",referral:"https://one.ndax.io/bfQiSL"},api:{public:{get:{Activate2FA:{cost:1},Authenticate2FA:{cost:1},AuthenticateUser:{cost:1},EnableXP2FA:{cost:1},GetL2Snapshot:{cost:1},GetLevel1:{cost:1},GetValidate2FARequiredEndpoints:{cost:1},LogOut:{cost:1},GetTickerHistory:{cost:1},GetProduct:{cost:1},GetProducts:{cost:1},GetInstrument:{cost:1},GetInstruments:{cost:1},GetEarliestTickTime:{cost:1},Ping:{cost:1},assets:{cost:1},orderbook:{cost:1},ticker:{cost:1},summary:{cost:1},trades:{cost:1},GetLastTrades:{cost:1},ConfirmWithdraw:{cost:1},SubscribeLevel1:{cost:1},SubscribeLevel2:{cost:1},SubscribeTicker:{cost:1},SubscribeTrades:{cost:1},SubscribeBlockTrades:{cost:1},UnsubscribeBlockTrades:{cost:1},UnsubscribeLevel1:{cost:1},UnsubscribeLevel2:{cost:1},UnsubscribeTicker:{cost:1},UnsubscribeTrades:{cost:1},Authenticate:{cost:1}}},private:{get:{GetUserAccountInfos:{cost:1},GetUserAccounts:{cost:1},GetUserAffiliateCount:{cost:1},GetUserAffiliateTag:{cost:1},GetUserConfig:{cost:1},GetAllUnredactedUserConfigsForUser:{cost:1},GetUnredactedUserConfigByKey:{cost:1},GetUserDevices:{cost:1},GetUserReportTickets:{cost:1},GetUserReportWriterResultRecords:{cost:1},GetAccountInfo:{cost:1},GetAccountPositions:{cost:1},GetAllAccountConfigs:{cost:1},GetTreasuryProductsForAccount:{cost:1},GetAccountTrades:{cost:1},GetAccountTransactions:{cost:1},GetOpenTradeReports:{cost:1},GetAllOpenTradeReports:{cost:1},GetTradesHistory:{cost:1},GetOpenOrders:{cost:1},GetOpenQuotes:{cost:1},GetOrderFee:{cost:1},GetOrderHistory:{cost:1},GetOrdersHistory:{cost:1},GetOrderStatus:{cost:1},GetOmsFeeTiers:{cost:1},GetAccountDepositTransactions:{cost:1},GetAccountWithdrawTransactions:{cost:1},GetAllDepositRequestInfoTemplates:{cost:1},GetDepositInfo:{cost:1},GetDepositRequestInfoTemplate:{cost:1},GetDeposits:{cost:1},GetDepositTicket:{cost:1},GetDepositTickets:{cost:1},GetOMSWithdrawFees:{cost:1},GetWithdrawFee:{cost:1},GetWithdraws:{cost:1},GetWithdrawTemplate:{cost:1},GetWithdrawTemplateTypes:{cost:1},GetWithdrawTicket:{cost:1},GetWithdrawTicketAttachment:{cost:1},GetWithdrawTickets:{cost:1},GetDepositTicketAttachment:{cost:1}},post:{AddUserAffiliateTag:{cost:1},AddDepositTicketAttachment:{cost:1},AddWithdrawTicketAttachment:{cost:1},CancelUserReport:{cost:1},RegisterNewDevice:{cost:1},SubscribeAccountEvents:{cost:1},UpdateUserAffiliateTag:{cost:1},GenerateTradeActivityReport:{cost:1},GenerateTransactionActivityReport:{cost:1},GenerateTreasuryActivityReport:{cost:1},ScheduleTradeActivityReport:{cost:1},ScheduleTransactionActivityReport:{cost:1},ScheduleTreasuryActivityReport:{cost:1},CancelAllOrders:{cost:1},CancelOrder:{cost:1},CancelQuote:{cost:1},CancelReplaceOrder:{cost:1},CreateQuote:{cost:1},ModifyOrder:{cost:1},SendOrder:{cost:1},SubmitBlockTrade:{cost:1},UpdateQuote:{cost:1},CancelWithdraw:{cost:1},CreateDepositTicket:{cost:1},CreateWithdrawTicket:{cost:1},SubmitDepositTicketComment:{cost:1},SubmitWithdrawTicketComment:{cost:1},GetOrderHistoryByOrderId:{cost:1}}}},features:{spot:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerDirection:!1,triggerPriceType:{last:!0,mark:!1,index:!1},stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!0},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:void 0,daysBack:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:void 0,fetchOHLCV:{limit:void 0}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},fees:{trading:{tierBased:!1,percentage:!0,maker:this.parseNumber("0.002"),taker:this.parseNumber("0.0025")}},requiredCredentials:{apiKey:!0,secret:!0,uid:!0,login:!0,password:!0},precisionMode:4,exceptions:{exact:{Not_Enough_Funds:a.InsufficientFunds,"Server Error":a.ExchangeError,"Resource Not Found":a.OrderNotFound},broad:{"Invalid InstrumentId":a.BadSymbol,"This endpoint requires 2FACode along with the payload":a.AuthenticationError}},options:{omsId:1,orderTypes:{Market:1,Limit:2,StopMarket:3,StopLimit:4,TrailingStopMarket:5,TrailingStopLimit:6,BlockTrade:7,1:1,2:2,3:3,4:4,5:5,6:6,7:7}}})}async fetchStatus(e={}){let t=await this.publicGetPing(e);return{status:"PONG"===this.safeString(t,"msg")?"ok":"error",updated:void 0,eta:void 0,url:void 0,info:t}}async signIn(e={}){if(this.checkRequiredCredentials(),void 0===this.login||void 0===this.password)throw new a.AuthenticationError(this.id+" signIn() requires exchange.login, exchange.password");let t={grant_type:"client_credentials"},i=await this.publicGetAuthenticate(this.extend(t,e)),s=this.safeString(i,"SessionToken");if(void 0!==s)return this.options.sessionToken=s,i;let r=this.safeString(i,"Pending2FaToken");if(void 0!==r){if(void 0===this.twofa)throw new a.AuthenticationError(this.id+" signIn() requires exchange.twofa credentials");this.options.pending2faToken=r,t={Code:(0,n.O)(this.twofa)};let i=await this.publicGetAuthenticate2FA(this.extend(t,e));return s=this.safeString(i,"SessionToken"),this.options.sessionToken=s,i}return i}async fetchCurrencies(e={}){let t=this.safeInteger(this.options,"omsId",1),i=await this.publicGetGetProducts(this.extend({omsId:t},e));return this.parseCurrencies(i)}parseCurrency(e){let t=this.safeString(e,"ProductId"),i=this.safeCurrencyCode(this.safeString(e,"Product")),s=this.safeString(e,"ProductType"),r="crypto";return"NationalCurrency"===s&&(r="fiat"),"Unknown"===s&&(r="other"),this.safeCurrencyStructure({id:t,name:this.safeString(e,"ProductFullName"),code:i,type:r,precision:this.safeNumber(e,"TickSize"),info:e,active:!this.safeBool(e,"IsDisabled",!1),deposit:this.safeBool(e,"DepositEnabled"),withdraw:this.safeBool(e,"WithdrawEnabled"),fee:void 0,limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}},networks:{},margin:this.safeBool(e,"MarginEnabled")})}async fetchMarkets(e={}){let t=this.safeInteger(this.options,"omsId",1),i=await this.publicGetGetInstruments(this.extend({omsId:t},e));return this.parseMarkets(i)}parseMarket(e){let t=this.safeString(e,"InstrumentId"),i=this.safeString(e,"Product1"),s=this.safeString(e,"Product2"),r=this.safeCurrencyCode(this.safeString(e,"Product1Symbol")),a=this.safeCurrencyCode(this.safeString(e,"Product2Symbol"));if(void 0===r||void 0===a)return;let o=this.safeString(e,"SessionStatus"),n=this.safeBool(e,"IsDisable");return this.safeMarketStructure({id:t,symbol:r+"/"+a,base:r,quote:a,settle:void 0,baseId:i,quoteId:s,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:"Running"===o&&!0!==n,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(e,"QuantityIncrement"),price:this.safeNumber(e,"PriceIncrement")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(e,"MinimumQuantity"),max:void 0},price:{min:this.safeNumber(e,"MinimumPrice"),max:void 0},cost:{min:void 0,max:void 0}},created:void 0,info:e})}parseOrderBook(e,t,i,s="bids",r="asks",a=6,o=8,n=2){let d,h=i,c={symbol:t,bids:[],asks:[],timestamp:void 0,datetime:void 0,nonce:void 0};for(let t=0;t<e.length;t++){let i=e[t];if(void 0===h)h=this.safeInteger(i,2);else{let e=this.safeInteger(i,2);void 0!==e&&(h=Math.max(h,e))}if(void 0===d)d=this.safeInteger(i,0);else{let e=this.safeInteger(i,0);void 0!==e&&(d=Math.max(d,e))}let n=this.parseOrderBookBidAsk(i,a,o),l=this.safeInteger(i,9);c[void 0!==l&&0!==l?r:s].push(n)}return c.bids=this.sortBy(c.bids,0,!0),c.asks=this.sortBy(c.asks,0),c.timestamp=h,c.datetime=this.iso8601(h),c.nonce=d,c}async fetchOrderBook(e,t,i={}){let s=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets();let r={omsId:s,InstrumentId:this.market(e).id,Depth:void 0===t?100:t},a=await this.publicGetGetL2Snapshot(this.extend(r,i));return this.parseOrderBook(a,e)}parseTicker(e,t){let i=this.safeInteger(e,"TimeStamp"),s=this.safeString(e,"InstrumentId");void 0===s&&(s=this.safeString(e,"trading_pairs"));let r=this.safeMarket(s,t,"_"),a=this.safeSymbol(s,r),o=this.safeString2(e,"LastTradedPx","last_price"),n=this.safeString2(e,"Rolling24HrPxChangePercent","price_change_percent_24h"),d=this.safeString(e,"Rolling24HrPxChange"),h=this.safeString(e,"SessionOpen"),c=this.safeString2(e,"Rolling24HrVolume","base_volume"),l=this.safeString2(e,"Rolling24HrNotional","quote_volume");return this.safeTicker({symbol:a,timestamp:i,datetime:this.iso8601(i),high:this.safeString2(e,"SessionHigh","highest_price_24h"),low:this.safeString2(e,"SessionLow","lowest_price_24h"),bid:this.safeString2(e,"BestBid","highest_bid"),bidVolume:void 0,ask:this.safeString2(e,"BestOffer","lowest_ask"),askVolume:void 0,vwap:void 0,open:h,close:o,last:o,previousClose:void 0,change:d,percentage:n,average:void 0,baseVolume:c,quoteVolume:l,info:e},r)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetSummary(t),r=this.parseTickers(s);return this.filterByArrayTickers(r,"symbol",i)}async fetchTicker(e,t={}){let i=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={omsId:i,InstrumentId:s.id},a=await this.publicGetGetLevel1(this.extend(r,t));return this.parseTicker(a,s)}parseOHLCV(e,t){return[this.safeInteger(e,0),this.safeNumber(e,3),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,4),this.safeNumber(e,5)]}async fetchOHLCV(e,t="1m",i,s,r={}){let a=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={omsId:a,InstrumentId:o.id,Interval:this.safeString(this.timeframes,t,t)},d=this.parseTimeframe(t),h=this.milliseconds();void 0===i?void 0!==s&&(n.FromDate=this.ymdhms(h-d*s*1e3),n.ToDate=this.ymdhms(h)):(n.FromDate=this.ymdhms(i),void 0===s?n.ToDate=this.ymdhms(h):n.ToDate=this.ymdhms(this.sum(i,d*s*1e3)));let c=await this.publicGetGetTickerHistory(this.extend(n,r)),l=[];return Array.isArray(c)&&(l=c),this.parseOHLCVs(l,o,t,i,s)}parseTrade(e,t){let i,s,r,a,o,n,d,h,c,l,u={};if(Array.isArray(e)){i=this.safeString(e,3),s=this.safeString(e,2),a=this.safeInteger(e,6),o=this.safeString(e,0),n=this.safeString(e,1);let t=this.safeInteger(e,8);0===t?d="buy":1===t&&(d="sell"),h=this.safeString(e,4)}else{a=this.safeInteger2(e,"TradeTimeMS","ReceiveTime"),o=this.safeString(e,"TradeId"),h=this.safeString2(e,"OrderId","OrigOrderId"),n=this.safeString2(e,"InstrumentId","Instrument"),i=this.safeString(e,"Price"),s=this.safeString(e,"Quantity"),r=this.safeString2(e,"Value","GrossValueExecuted"),c=this.safeStringLower(e,"MakerTaker"),d=this.safeStringLower(e,"Side"),l=this.safeStringLower(e,"OrderType");let t=this.safeString(e,"Fee");if(void 0!==t){let i=this.safeString(e,"FeeProductId");u={cost:t,currency:this.safeCurrencyCode(i)}}}let f=this.safeSymbol(n,t);return this.safeTrade({info:e,id:o,symbol:f,timestamp:a,datetime:this.iso8601(a),order:h,type:l,side:d,takerOrMaker:c,price:i,amount:s,cost:r,fee:u},t)}async fetchTrades(e,t,i,s={}){let r=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={omsId:r,InstrumentId:a.id};void 0!==i&&(o.Count=i);let n=await this.publicGetGetLastTrades(this.extend(o,s));return this.parseTrades(n,a,t,i)}async fetchAccounts(e={}){if(void 0===this.login||""===this.login)throw new a.AuthenticationError(this.id+" fetchAccounts() requires exchange.login email credential");let t=this.safeInteger(this.options,"omsId",1);this.checkRequiredCredentials();let i={omsId:t,UserId:this.uid,UserName:this.login},s=await this.privateGetGetUserAccounts(this.extend(i,e)),r=[];for(let e=0;e<s.length;e++){let t=this.safeString(s,e);r.push({id:t,type:void 0,currency:void 0,info:t})}return r}parseBalance(e){let t={info:e,timestamp:void 0,datetime:void 0};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),r=this.safeString(s,"ProductId");if(void 0!==r&&void 0!==this.currencies_by_id&&r in this.currencies_by_id){let e=this.safeCurrencyCode(r),i=this.account();i.total=this.safeString(s,"Amount"),i.used=this.safeString(s,"Hold"),void 0!==e&&(t[e]=i)}}return this.safeBalance(t)}async fetchBalance(e={}){let t=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let i=this.safeInteger2(this.options,"accountId","AccountId"),s=this.safeInteger2(e,"accountId","AccountId",i);void 0===s&&(s=this.parseToInt(this.accounts[0].id));let r=this.omit(e,["accountId","AccountId"]),a={omsId:t,AccountId:s},o=await this.privateGetGetAccountPositions(this.extend(a,r));return this.parseBalance(o)}parseLedgerEntryType(e){return this.safeString({Trade:"trade",Deposit:"transaction",Withdraw:"transaction",Transfer:"transfer",OrderHold:"trade",WithdrawHold:"transaction",DepositHold:"transaction",MarginHold:"trade",ManualHold:"trade",ManualEntry:"trade",MarginAcquisition:"trade",MarginRelinquish:"trade",MarginQuoteHold:"trade"},e,e)}parseLedgerEntry(e,t){let i,s,r,a=this.safeString(e,"ProductId"),n=this.safeCurrency(a,t),d=this.safeString(e,"CR"),h=this.safeString(e,"DR");o.Y.stringLt(d,"0")?(i=d,s="in"):o.Y.stringLt(h,"0")&&(i=h,s="out");let c=this.safeString(e,"Balance");"out"===s?r=o.Y.stringAdd(c,i):"in"===s&&(r=o.Y.stringMax("0",o.Y.stringSub(c,i)));let l=this.safeInteger(e,"TimeStamp");return this.safeLedgerEntry({info:e,id:this.safeString(e,"TransactionId"),direction:s,account:this.safeString(e,"AccountId"),referenceId:this.safeString(e,"ReferenceId"),referenceAccount:this.safeString(e,"Counterparty"),type:this.parseLedgerEntryType(this.safeString(e,"ReferenceType")),currency:this.safeCurrencyCode(a,n),amount:this.parseNumber(i),before:this.parseNumber(r),after:this.parseNumber(c),status:"ok",timestamp:l,datetime:this.iso8601(l),fee:void 0},n)}async fetchLedger(e,t,i,s={}){let r,a=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let o=this.safeInteger2(this.options,"accountId","AccountId",this.parseToInt(this.accounts[0].id)),n=this.safeInteger2(s,"accountId","AccountId",o),d=this.omit(s,["accountId","AccountId"]),h={omsId:a,AccountId:n};void 0!==i&&(h.Depth=i);let c=await this.privateGetGetAccountTransactions(this.extend(h,d));return void 0!==e&&(r=this.currency(e)),this.parseLedger(c,r,t,i)}parseOrderStatus(e){if(void 0!==e)return this.safeString({Accepted:"open",Rejected:"rejected",Working:"open",Canceled:"canceled",Expired:"expired",FullyExecuted:"closed"},e,e)}parseOrder(e,t){let i=this.safeInteger(e,"ReceiveTime"),s=this.safeString(e,"Instrument");return this.safeOrder({id:this.safeString2(e,"ReplacementOrderId","OrderId"),clientOrderId:this.safeString2(e,"ReplacementClOrdId","ClientOrderId"),info:e,timestamp:i,datetime:this.iso8601(i),lastTradeTimestamp:this.safeInteger(e,"LastUpdatedTime"),status:this.parseOrderStatus(this.safeString(e,"OrderState")),symbol:this.safeSymbol(s,t),type:this.safeStringLower(e,"OrderType"),timeInForce:void 0,postOnly:void 0,side:this.safeStringLower(e,"Side"),price:this.safeString(e,"Price"),triggerPrice:this.parseNumber(this.omitZero(this.safeString(e,"StopPrice"))),cost:this.safeString(e,"GrossValueExecuted"),amount:this.safeString(e,"OrigQuantity"),filled:this.safeString(e,"QuantityExecuted"),average:this.safeString(e,"AvgPrice"),remaining:void 0,fee:void 0,trades:void 0},t)}async createOrder(e,t,i,s,r,a={}){let o=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let n=this.safeInteger2(this.options,"accountId","AccountId",this.parseToInt(this.accounts[0].id)),d=this.safeInteger2(a,"accountId","AccountId",n),h=this.safeInteger2(a,"ClientOrderId","clientOrderId"),c=this.safeInteger(this.options.orderTypes,this.capitalize(t)),l=this.safeString(a,"triggerPrice");void 0!==l&&("market"===t?c=3:"limit"===t&&(c=4));let u=this.omit(a,["accountId","AccountId","clientOrderId","ClientOrderId","triggerPrice"]),f=this.market(e),p=this.amountToPrecision(e,s),m={InstrumentId:this.parseToInt(f.id),omsId:o,AccountId:d,TimeInForce:1,Side:+("buy"!==i),Quantity:void 0===p?void 0:parseFloat(p),OrderType:c};if(void 0!==r){let t=this.priceToPrecision(e,r);void 0===t&&(t="0"),m.LimitPrice=parseFloat(t)}void 0!==h&&(m.ClientOrderId=h),void 0!==l&&(m.StopPrice=l);let g=await this.privatePostSendOrder(this.extend(m,u));return this.parseOrder(g,f)}async editOrder(e,t,i,s,r,a,o={}){let n=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let d=this.safeInteger2(this.options,"accountId","AccountId",this.parseToInt(this.accounts[0].id)),h=this.safeInteger2(o,"accountId","AccountId",d),c=this.safeInteger2(o,"ClientOrderId","clientOrderId"),l=this.omit(o,["accountId","AccountId","clientOrderId","ClientOrderId"]),u=this.market(t),f=this.amountToPrecision(t,r),p={OrderIdToReplace:parseInt(e),InstrumentId:this.parseToInt(u.id),omsId:n,AccountId:h,TimeInForce:1,Side:+("buy"!==s),Quantity:void 0===f?void 0:parseFloat(f),OrderType:this.safeInteger(this.options.orderTypes,this.capitalize(i))};if(void 0!==a){let e=this.priceToPrecision(t,a);void 0===e&&(e="0"),p.LimitPrice=parseFloat(e)}void 0!==c&&(p.ClientOrderId=c);let m=await this.privatePostCancelReplaceOrder(this.extend(p,l));return this.parseOrder(m,u)}async fetchMyTrades(e,t,i,s={}){let r,a=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let o=this.safeInteger2(this.options,"accountId","AccountId",this.parseToInt(this.accounts[0].id)),n=this.safeInteger2(s,"accountId","AccountId",o),d=this.omit(s,["accountId","AccountId"]),h={omsId:a,AccountId:n};void 0!==e&&(h.InstrumentId=(r=this.market(e)).id),void 0!==t&&(h.StartTimeStamp=this.parseToInt(t/1e3)),void 0!==i&&(h.Depth=i);let c=await this.privateGetGetTradesHistory(this.extend(h,d));return this.parseTrades(c,r,t,i)}async cancelAllOrders(e,t={}){let i=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let s=this.safeInteger2(this.options,"accountId","AccountId",this.parseToInt(this.accounts[0].id)),r=this.safeInteger2(t,"accountId","AccountId",s),a=this.omit(t,["accountId","AccountId"]),o={omsId:i,AccountId:r};void 0!==e&&(o.IntrumentId=this.market(e).id);let n=await this.privatePostCancelAllOrders(this.extend(o,a));return[this.safeOrder({info:n})]}async cancelOrder(e,t,i={}){let s,r=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts(),void 0!==t&&(s=this.market(t));let a={omsId:r},o=this.safeInteger2(i,"clientOrderId","ClOrderId");void 0!==o?a.ClOrderId=o:a.OrderId=parseInt(e);let n=this.omit(i,["clientOrderId","ClOrderId"]),d=await this.privatePostCancelOrder(this.extend(a,n)),h=this.parseOrder(d,s);return this.extend(h,{id:e,clientOrderId:o})}async fetchOpenOrders(e,t,i,s={}){let r,a=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let o=this.safeInteger2(this.options,"accountId","AccountId",this.parseToInt(this.accounts[0].id)),n=this.safeInteger2(s,"accountId","AccountId",o),d=this.omit(s,["accountId","AccountId"]);void 0!==e&&(r=this.market(e));let h=await this.privateGetGetOpenOrders(this.extend({omsId:a,AccountId:n},d));return this.parseOrders(h,r,t,i)}async fetchOrders(e,t,i,s={}){let r,a=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let o=this.safeInteger2(this.options,"accountId","AccountId",this.parseToInt(this.accounts[0].id)),n=this.safeInteger2(s,"accountId","AccountId",o),d=this.omit(s,["accountId","AccountId"]),h={omsId:a,AccountId:n};void 0!==e&&(h.InstrumentId=(r=this.market(e)).id),void 0!==t&&(h.StartTimeStamp=this.parseToInt(t/1e3)),void 0!==i&&(h.Depth=i);let c=await this.privateGetGetOrdersHistory(this.extend(h,d));return this.parseOrders(c,r,t,i)}async fetchOrder(e,t,i={}){let s,r=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let a=this.safeInteger2(this.options,"accountId","AccountId",this.parseToInt(this.accounts[0].id)),o=this.safeInteger2(i,"accountId","AccountId",a),n=this.omit(i,["accountId","AccountId"]);void 0!==t&&(s=this.market(t));let d={omsId:r,AccountId:o,OrderId:parseInt(e)},h=await this.privateGetGetOrderStatus(this.extend(d,n));return this.parseOrder(h,s)}async fetchOrderTrades(e,t,i,s,r={}){let a,o=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts(),void 0!==t&&(a=this.market(t));let n={OMSId:this.parseToInt(o),OrderId:parseInt(e)},d=await this.privatePostGetOrderHistoryByOrderId(this.extend(n,r)),h=this.groupBy(d,"ChangeReason"),c=this.safeList(h,"Trade",[]);return this.parseTrades(c,a,i,s)}async fetchDepositAddress(e,t={}){let i=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let s=this.safeInteger2(this.options,"accountId","AccountId",this.parseToInt(this.accounts[0].id)),r=this.safeInteger2(t,"accountId","AccountId",s),a=this.omit(t,["accountId","AccountId"]),o=this.currency(e),n={omsId:i,AccountId:r,ProductId:o.id,GenerateNewKey:!1},d=await this.privateGetGetDepositInfo(this.extend(n,a));return this.parseDepositAddress(d,o)}parseDepositAddress(e,t){let i,s=JSON.parse(this.safeString(e,"DepositInfo","[]")),r=s.length,a=this.safeString(s,r-1,"").split("?memo="),o=this.safeString(a,0),n=this.safeString(a,1);return void 0!==t&&(i=this.safeString(t,"code")),this.checkAddress(o),{info:e,currency:i,network:void 0,address:o,tag:n}}async createDepositAddress(e,t={}){return await this.fetchDepositAddress(e,this.extend({GenerateNewKey:!0},t))}async fetchDeposits(e,t,i,s={}){let r,a=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let o=this.safeInteger2(this.options,"accountId","AccountId",this.parseToInt(this.accounts[0].id)),n=this.safeInteger2(s,"accountId","AccountId",o),d=this.omit(s,["accountId","AccountId"]);void 0!==e&&(r=this.currency(e));let h=await this.privateGetGetDeposits(this.extend({omsId:a,AccountId:n},d));return"string"==typeof h?this.parseTransactions(JSON.parse(h),r,t,i):this.parseTransactions(h,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r,a=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let o=this.safeInteger2(this.options,"accountId","AccountId",this.parseToInt(this.accounts[0].id)),n=this.safeInteger2(s,"accountId","AccountId",o),d=this.omit(s,["accountId","AccountId"]);void 0!==e&&(r=this.currency(e));let h=await this.privateGetGetWithdraws(this.extend({omsId:a,AccountId:n},d));return this.parseTransactions(h,r,t,i)}parseTransactionStatusByType(e,t){let i=void 0===t?{}:this.safeDict({deposit:{New:"pending",AdminProcessing:"pending",Accepted:"pending",Rejected:"rejected",SystemProcessing:"pending",FullyProcessed:"ok",Failed:"failed",Pending:"pending",Confirmed:"pending",AmlProcessing:"pending",AmlAccepted:"pending",AmlRejected:"rejected",AmlFailed:"failed",LimitsAccepted:"pending",LimitsRejected:"rejected"},withdrawal:{New:"pending",AdminProcessing:"pending",Accepted:"pending",Rejected:"rejected",SystemProcessing:"pending",FullyProcessed:"ok",Failed:"failed",Pending:"pending",Pending2Fa:"pending",AutoAccepted:"pending",Delayed:"pending",UserCanceled:"canceled",AdminCanceled:"canceled",AmlProcessing:"pending",AmlAccepted:"pending",AmlRejected:"rejected",AmlFailed:"failed",LimitsAccepted:"pending",LimitsRejected:"rejected",Submitted:"pending",Confirmed:"pending",ManuallyConfirmed:"pending",Confirmed2Fa:"pending"}},t,{});if(void 0!==e)return this.safeString(i,e,e)}parseTransaction(e,t){let i,s,r=this.safeString(e,"ProductId"),a=this.safeCurrencyCode(r,t);"DepositId"in e?(i=this.safeString(e,"DepositId"),s="deposit"):"WithdrawId"in e&&(i=this.safeString(e,"WithdrawId"),s="withdrawal");let o=this.parseJson(this.safeValue2(e,"TemplateForm","DepositInfo")),n=this.safeInteger(e,"LastUpdateTimeStamp");void 0!==o&&(n=this.safeInteger(o,"LastUpdated",n));let d=this.safeString2(o,"ExternalAddress","ToAddress"),h=this.safeInteger(o,"TimeSubmitted"),c=this.safeNumber(e,"FeeAmount"),l=this.safeString(e,"TicketStatus"),u={};return void 0!==c&&(u={currency:a,cost:c}),{info:e,id:i,txid:this.safeString2(o,"TxId","TXId"),timestamp:h,datetime:this.iso8601(h),address:d,addressTo:d,addressFrom:this.safeString(o,"FromAddress"),tag:void 0,tagTo:void 0,tagFrom:void 0,type:s,amount:this.safeNumber(e,"Amount"),currency:a,status:this.parseTransactionStatusByType(l,s),updated:n,fee:u,internal:void 0,comment:void 0,network:void 0}}async withdraw(e,t,i,s,r={}){let[o,d]=this.handleWithdrawTagAndParams(s,r);if(void 0===this.safeString(this.options,"sessionToken"))throw new a.AuthenticationError(this.id+" call signIn() method to obtain a session token");if(void 0===this.twofa)throw new a.AuthenticationError(this.id+" withdraw() requires exchange.twofa credentials");this.checkAddress(i);let h=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets(),await this.loadAccounts();let c=this.safeInteger2(this.options,"accountId","AccountId",this.parseToInt(this.accounts[0].id)),l=this.safeInteger2(d,"accountId","AccountId",c),u=this.omit(d,["accountId","AccountId"]),f=this.currency(e),p={omsId:h,AccountId:l,ProductId:f.id},m=await this.privateGetGetWithdrawTemplateTypes(p),g=this.safeList(m,"TemplateTypes",[]),v=this.safeDict(g,0);if(void 0===v)throw new a.ExchangeError(this.id+" withdraw() could not find a withdraw template type for "+f.code);let y=this.safeString(v,"TemplateName"),b={omsId:h,AccountId:l,ProductId:f.id,TemplateType:y,AccountProviderId:v.AccountProviderId},w=await this.privateGetGetWithdrawTemplate(b),k=this.safeString(w,"Template");if(void 0===k)throw new a.ExchangeError(this.id+" withdraw() could not find a withdraw template for "+f.code);let S=JSON.parse(k);S.ExternalAddress=i,void 0!==o&&"Memo"in S&&(S.Memo=o);let O={omsId:h,AccountId:l,ProductId:f.id,TemplateForm:this.json(S),TemplateType:y},T={TfaType:"Google",TFaCode:(0,n.O)(this.twofa),Payload:this.json(O)},P=await this.privatePostCreateWithdrawTicket(this.deepExtend(T,u));return this.parseTransaction(P,f)}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},o,n){let d,h,c=this.safeString(this.urls.api,t);if(void 0===c)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let l=c+"/"+this.implodeParams(e,r),u=this.omit(r,this.extractParams(e));if("public"===t){if("Authenticate"===e){let e=this.login+":"+this.password;h={Authorization:"Basic "+this.stringToBase64(e)}}else if("Authenticate2FA"===e){let e=this.safeString(this.options,"pending2faToken");void 0!==e&&(h={Pending2FaToken:e},u=this.omit(u,"pending2faToken"))}Object.keys(u).length>0&&(l+="?"+this.urlencode(u))}else if("private"===t){this.checkRequiredCredentials();let e=this.safeString(this.options,"sessionToken");if(void 0===e){let e=this.nonce().toString(),t=e+this.uid+this.apiKey,i=this.hmac(this.encode(t),this.encode(this.secret),s.sc);h={Nonce:e,APIKey:this.apiKey,Signature:i,UserId:this.uid}}else h={APToken:e};"POST"===i?(h["Content-Type"]="application/json",d=this.json(u)):Object.keys(u).length>0&&(l+="?"+this.urlencode(u))}return{url:l,method:i,body:void 0===d?n:d,headers:void 0===h?o:h}}handleErrors(e,t,i,s,r,o,n,d,h){if(404===e)throw new a.AuthenticationError(this.id+" "+o);if(void 0===n)return;let c=this.safeString(n,"errormsg");if(void 0!==c&&""!==c){let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,c,e),this.throwBroadlyMatchedException(this.exceptions.broad,o,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>d})},5058(e,t,i){"use strict";var s=i(4721),r=i(2481),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"okx",name:"OKX",countries:["CN","US"],version:"v5",rateLimit:100*1.1,pro:!0,certified:!0,has:{CORS:void 0,spot:!0,margin:!0,swap:!0,future:!0,option:!0,addMargin:!0,borrowCrossMargin:!0,cancelAllOrders:!1,cancelAllOrdersAfter:!0,cancelOrder:!0,cancelOrders:!0,cancelOrdersForSymbols:!0,closeAllPositions:!1,closePosition:!0,createConvertTrade:!0,createDepositAddress:!1,createMarketBuyOrderWithCost:!0,createMarketSellOrderWithCost:!0,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!0,createPostOnlyOrder:!0,createReduceOnlyOrder:!0,createStopLimitOrder:!0,createStopLossOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,createTakeProfitOrder:!0,createTrailingPercentOrder:!0,createTriggerOrder:!0,editOrder:!0,fetchAccounts:!0,fetchAllGreeks:!0,fetchBalance:!0,fetchBidsAsks:void 0,fetchBorrowInterest:!0,fetchBorrowRateHistories:!0,fetchBorrowRateHistory:!0,fetchCanceledOrders:!0,fetchClosedOrder:void 0,fetchClosedOrders:!0,fetchConvertCurrencies:!0,fetchConvertQuote:!0,fetchConvertTrade:!0,fetchConvertTradeHistory:!0,fetchCrossBorrowRate:!0,fetchCrossBorrowRates:!0,fetchCurrencies:!0,fetchDeposit:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!0,fetchDeposits:!0,fetchDepositsWithdrawals:!1,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!0,fetchFundingInterval:!0,fetchFundingIntervals:!1,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchGreeks:!0,fetchIndexOHLCV:!0,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchL3OrderBook:!1,fetchLedger:!0,fetchLedgerEntry:void 0,fetchLeverage:!0,fetchLeverageTiers:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!0,fetchMarginAdjustmentHistory:!0,fetchMarketLeverageTiers:!0,fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMarkPrice:!0,fetchMarkPrices:!0,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!0,fetchOpenInterests:!0,fetchOpenOrder:void 0,fetchOpenOrders:!0,fetchOption:!0,fetchOptionChain:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrders:!1,fetchOrderTrades:!0,fetchPosition:!0,fetchPositionHistory:"emulated",fetchPositionMode:!0,fetchPositions:!0,fetchPositionsForSymbol:!0,fetchPositionsHistory:!0,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!0,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!1,fetchTradingLimits:!1,fetchTransactionFee:!1,fetchTransactionFees:!1,fetchTransactions:!1,fetchTransfer:!0,fetchTransfers:!0,fetchUnderlyingAssets:!0,fetchVolatilityHistory:!1,fetchWithdrawal:!0,fetchWithdrawals:!0,fetchWithdrawalWhitelist:!1,reduceMargin:!0,repayCrossMargin:!0,sandbox:!0,setLeverage:!0,setMargin:!1,setMarginMode:!0,setPositionMode:!0,signIn:!1,transfer:!0,withdraw:!0},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1H","2h":"2H","4h":"4H","6h":"6H","12h":"12H","1d":"1D","1w":"1W","1M":"1M","3M":"3M"},hostname:"www.okx.com",urls:{logo:"https://user-images.githubusercontent.com/1294454/152485636-38b19e4a-bece-4dec-979a-5982859ffc04.jpg",api:{rest:"https://{hostname}"},www:"https://www.okx.com",doc:"https://www.okx.com/docs-v5/en/",fees:"https://www.okx.com/pages/products/fees.html",referral:{url:"https://www.okx.com/join/CCXTCOM",discount:.2},test:{rest:"https://{hostname}"}},api:{public:{get:{"market/tickers":{cost:1},"market/ticker":{cost:1},"market/books":{cost:.5},"market/books-full":{cost:2},"market/books-rpi":{cost:.5},"market/candles":{cost:.5},"market/history-candles":{cost:1},"market/trades":{cost:.2},"market/history-trades":{cost:2},"market/option/instrument-family-trades":{cost:1},"market/platform-24-volume":{cost:10},"market/call-auction-detail":{cost:1},"market/call-auction-details":{cost:1},"market/books-sbe":{cost:10},"market/block-tickers":{cost:1},"market/block-ticker":{cost:1},"market/sprd-ticker":{cost:1},"market/sprd-candles":{cost:.5},"market/sprd-history-candles":{cost:1},"market/index-tickers":{cost:1},"market/index-candles":{cost:1},"market/history-index-candles":{cost:2},"market/mark-price-candles":{cost:1},"market/history-mark-price-candles":{cost:1},"market/exchange-rate":{cost:20},"market/index-components":{cost:1},"market/open-oracle":{cost:50},"market/books-lite":{cost:5/3},"public/option-trades":{cost:1},"public/block-trades":{cost:1},"public/instruments":{cost:1},"public/estimated-price":{cost:2},"public/delivery-exercise-history":{cost:.5},"public/estimated-settlement-info":{cost:2},"public/settlement-history":{cost:.5},"public/funding-rate":{cost:2},"public/funding-rate-history":{cost:2},"public/open-interest":{cost:1},"public/price-limit":{cost:1},"public/opt-summary":{cost:1},"public/discount-rate-interest-free-quota":{cost:10},"public/time":{cost:2},"public/mark-price":{cost:2},"public/position-tiers":{cost:2},"public/interest-rate-loan-quota":{cost:10},"public/underlying":{cost:1},"public/insurance-fund":{cost:2},"public/convert-contract-coin":{cost:2},"public/instrument-tick-bands":{cost:4},"public/premium-history":{cost:1},"public/economic-calendar":{cost:50},"public/market-data-history":{cost:4},"public/event-contract/events":{cost:1},"public/event-contract/markets":{cost:1},"public/event-contract/series":{cost:1},"public/vip-interest-rate-loan-quota":{cost:10},"public/mm-instrument-types":{cost:4},"public/delta-hedge-currencies":{cost:1},"rubik/stat/trading-data/support-coin":{cost:4},"rubik/stat/contracts/open-interest-history":{cost:2},"rubik/stat/taker-volume":{cost:4},"rubik/stat/taker-volume-contract":{cost:4},"rubik/stat/margin/loan-ratio":{cost:4},"rubik/stat/contracts/long-short-account-ratio-contract-top-trader":{cost:4},"rubik/stat/contracts/long-short-position-ratio-contract-top-trader":{cost:4},"rubik/stat/contracts/long-short-account-ratio-contract":{cost:4},"rubik/stat/contracts/long-short-account-ratio":{cost:4},"rubik/stat/contracts/open-interest-volume":{cost:4},"rubik/stat/option/open-interest-volume":{cost:4},"rubik/stat/option/open-interest-volume-ratio":{cost:4},"rubik/stat/option/open-interest-volume-expiry":{cost:4},"rubik/stat/option/open-interest-volume-strike":{cost:4},"rubik/stat/option/taker-block-volume":{cost:4},"system/status":{cost:50},"sprd/spreads":{cost:1},"sprd/books":{cost:1},"sprd/public-trades":{cost:1},"sprd/ticker":{cost:1},"tradingBot/grid/ai-param":{cost:1},"tradingBot/grid/min-investment":{cost:1},"tradingBot/public/rsi-back-testing":{cost:1},"tradingBot/grid/grid-quantity":{cost:4},"asset/exchange-list":{cost:5/3},"finance/staking-defi/eth/apy-history":{cost:5/3},"finance/staking-defi/sol/apy-history":{cost:5/3},"finance/savings/lending-rate-summary":{cost:5/3},"finance/savings/lending-rate-history":{cost:5/3},"finance/fixed-loan/lending-offers":{cost:10/3},"finance/fixed-loan/lending-apy-history":{cost:10/3},"finance/fixed-loan/pending-lending-volume":{cost:10/3},"finance/sfp/dcd/products":{cost:2/3},"copytrading/public-config":{cost:4},"copytrading/public-lead-traders":{cost:4},"copytrading/public-weekly-pnl":{cost:4},"copytrading/public-pnl":{cost:4},"copytrading/public-stats":{cost:4},"copytrading/public-preference-currency":{cost:4},"copytrading/public-current-subpositions":{cost:4},"copytrading/public-subpositions-history":{cost:4},"copytrading/public-copy-traders":{cost:4},"support/announcements":{cost:4},"support/announcements-types":{cost:20},"support/announcement-types":{cost:20}},post:{"tradingBot/grid/min-investment":{cost:1}}},private:{get:{"rfq/counterparties":{cost:4},"rfq/maker-instrument-settings":{cost:4},"rfq/mmp-config":{cost:4},"rfq/rfqs":{cost:10},"rfq/quotes":{cost:10},"rfq/trades":{cost:4},"rfq/public-trades":{cost:4},"sprd/order":{cost:1},"sprd/orders-pending":{cost:2},"sprd/orders-history":{cost:1},"sprd/orders-history-archive":{cost:1},"sprd/trades":{cost:1},"trade/order":{cost:1/3},"trade/orders-pending":{cost:1/3},"trade/orders-history":{cost:.5},"trade/orders-history-archive":{cost:1},"trade/fills":{cost:1/3},"trade/fills-history":{cost:2},"trade/fills-archive":{cost:2},"trade/order-algo":{cost:1},"trade/orders-algo-pending":{cost:1},"trade/orders-algo-history":{cost:1},"trade/easy-convert-currency-list":{cost:20},"trade/easy-convert-history":{cost:20},"trade/one-click-repay-currency-list":{cost:20},"trade/one-click-repay-currency-list-v2":{cost:20},"trade/one-click-repay-history":{cost:20},"trade/one-click-repay-history-v2":{cost:20},"trade/account-rate-limit":{cost:1},"asset/currencies":{cost:5/3},"asset/balances":{cost:5/3},"asset/non-tradable-assets":{cost:5/3},"asset/asset-valuation":{cost:10},"asset/transfer-state":{cost:1},"asset/bills":{cost:5/3},"asset/bills-history":{cost:10},"asset/deposit-lightning":{cost:5},"asset/deposit-address":{cost:5/3},"asset/deposit-history":{cost:5/3},"asset/withdrawal-history":{cost:5/3},"asset/deposit-withdraw-status":{cost:20},"asset/monthly-statement":{cost:2},"asset/convert/currencies":{cost:5/3},"asset/convert/currency-pair":{cost:5/3},"asset/convert/history":{cost:5/3},"fiat/deposit-payment-methods":{cost:10/3},"fiat/withdrawal-payment-methods":{cost:10/3},"fiat/deposit-order-history":{cost:10/3},"fiat/deposit":{cost:10/3},"fiat/withdrawal-order-history":{cost:10/3},"fiat/withdrawal":{cost:10/3},"fiat/buy-sell/currencies":{cost:5/3},"fiat/buy-sell/currency-pair":{cost:5/3},"fiat/buy-sell/history":{cost:5/3},"account/instruments":{cost:1},"account/balance":{cost:2},"account/positions":{cost:2},"account/positions-history":{cost:2},"account/account-position-risk":{cost:2},"account/bills":{cost:2},"account/bills-archive":{cost:4},"account/bills-history-archive":{cost:2},"account/config":{cost:4},"account/subtypes":{cost:4},"account/max-size":{cost:1},"account/max-avail-size":{cost:1},"account/leverage-info":{cost:1},"account/adjust-leverage-info":{cost:4},"account/max-loan":{cost:1},"account/trade-fee":{cost:4},"account/interest-accrued":{cost:4},"account/interest-rate":{cost:4},"account/max-withdrawal":{cost:1},"account/risk-state":{cost:2},"account/interest-limits":{cost:4},"account/spot-borrow-repay-history":{cost:4},"account/greeks":{cost:2},"account/position-tiers":{cost:2},"account/set-account-switch-precheck":{cost:4},"account/collateral-assets":{cost:4},"account/mmp-config":{cost:4},"account/move-positions-history":{cost:10},"account/precheck-set-delta-neutral":{cost:20},"account/quick-margin-borrow-repay-history":{cost:4},"account/borrow-repay-history":{cost:4},"account/vip-interest-accrued":{cost:4},"account/vip-interest-deducted":{cost:4},"account/vip-loan-order-list":{cost:4},"account/vip-loan-order-detail":{cost:4},"account/fixed-loan/borrowing-limit":{cost:4},"account/fixed-loan/borrowing-quote":{cost:5},"account/fixed-loan/borrowing-orders-list":{cost:5},"account/spot-manual-borrow-repay":{cost:30},"account/set-auto-repay":{cost:4},"users/subaccount/list":{cost:10},"account/subaccount/balances":{cost:10/3},"asset/subaccount/balances":{cost:10/3},"account/subaccount/max-withdrawal":{cost:1},"asset/subaccount/bills":{cost:5/3},"asset/subaccount/managed-subaccount-bills":{cost:5/3},"users/entrust-subaccount-list":{cost:10},"account/subaccount/interest-limits":{cost:4},"users/subaccount/apikey":{cost:10},"tradingBot/grid/orders-algo-pending":{cost:1},"tradingBot/grid/orders-algo-history":{cost:1},"tradingBot/grid/orders-algo-details":{cost:1},"tradingBot/grid/sub-orders":{cost:1},"tradingBot/grid/positions":{cost:1},"tradingBot/grid/ai-param":{cost:1},"tradingBot/signal/signals":{cost:1},"tradingBot/signal/orders-algo-details":{cost:1},"tradingBot/signal/orders-algo-pending":{cost:1},"tradingBot/signal/orders-algo-history":{cost:1},"tradingBot/signal/positions":{cost:1},"tradingBot/signal/positions-history":{cost:2},"tradingBot/signal/sub-orders":{cost:1},"tradingBot/signal/event-history":{cost:1},"tradingBot/recurring/orders-algo-pending":{cost:1},"tradingBot/recurring/orders-algo-history":{cost:1},"tradingBot/recurring/orders-algo-details":{cost:1},"tradingBot/recurring/sub-orders":{cost:1},"tradingBot/dca/ongoing-list":{cost:1},"tradingBot/dca/history-list":{cost:1},"tradingBot/dca/orders":{cost:1},"tradingBot/dca/position-details":{cost:1},"tradingBot/dca/cycle-list":{cost:1},"finance/savings/balance":{cost:5/3},"finance/savings/lending-history":{cost:5/3},"finance/staking-defi/offers":{cost:10/3},"finance/staking-defi/orders-active":{cost:10/3},"finance/staking-defi/orders-history":{cost:10/3},"finance/staking-defi/eth/product-info":{cost:10/3},"finance/staking-defi/eth/balance":{cost:5/3},"finance/staking-defi/eth/purchase-redeem-history":{cost:5/3},"finance/staking-defi/sol/product-info":{cost:10/3},"finance/staking-defi/sol/balance":{cost:5/3},"finance/staking-defi/sol/purchase-redeem-history":{cost:5/3},"finance/flexible-loan/borrow-currencies":{cost:4},"finance/flexible-loan/collateral-assets":{cost:4},"finance/flexible-loan/max-collateral-redeem-amount":{cost:4},"finance/flexible-loan/loan-info":{cost:4},"finance/flexible-loan/loan-history":{cost:4},"finance/flexible-loan/interest-accrued":{cost:4},"finance/flexible-loan/emode-info":{cost:4},"finance/okusd/limits":{cost:10},"finance/okusd/account":{cost:10},"finance/okusd/subscribe/history":{cost:4},"finance/okusd/redeem/history":{cost:4},"finance/okusd/rewards/history":{cost:4},"finance/okusd/rate/history":{cost:4},"finance/stable-rewards/product-info":{cost:4},"finance/stable-rewards/balance":{cost:4},"finance/stable-rewards/apy-history":{cost:5/3},"users/glp/todayperformance":{cost:4},"users/glp/historicalperformance":{cost:4},"copytrading/current-subpositions":{cost:1},"copytrading/subpositions-history":{cost:1},"copytrading/instruments":{cost:4},"copytrading/profit-sharing-details":{cost:4},"copytrading/total-profit-sharing":{cost:4},"copytrading/unrealized-profit-sharing-details":{cost:4},"copytrading/total-unrealized-profit-sharing":{cost:4},"copytrading/config":{cost:4},"copytrading/copy-settings":{cost:4},"copytrading/current-lead-traders":{cost:4},"copytrading/batch-leverage-info":{cost:4},"copytrading/lead-traders-history":{cost:4},"broker/dma/subaccount-info":{cost:2},"broker/dma/subaccount-trade-fee":{cost:10},"broker/dma/subaccount/apikey":{cost:10},"broker/dma/rebate-per-orders":{cost:300},"broker/fd/rebate-per-orders":{cost:300},"broker/fd/if-rebate":{cost:5},"broker/nd/info":{cost:10},"broker/nd/subaccount-info":{cost:10},"broker/nd/subaccount/apikey":{cost:10},"asset/broker/nd/subaccount-deposit-address":{cost:5/3},"asset/broker/nd/subaccount-deposit-history":{cost:4},"asset/broker/nd/subaccount-withdrawal-history":{cost:4},"broker/nd/rebate-daily":{cost:100},"broker/nd/rebate-per-orders":{cost:300},"finance/sfp/dcd/order":{cost:2},"finance/sfp/dcd/orders":{cost:2},"finance/sfp/dcd/currency-pair":{cost:2},"finance/sfp/dcd/order-status":{cost:2},"finance/sfp/dcd/order-history":{cost:2},"affiliate/invitee/detail":{cost:1},"affiliate/performance/summary":{cost:10/3},"affiliate/invitee/list":{cost:10/3},"affiliate/link/list":{cost:10/3},"affiliate/co-inviter/list":{cost:10/3},"affiliate/sub-affiliate/list":{cost:10/3},"users/partner/if-rebate":{cost:1},"support/announcements":{cost:4}},post:{"rfq/create-rfq":{cost:4},"rfq/cancel-rfq":{cost:4},"rfq/cancel-batch-rfqs":{cost:10},"rfq/cancel-all-rfqs":{cost:10},"rfq/execute-quote":{cost:15},"rfq/maker-instrument-settings":{cost:4},"rfq/mmp-reset":{cost:4},"rfq/mmp-config":{cost:100},"rfq/create-quote":{cost:.4},"rfq/cancel-quote":{cost:.4},"rfq/cancel-batch-quotes":{cost:10},"rfq/cancel-all-quotes":{cost:10},"rfq/cancel-all-after":{cost:10},"sprd/order":{cost:1},"sprd/cancel-order":{cost:1},"sprd/mass-cancel":{cost:1},"sprd/amend-order":{cost:1},"sprd/cancel-all-after":{cost:10},"trade/order":{cost:1/3},"trade/batch-orders":{cost:1/15},"trade/cancel-order":{cost:1/3},"trade/cancel-batch-orders":{cost:1/15},"trade/amend-order":{cost:1/3},"trade/amend-batch-orders":{cost:1/150},"trade/close-position":{cost:1},"trade/fills-archive":{cost:172800},"trade/cancel-advance-algos":{cost:1},"trade/easy-convert":{cost:20},"trade/one-click-repay":{cost:20},"trade/one-click-repay-v2":{cost:20},"trade/mass-cancel":{cost:4},"trade/cancel-all-after":{cost:10},"trade/order-precheck":{cost:4},"trade/order-algo":{cost:1},"trade/cancel-algos":{cost:1},"trade/amend-algos":{cost:1},"asset/transfer":{cost:5},"asset/withdrawal":{cost:5/3},"asset/withdrawal-lightning":{cost:5},"asset/cancel-withdrawal":{cost:5/3},"asset/convert-dust-assets":{cost:10},"asset/monthly-statement":{cost:1296e3},"asset/convert/estimate-quote":{cost:50},"asset/convert/trade":{cost:1},"fiat/create-withdrawal":{cost:10/3},"fiat/cancel-withdrawal":{cost:10/3},"fiat/buy-sell/quote":{cost:50},"fiat/buy-sell/trade":{cost:50},"account/bills-history-archive":{cost:72e3},"account/set-position-mode":{cost:4},"account/set-leverage":{cost:1},"account/position/margin-balance":{cost:1},"account/set-fee-type":{cost:4},"account/set-greeks":{cost:4},"account/set-isolated-mode":{cost:4},"account/spot-manual-borrow-repay":{cost:30},"account/set-auto-repay":{cost:4},"account/quick-margin-borrow-repay":{cost:4},"account/borrow-repay":{cost:5/3},"account/simulated_margin":{cost:10},"account/position-builder":{cost:10},"account/position-builder-graph":{cost:50},"account/set-riskOffset-type":{cost:2},"account/set-riskOffset-amt":{cost:2},"account/activate-option":{cost:4},"account/set-auto-loan":{cost:4},"account/account-level-switch-preset":{cost:4},"account/set-account-level":{cost:4},"account/set-collateral-assets":{cost:4},"account/mmp-reset":{cost:4},"account/mmp-config":{cost:50},"account/fixed-loan/borrowing-order":{cost:5},"account/fixed-loan/amend-borrowing-order":{cost:5},"account/fixed-loan/manual-reborrow":{cost:5},"account/fixed-loan/repay-borrowing-order":{cost:5},"account/move-positions":{cost:10},"account/set-auto-earn":{cost:10},"account/set-settle-currency":{cost:1},"account/set-trading-config":{cost:20},"account/demo-adjust-balance":{cost:20},"asset/subaccount/transfer":{cost:10},"account/subaccount/set-loan-allocation":{cost:4},"users/subaccount/create-subaccount":{cost:10},"users/subaccount/apikey":{cost:10},"users/subaccount/modify-apikey":{cost:10},"users/subaccount/subaccount-apikey":{cost:10},"users/subaccount/delete-apikey":{cost:10},"users/subaccount/set-transfer-out":{cost:10},"tradingBot/grid/order-algo":{cost:1},"tradingBot/grid/copy-order-algo":{cost:1},"tradingBot/grid/amend-algo-basic-param":{cost:1},"tradingBot/grid/amend-order-algo":{cost:1},"tradingBot/grid/stop-order-algo":{cost:1},"tradingBot/grid/close-position":{cost:1},"tradingBot/grid/cancel-close-order":{cost:1},"tradingBot/grid/order-instant-trigger":{cost:1},"tradingBot/grid/withdraw-income":{cost:1},"tradingBot/grid/compute-margin-balance":{cost:1},"tradingBot/grid/margin-balance":{cost:1},"tradingBot/grid/min-investment":{cost:1},"tradingBot/grid/adjust-investment":{cost:1},"tradingBot/signal/create-signal":{cost:1},"tradingBot/signal/order-algo":{cost:1},"tradingBot/signal/stop-order-algo":{cost:1},"tradingBot/signal/margin-balance":{cost:1},"tradingBot/signal/amendTPSL":{cost:1},"tradingBot/signal/set-instruments":{cost:1},"tradingBot/signal/close-position":{cost:1},"tradingBot/signal/sub-order":{cost:1},"tradingBot/signal/cancel-sub-order":{cost:1},"tradingBot/recurring/order-algo":{cost:1},"tradingBot/recurring/amend-order-algo":{cost:1},"tradingBot/recurring/stop-order-algo":{cost:1},"tradingBot/dca/create":{cost:1},"tradingBot/dca/amend-order-algo":{cost:1},"tradingBot/dca/stop":{cost:1},"tradingBot/dca/orders/manual-buy":{cost:1},"tradingBot/dca/settings/reinvestment":{cost:1},"tradingBot/dca/settings/take-profit":{cost:1},"tradingBot/dca/margin/add":{cost:1},"tradingBot/dca/margin/reduce":{cost:1},"tradingBot/recurring/add-investment":{cost:1},"tradingBot/recurring/amend-price-range":{cost:1},"tradingBot/recurring/amend-recurring-amount":{cost:1},"tradingBot/recurring/amend-recurring-time":{cost:1},"tradingBot/recurring/pause":{cost:1},"tradingBot/recurring/restart":{cost:1},"finance/savings/purchase-redempt":{cost:5/3},"finance/savings/set-lending-rate":{cost:5/3},"finance/staking-defi/purchase":{cost:5},"finance/staking-defi/redeem":{cost:5},"finance/staking-defi/cancel":{cost:5},"finance/staking-defi/eth/purchase":{cost:5},"finance/staking-defi/eth/redeem":{cost:5},"finance/staking-defi/eth/cancel-redeem":{cost:5},"finance/staking-defi/sol/purchase":{cost:5},"finance/staking-defi/sol/redeem":{cost:5},"finance/staking-defi/sol/cancel-redeem":{cost:5},"finance/flexible-loan/max-loan":{cost:4},"finance/flexible-loan/adjust-collateral":{cost:4},"finance/flexible-loan/borrow":{cost:10},"finance/flexible-loan/repay":{cost:10},"finance/okusd/subscribe":{cost:20},"finance/okusd/redeem":{cost:20},"copytrading/algo-order":{cost:1},"copytrading/close-subposition":{cost:1},"copytrading/set-instruments":{cost:4},"copytrading/amend-profit-sharing-ratio":{cost:4},"copytrading/first-copy-settings":{cost:4},"copytrading/amend-copy-settings":{cost:4},"copytrading/stop-copy-trading":{cost:4},"copytrading/batch-set-leverage":{cost:4},"broker/nd/create-subaccount":{cost:.25},"broker/nd/delete-subaccount":{cost:1},"broker/nd/subaccount/apikey":{cost:.25},"broker/nd/subaccount/modify-apikey":{cost:1},"broker/nd/subaccount/delete-apikey":{cost:1},"broker/nd/set-subaccount-level":{cost:4},"broker/nd/set-subaccount-fee-rate":{cost:4},"broker/nd/set-subaccount-assets":{cost:.25},"asset/broker/nd/subaccount-deposit-address":{cost:1},"asset/broker/nd/modify-subaccount-deposit-address":{cost:5/3},"broker/nd/rebate-per-orders":{cost:36e3},"finance/sfp/dcd/quote":{cost:10},"finance/sfp/dcd/order":{cost:10},"finance/sfp/dcd/trade":{cost:10},"finance/sfp/dcd/redeem-quote":{cost:10},"finance/sfp/dcd/redeem":{cost:10},"broker/nd/report-subaccount-ip":{cost:.25},"broker/dma/subaccount/apikey":{cost:1/4},"broker/dma/trades":{cost:36e3},"broker/fd/rebate-per-orders":{cost:36e3}}}},fees:{trading:{taker:this.parseNumber("0.0015"),maker:this.parseNumber("0.0010")},spot:{taker:this.parseNumber("0.0015"),maker:this.parseNumber("0.0010")},future:{taker:this.parseNumber("0.0005"),maker:this.parseNumber("0.0002")},swap:{taker:this.parseNumber("0.00050"),maker:this.parseNumber("0.00020")}},requiredCredentials:{apiKey:!0,secret:!0,password:!0},exceptions:{exact:{1:a.ExchangeError,2:a.ExchangeError,4088:a.ManualInteractionNeeded,5e4:a.BadRequest,50001:a.OnMaintenance,50002:a.BadRequest,50004:a.RequestTimeout,50005:a.ExchangeNotAvailable,50006:a.BadRequest,50007:a.AccountSuspended,50008:a.AuthenticationError,50009:a.AccountSuspended,50010:a.ExchangeError,50011:a.RateLimitExceeded,50012:a.ExchangeError,50013:a.ExchangeNotAvailable,50014:a.BadRequest,50015:a.ExchangeError,50016:a.ExchangeError,50017:a.ExchangeError,50018:a.ExchangeError,50019:a.ExchangeError,50020:a.ExchangeError,50021:a.ExchangeError,50022:a.ExchangeError,50023:a.ExchangeError,50024:a.BadRequest,50025:a.ExchangeError,50026:a.ExchangeNotAvailable,50027:a.PermissionDenied,50028:a.ExchangeError,50044:a.BadRequest,50061:a.ExchangeError,50062:a.ExchangeError,50100:a.ExchangeError,50101:a.AuthenticationError,50102:a.InvalidNonce,50103:a.AuthenticationError,50104:a.AuthenticationError,50105:a.AuthenticationError,50106:a.AuthenticationError,50107:a.AuthenticationError,50108:a.ExchangeError,50109:a.ExchangeError,50110:a.PermissionDenied,50111:a.AuthenticationError,50112:a.AuthenticationError,50113:a.AuthenticationError,50114:a.AuthenticationError,50115:a.BadRequest,51e3:a.BadRequest,51001:a.BadSymbol,51002:a.BadSymbol,51003:a.BadRequest,51004:a.InvalidOrder,51005:a.InvalidOrder,51006:a.InvalidOrder,51007:a.InvalidOrder,51008:a.InsufficientFunds,51009:a.AccountSuspended,51010:a.AccountNotEnabled,51011:a.InvalidOrder,51012:a.BadSymbol,51014:a.BadSymbol,51015:a.BadSymbol,51016:a.InvalidOrder,51017:a.ExchangeError,51018:a.ExchangeError,51019:a.ExchangeError,51020:a.InvalidOrder,51021:a.ContractUnavailable,51022:a.ContractUnavailable,51023:a.ExchangeError,51024:a.AccountSuspended,51025:a.ExchangeError,51026:a.BadSymbol,51027:a.ContractUnavailable,51028:a.ContractUnavailable,51029:a.ContractUnavailable,51030:a.ContractUnavailable,51031:a.InvalidOrder,51046:a.InvalidOrder,51047:a.InvalidOrder,51051:a.InvalidOrder,51072:a.InvalidOrder,51073:a.InvalidOrder,51074:a.InvalidOrder,51090:a.InvalidOrder,51091:a.InvalidOrder,51092:a.InvalidOrder,51093:a.InvalidOrder,51094:a.InvalidOrder,51095:a.InvalidOrder,51096:a.InvalidOrder,51098:a.InvalidOrder,51099:a.InvalidOrder,51100:a.InvalidOrder,51101:a.InvalidOrder,51102:a.InvalidOrder,51103:a.InvalidOrder,51104:a.InvalidOrder,51105:a.InvalidOrder,51106:a.InvalidOrder,51107:a.InvalidOrder,51108:a.InvalidOrder,51109:a.InvalidOrder,51110:a.InvalidOrder,51111:a.BadRequest,51112:a.InvalidOrder,51113:a.RateLimitExceeded,51115:a.InvalidOrder,51116:a.InvalidOrder,51117:a.InvalidOrder,51118:a.InvalidOrder,51119:a.InsufficientFunds,51120:a.InvalidOrder,51121:a.InvalidOrder,51122:a.InvalidOrder,51124:a.InvalidOrder,51125:a.InvalidOrder,51126:a.InvalidOrder,51127:a.InsufficientFunds,51128:a.InvalidOrder,51129:a.InvalidOrder,51130:a.BadSymbol,51131:a.InsufficientFunds,51132:a.InvalidOrder,51133:a.InvalidOrder,51134:a.InvalidOrder,51135:a.InvalidOrder,51136:a.InvalidOrder,51137:a.InvalidOrder,51138:a.InvalidOrder,51139:a.InvalidOrder,51155:a.RestrictedLocation,51156:a.BadRequest,51159:a.BadRequest,51162:a.InvalidOrder,51163:a.InvalidOrder,51166:a.InvalidOrder,51174:a.InvalidOrder,51185:a.InvalidOrder,51201:a.InvalidOrder,51202:a.InvalidOrder,51203:a.InvalidOrder,51204:a.InvalidOrder,51205:a.InvalidOrder,51250:a.InvalidOrder,51251:a.InvalidOrder,51252:a.InvalidOrder,51253:a.InvalidOrder,51254:a.InvalidOrder,51255:a.InvalidOrder,51256:a.InvalidOrder,51257:a.InvalidOrder,51258:a.InvalidOrder,51259:a.InvalidOrder,51260:a.InvalidOrder,51261:a.InvalidOrder,51262:a.InvalidOrder,51263:a.InvalidOrder,51264:a.InvalidOrder,51265:a.InvalidOrder,51267:a.InvalidOrder,51268:a.InvalidOrder,51269:a.InvalidOrder,51270:a.InvalidOrder,51271:a.InvalidOrder,51272:a.InvalidOrder,51273:a.InvalidOrder,51274:a.InvalidOrder,51275:a.InvalidOrder,51276:a.InvalidOrder,51277:a.InvalidOrder,51278:a.InvalidOrder,51279:a.InvalidOrder,51280:a.InvalidOrder,51321:a.InvalidOrder,51322:a.InvalidOrder,51323:a.BadRequest,51324:a.BadRequest,51325:a.InvalidOrder,51327:a.InvalidOrder,51328:a.InvalidOrder,51329:a.InvalidOrder,51330:a.InvalidOrder,51400:a.OrderNotFound,51401:a.OrderNotFound,51402:a.OrderNotFound,51403:a.InvalidOrder,51404:a.InvalidOrder,51405:a.ExchangeError,51406:a.ExchangeError,51407:a.BadRequest,51408:a.ExchangeError,51409:a.ExchangeError,51410:a.CancelPending,51500:a.ExchangeError,51501:a.ExchangeError,51502:a.InsufficientFunds,51503:a.ExchangeError,51506:a.ExchangeError,51508:a.ExchangeError,51509:a.ExchangeError,51510:a.ExchangeError,51511:a.ExchangeError,51600:a.ExchangeError,51601:a.ExchangeError,51602:a.ExchangeError,51603:a.OrderNotFound,51732:a.AuthenticationError,51733:a.AuthenticationError,51734:a.AuthenticationError,51735:a.ExchangeError,51736:a.InsufficientFunds,51763:a.AccountNotEnabled,51764:a.InsufficientFunds,51765:a.BadRequest,51766:a.ExchangeError,51767:a.OnMaintenance,51768:a.BadRequest,51769:a.ExchangeError,51770:a.BadRequest,51771:a.ExchangeError,51772:a.InsufficientFunds,51773:a.PermissionDenied,51774:a.OnMaintenance,52e3:a.ExchangeError,54e3:a.ExchangeError,54001:a.ExchangeError,54008:a.InvalidOrder,54009:a.InvalidOrder,54011:a.InvalidOrder,54051:a.InvalidOrder,54072:a.ExchangeError,54073:a.BadRequest,54074:a.ExchangeError,54094:a.InvalidOrder,55100:a.InvalidOrder,55101:a.InvalidOrder,55102:a.InvalidOrder,55103:a.InvalidOrder,55104:a.InvalidOrder,55111:a.InvalidOrder,55112:a.InvalidOrder,55113:a.InvalidOrder,58e3:a.ExchangeError,58001:a.AuthenticationError,58002:a.PermissionDenied,58003:a.ExchangeError,58004:a.AccountSuspended,58005:a.ExchangeError,58006:a.ExchangeError,58007:a.ExchangeError,58100:a.ExchangeError,58101:a.AccountSuspended,58102:a.RateLimitExceeded,58103:a.ExchangeError,58104:a.ExchangeError,58105:a.ExchangeError,58106:a.ExchangeError,58107:a.ExchangeError,58108:a.ExchangeError,58109:a.ExchangeError,58110:a.ExchangeError,58111:a.ExchangeError,58112:a.ExchangeError,58114:a.ExchangeError,58115:a.ExchangeError,58116:a.ExchangeError,58117:a.ExchangeError,58125:a.BadRequest,58126:a.BadRequest,58127:a.BadRequest,58128:a.BadRequest,58200:a.ExchangeError,58201:a.ExchangeError,58202:a.ExchangeError,58203:a.InvalidAddress,58204:a.AccountSuspended,58205:a.ExchangeError,58206:a.ExchangeError,58207:a.InvalidAddress,58208:a.ExchangeError,58209:a.ExchangeError,58210:a.ExchangeError,58211:a.ExchangeError,58212:a.ExchangeError,58213:a.AuthenticationError,58221:a.BadRequest,58222:a.BadRequest,58224:a.BadRequest,58227:a.BadRequest,58228:a.BadRequest,58229:a.InsufficientFunds,58300:a.ExchangeError,58350:a.InsufficientFunds,59e3:a.ExchangeError,59001:a.ExchangeError,59100:a.ExchangeError,59101:a.ExchangeError,59102:a.ExchangeError,59103:a.InsufficientFunds,59104:a.ExchangeError,59105:a.ExchangeError,59106:a.ExchangeError,59107:a.ExchangeError,59108:a.InsufficientFunds,59109:a.ExchangeError,59113:a.AuthenticationError,59128:a.InvalidOrder,59200:a.InsufficientFunds,59201:a.InsufficientFunds,59216:a.BadRequest,59260:a.PermissionDenied,59262:a.PermissionDenied,59300:a.ExchangeError,59301:a.ExchangeError,59313:a.ExchangeError,59401:a.ExchangeError,59410:a.OperationRejected,59411:a.InsufficientFunds,59412:a.OperationRejected,59413:a.OperationRejected,59414:a.BadRequest,59500:a.ExchangeError,59501:a.ExchangeError,59502:a.ExchangeError,59503:a.ExchangeError,59504:a.ExchangeError,59505:a.ExchangeError,59506:a.ExchangeError,59507:a.ExchangeError,59508:a.AccountSuspended,59515:a.ExchangeError,59516:a.ExchangeError,59517:a.ExchangeError,59518:a.ExchangeError,59519:a.ExchangeError,59642:a.BadRequest,59643:a.ExchangeError,59683:a.ExchangeError,59684:a.BadRequest,59686:a.BadRequest,60001:a.AuthenticationError,60002:a.AuthenticationError,60003:a.AuthenticationError,60004:a.AuthenticationError,60005:a.AuthenticationError,60006:a.InvalidNonce,60007:a.AuthenticationError,60008:a.AuthenticationError,60009:a.AuthenticationError,60010:a.AuthenticationError,60011:a.AuthenticationError,60012:a.BadRequest,60013:a.BadRequest,60014:a.RateLimitExceeded,60015:a.NetworkError,60016:a.ExchangeNotAvailable,60017:a.BadRequest,60018:a.BadRequest,60019:a.BadRequest,60020:a.ExchangeError,60021:a.AccountNotEnabled,60022:a.AuthenticationError,60023:a.DDoSProtection,60024:a.AuthenticationError,60025:a.ExchangeError,60026:a.AuthenticationError,60027:a.ArgumentsRequired,60028:a.NotSupported,60029:a.AccountNotEnabled,60030:a.AccountNotEnabled,60031:a.AuthenticationError,60032:a.AuthenticationError,63999:a.ExchangeError,64e3:a.BadRequest,64001:a.BadRequest,64002:a.BadRequest,64003:a.AccountNotEnabled,64004:a.BadRequest,64008:a.NetworkError,70010:a.BadRequest,70013:a.BadRequest,70016:a.BadRequest,70060:a.BadRequest,70061:a.BadRequest,70062:a.BadRequest,70064:a.BadRequest,70065:a.BadRequest,70066:a.BadRequest,70067:a.BadRequest,1009:a.BadRequest,4001:a.AuthenticationError,4002:a.BadRequest,4003:a.RateLimitExceeded,4004:a.NetworkError,4005:a.ExchangeNotAvailable,4006:a.BadRequest,4007:a.AuthenticationError,4008:a.RateLimitExceeded},broad:{"Internal Server Error":a.ExchangeNotAvailable,"server error":a.ExchangeNotAvailable}},httpExceptions:{429:a.ExchangeNotAvailable},precisionMode:4,options:{sandboxMode:!1,defaultNetwork:"ERC20",defaultNetworks:{ETH:"ERC20",BTC:"BTC",USDT:"TRC20"},networks:{BTC:"Bitcoin",BTCLIGHTNING:"Lightning",BSC:"BSC",BEP20:"BSC",BRC20:"BRC20",ETH:"ERC20",ERC20:"ERC20",TRX:"TRC20",TRC20:"TRC20",CRC20:"Crypto",CRONOS:"Crypto",ACA:"Acala",ALGO:"Algorand",APT:"Aptos",SONIC:"Sonic",SCROLL:"Scroll",ARBITRUM:"Arbitrum One",AVAXC:"Avalanche C-Chain",AVAXX:"Avalanche X-Chain",BASE:"Base",SUI:"SUI",ZKSYNCERA:"zkSync Era",LINEA:"Linea",VAULTA:"Vaulta",AR:"Arweave",ASTR:"Astar",BCH:"BitcoinCash",BSV:"Bitcoin SV",ADA:"Cardano",CSPR:"Casper",CANTON:"Canton Network",CELO:"CELO",XCH:"Chia",BABY:"Babylon",ATOM:"Cosmos",DGB:"Digibyte",DOGE:"Dogecoin",EGLD:"Elrond",CFX:"Conflux",EOS:"EOS",CORE:"CORE",ETC:"Ethereum Classic",ETHW:"EthereumPow",FIL:"Filecoin",HBAR:"Hedera",HYPER:"HyperEVM",ICP:"Dfinity",PI:"PI",IOTA:"MIOTA",KLAY:"Klaytn",KSM:"Kusama",LSK:"Lisk",LTC:"Litecoin",METIS:"Metis",MINA:"Mina",GLRM:"Moonbeam",MOVR:"Moonriver",NANO:"Nano",NEAR:"NEAR",NULS:"NULS",OASYS:"OASYS",ONT:"Ontology",OP:"Optimism",DOT:"Polkadot",MATIC:"Polygon",RVN:"Ravencoin",XRP:"Ripple",SC:"Siacoin",SOL:"Solana",STX:"l-Stacks",XLM:"Stellar Lumens",XTZ:"Tezos",TON:"TON",THETA:"Theta",WAX:"Wax",ZIL:"Zilliqa",ZEC:"Zcash",ZETA:"ZetaChain",TIA:"Celestia",SEI:"SEI",QUANTUM:"Quantum",PHAROS:"Pharos",RONIN:"Ronin",MEGAETH:"MegaETH",INJ:"INJ",FOGO:"Fogo",FLR:"Flare",FLOW:"FLOW",DYDX:"DYDX",AELF:"AELF",BERA:"Berachain",TEMPO:"Tempo",MONAD:"Monad",PLASMA:"Plasma"},networksById:{ERC20:"ERC20",TRC20:"TRC20",BEP20:"BEP20"},fetchOpenInterestHistory:{timeframes:{"5m":"5m","1h":"1H","8h":"8H","1d":"1D","5M":"5m","1H":"1H","8H":"8H","1D":"1D"}},fetchOHLCV:{timezone:"UTC"},fetchPositions:{method:"privateGetAccountPositions"},createOrder:"privatePostTradeBatchOrders",createMarketBuyOrderRequiresPrice:!1,fetchMarkets:{types:["spot","future","swap","option"]},timeDifference:0,adjustForTimeDifference:!1,defaultType:"spot",fetchLedger:{method:"privateGetAccountBills"},fetchOrder:{method:"privateGetTradeOrder"},fetchOpenOrders:{method:"privateGetTradeOrdersPending"},cancelOrders:{method:"privatePostTradeCancelBatchOrders"},fetchCanceledOrders:{method:"privateGetTradeOrdersHistory",paginationDirection:"forward"},fetchClosedOrders:{method:"privateGetTradeOrdersHistory",paginationDirection:"forward"},withdraw:{password:void 0,pwd:void 0},algoOrderTypes:{conditional:!0,trigger:!0,oco:!0,move_order_stop:!0,iceberg:!0,twap:!0},accountsByType:{funding:"6",trading:"18",spot:"18",future:"18",futures:"18",margin:"18",swap:"18",option:"18"},accountsById:{6:"funding",18:"trading"},exchangeType:{spot:"SPOT",margin:"MARGIN",swap:"SWAP",future:"FUTURES",futures:"FUTURES",option:"OPTION",SPOT:"SPOT",MARGIN:"MARGIN",SWAP:"SWAP",FUTURES:"FUTURES",OPTION:"OPTION"},brokerId:"6b9ad766b55dBCDE"},features:{default:{sandbox:!0,createOrder:{marginMode:!0,triggerPrice:!0,triggerPriceType:{last:!0,mark:!0,index:!0},triggerDirection:!1,stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:{triggerPriceType:{last:!0,mark:!0,index:!0},price:!0},timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!0,trailing:!0,iceberg:!0,leverage:!1,selfTradePrevention:!0,marketBuyByCost:!0,marketBuyRequiresPrice:!1},createOrders:{max:20},fetchMyTrades:{marginMode:!1,daysBack:90,limit:100,untilDays:1e4,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!0,trailing:!0,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:100,trigger:!0,trailing:!0,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:100,daysBack:90,daysBackCanceled:1/12,untilDays:void 0,trigger:!0,trailing:!0,symbolRequired:!1},fetchOHLCV:{limit:300,mark:100,index:100}},spot:{extends:"default",fetchCurrencies:{private:!0}},swap:{linear:{extends:"default"},inverse:{extends:"default"}},future:{linear:{extends:"default"},inverse:{extends:"default"}}},currencies:{USD:this.safeCurrencyStructure({id:"USD",code:"USD",precision:this.parseNumber("0.0001")}),EUR:this.safeCurrencyStructure({id:"EUR",code:"EUR",precision:this.parseNumber("0.0001")}),AED:this.safeCurrencyStructure({id:"AED",code:"AED",precision:this.parseNumber("0.0001")}),GBP:this.safeCurrencyStructure({id:"GBP",code:"GBP",precision:this.parseNumber("0.0001")}),AUD:this.safeCurrencyStructure({id:"AUD",code:"AUD",precision:this.parseNumber("0.0001")})},commonCurrencies:{AE:"AET"},rollingWindowSize:0})}handleMarketTypeAndParams(e,t,i={},s){let r=this.safeString(i,"instType"),a=this.omit(i,"instType");return void 0===this.safeString(a,"type")&&void 0!==r&&(a.type=r),super.handleMarketTypeAndParams(e,t,a,s)}convertToInstrumentType(e){let t=this.safeDict(this.options,"exchangeType",{});return this.safeString(t,e,e)}createExpiredOptionMarket(e){let t,i=e.split("-"),s=e.split("/"),r=t=e.indexOf("/")>-1?this.safeString(s,0):this.safeString(i,0),a=this.safeString(i,2),o=this.safeString(i,3),n=this.safeString(i,4),d=void 0===a?void 0:this.convertExpireDate(a),h=this.parse8601(d);return{id:t+"-USD-"+a+"-"+o+"-"+n,symbol:t+"/USD:"+r+"-"+a+"-"+o+"-"+n,base:t,quote:"USD",settle:r,baseId:t,quoteId:"USD",settleId:r,active:!1,type:"option",linear:void 0,inverse:void 0,spot:!1,swap:!1,future:!1,option:!0,margin:!1,contract:!0,contractSize:this.parseNumber("1"),expiry:h,expiryDatetime:d,optionType:"C"===n?"call":"put",strike:this.parseNumber(o),precision:{amount:void 0,price:void 0},limits:{amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:void 0,max:void 0}},info:void 0}}safeMarket(e,t,i,s){let r=!1;return(void 0!==e&&(r=e.split("-").length>3&&(e.endsWith("-C")||e.endsWith("-P"))),!r||void 0===e||void 0!==this.markets_by_id&&e in this.markets_by_id)?super.safeMarket(e,t,i,s):this.createExpiredOptionMarket(e)}async fetchStatus(e={}){let t=await this.publicGetSystemStatus(e),i=this.safeList(t,"data",[]),s={updated:void 0,status:0===i.length?"ok":"maintenance",eta:void 0,url:void 0,info:t};for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),r=this.safeString(t,"state");s.eta=this.safeInteger(t,"end"),s.url=this.safeString(t,"href"),"ongoing"===r?s.status="maintenance":"scheduled"===r||"completed"===r?s.status="ok":"canceled"===r&&(s.status="ok")}return s}async fetchTime(e={}){let t=await this.publicGetPublicTime(e),i=this.safeList(t,"data",[]),s=this.safeDict(i,0,{});return this.safeInteger(s,"ts")}async fetchAccounts(e={}){let t=await this.privateGetAccountConfig(e),i=this.safeList(t,"data",[]),s=[];for(let e=0;e<i.length;e++){let t=i[e],r=this.safeString(t,"uid"),a=this.safeString(t,"acctLv");s.push({id:r,type:a,currency:void 0,info:t,code:void 0})}return s}nonce(){let e=this.safeInteger(this.options,"timeDifference");if(void 0===e)throw new a.ExchangeError(this.id+' nonce() requires a numeric options["timeDifference"]');return this.milliseconds()-e}async fetchMarkets(e={}){this.safeBool(this.options,"adjustForTimeDifference",!1)&&await this.loadTimeDifference();let t=["spot","future","swap","option"],i=this.safeDict(this.options,"fetchMarkets");t=void 0!==i?this.safeList(i,"types",t):this.safeList(this.options,"fetchMarkets",t);let s=[],r=[];for(let i=0;i<t.length;i++)s.push(this.fetchMarketsByType(t[i],e));s=await Promise.all(s);for(let e=0;e<s.length;e++)r=this.arrayConcat(r,s[e]);return r}parseMarket(e){let t,i,s,r=this.safeString(e,"instId",""),a=this.safeStringLower(e,"instType");"futures"===a&&(a="future");let n="spot"===a,d="future"===a,h="swap"===a,c="option"===a,l=h||d||c,u=this.safeString(e,"baseCcy",""),f=this.safeString(e,"quoteCcy",""),p=this.safeString(e,"settleCcy"),m=this.safeCurrencyCode(p),g=this.safeString(e,"uly");if(void 0!==g&&!n){let e=g.split("-");u=this.safeString(e,0,""),f=this.safeString(e,1,"")}if((""===u||""===f)&&n){let t=this.safeString(e,"instId","").split("-");u=this.safeString(t,0,""),f=this.safeString(t,1,"")}let v=this.safeCurrencyCode(u),y=this.safeCurrencyCode(f);if(void 0===v||void 0===y)return;let b=v+"/"+y;(""===v||""===y)&&(b=r),l&&(void 0!==m&&(b=b+":"+m),d?void 0!==(t=this.safeInteger(e,"expTime"))&&(b=b+"-"+this.yymmdd(t)):c&&(t=this.safeInteger(e,"expTime"),i=this.safeString(e,"stk"),s=this.safeString(e,"optType"),void 0!==t&&(b=b+"-"+this.yymmdd(t)+"-"+i+"-"+s,s="P"===s?"put":"call")));let w=void 0===a?"":a,k=this.safeDict2(this.fees,w,"trading",{}),S=this.safeString(e,"lever","1");S=o.Y.stringMax(S,"1");let O=this.safeNumber(e,"maxMktSz"),T=o.Y.stringGt(S,"1"),P=f===p,I=u===p,A=this.safeString(e,"state"),x=this.safeInteger(e,"instIdCode");return this.extend(k,{id:r,instIdCode:x,symbol:b,base:v,quote:y,settle:m,baseId:u,quoteId:f,settleId:p,type:a,spot:n,margin:n&&T,swap:h,future:d,option:c,active:"live"===A,contract:l,linear:l?P:void 0,inverse:l?I:void 0,contractSize:l?this.safeNumber(e,"ctVal"):void 0,expiry:t,expiryDatetime:this.iso8601(t),strike:this.parseNumber(i),optionType:s,created:this.safeInteger2(e,"contTdSwTime","listTime"),precision:{amount:this.safeNumber(e,"lotSz"),price:this.safeNumber(e,"tickSz")},limits:{leverage:{min:this.parseNumber("1"),max:this.parseNumber(S)},amount:{min:this.safeNumber(e,"minSz"),max:this.safeNumber(e,"maxLmtSz")},price:{min:void 0,max:void 0},cost:{min:void 0,max:l?void 0:O}},info:e})}async fetchMarketsByType(e,t={}){let i={instType:this.convertToInstrumentType(e)};if("option"===e){let e=this.safeList(this.options,"defaultUnderlying",["BTC-USD","ETH-USD"]),s=[];for(let r=0;r<e.length;r++)i.uly=e[r],s.push(this.publicGetPublicInstruments(this.extend(i,t)));let r=await Promise.all(s),a=[];for(let e=0;e<r.length;e++){let t=this.safeDict(r,e,{}),i=this.safeList(t,"data",[]);a=this.arrayConcat(a,i)}return this.parseMarkets(a)}let s=await this.publicGetPublicInstruments(this.extend(i,t)),r=this.safeList(s,"data",[]),a=[];for(let e=0;e<r.length;e++){let t=r[e];if(""!==this.safeString(t,"instId","")){if(this.isSandboxModeEnabled&&this.safeString(t,"instFamily","").startsWith("TEST"))continue;a.push(t)}}return this.parseMarkets(a)}async fetchCurrencies(e={}){let t=this.safeBool(this.options,"sandboxMode",!1);if(!this.checkRequiredCredentials(!1)||!0===t)return{};let i=await this.privateGetAssetCurrencies(e),s=this.safeList(i,"data",[]),r=Object.values(this.groupBy(s,"ccy"));return this.parseCurrencies(r)}parseCurrency(e){let t=this.safeDict(e,0,{}),i=this.safeString(t,"ccy"),s=this.safeCurrencyCode(i),r={},a="crypto",o=e.length;for(let t=0;t<o;t++){let i=this.safeDict(e,t),o=this.safeString(i,"chain","");""===o&&(a="fiat");let n=o.split("-"),d=this.arraySlice(n,1).join("-"),h=this.networkIdToCode(d,s);void 0!==h&&(r[h]={id:o,network:h,active:void 0,deposit:this.safeBool(i,"canDep"),withdraw:this.safeBool(i,"canWd"),fee:this.safeNumber(i,"fee"),precision:this.parseNumber(this.parsePrecision(this.safeString(i,"wdTickSz"))),limits:{withdraw:{min:this.safeNumber(i,"minWd"),max:this.safeNumber(i,"maxWd")}},info:i})}return this.safeCurrencyStructure({info:e,code:s,id:i,name:this.safeString(t,"name"),active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,precision:void 0,limits:{amount:{min:void 0,max:void 0}},type:a,networks:r})}async fetchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r={instId:this.market(e).id},[a,o]=this.handleOptionBoolAndParams(i,"fetchOrderBook","rpi",!1),[n,d]=this.handleOptionStringAndParams(o,"fetchOrderBook","method","publicGetMarketBooks"),h=void 0===t?"publicGetMarketBooksFull"===n?5e3:100:t,c=h;a&&h>400&&(c=400),void 0!==c&&(r.sz=c),s=a?await this.publicGetMarketBooksRpi(this.extend(r,d)):"publicGetMarketBooksFull"===n||c>400?await this.publicGetMarketBooksFull(this.extend(r,d)):await this.publicGetMarketBooks(this.extend(r,d));let l=this.safeList(s,"data",[]),u=this.safeDict(l,0,{}),f=this.safeInteger(u,"ts");return this.parseOrderBook(u,e,f)}parseTicker(e,t){let i,s=this.safeString(e,"instType");void 0!==s&&(i="SPOT"===s?"spot":"swap");let r=this.safeInteger(e,"ts"),a=this.safeString(e,"instId"),o=this.safeMarket(a,t,"-",i),n=o.symbol,d=this.safeString(e,"last"),h=this.safeString(e,"open24h"),c=!0===this.safeBool(o,"spot",!1)?this.safeString(e,"volCcy24h"):void 0,l=this.safeString(e,"vol24h"),u=this.safeString(e,"high24h"),f=this.safeString(e,"low24h");return this.safeTicker({symbol:n,timestamp:r,datetime:this.iso8601(r),high:u,low:f,bid:this.safeString(e,"bidPx"),bidVolume:this.safeString(e,"bidSz"),ask:this.safeString(e,"askPx"),askVolume:this.safeString(e,"askSz"),vwap:void 0,open:h,close:d,last:d,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:l,quoteVolume:c,markPrice:this.safeString(e,"markPx"),indexPrice:this.safeString(e,"idxPx"),info:e},o)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instId:i.id},r=await this.publicGetMarketTicker(this.extend(s,t)),a=this.safeList(r,"data",[]),o=this.safeDict(a,0,{});return this.parseTicker(o,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=this.getMarketFromSymbols(i),[r,o]=this.handleMarketTypeAndParams("fetchTickers",s,t),n={instType:this.convertToInstrumentType(r)};if("option"===r){let e=this.safeString(this.options,"defaultUnderlying","BTC-USD"),t=this.safeString2(o,"uly","marketId",e);if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchTickers() requires an underlying uly or marketId parameter for options markets");n.uly=t}let d=await this.publicGetMarketTickers(this.extend(n,o)),h=this.safeList(d,"data",[]);return this.parseTickers(h,i)}async fetchMarkPrice(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instId:i.id},r=await this.publicGetPublicMarkPrice(this.extend(s,t)),a=this.safeList(r,"data");return this.parseTicker(this.safeDict(a,0),i)}async fetchMarkPrices(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=this.getMarketFromSymbols(i),[r,o]=this.handleMarketTypeAndParams("fetchMarkPrices",s,t,"swap"),n={instType:this.convertToInstrumentType(r)};if("option"===r){let e=this.safeString(this.options,"defaultUnderlying","BTC-USD"),t=this.safeString2(o,"uly","marketId",e);if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchMarkPrices() requires an underlying uly or marketId parameter for options markets");n.uly=t}let d=await this.publicGetPublicMarkPrice(this.extend(n,o)),h=this.safeList(d,"data",[]);return this.parseTickers(h,i)}parseTrade(e,t){let i,s=this.safeString(e,"tradeId"),r=this.safeString(e,"instId"),a=this.safeMarket(r,t,"-"),n=a.symbol,d=this.safeInteger(e,"ts"),h=this.safeString2(e,"fillPx","px"),c=this.safeString2(e,"fillSz","sz"),l=this.safeString(e,"side"),u=this.safeString(e,"ordId"),f=this.safeString(e,"fee");if(void 0!==f){let t=o.Y.stringNeg(f),s=this.safeString(e,"feeCcy");i={cost:t,currency:this.safeCurrencyCode(s)}}let p=this.safeString(e,"execType");return"T"===p?p="taker":"M"===p&&(p="maker"),this.safeTrade({info:e,timestamp:d,datetime:this.iso8601(d),symbol:n,id:s,order:u,type:void 0,takerOrMaker:p,side:l,price:h,amount:c,cost:void 0,fee:i},a)}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchTrades","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchTrades",e,t,i,o,"tradeId","after",void 0,100);let n=this.market(e),d={instId:n.id};if(!0===n.option)r=await this.publicGetPublicOptionTrades(this.extend(d,o));else{void 0!==i&&(d.limit=i);let[e,t]=this.handleOptionStringAndParams(o,"fetchTrades","method","publicGetMarketTrades");"publicGetMarketTrades"===e?r=await this.publicGetMarketTrades(this.extend(d,t)):"publicGetMarketHistoryTrades"===e&&(r=await this.publicGetMarketHistoryTrades(this.extend(d,t)))}let h=this.safeList(r,"data",[]);return this.parseTrades(h,n,t,i)}parseOHLCV(e,t){let i=this.handleMarketTypeAndParams("fetchOHLCV",t,void 0)[0];return[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,"spot"===i?5:6)]}async fetchOHLCV(e,t="1m",i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),[n,d]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(n)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,d,200);let h=this.safeString(d,"price"),c=this.inArray(h,["mark","index"]),l=this.omit(d,"price"),u=this.safeDict(this.options,"fetchOHLCV",{}),f=this.safeString(u,"timezone","UTC"),p=void 0===s,m=300;c&&(m=100);let g=100;void 0!==s&&(g=Math.min(s,m));let v=this.parseTimeframe(t),y=this.safeString(this.timeframes,t,t);"UTC"===f&&v>=21600&&(y+=f.toLowerCase());let b={instId:o.id,bar:y,limit:g},w="Candles";if(void 0!==i){let e=this.milliseconds(),t=1e3*v;i<e-1439*t&&(w="HistoryCandles",g=Math.min(g,c?100:300)),b.before=Math.max(i-1,0),b.after=this.sum(i,t*g)}let k=this.safeInteger(l,"until");void 0!==k&&(b.after=k);let S=void 0!==k?this.omit(l,"until"):l;w=this.safeString(u,"type",w);let O=this.safeString(S,"type",w),T=this.omit(S,"type"),P="HistoryCandles"===O;"mark"===h?a=P?await this.publicGetMarketHistoryMarkPriceCandles(this.extend(b,T)):await this.publicGetMarketMarkPriceCandles(this.extend(b,T)):"index"===h?(b.instId=o.info.instFamily,a=P?await this.publicGetMarketHistoryIndexCandles(this.extend(b,T)):await this.publicGetMarketIndexCandles(this.extend(b,T))):P?(p&&100===g&&(g=300,b.limit=300),a=await this.publicGetMarketHistoryCandles(this.extend(b,T))):a=await this.publicGetMarketCandles(this.extend(b,T));let I=this.safeList(a,"data",[]);return this.parseOHLCVs(I,o,t,i,g)}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let[r,o]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(r)return await this.fetchPaginatedCallDeterministic("fetchFundingRateHistory",e,t,i,"8h",o,100);let n=this.market(e),d={instId:n.id};void 0!==t&&(d.before=Math.max(t-1,0)),void 0!==i&&(d.limit=i);let h=await this.publicGetPublicFundingRateHistory(this.extend(d,o)),c=[],l=this.safeList(h,"data",[]);for(let e=0;e<l.length;e++){let t=l[e],i=this.safeInteger(t,"fundingTime");c.push({info:t,symbol:this.safeSymbol(this.safeString(t,"instId")),fundingRate:this.safeNumber(t,"realizedRate"),timestamp:i,datetime:this.iso8601(i)})}let u=this.sortBy(c,"timestamp");return this.filterBySymbolSinceLimit(u,this.safeString(n,"symbol"),t,i)}parseBalanceByType(e,t){return"funding"===e?this.parseFundingBalance(t):this.parseTradingBalance(t)}parseTradingBalance(e){let t={info:e},i=this.safeList(e,"data",[]),s=this.safeDict(i,0,{}),r=this.safeInteger(s,"uTime"),a=this.safeList(s,"details",[]);for(let e=0;e<a.length;e++){let i=this.safeDict(a,e),s=this.safeString(i,"ccy"),r=this.safeCurrencyCode(s),o=this.account(),n=this.safeString(i,"eq"),d=this.safeString(i,"availEq");o.total=n,void 0===d?(o.free=this.safeString(i,"availBal"),o.used=this.safeString(i,"frozenBal")):o.free=d,void 0!==r&&(t[r]=o)}return t.timestamp=r,t.datetime=this.iso8601(r),this.safeBalance(t)}parseFundingBalance(e){let t={info:e},i=this.safeList(e,"data",[]);for(let e=0;e<i.length;e++){let s=this.safeDict(i,e),r=this.safeString(s,"ccy"),a=this.safeCurrencyCode(r),o=this.account();o.total=this.safeString(s,"bal"),o.free=this.safeString(s,"availBal"),o.used=this.safeString(s,"frozenBal"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}parseTradingFee(e,t){return{info:e,symbol:this.safeSymbol(void 0,t),maker:this.parseNumber(o.Y.stringNeg(this.safeString2(e,"maker","makerU"))),taker:this.parseNumber(o.Y.stringNeg(this.safeString2(e,"taker","takerU"))),percentage:void 0,tierBased:void 0}}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instType:this.convertToInstrumentType(i.type)};if(!0===i.spot)s.instId=i.id;else if(!0===i.swap||!0===i.future||!0===i.option)s.uly=i.baseId+"-"+i.quoteId;else throw new a.NotSupported(this.id+" fetchTradingFee() supports spot, swap, future or option markets only");let r=await this.privateGetAccountTradeFee(this.extend(s,t)),o=this.safeList(r,"data",[]),n=this.safeDict(o,0,{});return this.parseTradingFee(n,i)}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleMarketTypeAndParams("fetchBalance",void 0,e),r={};return t="funding"===i?await this.privateGetAssetBalances(this.extend(r,s)):await this.privateGetAccountBalance(this.extend(r,s)),this.parseBalanceByType(i,t)}async createMarketBuyOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new a.NotSupported(this.id+" createMarketBuyOrderWithCost() supports spot markets only");return await this.createOrder(e,"market","buy",t,void 0,this.extend({createMarketBuyOrderRequiresPrice:!1,tgtCcy:"quote_ccy"},i))}async createMarketSellOrderWithCost(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),!0!==this.market(e).spot)throw new a.NotSupported(this.id+" createMarketSellOrderWithCost() supports spot markets only");return await this.createOrder(e,"market","sell",t,void 0,this.extend({createMarketBuyOrderRequiresPrice:!1,tgtCcy:"quote_ccy"},i))}createOrderRequest(e,t,i,s,r,n={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let d=this.market(e),h=this.safeValue2(n,"takeProfitPrice","tpTriggerPx"),c=this.safeValue2(n,"stopLossPrice","slTriggerPx"),l=void 0!==c||void 0!==h||"conditional"===t,u={instId:d.id,side:i,ordType:t},f=l||"oco"===t,p=this.safeString(n,"closeFraction");f&&void 0!==p||(u.sz=this.amountToPrecision(e,s));let m=d.spot,g=d.contract,v=this.safeValueN(n,["triggerPrice","stopPrice","triggerPx"]),y=this.safeString(n,"timeInForce","GTC"),b=this.safeNumber(n,"tpOrdPx",r),w=this.safeString(n,"tpTriggerPxType","last"),k=this.safeNumber(n,"slOrdPx",r),S=this.safeString(n,"slTriggerPxType","last"),O=this.safeString2(n,"clOrdId","clientOrderId"),T=this.safeDict(n,"stopLoss"),P=this.safeDict(n,"takeProfit"),I=void 0!==T,A=void 0!==P,x=this.safeString2(n,"trailingPercent","callbackRatio"),M=void 0!==x,_=this.safeString2(n,"trailingPrice","callbackSpread"),C=void 0!==_,B=void 0!==v||"trigger"===t,E=this.safeBool(n,"reduceOnly",!1)||void 0!==p,R=this.safeString2(this.options,"defaultMarginMode","marginMode","cross"),L=this.safeString2(n,"marginMode","tdMode"),N=!1;void 0!==L&&"cash"!==L?N=!0:(L=R,N=this.safeBool(n,"margin",!1));let D=!0===g&&(!0===d.swap||!0===d.future),[q,F]=this.handleOptionStringAndParams(n,"createOrder","positionSide"),V=n;D&&(V=F);let G=D&&void 0===q,[H,U]=this.handleOptionBoolAndParams(V,"createOrder","hedged"),W=V;G&&(W=U);let j=W;if(G&&!0===H&&E&&(j=this.omit(W,"reduceOnly")),!0===m){if(!0===N){let e="buy"===i?d.quote:d.base,t=this.safeString(n,"ccy",e);u.ccy=this.safeCurrencyCode(t)}let e=!0===N?L:"cash";u.tdMode=e}else if(!0===g){if(!0===d.swap||!0===d.future){if(void 0!==q)u.posSide=q;else if(!0===H){let e="buy"===i;void 0!==h||void 0!==c||E?u.posSide=e?"short":"long":u.posSide=e?"long":"short"}}u.tdMode=L}let K="market"===t,[z,Y]=this.handlePostOnly(K,"post_only"===t,j),X=this.omit(Y,["currency","ccy","marginMode","timeInForce","stopPrice","triggerPrice","clientOrderId","stopLossPrice","takeProfitPrice","slOrdPx","tpOrdPx","margin","stopLoss","takeProfit","trailingPercent"]),Q="IOC"===y||"ioc"===t,Z="FOK"===y||"fok"===t,J=K&&Q||"optimal_limit_ioc"===t,$=this.safeString(this.options,"tgtCcy","base_ccy"),ee=this.safeString(X,"tgtCcy",$);if(!0!==g&&!0!==N&&(u.tgtCcy=ee),K||J){if(u.ordType="market",!0===m&&"buy"===i&&"quote_ccy"===ee){let[t,i]=this.handleOptionBoolAndParams(X,"createOrder","createMarketBuyOrderRequiresPrice",!0),n=this.safeNumber2(i,"cost","sz");if(X=this.omit(i,["cost","sz"]),t){if(void 0!==r){if(void 0===n){let e=this.numberToString(s),t=this.numberToString(r),i=o.Y.stringMul(e,t);n=this.parseNumber(i)}}else if(void 0===n)throw new a.InvalidOrder(this.id+" createOrder() requires the price argument with market buy orders to calculate total order cost (amount to spend), where cost = amount * price. Supply a price argument to createOrder() call if you want the cost to be calculated for you from price and amount, or, alternatively, add .options['createMarketBuyOrderRequiresPrice'] = false and supply the total cost value in the 'amount' argument or in the 'cost' unified extra parameter or in exchange-specific 'sz' extra parameter (the exchange-specific behaviour)")}else n=void 0===n?s:n;u.sz=this.costToPrecision(e,n)}J&&!0===g&&(u.ordType="optimal_limit_ioc")}else B||l||(u.px=this.priceToPrecision(e,r));if(z?u.ordType="post_only":Q&&!J?u.ordType="ioc":Z&&(u.ordType="fok"),M){let e=o.Y.stringDiv(x,"100");u.callbackRatio=e,u.ordType="move_order_stop"}else if(C)u.callbackSpread=_,u.ordType="move_order_stop";else if(I||A){let t={};if(I){let i=this.safeValueN(T,["triggerPrice","stopPrice","slTriggerPx"]);if(void 0===i)throw new a.InvalidOrder(this.id+' createOrder() requires a trigger price in params["stopLoss"]["triggerPrice"], or params["stopLoss"]["stopPrice"], or params["stopLoss"]["slTriggerPx"] for a stop loss order');let s=this.priceToPrecision(e,i),r={};r.slTriggerPx=s;let o=this.safeValueN(T,["price","stopLossPrice","slOrdPx"]),n=this.safeString(T,"type");if(void 0!==n){let t="limit"===n;if(t||"market"===n)if(t)if(void 0===o)throw new a.InvalidOrder(this.id+' createOrder() requires a limit price in params["stopLoss"]["price"] or params["stopLoss"]["slOrdPx"] for a stop loss limit order');else r.slOrdPx=this.priceToPrecision(e,o);else"market"===n&&(r.slOrdPx="-1");else throw new a.InvalidOrder(this.id+' createOrder() params["stopLoss"]["type"] must be either "limit" or "market"')}else void 0!==o?r.slOrdPx=this.priceToPrecision(e,o):r.slOrdPx="-1";let d=this.safeString2(T,"triggerPriceType","slTriggerPxType","last");if(void 0!==d){if("last"!==d&&"index"!==d&&"mark"!==d)throw new a.InvalidOrder(this.id+' createOrder() stop loss trigger price type must be one of "last", "index" or "mark"');r.slTriggerPxType=d}t=this.extend(t,r)}if(A){let i=this.safeValueN(P,["triggerPrice","stopPrice","tpTriggerPx"]);if(void 0===i)throw new a.InvalidOrder(this.id+' createOrder() requires a trigger price in params["takeProfit"]["triggerPrice"], or params["takeProfit"]["stopPrice"], or params["takeProfit"]["tpTriggerPx"] for a take profit order');let s={};s.tpTriggerPx=this.priceToPrecision(e,i);let r=this.safeValueN(P,["price","takeProfitPrice","tpOrdPx"]),o=this.safeString2(P,"type","tpOrdKind");if(void 0!==o){let t="limit"===o,i="market"===o;if(t||i)if(t)if(void 0===r)throw new a.InvalidOrder(this.id+' createOrder() requires a limit price in params["takeProfit"]["price"] or params["takeProfit"]["tpOrdPx"] for a take profit limit order');else s.tpOrdKind=o,s.tpOrdPx=this.priceToPrecision(e,r);else"market"===o&&(s.tpOrdPx="-1");else throw new a.InvalidOrder(this.id+' createOrder() params["takeProfit"]["type"] must be either "limit" or "market"')}else void 0!==r?(s.tpOrdKind="limit",s.tpOrdPx=this.priceToPrecision(e,r)):s.tpOrdPx="-1";let n=this.safeString2(P,"triggerPriceType","tpTriggerPxType","last");if(void 0!==n){if("last"!==n&&"index"!==n&&"mark"!==n)throw new a.InvalidOrder(this.id+' createOrder() take profit trigger price type must be one of "last", "index" or "mark"');s.tpTriggerPxType=n}t=this.extend(t,s)}Object.keys(t).length>0&&(u.attachAlgoOrds=[t])}if(B)u.ordType="trigger",u.triggerPx=this.priceToPrecision(e,v),u.orderPx=K?"-1":this.priceToPrecision(e,r);else if(l){if(u.ordType="conditional",void 0!==h&&void 0!==c&&(u.ordType="oco"),"sell"===i&&(u=this.omit(u,"tgtCcy")),"cash"===this.safeString(u,"tdMode")&&(u.tdMode=L),void 0!==h){u.tpTriggerPx=this.priceToPrecision(e,h);let t="-1";void 0!==b&&(t=this.priceToPrecision(e,b)),u.tpOrdPx=t,u.tpTriggerPxType=w}if(void 0!==c){u.slTriggerPx=this.priceToPrecision(e,c);let t="-1";void 0!==k&&(t=this.priceToPrecision(e,k)),u.slOrdPx=t,u.slTriggerPxType=S}}if(void 0===O){let e=this.safeString(this.options,"brokerId");void 0!==e&&(u.clOrdId=e+this.uuid16(),u.tag=e)}else u.clOrdId=O,X=this.omit(X,["clOrdId","clientOrderId"]);return this.extend(u,X)}async createOrder(e,t,i,s,r,o={}){let n;void 0===this.markets&&await this.loadMarkets();let d=this.market(e),h=this.createOrderRequest(e,t,i,s,r,o),c=this.safeString(this.options,"createOrder","privatePostTradeBatchOrders"),l=this.safeString(h,"ordType");if(("trigger"===l||"conditional"===l||"move_order_stop"===l||"move_order_stop"===t||"oco"===t||"iceberg"===t||"twap"===t)&&(c="privatePostTradeOrderAlgo"),"privatePostTradeOrder"!==c&&"privatePostTradeOrderAlgo"!==c&&"privatePostTradeBatchOrders"!==c)throw new a.ExchangeError(this.id+' createOrder() this.options["createOrder"] must be either privatePostTradeBatchOrders or privatePostTradeOrder or privatePostTradeOrderAlgo');"privatePostTradeBatchOrders"===c&&(h=[h]),n="privatePostTradeOrder"===c?await this.privatePostTradeOrder(h):"privatePostTradeOrderAlgo"===c?await this.privatePostTradeOrderAlgo(h):await this.privatePostTradeBatchOrders(h);let u=this.safeList(n,"data",[]),f=this.safeDict(u,0,{}),p=this.parseOrder(f,d);return p.type=t,p.side=i,p}async createOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=[];for(let s=0;s<e.length;s++){let r=this.safeDict(e,s),o=this.safeString(r,"symbol");if(void 0===o)throw new a.ArgumentsRequired(this.id+" createOrders() requires a symbol for each order");let n=this.safeString(r,"type",""),d=this.safeString(r,"side"),h=this.safeNumber(r,"amount"),c=this.safeNumber(r,"price"),l=this.safeDict(r,"params",{}),u=this.extend(l,t),f=this.createOrderRequest(o,n,d,h,c,u);i.push(f)}let s=await this.privatePostTradeBatchOrders(i),r=this.safeList(s,"data",[]);return this.parseOrders(r)}editOrderRequest(e,t,i,s,r,o,n={}){let d,h={instId:this.market(t).id};("trigger"===i||"conditional"===i||"move_order_stop"===i||"oco"===i||"iceberg"===i||"twap"===i)&&(d=!0);let c=this.safeString2(n,"clOrdId","clientOrderId");void 0!==c?d?h.algoClOrdId=c:h.clOrdId=c:d?h.algoId=e:h.ordId=e;let l=this.safeNumber2(n,"stopLossPrice","newSlTriggerPx"),u=this.safeNumber(n,"newSlOrdPx"),f=this.safeString(n,"newSlTriggerPxType","last"),p=this.safeNumber2(n,"takeProfitPrice","newTpTriggerPx"),m=this.safeNumber(n,"newTpOrdPx"),g=this.safeString(n,"newTpTriggerPxType","last"),v=this.safeDict(n,"stopLoss"),y=this.safeDict(n,"takeProfit"),b=void 0!==v,w=void 0!==y;if(d){if(void 0===l&&void 0===p)throw new a.BadRequest(this.id+" editOrder() requires a stopLossPrice or takeProfitPrice parameter for editing an algo order");if(void 0!==l){if(void 0===u)throw new a.BadRequest(this.id+" editOrder() requires a newSlOrdPx parameter for editing an algo order");h.newSlTriggerPx=this.priceToPrecision(t,l),h.newSlOrdPx="market"===i?"-1":this.priceToPrecision(t,u),h.newSlTriggerPxType=f}if(void 0!==p){if(void 0===m)throw new a.BadRequest(this.id+" editOrder() requires a newTpOrdPx parameter for editing an algo order");h.newTpTriggerPx=this.priceToPrecision(t,p),h.newTpOrdPx="market"===i?"-1":this.priceToPrecision(t,m),h.newTpTriggerPxType=g}}else{if(void 0!==l&&(h.newSlTriggerPx=this.priceToPrecision(t,l),h.newSlOrdPx="market"===i?"-1":this.priceToPrecision(t,u),h.newSlTriggerPxType=f),void 0!==p&&(h.newTpTriggerPx=this.priceToPrecision(t,p),h.newTpOrdPx="market"===i?"-1":this.priceToPrecision(t,m),h.newTpTriggerPxType=g),b){l=this.safeNumber(v,"triggerPrice"),u=this.safeNumber(v,"price");let e=this.safeString(v,"type");h.newSlTriggerPx=this.priceToPrecision(t,l),h.newSlOrdPx="market"===e?"-1":this.priceToPrecision(t,u),h.newSlTriggerPxType=f}if(w){p=this.safeNumber(y,"triggerPrice"),m=this.safeNumber(y,"price");let e=this.safeString(y,"type");h.newTpOrdKind="limit"===e?e:"condition",h.newTpTriggerPx=this.priceToPrecision(t,p),h.newTpOrdPx="market"===e?"-1":this.priceToPrecision(t,m),h.newTpTriggerPxType=g}}void 0!==r&&(h.newSz=this.amountToPrecision(t,r)),d||void 0===o||(h.newPx=this.priceToPrecision(t,o));let k=this.omit(n,["clOrdId","clientOrderId","takeProfitPrice","stopLossPrice","stopLoss","takeProfit","postOnly"]);return this.extend(h,k)}async editOrder(e,t,i,s,r,a,o={}){let n,d;void 0===this.markets&&await this.loadMarkets();let h=this.market(t),c=this.editOrderRequest(e,t,i,s,r,a,o);("trigger"===i||"conditional"===i||"move_order_stop"===i||"oco"===i||"iceberg"===i||"twap"===i)&&(d=!0),n=d?await this.privatePostTradeAmendAlgos(this.extend(c,o)):await this.privatePostTradeAmendOrder(this.extend(c,o));let l=this.safeList(n,"data",[]),u=this.safeDict(l,0,{}),f=this.parseOrder(u,h);return f.type=i,f.side=s,f}async cancelOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");let s=this.safeBool2(i,"stop","trigger"),r=this.safeBool(i,"trailing",!1);if(!0===s||!0===r){let s=await this.cancelOrders([e],t,i);return this.safeDict(s,0)}void 0===this.markets&&await this.loadMarkets();let o=this.market(t),n={instId:o.id},d=this.safeString2(i,"clOrdId","clientOrderId");void 0!==d?n.clOrdId=d:n.ordId=e;let h=this.omit(i,["clOrdId","clientOrderId"]),c=await this.privatePostTradeCancelOrder(this.extend(n,h)),l=this.safeList(c,"data",[]),u=this.safeDict(l,0);return this.parseOrder(u,o)}parseIds(e){return void 0!==e&&"string"==typeof e?e.split(","):e}async cancelOrders(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),o=[],n=this.safeDict(this.options,"cancelOrders",{}),d=this.safeString(n,"method","privatePostTradeCancelBatchOrders"),h=this.safeString(i,"method",d),c=this.parseIds(this.safeValue2(i,"clOrdId","clientOrderId")),l=this.parseIds(this.safeValue(i,"algoId")),u=this.safeBool2(i,"stop","trigger"),f=this.safeBool(i,"trailing",!1),p=!0===u;if((p||!0===f)&&(h="privatePostTradeCancelAlgos"),void 0===c){let t=this.parseIds(e);if(void 0!==l)for(let e=0;e<l.length;e++)o.push({algoId:l[e],instId:r.id});for(let e=0;e<t.length;e++)!0===f||p?o.push({algoId:t[e],instId:r.id}):o.push({ordId:t[e],instId:r.id})}else for(let e=0;e<c.length;e++)!0===f||p?o.push({instId:r.id,algoClOrdId:c[e]}):o.push({instId:r.id,clOrdId:c[e]});s="privatePostTradeCancelAlgos"===h?await this.privatePostTradeCancelAlgos(o):await this.privatePostTradeCancelBatchOrders(o);let m=this.safeList(s,"data",[]),g=this.omit(i,["clOrdId","clientOrderId","algoId","stop","trigger","trailing","method"]);return this.parseOrders(m,r,void 0,void 0,g)}async cancelOrdersForSymbols(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=[],r=this.safeDict(this.options,"cancelOrders",{}),o=this.safeString(r,"method","privatePostTradeCancelBatchOrders"),n=this.safeString(t,"method",o),d=this.safeBool2(t,"stop","trigger"),h=this.safeBool(t,"trailing",!1),c=!0===d||!0===h;!0===c&&(n="privatePostTradeCancelAlgos");for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),r=this.safeString(i,"id"),o=this.safeString2(i,"clOrdId","clientOrderId"),n=this.safeString(i,"symbol");if(void 0===n)throw new a.ArgumentsRequired(this.id+" cancelOrders() requires a symbol for each order");let d=this.market(n),h="ordId";!0===c?h="algoId":void 0!==o&&(h="clOrdId");let l={instId:d.id};l[h]=void 0!==o?o:r,s.push(l)}i="privatePostTradeCancelAlgos"===n?await this.privatePostTradeCancelAlgos(s):await this.privatePostTradeCancelBatchOrders(s);let l=this.safeList(i,"data",[]);return this.parseOrders(l,void 0,void 0,void 0,t)}async cancelAllOrdersAfter(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=0;void 0!==e&&e>0&&(i=this.parseToInt(e/1e3));let s={timeOut:i};return await this.privatePostTradeCancelAllAfter(this.extend(s,t))}parseOrderStatus(e){if(void 0!==e)return this.safeString({canceled:"canceled",order_failed:"canceled",mmp_canceled:"canceled",live:"open",partially_filled:"open",partially_effective:"open",filled:"closed",effective:"closed"},e,e)}parseOrder(e,t){let i,s,r,a,n,d=this.safeString(e,"sCode");if(void 0!==d&&"0"!==d)return this.safeOrder({id:this.safeString(e,"ordId"),clientOrderId:this.safeString(e,"clOrdId"),status:"rejected",info:e});let h=this.safeString2(e,"algoId","ordId"),c=this.safeInteger(e,"cTime"),l=this.safeInteger(e,"uTime"),u=this.safeInteger(e,"fillTime"),f=this.safeString(e,"side"),p=this.safeString(e,"ordType");"post_only"===p?(i=!0,p="limit"):"fok"===p?(s="FOK",p="limit"):"ioc"===p?(s="IOC",p="limit"):"rpi"===p&&(i=!0,p="limit");let m=this.safeString(e,"instId"),g=this.safeMarket(m,t),v=this.safeSymbol(m,g,"-"),y=this.safeString(e,"accFillSz"),b=this.safeString2(e,"px","ordPx"),w=this.safeString(e,"avgPx"),k=this.parseOrderStatus(this.safeString(e,"state")),S=this.safeString(e,"fee"),O=this.safeString(this.options,"tgtCcy","base_ccy"),T=this.safeString(e,"tgtCcy",O),P=this.safeString(e,"instType");if("buy"===f&&"market"===p&&"SPOT"===P&&"quote_ccy"===T?a=this.safeString(e,"sz"):r=this.safeString(e,"sz"),void 0!==S){let t=o.Y.stringNeg(S),i=this.safeString(e,"feeCcy"),s=this.safeCurrencyCode(i);n={cost:this.parseNumber(t),currency:s}}let I=this.safeString(e,"clOrdId");void 0!==I&&I.length<1&&(I=void 0);let A=this.safeNumber2(e,"slTriggerPx","slOrdPx"),x=this.safeNumber2(e,"tpTriggerPx","tpOrdPx"),M=this.safeString(e,"reduceOnly"),_=!1;return void 0!==M&&(_="true"===M),this.safeOrder({info:e,id:h,clientOrderId:I,timestamp:c,datetime:this.iso8601(c),lastTradeTimestamp:u,lastUpdateTimestamp:l,symbol:v,type:p,timeInForce:s,postOnly:i,side:f,price:b,stopLossPrice:A,takeProfitPrice:x,triggerPrice:this.safeNumberN(e,["triggerPx","moveTriggerPx"]),average:w,cost:a,amount:r,filled:y,remaining:void 0,status:k,fee:n,trades:void 0,reduceOnly:_},g)}async fetchOrder(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),o={instId:r.id},n=this.safeString2(i,"clOrdId","clientOrderId"),d=this.safeDict(this.options,"fetchOrder",{}),h=this.safeString(d,"method","privateGetTradeOrder"),c=this.safeString(i,"method",h);!0===this.safeBool2(i,"stop","trigger")?(c="privateGetTradeOrderAlgo",void 0!==n?o.algoClOrdId=n:o.algoId=e):void 0!==n?o.clOrdId=n:o.ordId=e;let l=this.omit(i,["method","clOrdId","clientOrderId","stop","trigger"]);s="privateGetTradeOrderAlgo"===c?await this.privateGetTradeOrderAlgo(this.extend(o,l)):await this.privateGetTradeOrder(this.extend(o,l));let u=this.safeList(s,"data",[]),f=this.safeDict(u,0);return this.parseOrder(f,r)}async fetchOpenOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(s,"fetchOpenOrders","paginate",!1);if(o)return await this.fetchPaginatedCallDynamic("fetchOpenOrders",e,t,i,n,100);let d={};void 0!==e&&(d.instId=(a=this.market(e)).id),void 0!==i&&(d.limit=Math.min(i,100));let h=this.safeDict(this.options,"fetchOpenOrders",{}),c=this.safeDict(this.options,"algoOrderTypes",{}),l=this.safeString(h,"method","privateGetTradeOrdersPending"),u=this.safeString(n,"method",l),f=this.safeString(n,"ordType"),p=this.safeBool2(n,"stop","trigger"),m=this.safeBool(n,"trailing",!1),g=!0===p;(!0===m||g||void 0!==f&&f in c)&&(u="privateGetTradeOrdersAlgoPending"),!0===m?d.ordType="move_order_stop":g&&void 0===f&&(d.ordType="trigger");let v=this.omit(n,["method","stop","trigger","trailing"]);r="privateGetTradeOrdersAlgoPending"===u?await this.privateGetTradeOrdersAlgoPending(this.extend(d,v)):await this.privateGetTradeOrdersPending(this.extend(d,v));let y=this.safeList(r,"data",[]);return this.parseOrders(y,a,t,i)}async fetchCanceledOrders(e,t,i,s={}){let r,o,n,d;void 0===this.markets&&await this.loadMarkets();let h={};void 0!==e&&(h.instId=(n=this.market(e)).id),[d,r]=this.handleMarketTypeAndParams("fetchCanceledOrders",n,s),h.instType=this.convertToInstrumentType(d),void 0!==i&&(h.limit=i),h.state="canceled";let c=this.safeDict(this.options,"fetchCanceledOrders",{}),l=this.safeDict(this.options,"algoOrderTypes",{}),u=this.safeString(c,"method","privateGetTradeOrdersHistory"),f=this.safeString(s,"method",u),p=this.safeString(s,"ordType"),m=this.safeBool2(s,"stop","trigger"),g=this.safeBool(s,"trailing",!1),v=!0===m;if(!0===g)f="privateGetTradeOrdersAlgoHistory",h.ordType="move_order_stop";else if(v||void 0!==p&&p in l){f="privateGetTradeOrdersAlgoHistory";let e=this.safeString(s,"algoId");if(void 0!==e&&(h.algoId=e),v&&void 0===p)throw new a.ArgumentsRequired(this.id+' fetchCanceledOrders() requires an "ordType" string parameter, "conditional", "oco", "trigger", "move_order_stop", "iceberg", or "twap"')}else{void 0!==t&&(h.begin=t);let e=this.safeInteger(r,"until");void 0!==e&&(h.end=e,r=this.omit(r,["until"]))}let y=this.omit(r,["method","stop","trigger","trailing"]);o="privateGetTradeOrdersAlgoHistory"===f?await this.privateGetTradeOrdersAlgoHistory(this.extend(h,y)):await this.privateGetTradeOrdersHistory(this.extend(h,y));let b=this.safeList(o,"data",[]);return this.parseOrders(b,n,t,i)}async fetchClosedOrders(e,t,i,s={}){let r,a,o,n;void 0===this.markets&&await this.loadMarkets();let[d,h]=this.handleOptionBoolAndParams(s,"fetchClosedOrders","paginate",!1);if(d)return await this.fetchPaginatedCallDynamic("fetchClosedOrders",e,t,i,h,100);let c={};void 0!==e&&(c.instId=(o=this.market(e)).id),[n,r]=this.handleMarketTypeAndParams("fetchClosedOrders",o,h),c.instType=this.convertToInstrumentType(n),void 0!==i&&(c.limit=Math.min(i,100));let l=this.safeDict(this.options,"fetchClosedOrders",{}),u=this.safeDict(this.options,"algoOrderTypes",{}),f=this.safeString(l,"method","privateGetTradeOrdersHistory"),p=this.safeString(h,"method",f),m=this.safeString(h,"ordType"),g=this.safeBool2(h,"stop","trigger"),v=this.safeBool(h,"trailing",!1);if((!0===v||!0===g||void 0!==m&&m in u)&&(p="privateGetTradeOrdersAlgoHistory",c.state="effective"),!0===v)c.ordType="move_order_stop";else if(!0===g)void 0===m&&(c.ordType="trigger");else{void 0!==t&&(c.begin=t);let e=this.safeInteger(r,"until");void 0!==e&&(c.end=e,r=this.omit(r,["until"])),c.state="filled"}let y=this.omit(r,["method","stop","trigger","trailing"]);a="privateGetTradeOrdersAlgoHistory"===p?await this.privateGetTradeOrdersAlgoHistory(this.extend(c,y)):"privateGetTradeOrdersHistoryArchive"===p?await this.privateGetTradeOrdersHistoryArchive(this.extend(c,y)):await this.privateGetTradeOrdersHistory(this.extend(c,y));let b=this.safeList(a,"data",[]);return this.parseOrders(b,o,t,i)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,o);let n={};void 0!==e&&(n.instId=(r=this.market(e)).id),void 0!==t&&(n.begin=t);let[d,h]=this.handleUntilOption("end",n,o),[c,l]=this.handleMarketTypeAndParams("fetchMyTrades",r,h);d.instType=this.convertToInstrumentType(c),void 0!==i&&void 0===t&&(d.limit=i);let u=await this.privateGetTradeFillsHistory(this.extend(d,l)),f=this.safeList(u,"data",[]);return this.parseTrades(f,r,t,i,l)}async fetchOrderTrades(e,t,i,s,r={}){return await this.fetchMyTrades(t,i,s,this.extend({ordId:e},r))}async fetchLedger(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let[o,n]=this.handleOptionBoolAndParams(s,"fetchLedger","paginate",!1);if(o)return await this.fetchPaginatedCallDynamic("fetchLedger",e,t,i,n);let d=this.safeDict(this.options,"fetchLedger",{}),h=this.safeString(d,"method");h=this.safeString(n,"method",h);let c=this.omit(n,"method"),l={},[u,f]=this.handleMarginModeAndParams("fetchLedger",c),p=void 0===u?this.safeString(f,"mgnMode"):u;"privateGetAssetBills"!==h&&void 0!==p&&(l.mgnMode=p);let[m,g]=this.handleMarketTypeAndParams("fetchLedger",void 0,f);void 0!==m&&(l.instType=this.convertToInstrumentType(m)),void 0!==i&&(l.limit=i),void 0!==e&&(l.ccy=(a=this.currency(e)).id);let v=this.handleUntilOption("end",l,f)[0];r="privateGetAccountBillsArchive"===h?await this.privateGetAccountBillsArchive(this.extend(v,g)):"privateGetAssetBills"===h?await this.privateGetAssetBills(this.extend(v,g)):await this.privateGetAccountBills(this.extend(v,g));let y=this.safeList(r,"data",[]);return this.parseLedger(y,a,t,i)}parseLedgerEntryType(e){return this.safeString({1:"transfer",2:"trade",3:"trade",4:"rebate",5:"trade",6:"transfer",7:"trade",8:"fee",9:"trade",10:"trade",11:"trade"},e,e)}parseLedgerEntry(e,t){let i,s=this.safeString(e,"ccy"),r=this.safeCurrencyCode(s,t),a=this.safeCurrency(s,t),n=this.safeInteger(e,"ts"),d=this.safeString(e,"fee");void 0!==d&&(i={cost:this.parseNumber(o.Y.stringNeg(d)),currency:r});let h=this.safeString(e,"instId"),c=this.safeSymbol(h,void 0,"-");return this.safeLedgerEntry({info:e,id:this.safeString(e,"billId"),timestamp:n,datetime:this.iso8601(n),account:void 0,referenceId:this.safeString(e,"ordId"),referenceAccount:void 0,type:this.parseLedgerEntryType(this.safeString(e,"type")),currency:r,symbol:c,amount:this.safeNumber(e,"balChg"),before:void 0,after:this.safeNumber(e,"bal"),status:"ok",fee:i},a)}parseDepositAddress(e,t){let i=this.safeString(e,"addr"),s=this.safeStringN(e,["tag","pmtId","memo"]);if(void 0===s){let t=this.safeDict(e,"addrEx",{});s=this.safeString(t,"comment")}let r=this.safeString(e,"ccy"),a=this.safeCurrency(r,t),o=a.code,n=this.safeString(e,"chain"),d=this.safeDict(a,"networks",{}),h=this.indexBy(d,"id"),c=void 0===n?void 0:this.safeDict(h,n);"USDT-Polygon"===n&&(c=this.safeDict2(h,"USDT-Polygon-Bridge","USDT-Polygon"));let l=this.safeString(c,"network"),u=this.networkIdToCode(l,o);return this.checkAddress(i),{info:e,currency:o,network:u,address:i,tag:s}}async fetchDepositAddressesByNetwork(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.currency(e),s={ccy:i.id},r=await this.privateGetAssetDepositAddress(this.extend(s,t)),a=this.safeList(r,"data",[]),o=this.filterBy(a,"selected",!0),n=this.parseDepositAddresses(o,[i.code],!1);return this.indexBy(n,"network")}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeString(t,"network"),s=this.omit(t,"network"),r=this.safeCurrencyCode(e),o=this.networkIdToCode(i,r),n=await this.fetchDepositAddressesByNetwork(r,s);if(void 0!==o){let e=this.safeDict(n,o);if(void 0===e)throw new a.InvalidAddress(this.id+" fetchDepositAddress() cannot find "+o+" deposit address for "+r);return e}let d=this.networkIdToCode(r,r);if(void 0!==d&&d in n)return n[d];let h=Object.keys(n),c=this.safeString(h,0,"");return this.safeDict(n,c)}async withdraw(e,t,i,s,r={}){let[o,n]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets();let d=this.currency(e),h=void 0!==o&&o.length>0,c=i;h&&(c=i+":"+o);let l={ccy:d.id,toAddr:c,dest:"4",amt:this.numberToString(t)},u=this.safeString(n,"network");if(void 0!==u){let e=this.safeDict(this.options,"networks",{});u=this.safeString(e,u.toUpperCase(),u),l.chain=d.id+"-"+u}let f=["fee"];void 0!==u&&f.push("network");let p=this.safeString(n,"fee");if(void 0===p){let e=await this.fetchCurrencies();this.currencies=this.mapToSafeMap(this.deepExtend(this.currencies,e));let t=this.networkIdToCode(u,this.safeString(d,"code")),i=void 0===t?{}:this.safeDict(d.networks,t,{});if(void 0===(p=this.safeString(i,"fee")))throw new a.ArgumentsRequired(this.id+' withdraw() requires a "fee" string parameter, network transaction fee must be ≥ 0. Withdrawals to OKCoin or OKX are fee-free, please set "0". Withdrawing to external digital asset address requires network transaction fee.')}l.fee=this.numberToString(p);let m=this.omit(n,f),g=await this.privatePostAssetWithdrawal(this.extend(l,m)),v=this.safeList(g,"data",[]),y=this.safeDict(v,0);return this.parseTransaction(y,d)}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchDeposits","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchDeposits",e,t,i,o);let n={};void 0!==e&&(n.ccy=(r=this.currency(e)).id),void 0!==t&&(n.before=Math.max(t-1,0)),void 0!==i&&(n.limit=i);let[d,h]=this.handleUntilOption("after",n,o),c=await this.privateGetAssetDepositHistory(this.extend(d,h)),l=this.safeList(c,"data",[]);return this.parseTransactions(l,r,t,i,h)}async fetchDeposit(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r={depId:e};void 0!==t&&(r.ccy=(s=this.currency(t)).id);let a=await this.privateGetAssetDepositHistory(this.extend(r,i)),o=this.safeList(a,"data"),n=this.safeDict(o,0,{});return this.parseTransaction(n,s)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchWithdrawals","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchWithdrawals",e,t,i,o);let n={};void 0!==e&&(n.ccy=(r=this.currency(e)).id),void 0!==t&&(n.before=Math.max(t-1,0)),void 0!==i&&(n.limit=i);let[d,h]=this.handleUntilOption("after",n,o),c=await this.privateGetAssetWithdrawalHistory(this.extend(d,h)),l=this.safeList(c,"data",[]);return this.parseTransactions(l,r,t,i,h)}async fetchWithdrawal(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={wdId:e};void 0!==t&&(s.ccy=this.currency(t).id);let r=await this.privateGetAssetWithdrawalHistory(this.extend(s,i)),a=this.safeList(r,"data",[]),o=this.safeDict(a,0,{});return this.parseTransaction(o)}parseTransactionStatus(e){if(void 0!==e)return this.safeString({"-3":"pending","-2":"canceled","-1":"failed",0:"pending",1:"pending",2:"ok",3:"pending",4:"pending",5:"pending",6:"pending",7:"pending",8:"pending",9:"pending",10:"pending",12:"pending",15:"pending",16:"pending"},e,e)}parseTransaction(e,t){let i,s,r,a,o=this.safeString(e,"wdId"),n=this.safeString(e,"from"),d=this.safeString(e,"to"),h=this.safeString2(e,"tag","memo");h=void 0===h?this.safeString(e,"pmtId"):this.safeString2(e,"pmtId",h),void 0!==o?(i="withdrawal",s=o):(s=this.safeString(e,"depId"),i="deposit");let c=this.safeString(e,"ccy"),l=this.safeCurrencyCode(c),u=this.safeString(e,"chain");if(void 0!==u){let e=u.split("-"),t=this.arraySlice(e,1).join("-");r=this.networkIdToCode(t,l)}let f=this.safeNumber(e,"amt"),p=this.parseTransactionStatus(this.safeString(e,"state")),m=this.safeString(e,"txId"),g=this.safeInteger(e,"ts");return a="deposit"===i?0:this.safeNumber(e,"fee"),{info:e,id:s,currency:l,amount:f,network:r,addressFrom:n,addressTo:d,address:d,tagFrom:void 0,tagTo:h,tag:h,status:p,type:i,updated:void 0,txid:m,timestamp:g,datetime:this.iso8601(g),internal:void 0,comment:void 0,fee:{currency:l,cost:a}}}async fetchLeverage(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeString(t,"mgnMode","cross"),[s,r]=this.handleMarginModeAndParams("fetchLeverage",t,i);if("cross"!==s&&"isolated"!==s)throw new a.BadRequest(this.id+" fetchLeverage() requires a marginMode parameter that must be either cross or isolated");let o=this.market(e),n={instId:o.id,mgnMode:s},d=await this.privateGetAccountLeverageInfo(this.extend(n,r)),h=this.safeList(d,"data",[]);return this.parseLeverage(h,o)}parseLeverage(e,t){let i,s,r,a;for(let t=0;t<e.length;t++){let o=this.safeDict(e,t);s=this.safeStringLower(o,"mgnMode"),i=this.safeString(o,"instId");let n=this.safeStringLower(o,"posSide");"long"===n?r=this.safeInteger(o,"lever"):("short"===n||(r=this.safeInteger(o,"lever")),a=this.safeInteger(o,"lever"))}return{info:e,symbol:this.safeSymbol(i,t),marginMode:s,longLeverage:r,shortLeverage:a}}async fetchPosition(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),[s,r]=this.handleMarketTypeAndParams("fetchPosition",i,t),o={instId:i.id};void 0!==s&&(o.instType=this.convertToInstrumentType(s));let n=await this.privateGetAccountPositions(this.extend(o,r)),d=this.safeList(n,"data",[]),h=this.safeDict(d,0);if(void 0===h)throw new a.NullResponse(this.id+" fetchPosition() could not find a position for "+e);return this.parsePosition(h,i)}async fetchPositions(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={};if(void 0!==e){let t=[];for(let i=0;i<e.length;i++){let s=e[i],r=this.market(s);t.push(r.id)}t.length>0&&(s.instId=t.join(","))}let r=this.safeDict(this.options,"fetchPositions",{});i="privateGetAccountPositionsHistory"===this.safeString(r,"method","privateGetAccountPositions")?await this.privateGetAccountPositionsHistory(this.extend(s,t)):await this.privateGetAccountPositions(this.extend(s,t));let a=this.safeList(i,"data",[]),o=[];for(let e=0;e<a.length;e++)o.push(this.parsePosition(a[e]));return this.filterByArrayPositions(o,"symbol",this.marketSymbols(e))}async fetchPositionsForSymbol(e,t={}){return await this.fetchPositions([e],t)}parsePosition(e,t){let i,s,r,a=this.safeString(e,"instId"),n=this.safeMarket(a,t,void 0,"contract"),d=n.symbol,h=this.safeString(e,"pos"),c=o.Y.stringAbs(h),l=this.safeString2(e,"posSide","direction"),u="net"!==l,f=this.parseNumber(c);if(!0===n.margin){if("net"===l){let t=this.safeString(e,"posCcy"),i=this.safeCurrencyCode(t);void 0!==i&&(l=n.base===i?"long":"short")}void 0===l&&(l=this.safeString(e,"direction"))}else void 0!==h&&"net"===l&&(l=o.Y.stringGt(h,"0")?"long":o.Y.stringLt(h,"0")?"short":void 0);let p=this.safeNumber(n,"contractSize"),m=this.numberToString(p),g=this.safeString(e,"markPx"),v=this.safeString(e,"notionalUsd");!0===n.inverse&&(v=o.Y.stringDiv(o.Y.stringMul(c,m),g));let y=this.parseNumber(v),b=this.safeString(e,"mgnMode"),w=this.safeString2(e,"avgPx","openAvgPx"),k=this.safeString(e,"upl"),S=this.safeString(e,"lever");"cross"===b?(i=this.safeString(e,"imr"),r=o.Y.stringAdd(i,k)):"isolated"===b&&(s=o.Y.stringDiv("1",S),r=this.safeString(e,"margin"));let O=this.safeString(e,"mmr"),T=this.parseNumber(O),P=o.Y.stringDiv(O,v);if(void 0===s)s=this.parseNumber(o.Y.stringDiv(i,v,4));else if(void 0===i)if(!0===n.linear){let e=this.numberToString(s);i=o.Y.stringMul(e,v)}else i=o.Y.stringDiv(o.Y.stringDiv(o.Y.stringMul(c,m),w),S);let I=this.parseNumber(o.Y.stringDiv(o.Y.stringAdd(P,"0.00005"),"1",4)),A=this.safeNumber(e,"liqPx"),x=this.safeString(e,"uplRatio"),M=this.parseNumber(o.Y.stringMul(x,"100")),_=this.safeInteger(e,"cTime"),C=this.parseNumber(o.Y.stringDiv(O,r,4));return this.safePosition({info:e,id:this.safeString(e,"posId"),symbol:d,notional:y,marginMode:b,liquidationPrice:A,entryPrice:this.parseNumber(w),unrealizedPnl:this.parseNumber(k),realizedPnl:this.safeNumber(e,"realizedPnl"),percentage:M,contracts:f,contractSize:p,markPrice:this.parseNumber(g),lastPrice:this.safeNumber(e,"closeAvgPx"),side:l,hedged:u,timestamp:_,datetime:this.iso8601(_),lastUpdateTimestamp:this.safeInteger(e,"uTime"),maintenanceMargin:T,maintenanceMarginPercentage:I,collateral:this.parseNumber(r),initialMargin:this.parseNumber(i),initialMarginPercentage:this.parseNumber(s),leverage:this.parseNumber(S),marginRatio:C,stopLossPrice:void 0,takeProfitPrice:void 0})}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(e),o=this.safeDict(this.options,"accountsByType",{}),n=this.safeString(o,i,i),d=this.safeString(o,s,s),h={ccy:a.id,amt:this.currencyToPrecision(e,t),type:"0",from:n,to:d};"master"===n?(h.type="1",h.subAcct=d,h.from=this.safeString(r,"from","6"),h.to=this.safeString(r,"to","6")):"master"===d&&(h.type="2",h.subAcct=n,h.from=this.safeString(r,"from","6"),h.to=this.safeString(r,"to","6"));let c=await this.privatePostAssetTransfer(this.extend(h,r)),l=this.safeList(c,"data",[]),u=this.safeDict(l,0,{});return this.parseTransfer(u,a)}parseTransfer(e,t){let i=this.safeString2(e,"transId","billId"),s=this.safeString(e,"ccy"),r=this.safeCurrencyCode(s,t),a=this.safeNumber(e,"amt"),n=this.safeString(e,"from"),d=this.safeString(e,"to"),h=this.safeDict(this.options,"accountsById",{}),c=this.safeInteger(e,"ts"),l=this.safeString(e,"sz");return void 0!==l&&(a=this.parseNumber(o.Y.stringAbs(l))),{info:e,id:i,timestamp:c,datetime:this.iso8601(c),currency:r,amount:a,fromAccount:void 0===n?void 0:this.safeString(h,n),toAccount:void 0===d?void 0:this.safeString(h,d),status:this.parseTransferStatus(this.safeString(e,"state"))}}parseTransferStatus(e){if(void 0!==e)return this.safeString({success:"ok"},e,e)}async fetchTransfer(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateGetAssetTransferState(this.extend({transId:e},i)),r=this.safeList(s,"data",[]),a=this.safeDict(r,0);return this.parseTransfer(a)}async fetchTransfers(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={type:"1"};void 0!==e&&(a.ccy=(r=this.currency(e)).id),void 0!==t&&(a.begin=t),void 0!==i&&(a.limit=i);let o=await this.privateGetAccountBillsArchive(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTransfers(n,r,t,i,s)}sign(e,t="public",i="GET",r={},o,n){let d,h,c=Array.isArray(r),l="/api/"+this.version+"/"+this.implodeParams(e,r),u=this.omit(r,this.extractParams(e)),f=this.safeString(this.urls.api,"rest");if(void 0===f)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let p=this.implodeHostname(f)+l,m=!1;if("public"===t)Object.keys(u).length>0&&(p+="?"+this.urlencode(u));else if("private"===t){if(this.checkRequiredCredentials(),"POST"===i&&("trade/batch-orders"===e||"trade/order-algo"===e||"trade/order"===e)){let e=this.safeString(this.options,"brokerId","6b9ad766b55dBCDE");if(Array.isArray(r))for(let t=0;t<r.length;t++){let i=r[t];void 0===this.safeString(i,"clOrdId")&&(i.clOrdId=e+this.uuid16(),i.tag=e,r[t]=i)}else void 0===this.safeString(r,"clOrdId")&&(r.clOrdId=e+this.uuid16(),r.tag=e)}h=(m="GET"!==i&&(c||Object.keys(u).length>0))?this.json(u):void 0;let t=this.iso8601(this.nonce());d={"OK-ACCESS-KEY":this.apiKey,"OK-ACCESS-PASSPHRASE":this.password,"OK-ACCESS-TIMESTAMP":t};let a=t+i+l;if("GET"===i){if(Object.keys(u).length>0){let e="?"+this.urlencode(u);p+=e,a+=e}}else m&&(a+=h),d["Content-Type"]="application/json";let o=this.hmac(this.encode(a),this.encode(this.secret),s.sc,"base64");d["OK-ACCESS-SIGN"]=o}let g=n;return m&&(g=h),{url:p,method:i,body:g,headers:"private"===t?d:o}}parseFundingRate(e,t){let i=this.safeInteger(e,"nextFundingTime"),s=this.safeString(e,"instId"),r=this.safeSymbol(s,t),a=this.safeNumber(e,"nextFundingRate"),n=this.safeInteger(e,"fundingTime"),d=this.safeString(e,"fundingTime"),h=this.safeString(e,"nextFundingTime"),c=o.Y.stringSub(h,d);return{info:e,symbol:r,markPrice:void 0,indexPrice:void 0,interestRate:this.parseNumber("0"),estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:this.safeNumber(e,"fundingRate"),fundingTimestamp:n,fundingDatetime:this.iso8601(n),nextFundingRate:a,nextFundingTimestamp:i,nextFundingDatetime:this.iso8601(i),previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:this.parseFundingInterval(c)}}parseFundingInterval(e){return this.safeString({36e5:"1h",72e5:"2h",144e5:"4h",288e5:"8h",576e5:"16h",864e5:"24h"},e,e)}async fetchFundingInterval(e,t={}){return await this.fetchFundingRate(e,t)}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.safeDict(i,"info",{}),r=this.safeString(s,"ruleType");if(!0!==i.swap&&"xperp"!==r)throw new a.ExchangeError(this.id+" fetchFundingRate() is only valid for swap markets or XPERP futures");let o={instId:i.id},n=await this.publicGetPublicFundingRate(this.extend(o,t)),d=this.safeList(n,"data",[]),h=this.safeDict(d,0,{});return this.parseFundingRate(h,i)}async fetchFundingRates(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0);if(void 0!==i)for(let e=0;e<i.length;e++){let t=this.market(i[e]),s=this.safeDict(t,"info",{}),r="xperp"===this.safeString(s,"ruleType");if(!0!==t.swap&&!r)throw new a.BadRequest(this.id+" fetchFundingRates() symbols must be swap markets or XPERP futures, "+i[e]+" is not")}let s=await this.publicGetPublicFundingRate(this.extend({instId:"ANY"},t)),r=this.safeList(s,"data",[]);return this.parseFundingRates(r,i)}async fetchFundingHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={type:"8"};void 0!==i&&(a.limit=i.toString()),void 0!==e&&!0===(r=this.market(e)).contract&&(!0===r.linear?(a.ctType="linear",a.ccy=r.quoteId):(a.ctType="inverse",a.ccy=r.baseId));let n=void 0!==r?this.safeString(r,"symbol"):e,[d,h]=this.handleMarketTypeAndParams("fetchFundingHistory",r,s);"swap"===d&&(a.instType=this.convertToInstrumentType(d));let c=await this.privateGetAccountBillsArchive(this.extend(a,h)),l=this.safeList(c,"data",[]),u=[];for(let e=0;e<l.length;e++){let t,i=l[e],s=this.safeInteger(i,"ts"),r=this.safeString(i,"instId"),a=this.safeMarket(r),n=this.safeString(i,"ccy"),d=this.safeCurrencyCode(n),h=this.safeString(i,"balChg"),c=this.safeString(i,"posBalChg");t=void 0===h||o.Y.stringEq(h,"0")?c:h,u.push({info:i,symbol:a.symbol,code:d,timestamp:s,datetime:this.iso8601(s),id:this.safeString(i,"billId"),amount:this.parseNumber(t)})}let f=this.sortBy(u,"timestamp");return this.filterBySymbolSinceLimit(f,n,t,i)}async setLeverage(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");if(e<1||e>125)throw new a.BadRequest(this.id+" setLeverage() leverage should be between 1 and 125");void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r=this.safeString(i,"mgnMode","cross"),[o,n]=this.handleMarginModeAndParams("setLeverage",i,r);if("cross"!==o&&"isolated"!==o)throw new a.BadRequest(this.id+" setLeverage() requires a marginMode parameter that must be either cross or isolated");let d={lever:e,mgnMode:o,instId:s.id},h=this.safeString(n,"posSide","net");if("isolated"===o){if("long"!==h&&"short"!==h&&"net"!==h)throw new a.BadRequest(this.id+' setLeverage() requires the posSide argument to be either "long", "short" or "net"');d.posSide=h}return await this.privatePostAccountSetLeverage(this.extend(d,n))}async fetchPositionMode(e,t={}){let i,s=await this.fetchAccounts();if(s.length>1){let e=this.safeString(t,"accountId");if(void 0===e){let e=this.getListFromObjectValues(s,"id");throw new a.ExchangeError(this.id+' fetchPositionMode() can not detect position mode, because you have multiple accounts. Set params["accountId"] to desired id from: '+e.join(", "))}{let t=this.indexBy(s,"id");i=this.safeDict(t,e)}}else i=s[0];let r=i.info,o=this.safeString(r,"posMode");return{info:r,hedged:"long_short_mode"===o}}async setPositionMode(e,t,i={}){return await this.privatePostAccountSetPositionMode(this.extend({posMode:e?"long_short_mode":"net_mode"},i))}async setMarginMode(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");let s=e.toLowerCase();if("cross"!==s&&"isolated"!==s)throw new a.BadRequest(this.id+" setMarginMode() marginMode must be either cross or isolated");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),o=this.safeInteger2(i,"lever","leverage");if(void 0===o||o<1||o>125)throw new a.BadRequest(this.id+' setMarginMode() params["lever"] should be between 1 and 125');let n=this.omit(i,["leverage"]),d={lever:o,mgnMode:s,instId:r.id};return await this.privatePostAccountSetLeverage(this.extend(d,n))}async fetchCrossBorrowRates(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetAccountInterestRate(e),i=this.safeList(t,"data",[]),s={};for(let e=0;e<i.length;e++){let t=this.parseBorrowRate(i[e]),r=this.safeString(t,"currency");void 0!==r&&(s[r]=t)}return s}async fetchCrossBorrowRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={ccy:this.currency(e).id},s=await this.privateGetAccountInterestRate(this.extend(i,t)),r=this.safeList(s,"data",[]),a=this.safeDict(r,0,{});return this.parseBorrowRate(a)}parseBorrowRate(e,t){let i=this.safeString(e,"ccy"),s=this.safeInteger(e,"ts");return{currency:this.safeCurrencyCode(i),rate:this.safeNumber2(e,"interestRate","rate"),period:36e5,timestamp:s,datetime:this.iso8601(s),info:e}}parseBorrowRateHistories(e,t,i,s){let r={};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i),a=this.safeCurrencyCode(this.safeString(s,"ccy"));if(void 0!==a&&(void 0===t||this.inArray(a,t))){a in r||(r[a]=[]);let e=this.parseBorrowRate(s);e.period=31536e6,r[a].push(e)}}let a=Object.keys(r);for(let e=0;e<a.length;e++){let t=a[e];r[t]=this.filterByCurrencySinceLimit(r[t],t,i,s)}return r}async fetchBorrowRateHistories(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={};void 0!==t&&(r.before=t),void 0!==i&&(r.limit=i);let a=await this.publicGetFinanceSavingsLendingRateHistory(this.extend(r,s)),o=this.safeList(a,"data",[]);return this.parseBorrowRateHistories(o,e,t,i)}async fetchBorrowRateHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={ccy:this.currency(e).id};void 0!==t&&(r.before=t),void 0!==i&&(r.limit=i);let a=await this.publicGetFinanceSavingsLendingRateHistory(this.extend(r,s)),o=this.safeList(a,"data",[]);return this.parseBorrowRateHistory(o,e,t,i)}async modifyMarginHelper(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=this.safeString(s,"posSide","net"),o=this.omit(s,["posSide"]),n={instId:r.id,amt:t,type:i,posSide:a},d=await this.privatePostAccountPositionMarginBalance(this.extend(n,o)),h=this.safeList(d,"data",[]),c=this.safeDict(h,0,{}),l=this.safeString(d,"code");return this.extend(this.parseMarginModification(c,r),{status:"0"===l?"ok":"failed"})}parseMarginModification(e,t){let i,s=this.safeString2(e,"amt","posBalChg"),r=this.safeString(e,"type");i="6"===r?o.Y.stringGt(s,"0")?"add":"reduce":r;let a=o.Y.stringAbs(s),n=this.safeString(e,"instId"),d=this.safeMarket(n,t),h=!0===d.inverse?d.base:d.quote,c=this.safeInteger(e,"ts");return{info:e,symbol:d.symbol,type:i,marginMode:"isolated",amount:this.parseNumber(a),code:h,total:void 0,status:void 0,timestamp:c,datetime:this.iso8601(c)}}async reduceMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,"reduce",i)}async addMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,"add",i)}async fetchMarketLeverageTiers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=!0===i.spot?"MARGIN":this.convertToInstrumentType(i.type),r=this.safeString(i.info,"uly");if((void 0===r||""===r)&&"MARGIN"!==s)throw new a.BadRequest(this.id+" fetchMarketLeverageTiers() cannot fetch leverage tiers for "+e);let o=this.safeString(t,"tdMode","cross"),[n,d]=this.handleMarginModeAndParams("fetchMarketLeverageTiers",t,o),h={instType:s,tdMode:n,uly:r};"MARGIN"===s&&(h.instId=i.id);let c=await this.publicGetPublicPositionTiers(this.extend(h,d)),l=this.safeList(c,"data",[]);return this.parseMarketLeverageTiers(l,i)}parseMarketLeverageTiers(e,t){let i=[];for(let s=0;s<e.length;s++){let r=this.safeDict(e,s),a=this.safeString(r,"instId");i.push({tier:this.safeInteger(r,"tier"),symbol:this.safeSymbol(a,t),currency:this.safeString(t,"quote"),minNotional:this.safeNumber(r,"minSz"),maxNotional:this.safeNumber(r,"maxSz"),maintenanceMarginRate:this.safeNumber(r,"mmr"),maxLeverage:this.safeNumber(r,"maxLever"),info:r})}return i}async fetchBorrowInterest(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.safeString(r,"mgnMode","cross"),[o,n]=this.handleMarginModeAndParams("fetchBorrowInterest",r,a),d={mgnMode:o};void 0!==e&&(d.ccy=this.currency(e).id),void 0!==i&&(d.before=i-1),void 0!==s&&(d.limit=s),void 0!==t&&(d.instId=this.market(t).id);let h=await this.privateGetAccountInterestAccrued(this.extend(d,n)),c=this.safeList(h,"data",[]),l=this.parseBorrowInterests(c);return this.filterByCurrencySinceLimit(l,e,i,s)}parseBorrowInterest(e,t){let i=this.safeString(e,"instId"),s=void 0!==i?this.safeMarket(i,t):t,r=this.safeInteger(e,"ts");return{info:e,symbol:this.safeString(s,"symbol"),currency:this.safeCurrencyCode(this.safeString(e,"ccy")),interest:this.safeNumber(e,"interest"),interestRate:this.safeNumber(e,"interestRate"),amountBorrowed:this.safeNumber(e,"liab"),marginMode:this.safeString(e,"mgnMode"),timestamp:r,datetime:this.iso8601(r)}}async borrowCrossMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.currency(e),r={ccy:s.id,amt:this.currencyToPrecision(e,t),side:"borrow"},a=await this.privatePostAccountBorrowRepay(this.extend(r,i)),o=this.safeList(a,"data",[]),n=this.safeDict(o,0,{});return this.parseMarginLoan(n,s)}async repayCrossMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.safeString2(i,"id","ordId"),r=this.omit(i,"id");if(void 0===s)throw new a.ArgumentsRequired(this.id+" repayCrossMargin() requires an id parameter");let o=this.currency(e),n={ccy:o.id,amt:this.currencyToPrecision(e,t),side:"repay",ordId:s},d=await this.privatePostAccountBorrowRepay(this.extend(n,r)),h=this.safeList(d,"data",[]),c=this.safeDict(h,0,{});return this.parseMarginLoan(c,o)}parseMarginLoan(e,t){let i=this.safeString(e,"ccy");return{id:void 0,currency:this.safeCurrencyCode(i,t),amount:this.safeNumber(e,"amt"),symbol:void 0,timestamp:void 0,datetime:void 0,info:e}}async fetchOpenInterest(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.contract)throw new a.BadRequest(this.id+" fetchOpenInterest() supports contract markets only");let s={instType:this.convertToInstrumentType(i.type),uly:this.safeString(i.info,"uly"),instId:i.id},r=await this.publicGetPublicOpenInterest(this.extend(s,t)),o=this.safeList(r,"data",[]);return this.parseOpenInterest(o[0],i)}async fetchOpenInterests(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!0,!0);void 0!==r&&(i=this.market(r[0]));let o={};[s,o]=this.handleSubTypeAndParams("fetchOpenInterests",i,t,"swap");let n="SWAP";"future"===s?n="FUTURES":"option"===n&&(n="OPTION");let d={instType:n},h=this.safeString(o,"uly");void 0!==h&&(d.uly=h);let c=this.safeString(o,"instFamily");if(void 0!==c&&(d.instFamily=c),"OPTION"===n&&void 0===h&&void 0===c)throw new a.BadRequest(this.id+" fetchOpenInterests() requires either uly or instFamily parameter for OPTION markets");let l=await this.publicGetPublicOpenInterest(this.extend(d,o)),u=this.safeList(l,"data",[]);return this.parseOpenInterests(u,r)}async fetchOpenInterestHistory(e,t="1d",i,s,r={}){let o,n,d,h=this.safeDict(this.options,"fetchOpenInterestHistory",{}),c=this.safeDict(h,"timeframes",{}),l=this.safeString(c,t,t);if("5m"!==l&&"1H"!==l&&"1D"!==l)throw new a.BadRequest(this.id+" fetchOpenInterestHistory cannot only use the 5m, 1h, and 1d timeframe");if(void 0===this.markets&&await this.loadMarkets(),void 0!==this.markets&&e in this.markets||void 0!==this.markets_by_id&&e in this.markets_by_id)d=this.market(e),n=this.safeString(d,"baseId");else{let t=this.currency(e);n=this.safeString(t,"id")}let u={ccy:n,period:l},[f,p]=this.handleMarketTypeAndParams("fetchOpenInterestHistory",d,r);if(void 0!==d&&(!0===d.swap||!0===d.future)){let e={instId:d.id,period:l},[t,r]=this.handleTradingStatisticsWindow(e,l,i,s,p);o=await this.publicGetRubikStatContractsOpenInterestHistory(this.extend(t,r));let a=this.safeList(o,"data",[]);return this.parseOpenInterestsHistory(a,d,i,s)}if("option"===f)o=await this.publicGetRubikStatOptionOpenInterestVolume(this.extend(u,p));else{void 0!==i&&(u.begin=i);let e=this.safeInteger(p,"until");void 0!==e&&(u.end=e);let t=void 0!==e?this.omit(p,["until"]):p;o=await this.publicGetRubikStatContractsOpenInterestVolume(this.extend(u,t))}let m=this.safeList(o,"data",[]);return this.parseOpenInterestsHistory(m,void 0,i,s)}handleTradingStatisticsWindow(e,t,i,s,r={}){let a,o=void 0===s?100:Math.min(s,100);void 0!==s&&(e.limit=o),void 0!==i&&(e.begin=i-1);let n=this.safeInteger(r,"until"),d=this.omit(r,"until");if(void 0!==n&&(a=this.sum(n,1)),void 0!==i){let s,r=t.endsWith("utc")?t.slice(0,-3):t;if("M"===r.slice(-1)){let t=this.parseToInt(r.slice(0,-1));s=Math.min(o*t*26784e5,100*t*24192e5),e.limit=100}else s=o*this.parseTimeframe(r.toLowerCase())*1e3;let n=this.sum(i,s);a=void 0===a?n:Math.min(a,n)}return void 0!==a&&(e.end=a),[e,d]}parseOpenInterest(e,t){let i,s,r,a,o=this.safeString(e,"instId"),n=this.safeMarket(o,t),d=this.safeInteger(e,"ts"),h=this.safeInteger(e,0,d),c=this.safeString(this.options,"defaultType");return Array.isArray(e)?e.length>3?(r=this.safeNumber(e,1),i=this.safeNumber(e,2),a=this.safeNumber(e,3)):"option"===c?(r=this.safeNumber(e,1),i=this.safeNumber(e,2)):(a=this.safeNumber(e,1),s=this.safeNumber(e,2)):(i=this.safeNumber(e,"oiCcy"),r=this.safeNumber(e,"oi"),a=this.safeNumber(e,"oiUsd")),this.safeOpenInterest({symbol:this.safeSymbol(o),baseVolume:i,quoteVolume:s,openInterestAmount:r,openInterestValue:a,timestamp:h,datetime:this.iso8601(h),info:e},n)}setSandboxMode(e){super.setSandboxMode(e),this.options.sandboxMode=e,e?this.headers["x-simulated-trading"]="1":"x-simulated-trading"in this.headers&&(this.headers=this.omit(this.headers,"x-simulated-trading"))}async fetchDepositWithdrawFees(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={};void 0!==e&&(i.ccy=this.currencyIds(e).join(","));let s=await this.privateGetAssetCurrencies(this.extend(i,t)),r=this.safeList(s,"data");return this.parseDepositWithdrawFees(r,e)}parseDepositWithdrawFees(e,t,i){let s={},r=this.marketCodes(t);for(let t=0;t<e.length;t++){let i=e[t],a=this.safeString(i,"ccy"),o=this.safeCurrencyCode(a);if(void 0!==o&&(void 0===r||this.inArray(o,r))){void 0===this.safeDict(s,o)&&(s[o]=this.depositWithdrawFee({})),void 0!==a&&(s[o].info[a]=i);let e=this.safeString(i,"chain");if(void 0===e)continue;let t=e.split("-"),r=this.safeString(t,1),n=this.safeNumber(i,"fee"),d={fee:n,percentage:void 0===n&&void 0},h={fee:void 0,percentage:void 0},c=this.networkIdToCode(r,o);void 0!==c&&(s[o].networks[c]={withdraw:d,deposit:h})}}let a=Object.keys(s);for(let e=0;e<a.length;e++){let t=a[e],i=this.currency(t);s[t]=this.assignDefaultDepositWithdrawFees(s[t],i)}return s}async fetchSettlementHistory(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchSettlementHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),[o,n]=this.handleMarketTypeAndParams("fetchSettlementHistory",r,s);if("future"!==o&&"option"!==o)throw new a.NotSupported(this.id+" fetchSettlementHistory() supports futures and options markets only");let d={instType:this.convertToInstrumentType(o),uly:r.baseId+"-"+r.quoteId};void 0!==t&&(d.before=t-1),void 0!==i&&(d.limit=i);let h=await this.publicGetPublicDeliveryExerciseHistory(this.extend(d,n)),c=this.safeList(h,"data",[]),l=this.parseSettlements(c,r),u=this.sortBy(l,"timestamp");return this.filterBySymbolSinceLimit(u,this.safeString(r,"symbol"),t,i)}parseSettlement(e,t){let i=this.safeString(e,"insId");return{info:e,symbol:this.safeSymbol(i,t),price:this.safeNumber(e,"px"),timestamp:void 0,datetime:void 0}}parseSettlements(e,t){let i=[];for(let s=0;s<e.length;s++){let r=this.safeDict(e,s),a=this.safeInteger(r,"ts"),o=this.safeList(r,"details",[]);for(let e=0;e<o.length;e++){let s=this.parseSettlement(o[e],t);i.push(this.extend(s,{timestamp:a,datetime:this.iso8601(a)}))}}return i}async fetchUnderlyingAssets(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleMarketTypeAndParams("fetchUnderlyingAssets",void 0,e),s=void 0===t||"spot"===t,r=t;if(s&&(r="option"),"option"!==r&&"swap"!==r&&"future"!==r)throw new a.NotSupported(this.id+" fetchUnderlyingAssets() supports contract markets only");let o={instType:this.convertToInstrumentType(r)},n=await this.publicGetPublicUnderlying(this.extend(o,i));return this.safeList(n,"data",[])[0]}async fetchGreeks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.safeString(i,"id",""),r=s.split("-"),o={uly:i.info.uly,instFamily:i.info.instFamily,expTime:this.safeString(r,2)},n=await this.publicGetPublicOptSummary(this.extend(o,t)),d=this.safeList(n,"data",[]);for(let e=0;e<d.length;e++){let t=d[e];if(this.safeString(t,"instId")===s)return this.parseGreeks(t,i)}throw new a.NullResponse(this.id+" fetchGreeks() could not find greeks for "+e)}async fetchAllGreeks(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r={},o=this.marketSymbols(e,void 0,!0,!0,!0);if(void 0!==o&&(i=o.length),void 0===o||1!==i){let e=this.safeString(t,"uly");void 0!==e&&(r.uly=e);let i=this.safeString(t,"instFamily");if(void 0!==i&&(r.instFamily=i),void 0===e&&void 0===i)throw new a.BadRequest(this.id+" fetchAllGreeks() requires either a uly or instFamily parameter")}if(void 0!==o&&1===i){s=this.market(o[0]);let e=this.safeString(s,"id","").split("-");r.uly=s.info.uly,r.instFamily=s.info.instFamily,r.expTime=this.safeString(e,2)}let n=this.omit(t,["uly","instFamily"]),d=await this.publicGetPublicOptSummary(this.extend(r,n)),h=this.safeList(d,"data",[]);return this.parseAllGreeks(h,o)}parseGreeks(e,t){let i=this.safeInteger(e,"ts"),s=this.safeString(e,"instId");return{symbol:this.safeSymbol(s,t),timestamp:i,datetime:this.iso8601(i),delta:this.safeNumber(e,"delta"),gamma:this.safeNumber(e,"gamma"),theta:this.safeNumber(e,"theta"),vega:this.safeNumber(e,"vega"),rho:void 0,bidSize:void 0,askSize:void 0,bidImpliedVolatility:this.safeNumber(e,"bidVol"),askImpliedVolatility:this.safeNumber(e,"askVol"),markImpliedVolatility:this.safeNumber(e,"markVol"),bidPrice:void 0,askPrice:void 0,markPrice:void 0,lastPrice:void 0,underlyingPrice:void 0,info:e}}async closePosition(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=this.safeString(i,"clientOrderId"),a=this.safeString(i,"code"),[o,n]=this.handleMarginModeAndParams("closePosition",i,"cross"),d={instId:s.id,mgnMode:o};void 0!==t&&("buy"===t?d.posSide="long":"sell"===t?d.posSide="short":d.posSide=t),void 0!==r&&(d.clOrdId=r),void 0!==a&&(d.ccy=this.currency(a).id);let h=await this.privatePostTradeClosePosition(this.extend(d,n)),c=this.safeList(h,"data",[]),l=this.safeDict(c,0);return this.parseOrder(l,s)}async fetchOption(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instId:i.id},r=await this.publicGetMarketTicker(this.extend(s,t)),a=this.safeList(r,"data",[]),o=this.safeDict(a,0,{});return this.parseOption(o,void 0,i)}async fetchOptionChain(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={uly:this.currency(e).code+"-USD",instType:"OPTION"},s=await this.publicGetMarketTickers(this.extend(i,t)),r=this.safeList(s,"data",[]);return this.parseOptionChain(r,void 0,"instId")}parseOption(e,t,i){let s=this.safeString(e,"instId"),r=this.safeMarket(s,i),a=this.safeInteger(e,"ts");return{info:e,currency:void 0,symbol:r.symbol,timestamp:a,datetime:this.iso8601(a),impliedVolatility:void 0,openInterest:void 0,bidPrice:this.safeNumber(e,"bidPx"),askPrice:this.safeNumber(e,"askPx"),midPrice:void 0,markPrice:void 0,lastPrice:this.safeNumber(e,"last"),underlyingPrice:void 0,change:void 0,percentage:void 0,baseVolume:this.safeNumber(e,"volCcy24h"),quoteVolume:void 0}}async fetchConvertQuote(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={baseCcy:e.toUpperCase(),quoteCcy:t.toUpperCase(),rfqSzCcy:e.toUpperCase(),rfqSz:this.numberToString(i),side:"sell"},a=await this.privatePostAssetConvertEstimateQuote(this.extend(r,s)),o=this.safeList(a,"data",[]),n=this.safeDict(o,0,{}),d=this.safeString(n,"baseCcy",e),h=this.currency(d),c=this.safeString(n,"quoteCcy",t),l=this.currency(c);return this.parseConversion(n,h,l)}async createConvertTrade(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a={quoteId:e,baseCcy:t,quoteCcy:i,szCcy:t,sz:this.numberToString(s),side:"sell"},o=await this.privatePostAssetConvertTrade(this.extend(a,r)),n=this.safeList(o,"data",[]),d=this.safeDict(n,0,{}),h=this.safeString(d,"baseCcy",t),c=this.currency(h),l=this.safeString(d,"quoteCcy",i),u=this.currency(l);return this.parseConversion(d,c,u)}async fetchConvertTrade(e,t,i={}){let s,r;void 0===this.markets&&await this.loadMarkets();let a=await this.privateGetAssetConvertHistory(this.extend({clTReqId:e},i)),o=this.safeList(a,"data",[]),n=this.safeDict(o,0,{}),d=this.safeString(n,"baseCcy"),h=this.safeString(n,"quoteCcy");return void 0!==d&&(s=this.currency(d)),void 0!==h&&(r=this.currency(h)),this.parseConversion(n,s,r)}async fetchConvertTradeHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleUntilOption("after",{},s);void 0!==t&&(r.before=t),void 0!==i&&(r.limit=i);let o=await this.privateGetAssetConvertHistory(this.extend(r,a)),n=this.safeList(o,"data",[]);return this.parseConversions(n,e,"baseCcy","quoteCcy",t,i)}parseConversion(e,t,i){let s=this.safeInteger2(e,"quoteTime","ts"),r=this.safeString(e,"baseCcy"),a=this.safeCurrencyCode(r,t),o=this.safeString(e,"quoteCcy"),n=this.safeCurrencyCode(o,i);return{info:e,timestamp:s,datetime:this.iso8601(s),id:this.safeStringN(e,["clQReqId","tradeId","quoteId"]),fromCurrency:a,fromAmount:this.safeNumber2(e,"baseSz","fillBaseSz"),toCurrency:n,toAmount:this.safeNumber2(e,"quoteSz","fillQuoteSz"),price:this.safeNumber2(e,"cnvtPx","fillPx"),fee:void 0}}async fetchConvertCurrencies(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetAssetConvertCurrencies(e),i={},s=this.safeList(t,"data",[]);for(let e=0;e<s.length;e++){let t=s[e],r=this.safeString(t,"ccy"),a=this.safeCurrencyCode(r);void 0!==a&&(i[a]={info:t,id:r,code:a,networks:void 0,type:void 0,name:void 0,active:void 0,deposit:void 0,withdraw:void 0,fee:void 0,precision:void 0,limits:{amount:{min:this.safeNumber(t,"min"),max:this.safeNumber(t,"max")},withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},created:void 0})}return i}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"code");if("0"!==c&&"2"!==c){let e=this.id+" "+o,t=this.safeList(n,"data",[]);for(let i=0;i<t.length;i++){let s=this.safeDict(t,i),r=this.safeString(s,"sCode"),a=this.safeString(s,"sMsg");this.throwExactlyMatchedException(this.exceptions.exact,r,e),this.throwBroadlyMatchedException(this.exceptions.broad,a,e)}throw this.throwExactlyMatchedException(this.exceptions.exact,c,e),new a.ExchangeError(e)}}async fetchMarginAdjustmentHistory(e,t,i,s,r={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.safeBool(r,"auto");if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchMarginAdjustmentHistory () requires a type argument");let d="add"===t,h=d?"160":"161";if(!0===n)if(d)h="162";else throw new a.BadRequest(this.id+" cannot fetch margin adjustments for type "+t);let c={subType:h,mgnMode:"isolated"},l=this.safeInteger(r,"until"),u=this.omit(r,"until");void 0!==i&&(c.startTime=i),void 0!==s&&(c.limit=s),void 0!==l&&(c.endTime=l);let f=this.milliseconds();if(void 0===i||i>f-6048e5)o=await this.privateGetAccountBills(this.extend(c,u));else if(i>f-7776e6)o=await this.privateGetAccountBillsArchive(this.extend(c,u));else throw new a.BadRequest(this.id+" fetchMarginAdjustmentHistory () cannot fetch margin adjustments older than 3 months");let p=this.safeList(o,"data",[]),m=this.parseMarginModifications(p);return this.filterBySymbolSinceLimit(m,e,i,s)}async fetchPositionsHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.safeString(s,"marginMode"),a=this.safeStringUpper(s,"instType"),o=this.omit(s,["until","marginMode","instType"]),n=void 0===i?100:i,d={limit:n};void 0!==e&&1===e.length&&(d.instId=this.market(e[0]).id),void 0!==r&&(d.mgnMode=r),void 0!==a&&(d.instType=a);let h=await this.privateGetAccountPositionsHistory(this.extend(d,o)),c=this.safeList(h,"data",[]),l=this.parsePositions(c,e,o);return this.filterBySinceLimit(l,t,n)}async fetchLongShortRatioHistory(e,t,i,s,r={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ArgumentsRequired(this.id+" fetchLongShortRatioHistory() requires a symbol argument");let o=this.market(e),n={instId:o.id},d="5m";void 0!==t&&(n.period=d=this.safeString(this.timeframes,t,t));let[h,c]=this.handleTradingStatisticsWindow(n,d,i,s,r),l=await this.publicGetRubikStatContractsLongShortAccountRatioContract(this.extend(h,c)),u=this.safeList(l,"data",[]),f=[];for(let e=0;e<u.length;e++){let t=this.safeList(u,e);f.push({timestamp:this.safeString(t,0),longShortRatio:this.safeString(t,1)})}return this.parseLongShortRatioHistory(f,o,i,s)}parseLongShortRatio(e,t){let i,s=this.safeInteger(e,"timestamp");return void 0!==t&&(i=t.symbol),{info:e,symbol:i,timestamp:s,datetime:this.iso8601(s),timeframe:void 0,longShortRatio:this.safeNumber(e,"longShortRatio")}}}i.d(t,{A:()=>n})},1154(e,t,i){"use strict";var s=i(5058);class r extends s.A{describe(){return this.deepExtend(super.describe(),{id:"okxus",name:"OKX (US)",certified:!1,pro:!0,hostname:"us.okx.com",urls:{logo:"https://user-images.githubusercontent.com/1294454/152485636-38b19e4a-bece-4dec-979a-5982859ffc04.jpg",api:{rest:"https://{hostname}"},www:"https://app.okx.com",doc:"https://app.okx.com/docs-v5/en/#overview",fees:"https://app.okx.com/pages/products/fees.html",referral:{url:"https://www.app.okx.com/join/CCXT2023",discount:.2},test:{rest:"https://{hostname}"}},has:{CORS:void 0,spot:!0,margin:void 0,swap:!1,future:!1,option:!1},features:{future:{linear:void 0,inverse:void 0}},options:{fetchMarkets:{types:["spot"]}}})}}i.d(t,{A:()=>r})},363(e,t,i){"use strict";var s=i(3214),r=i(1453),a=i(7749);class o extends s.A{describe(){return this.deepExtend(super.describe(),{id:"onetrading",name:"One Trading",countries:["AT"],rateLimit:300,version:"v1",pro:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!0,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,closeAllPositions:!1,closePosition:!1,createDepositAddress:!1,createOrder:!0,createReduceOnlyOrder:!1,createStopLimitOrder:!0,createStopMarketOrder:!1,createStopOrder:!0,fetchAccounts:!1,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDeposit:!1,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!1,fetchDepositsWithdrawals:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLedger:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrice:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!1,fetchOrderTrades:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!1,fetchTradingFee:!1,fetchTradingFees:!0,fetchTransactionFee:!1,fetchTransactionFees:!1,fetchTransactions:!1,fetchTransfer:!1,fetchTransfers:!1,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,fetchWithdrawal:!1,fetchWithdrawals:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,transfer:!1,withdraw:!1},timeframes:{"1m":"1/MINUTES","5m":"5/MINUTES","15m":"15/MINUTES","30m":"30/MINUTES","1h":"1/HOURS","4h":"4/HOURS","1d":"1/DAYS","1w":"1/WEEKS","1M":"1/MONTHS"},urls:{logo:"https://github.com/user-attachments/assets/341a1b01-7660-402a-9a2b-876391e52f15",api:{public:"https://api.onetrading.com/fast",private:"https://api.onetrading.com/fast"},www:"https://onetrading.com/",doc:["https://docs.onetrading.com"],fees:"https://onetrading.com/fees"},api:{public:{get:{currencies:{cost:1},"candlesticks/{instrument_code}":{cost:1},fees:{cost:1},instruments:{cost:1},"order-book/{instrument_code}":{cost:1},"market-ticker":{cost:1},"market-ticker/{instrument_code}":{cost:1},time:{cost:1},"funding-rate":{cost:1},"funding-rate/history":{cost:1},"funding-rate/settings":{cost:1}}},private:{get:{"account/balances":{cost:1},"account/fees":{cost:1},"account/orders":{cost:1},"account/orders/{order_id}":{cost:1},"account/orders/client/{client_id}":{cost:1},"account/orders/{order_id}/trades":{cost:1},"account/trades":{cost:1},"account/trade/{trade_id}":{cost:1},"account/futures/summary":{cost:1},"account/futures/positions":{cost:1},"account/futures/positions-history":{cost:1},"account/futures/positions/{position_id}/trades":{cost:1},"account/futures/positions/{position_id}/funding-payments":{cost:1},"account/futures/funding-payments":{cost:1}},post:{"account/orders":{cost:1},"subaccounts/transfers":{cost:1}},delete:{"account/orders":{cost:1},"account/orders/{order_id}":{cost:1},"account/orders/client/{client_id}":{cost:1}}}},fees:{trading:{tierBased:!0,percentage:!0,taker:this.parseNumber("0.0015"),maker:this.parseNumber("0.001"),tiers:[{taker:[[this.parseNumber("0"),this.parseNumber("0.0015")],[this.parseNumber("100"),this.parseNumber("0.0013")],[this.parseNumber("250"),this.parseNumber("0.0013")],[this.parseNumber("1000"),this.parseNumber("0.001")],[this.parseNumber("5000"),this.parseNumber("0.0009")],[this.parseNumber("10000"),this.parseNumber("0.00075")],[this.parseNumber("20000"),this.parseNumber("0.00065")]],maker:[[this.parseNumber("0"),this.parseNumber("0.001")],[this.parseNumber("100"),this.parseNumber("0.001")],[this.parseNumber("250"),this.parseNumber("0.0009")],[this.parseNumber("1000"),this.parseNumber("0.00075")],[this.parseNumber("5000"),this.parseNumber("0.0006")],[this.parseNumber("10000"),this.parseNumber("0.0005")],[this.parseNumber("20000"),this.parseNumber("0.0005")]]}]}},requiredCredentials:{apiKey:!0,secret:!1},precisionMode:4,exceptions:{exact:{INVALID_CLIENT_UUID:r.InvalidOrder,ORDER_NOT_FOUND:r.OrderNotFound,ONLY_ONE_ERC20_ADDRESS_ALLOWED:r.InvalidAddress,DEPOSIT_ADDRESS_NOT_USED:r.InvalidAddress,INVALID_CREDENTIALS:r.AuthenticationError,MISSING_CREDENTIALS:r.AuthenticationError,INVALID_APIKEY:r.AuthenticationError,INVALID_SCOPES:r.AuthenticationError,INVALID_SUBJECT:r.AuthenticationError,INVALID_ISSUER:r.AuthenticationError,INVALID_AUDIENCE:r.AuthenticationError,INVALID_DEVICE_ID:r.AuthenticationError,INVALID_IP_RESTRICTION:r.AuthenticationError,APIKEY_REVOKED:r.AuthenticationError,APIKEY_EXPIRED:r.AuthenticationError,SYNCHRONIZER_TOKEN_MISMATCH:r.AuthenticationError,SESSION_EXPIRED:r.AuthenticationError,INTERNAL_ERROR:r.AuthenticationError,CLIENT_IP_BLOCKED:r.PermissionDenied,MISSING_PERMISSION:r.PermissionDenied,ILLEGAL_CHARS:r.BadRequest,UNSUPPORTED_MEDIA_TYPE:r.BadRequest,ACCOUNT_HISTORY_TIME_RANGE_TOO_BIG:r.BadRequest,CANDLESTICKS_TIME_RANGE_TOO_BIG:r.BadRequest,INVALID_INSTRUMENT_CODE:r.BadRequest,INVALID_ORDER_TYPE:r.BadRequest,INVALID_UNIT:r.BadRequest,INVALID_PERIOD:r.BadRequest,INVALID_TIME:r.BadRequest,INVALID_DATE:r.BadRequest,INVALID_CURRENCY:r.BadRequest,INVALID_AMOUNT:r.BadRequest,INVALID_PRICE:r.BadRequest,INVALID_LIMIT:r.BadRequest,INVALID_QUERY:r.BadRequest,INVALID_CURSOR:r.BadRequest,INVALID_ACCOUNT_ID:r.BadRequest,INVALID_SIDE:r.InvalidOrder,INVALID_ACCOUNT_HISTORY_FROM_TIME:r.BadRequest,INVALID_ACCOUNT_HISTORY_MAX_PAGE_SIZE:r.BadRequest,INVALID_ACCOUNT_HISTORY_TIME_PERIOD:r.BadRequest,INVALID_ACCOUNT_HISTORY_TO_TIME:r.BadRequest,INVALID_CANDLESTICKS_GRANULARITY:r.BadRequest,INVALID_CANDLESTICKS_UNIT:r.BadRequest,INVALID_ORDER_BOOK_DEPTH:r.BadRequest,INVALID_ORDER_BOOK_LEVEL:r.BadRequest,INVALID_PAGE_CURSOR:r.BadRequest,INVALID_TIME_RANGE:r.BadRequest,INVALID_TRADE_ID:r.BadRequest,INVALID_UI_ACCOUNT_SETTINGS:r.BadRequest,NEGATIVE_AMOUNT:r.InvalidOrder,NEGATIVE_PRICE:r.InvalidOrder,MIN_SIZE_NOT_SATISFIED:r.InvalidOrder,BAD_AMOUNT_PRECISION:r.InvalidOrder,BAD_PRICE_PRECISION:r.InvalidOrder,BAD_TRIGGER_PRICE_PRECISION:r.InvalidOrder,MAX_OPEN_ORDERS_EXCEEDED:r.BadRequest,MISSING_PRICE:r.InvalidOrder,MISSING_ORDER_TYPE:r.InvalidOrder,MISSING_SIDE:r.InvalidOrder,MISSING_CANDLESTICKS_PERIOD_PARAM:r.ArgumentsRequired,MISSING_CANDLESTICKS_UNIT_PARAM:r.ArgumentsRequired,MISSING_FROM_PARAM:r.ArgumentsRequired,MISSING_INSTRUMENT_CODE:r.ArgumentsRequired,MISSING_ORDER_ID:r.InvalidOrder,MISSING_TO_PARAM:r.ArgumentsRequired,MISSING_TRADE_ID:r.ArgumentsRequired,INVALID_ORDER_ID:r.OrderNotFound,NOT_FOUND:r.OrderNotFound,INSUFFICIENT_LIQUIDITY:r.InsufficientFunds,INSUFFICIENT_FUNDS:r.InsufficientFunds,NO_TRADING:r.ExchangeNotAvailable,SERVICE_UNAVAILABLE:r.ExchangeNotAvailable,GATEWAY_TIMEOUT:r.ExchangeNotAvailable,RATELIMIT:r.DDoSProtection,CF_RATELIMIT:r.DDoSProtection,INTERNAL_SERVER_ERROR:r.ExchangeError},broad:{"Order not found.":r.OrderNotFound}},commonCurrencies:{MIOTA:"IOTA"},options:{mica:!0,fetchTradingFees:{method:"fetchPrivateTradingFees"},fiat:["EUR","CHF"]},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerDirection:!1,triggerPriceType:void 0,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:30,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:100,untilDays:30,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:100,daysBack:1e5,daysBackCanceled:1/12,untilDays:30,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:5e3}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}}})}async fetchTime(e={}){let t=await this.publicGetTime(e);return this.safeInteger(t,"epoch_millis")}async fetchCurrencies(e={}){let t=await this.publicGetCurrencies(e);return this.parseCurrencies(t)}parseCurrency(e){let t=this.safeString(e,"code"),i=this.safeCurrencyCode(t);return this.safeCurrencyStructure({id:t,code:i,name:this.safeString(e,"name"),info:e,active:void 0,fee:void 0,precision:this.parseNumber(this.parsePrecision(this.safeString(e,"precision"))),withdraw:void 0,deposit:void 0,limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0}},networks:{}})}async fetchMarkets(e={}){let t=await this.publicGetInstruments(e);return this.parseMarkets(t)}parseMarket(e){let t=this.safeDict(e,"base",{}),i=this.safeDict(e,"quote",{}),s=this.safeString(t,"code"),r=this.safeString(i,"code"),a=this.safeString(e,"id"),o=this.safeCurrencyCode(s),n=this.safeCurrencyCode(r);if(void 0===o||void 0===n)return;let d=this.safeString(e,"state"),h="PERP"===this.safeString(e,"type"),c=o+"/"+n;return h&&(c=c+":"+n),this.safeMarketStructure({id:a,symbol:c,base:o,quote:n,settle:h?n:void 0,baseId:s,quoteId:r,settleId:h?r:void 0,type:h?"swap":"spot",spot:!h,margin:!1,swap:h,future:!1,option:!1,active:"ACTIVE"===d,contract:h,linear:!!h||void 0,inverse:!h&&void 0,contractSize:h?this.parseNumber("1"):void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(e,"amount_precision"))),price:this.parseNumber(this.parsePrecision(this.safeString(e,"market_precision")))},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(e,"min_size"),max:void 0}},created:void 0,info:e})}async fetchTradingFees(e={}){let t=this.safeString(e,"method"),i=this.omit(e,"method");if(void 0===t){let e=this.safeDict(this.options,"fetchTradingFees",{});t=this.safeString(e,"method","fetchPrivateTradingFees")}if("fetchPrivateTradingFees"===t)return await this.fetchPrivateTradingFees(i);if("fetchPublicTradingFees"===t)return await this.fetchPublicTradingFees(i);throw new r.NotSupported(this.id+" fetchTradingFees() does not support "+t+", fetchPrivateTradingFees and fetchPublicTradingFees are supported")}async fetchPublicTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.publicGetFees(e),i=this.safeDict(t,0,{}),s=this.safeDict(t,1,{}),r=this.safeList(i,"fee_tiers",[]),a=this.safeList(s,"fee_tiers",[]),o=this.parseFeeTiers(r),n=this.parseFeeTiers(a),d=this.safeDict(o,0,{}),h=this.safeDict(n,0,{}),c={},l=this.symbols;for(let e=0;e<l.length;e++){let t=l[e],s=!0===this.market(t).spot?d:h;c[t]={info:i,symbol:t,maker:this.safeNumber(s,"maker_fee"),taker:this.safeNumber(s,"taker_fee"),percentage:!0,tierBased:!0,tiers:o}}return c}async fetchPrivateTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetAccountFees(e),i=this.safeList(t,"active_fee_tiers"),s=this.safeDict(i,0,{}),r=this.safeDict(i,1,{}),o=this.safeString(s,"maker_fee"),n=this.safeString(s,"taker_fee");o=a.Y.stringDiv(o,"100"),n=a.Y.stringDiv(n,"100");let d=this.safeString(r,"maker_fee"),h=this.safeString(r,"taker_fee");d=a.Y.stringDiv(d,"100"),h=a.Y.stringDiv(h,"100");let c={},l=this.symbols;for(let e=0;e<l.length;e++){let i=l[e],s=this.market(i),r=!0===s.spot?o:d,a=!0===s.spot?n:h;c[i]={info:t,symbol:i,maker:this.parseNumber(r),taker:this.parseNumber(a),percentage:!0,tierBased:!0,tiers:void 0}}return c}parseFeeTiers(e,t){let i=[],s=[];for(let t=0;t<e.length;t++){let r=this.safeDict(e,t),o=this.safeNumber(r,"volume"),n=this.safeString(r,"taker_fee"),d=this.safeString(r,"maker_fee");d=a.Y.stringDiv(d,"100"),n=a.Y.stringDiv(n,"100"),s.push([o,this.parseNumber(d)]),i.push([o,this.parseNumber(n)])}return{maker:s,taker:i}}parseTicker(e,t){let i=this.parse8601(this.safeString(e,"time")),s=this.safeString(e,"instrument_code"),r=this.safeSymbol(s,t,"_"),a=this.safeString(e,"last_price"),o=this.safeString(e,"price_change_percentage"),n=this.safeString(e,"price_change"),d=this.safeString(e,"base_volume"),h=this.safeString(e,"quote_volume");return this.safeTicker({symbol:r,timestamp:i,datetime:this.iso8601(i),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"best_bid"),bidVolume:void 0,ask:this.safeString(e,"best_ask"),askVolume:void 0,vwap:void 0,open:void 0,close:a,last:a,previousClose:void 0,change:n,percentage:o,average:void 0,baseVolume:d,quoteVolume:h,info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={instrument_code:i.id},r=await this.publicGetMarketTickerInstrumentCode(this.extend(s,t));return this.parseTicker(r,i)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetMarketTicker(t),r={},a=this.toArray(s);for(let e=0;e<a.length;e++){let t=this.parseTicker(a[e]),i=t.symbol;void 0!==i&&(r[i]=t)}return this.filterByArrayTickers(r,"symbol",i)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={instrument_code:s.id};void 0!==t&&(r.depth=t);let a=await this.publicGetOrderBookInstrumentCode(this.extend(r,i)),o=this.parse8601(this.safeString(a,"time"));return this.parseOrderBook(a,s.symbol,o,"bids","asks","price","amount")}parseOHLCV(e,t){let i=this.safeDict(e,"granularity"),s=this.safeString(i,"unit"),a=this.safeString(i,"period"),o=this.safeString({MINUTES:"m",HOURS:"h",DAYS:"d",WEEKS:"w",MONTHS:"M"},s);if(void 0===a||void 0===o)throw new r.ExchangeError(this.id+" parseOHLCV() missing period/unit");let n=1e3*this.parseTimeframe(a+o),d=this.parse8601(this.safeString(e,"time"));if(void 0===d)throw new r.ExchangeError(this.id+" parseOHLCV() missing timestamp");let h=n*this.parseToInt(d/n),c=this.safeDict(this.options,"fetchOHLCV",{}),l=this.safeString(c,"volume","total_amount");return[h,this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,l)]}async fetchOHLCV(e,t="1m",i,s,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=this.safeString(this.timeframes,t);if(void 0===n)throw new r.ExchangeError(this.id+" fetchOHLCV() missing periodUnit");let[d,h]=n.split("/"),c=1e3*this.parseTimeframe(t),l=void 0===s?1500:s,u={instrument_code:o.id,period:d,unit:h};if(void 0===i){let e=this.milliseconds();u.to=this.iso8601(e),u.from=this.iso8601(e-l*c)}else u.from=this.iso8601(i),u.to=this.iso8601(this.sum(i,l*c));let f=await this.publicGetCandlesticksInstrumentCode(this.extend(u,a)),p=this.safeList(f,"candlesticks");return this.parseOHLCVs(p,o,t,i,l)}parseTrade(e,t){let i,s,r=this.safeDict(e,"fee",{}),a=this.safeDict(e,"trade",e),o=this.safeInteger(a,"trade_timestamp");void 0===o&&(o=this.parse8601(this.safeString(a,"time")));let n=this.safeStringLower2(a,"side","taker_side"),d=this.safeString(a,"price"),h=this.safeString(a,"amount"),c=this.safeString(a,"volume"),l=this.safeString(a,"instrument_code"),u=this.safeSymbol(l,t,"_"),f=this.safeString(r,"fee_amount");if(void 0!==f){let e=this.safeString(r,"fee_currency");s={cost:f,currency:this.safeCurrencyCode(e),rate:this.safeString(r,"fee_percentage")},i=this.safeStringLower(r,"fee_type")}return this.safeTrade({id:this.safeString2(a,"trade_id","sequence"),order:this.safeString(a,"order_id"),timestamp:o,datetime:this.iso8601(o),symbol:u,type:void 0,side:n,price:d,amount:h,cost:c,takerOrMaker:i,fee:s,info:a},t)}parseBalance(e){let t=this.safeList(e,"balances",[]),i={info:e};for(let e=0;e<t.length;e++){let s=this.safeDict(t,e),r=this.safeString(s,"currency_code"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(s,"available"),o.used=this.safeString(s,"locked"),void 0!==a&&(i[a]=o)}return this.safeBalance(i)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetAccountBalances(e);return this.parseBalance(t)}parseOrderStatus(e){return this.safeString({OPEN:"open",BOOKED:"open",FILL:"open",MOVED:"open",FILLED_FULLY:"closed",FILLED_CLOSED:"canceled",FILLED_REJECTED:"rejected",CANCELLED:"canceled",INSUFFICIENT_FUNDS:"rejected",INSUFFICIENT_LIQUIDITY:"rejected",RISK_FAILED_OVER_MAX_POSITION:"rejected"},e,e)}parseOrder(e,t){let i=this.safeDict(e,"order",e),s=this.safeString(i,"order_id"),r=this.safeString(i,"client_id"),a=this.parse8601(this.safeString(i,"time")),o=this.parseOrderStatus(this.safeString(i,"status")),n=this.safeString(i,"instrument_code"),d=this.safeSymbol(n,t,"_"),h=this.safeString(i,"price"),c=this.safeString(i,"amount"),l=this.safeString(i,"filled_amount"),u=this.safeStringLower(i,"side"),f=this.safeStringLower(i,"type"),p=this.parseTimeInForce(this.safeString(i,"time_in_force")),m=this.safeBool(i,"is_post_only"),g=this.safeList(e,"trades",[]);return this.safeOrder({id:s,clientOrderId:r,info:e,timestamp:a,datetime:this.iso8601(a),lastTradeTimestamp:void 0,symbol:d,type:f,timeInForce:p,postOnly:m,side:u,price:h,triggerPrice:this.safeNumber(i,"trigger_price"),amount:c,cost:void 0,average:void 0,filled:l,remaining:void 0,status:o,trades:g},t)}parseTimeInForce(e){return this.safeString({GOOD_TILL_CANCELLED:"GTC",GOOD_TILL_TIME:"GTT",IMMEDIATE_OR_CANCELLED:"IOC",FILL_OR_KILL:"FOK",POST_ONLY:"PO"},e,e)}async createOrder(e,t,i,s,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=t.toUpperCase();this.checkRequiredArgument("createOrder",i,"side");let h={instrument_code:n.id,type:d,side:i.toUpperCase(),amount:this.amountToPrecision(e,s)},c=!1;("LIMIT"===d||"STOP"===d)&&(c=!0);let l=this.safeNumberN(o,["triggerPrice","trigger_price","stopPrice"]);if(void 0!==l){if("MARKET"===d)throw new r.BadRequest(this.id+" createOrder() cannot place stop market orders, only stop limit");h.trigger_price=this.priceToPrecision(e,l),h.type="STOP"}else if("STOP"===d)throw new r.ArgumentsRequired(this.id+" createOrder() requires a triggerPrice param for "+t+" orders");c&&(h.price=this.priceToPrecision(e,a));let u=this.safeString2(o,"clientOrderId","client_id");void 0!==u&&(h.client_id=u);let f=void 0!==l?["triggerPrice","trigger_price","stopPrice"]:[],p=this.omit(o,this.arrayConcat(this.arrayConcat(f,void 0!==u?["clientOrderId","client_id"]:[]),["timeInForce"]));h.time_in_force=this.safeString2(o,"timeInForce","time_in_force","GOOD_TILL_CANCELLED");let m=await this.privatePostAccountOrders(this.extend(h,p));return this.parseOrder(m,n)}async cancelOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.safeString2(i,"clientOrderId","client_id"),a=this.omit(i,["clientOrderId","client_id"]),o="privateDeleteAccountOrdersOrderId",n={};return void 0!==r?(o="privateDeleteAccountOrdersClientClientId",n.client_id=r):n.order_id=e,s="privateDeleteAccountOrdersOrderId"===o?await this.privateDeleteAccountOrdersOrderId(this.extend(n,a)):await this.privateDeleteAccountOrdersClientClientId(this.extend(n,a)),this.parseOrder(s)}async cancelAllOrders(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={};void 0!==e&&(i.instrument_code=this.market(e).id);let s=await this.privateDeleteAccountOrders(this.extend(i,t));return[this.safeOrder({info:s})]}async cancelOrders(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={ids:e.join(",")},r=await this.privateDeleteAccountOrders(this.extend(s,i));return[this.safeOrder({info:r})]}async fetchOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateGetAccountOrdersOrderId(this.extend({order_id:e},i));return this.parseOrder(s)}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.instrument_code=(r=this.market(e)).id),void 0!==t&&(a.from=this.iso8601(t));let o=this.safeInteger(s,"until"),n=void 0!==o?this.omit(s,"until"):s;void 0!==o&&(a.to=this.iso8601(o)),void 0!==i&&(a.max_page_size=i);let d=await this.privateGetAccountOrders(this.extend(a,n)),h=this.safeList(d,"order_history",[]);return this.parseOrders(h,r,t,i)}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOpenOrders(e,t,i,this.extend({with_cancelled_and_rejected:!0},s))}async fetchOrderTrades(e,t,i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o={order_id:e};void 0!==s&&(o.max_page_size=s);let n=await this.privateGetAccountOrdersOrderIdTrades(this.extend(o,r)),d=this.safeList(n,"trade_history",[]);return void 0!==t&&(a=this.market(t)),this.parseTrades(d,a,i,s)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.instrument_code=(r=this.market(e)).id),void 0!==t&&(a.from=this.iso8601(t));let o=this.safeInteger(s,"until"),n=void 0!==o?this.omit(s,"until"):s;void 0!==o&&(a.to=this.iso8601(o)),void 0!==i&&(a.max_page_size=i);let d=await this.privateGetAccountTrades(this.extend(a,n)),h=this.safeList(d,"trade_history",[]);return this.parseTrades(h,r,t,i)}sign(e,t="public",i="GET",s={},a,o){let n=this.safeString(this.urls.api,t);if(void 0===n)throw new r.ExchangeError(this.id+" sign() has no API URL for this endpoint");let d=n+"/"+this.version+"/"+this.implodeParams(e,s),h=this.omit(s,this.extractParams(e));if("public"===t)Object.keys(h).length>0&&(d+="?"+this.urlencode(h));else if("private"===t){this.checkRequiredCredentials();let e={Accept:"application/json",Authorization:"Bearer "+this.apiKey},t="POST"===i?this.json(h):o;return"POST"===i?e["Content-Type"]="application/json":Object.keys(h).length>0&&(d+="?"+this.urlencode(h)),{url:d,method:i,body:t,headers:e}}return{url:d,method:i,body:o,headers:a}}handleErrors(e,t,i,s,a,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"error");if(void 0!==c){let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,c,e),this.throwBroadlyMatchedException(this.exceptions.broad,c,e),new r.ExchangeError(e)}}}i.d(t,{A:()=>o})},356(e,t,i){"use strict";var s=i(4721),r=i(3703),a=i(1453);class o extends r.A{describe(){return this.deepExtend(super.describe(),{id:"p2b",name:"p2b",countries:["LT"],rateLimit:100,version:"v2",pro:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!1,cancelOrder:!0,cancelOrders:!1,closeAllPositions:!1,closePosition:!1,createDepositAddress:!1,createMarketOrder:!1,createOrder:!0,createOrders:!1,createPostOnlyOrder:!1,createReduceOnlyOrder:!1,createStopLimitOrder:!1,createStopMarketOrder:!1,createStopOrder:!1,fetchAccounts:!1,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchDeposit:!1,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!1,fetchDepositsWithdrawals:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchIsolatedPositions:!1,fetchLedger:!1,fetchLedgerEntry:!1,fetchLeverage:!1,fetchLeverages:!1,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarginAdjustmentHistory:!1,fetchMarginMode:!1,fetchMarginModes:!1,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrice:!1,fetchMarkPrices:!1,fetchMyLiquidations:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!1,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrders:!1,fetchOrderTrades:!0,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchTradingLimits:!1,fetchTransactionFee:!1,fetchTransactionFees:!1,fetchTransactions:!1,fetchTransfers:!1,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,fetchWithdrawAddresses:!1,fetchWithdrawal:!1,fetchWithdrawals:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,signIn:!1,transfer:!1,withdraw:!1},timeframes:{"1m":"1m","1h":"1h","1d":"1d"},urls:{referral:"https://p2pb2b.com?referral=ee784c53",logo:"https://github.com/user-attachments/assets/122f0c86-f3a6-4334-910f-4d8edc865696",api:{public:"https://api.p2pb2b.com/api/v2/public",private:"https://api.p2pb2b.com/api/v2"},www:"https://p2pb2b.com/",doc:"https://github.com/P2B-team/p2b-api-docs/blob/master/api-doc.md",fees:"https://p2pb2b.com/fee-schedule/"},api:{public:{get:{markets:{cost:1},market:{cost:1},tickers:{cost:1},ticker:{cost:1},book:{cost:1},history:{cost:1},"depth/result":{cost:1},"market/kline":{cost:1}}},private:{post:{"account/balances":{cost:1},"account/balance":{cost:1},"order/new":{cost:1},"order/cancel":{cost:1},orders:{cost:1},"account/market_order_history":{cost:1},"account/market_deal_history":{cost:1},"account/order":{cost:1},"account/order_history":{cost:1},"account/executed_history":{cost:1}}}},fees:{trading:{tierBased:!0,percentage:!0,taker:[[this.parseNumber("0"),this.parseNumber("0.2")],[this.parseNumber("1"),this.parseNumber("0.19")],[this.parseNumber("5"),this.parseNumber("0.18")],[this.parseNumber("10"),this.parseNumber("0.17")],[this.parseNumber("25"),this.parseNumber("0.16")],[this.parseNumber("75"),this.parseNumber("0.15")],[this.parseNumber("100"),this.parseNumber("0.14")],[this.parseNumber("150"),this.parseNumber("0.13")],[this.parseNumber("300"),this.parseNumber("0.12")],[this.parseNumber("450"),this.parseNumber("0.11")],[this.parseNumber("500"),this.parseNumber("0.1")]],maker:[[this.parseNumber("0"),this.parseNumber("0.2")],[this.parseNumber("1"),this.parseNumber("0.18")],[this.parseNumber("5"),this.parseNumber("0.16")],[this.parseNumber("10"),this.parseNumber("0.14")],[this.parseNumber("25"),this.parseNumber("0.12")],[this.parseNumber("75"),this.parseNumber("0.1")],[this.parseNumber("100"),this.parseNumber("0.08")],[this.parseNumber("150"),this.parseNumber("0.06")],[this.parseNumber("300"),this.parseNumber("0.04")],[this.parseNumber("450"),this.parseNumber("0.02")],[this.parseNumber("500"),this.parseNumber("0.01")]]}},features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerDirection:!1,triggerPriceType:void 0,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1,symbolRequired:!0},fetchOrder:void 0,fetchOpenOrders:{marginMode:!1,limit:100,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:void 0,fetchClosedOrders:{marginMode:!1,limit:100,daysBack:1e5,daysBackCanceled:1/12,untilDays:1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:500}},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}},commonCurrencies:{},precisionMode:4,exceptions:{exact:{1001:a.AuthenticationError,1002:a.AuthenticationError,1003:a.AuthenticationError,1004:a.AuthenticationError,1005:a.AuthenticationError,1006:a.AuthenticationError,1007:a.AuthenticationError,1008:a.AuthenticationError,1009:a.AuthenticationError,1010:a.AuthenticationError,1011:a.AuthenticationError,1012:a.AuthenticationError,1013:a.RateLimitExceeded,1014:a.AuthenticationError,1015:a.ExchangeNotAvailable,1016:a.AuthenticationError,2010:a.BadRequest,2020:a.BadRequest,2021:a.BadRequest,2030:a.BadRequest,2040:a.InsufficientFunds,2050:a.BadRequest,2051:a.BadRequest,2052:a.BadRequest,2060:a.BadRequest,2061:a.BadRequest,2062:a.BadRequest,2070:a.BadRequest,3001:a.BadRequest,3020:a.BadRequest,3030:a.BadRequest,3040:a.BadRequest,3050:a.BadRequest,3060:a.BadRequest,3070:a.BadRequest,3080:a.BadRequest,3090:a.BadRequest,3100:a.BadRequest,3110:a.BadRequest,4001:a.ExchangeNotAvailable,6010:a.InsufficientFunds}},options:{}})}async fetchMarkets(e={}){let t=await this.publicGetMarkets(e),i=this.safeList(t,"result",[]);return this.parseMarkets(i)}parseMarket(e){let t=this.safeString(e,"name"),i=this.safeString(e,"stock"),s=this.safeString(e,"money"),r=this.safeCurrencyCode(i),a=this.safeCurrencyCode(s);if(void 0===r||void 0===a)return;let o=this.safeDict(e,"limits"),n=this.safeString(o,"max_amount"),d=this.safeString(o,"max_price");return{id:t,symbol:r+"/"+a,base:r,quote:a,settle:void 0,baseId:i,quoteId:s,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:!0,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.safeNumber(o,"step_size"),price:this.safeNumber(o,"tick_size")},limits:{leverage:{min:void 0,max:void 0},amount:{min:this.safeNumber(o,"min_amount"),max:this.parseNumber(this.omitZero(n))},price:{min:this.safeNumber(o,"min_price"),max:this.parseNumber(this.omitZero(d))},cost:{min:this.safeNumber(o,"min_total"),max:void 0}},created:void 0,info:e}}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.publicGetTickers(t),s=this.safeDict(i,"result",{});return this.parseTickers(s,e)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={market:i.id},r=await this.publicGetTicker(this.extend(s,t)),a=this.safeDict(r,"result",{});return this.parseTicker(a,i)}parseTicker(e,t){let i=this.safeIntegerProduct(e,"at",1e3),s=e;"ticker"in e&&(s=this.safeDict(e,"ticker"));let r=this.safeString(s,"last");return this.safeTicker({symbol:this.safeString(t,"symbol"),timestamp:i,datetime:this.iso8601(i),high:this.safeString(s,"high"),low:this.safeString(s,"low"),bid:this.safeString(s,"bid"),bidVolume:void 0,ask:this.safeString(s,"ask"),askVolume:void 0,vwap:void 0,open:this.safeString(s,"open"),close:r,last:r,previousClose:void 0,change:void 0,percentage:this.safeString(s,"change"),average:void 0,baseVolume:this.safeString2(s,"vol","volume"),quoteVolume:this.safeString(s,"deal"),info:s},t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={market:s.id};void 0!==t&&(r.limit=t);let a=await this.publicGetDepthResult(this.extend(r,i)),o=this.safeDict(a,"result",{}),n=this.safeIntegerProduct(a,"current_time",1e3);return this.parseOrderBook(o,s.symbol,n,"bids","asks",0,1)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.safeInteger(s,"lastId");if(void 0===r)throw new a.ArgumentsRequired(this.id+' fetchTrades () requires an extra parameter params["lastId"]');let o=this.market(e),n={market:o.id,lastId:r};void 0!==i&&(n.limit=i);let d=await this.publicGetHistory(this.extend(n,s)),h=this.safeList(d,"result",[]);return this.parseTrades(h,o,t,i)}parseTrade(e,t){let i=this.safeIntegerProduct2(e,"time","deal_time",1e3),s=this.safeString(e,"role");return"1"===s?s="maker":"2"===s&&(s="taker"),this.safeTrade({info:e,id:this.safeString2(e,"id","deal_id"),timestamp:i,datetime:this.iso8601(i),symbol:this.safeString(t,"symbol"),order:this.safeString2(e,"dealOrderId","deal_order_id"),type:void 0,side:this.safeString2(e,"type","side"),takerOrMaker:s,price:this.safeString(e,"price"),amount:this.safeString(e,"amount"),cost:this.safeString(e,"deal"),fee:{currency:this.safeString(t,"quote"),cost:this.safeString2(e,"fee","deal_fee")}},t)}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={market:a.id,interval:t};void 0!==s&&(o.limit=s);let n=await this.publicGetMarketKline(this.extend(o,r)),d=this.safeList(n,"result",[]);return this.parseOHLCVs(d,a,t,i,s)}parseOHLCV(e,t){return[this.safeIntegerProduct(e,0,1e3),this.safeNumber(e,1),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,2),this.safeNumber(e,5)]}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privatePostAccountBalances(e),i=this.safeDict(t,"result",{});return this.parseBalance(i)}parseBalance(e){let t={info:e},i=Object.keys(e);for(let s=0;s<i.length;s++){let r=i[s],a=this.safeDict(e,r),o=this.safeCurrencyCode(r),n=this.safeString(a,"freeze"),d={free:this.safeString(a,"available"),used:n};t[o]=d}return this.safeBalance(t)}async createOrder(e,t,i,s,r,o={}){if(void 0===this.markets&&await this.loadMarkets(),"market"===t)throw new a.BadRequest(this.id+' createOrder () can only accept orders with type "limit"');let n=this.market(e),d={market:n.id,side:i,amount:this.amountToPrecision(e,s),price:this.priceToPrecision(e,r)},h=await this.privatePostOrderNew(this.extend(d,o)),c=this.safeDict(h,"result");return this.parseOrder(c,n)}async cancelOrder(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s={market:this.market(t).id,orderId:e},r=await this.privatePostOrderCancel(this.extend(s,i)),o=this.safeDict(r,"result");return this.parseOrder(o)}async fetchOpenOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOpenOrders () requires the symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o={market:r.id};void 0!==i&&(o.limit=i);let n=await this.privatePostOrders(this.extend(o,s)),d=this.safeList(n,"result",[]);return this.parseOrders(d,r,t,i)}async fetchOrderTrades(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.safeMarket(t),o={orderId:e};void 0!==s&&(o.limit=s);let n=await this.privatePostAccountOrder(this.extend(o,r)),d=this.safeDict(n,"result",{}),h=this.safeList(d,"records",[]);return this.parseTrades(h,a,i,s)}async fetchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.safeInteger(s,"until"),o=this.omit(s,"until");void 0===r&&(r=void 0===t?this.milliseconds():t+864e5);let n=void 0===t?r-864e5:t;if(r-n>864e5)throw new a.BadRequest(this.id+' fetchMyTrades () the time between since and params["until"] cannot be greater than 24 hours');let d=this.market(e),h=this.parseToInt(n/1e3),c=this.parseToInt(r/1e3),l={market:d.id,startTime:h,endTime:c};void 0!==i&&(l.limit=i);let u=await this.privatePostAccountMarketDealHistory(this.extend(l,o)),f=this.safeDict(u,"result",{}),p=this.safeList(f,"deals",[]);return this.parseTrades(p,d,n,i)}async fetchClosedOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o=this.safeInteger(s,"until"),n=this.omit(s,"until");void 0!==e&&(r=this.market(e)),void 0===o&&(o=void 0===t?this.milliseconds():t+864e5);let d=void 0===t?o-864e5:t;if(o-d>864e5)throw new a.BadRequest(this.id+' fetchClosedOrders () the time between since and params["until"] cannot be greater than 24 hours');let h={startTime:this.parseToInt(d/1e3),endTime:this.parseToInt(o/1e3)};void 0!==r&&(h.market=r.id),void 0!==i&&(h.limit=i);let c=await this.privatePostAccountOrderHistory(this.extend(h,n)),l=this.safeDict(c,"result",{}),u=[],f=Object.keys(l);for(let e=0;e<f.length;e++){let t=l[f[e]],s=this.parseOrders(t,r,d,i);u=this.arrayConcat(u,s)}return u}parseOrder(e,t){let i=this.safeIntegerProduct2(e,"timestamp","ctime",1e3),s=this.safeString(e,"market"),r=this.safeMarket(s,t);return this.safeOrder({info:e,id:this.safeString2(e,"id","orderId"),clientOrderId:void 0,timestamp:i,datetime:this.iso8601(i),lastTradeTimestamp:void 0,symbol:r.symbol,type:this.safeString(e,"type"),timeInForce:void 0,postOnly:void 0,side:this.safeString(e,"side"),price:this.safeString(e,"price"),triggerPrice:void 0,amount:this.safeString(e,"amount"),cost:void 0,average:void 0,filled:this.safeString(e,"dealStock"),remaining:this.safeString(e,"left"),status:void 0,fee:{currency:r.quote,cost:this.safeString(e,"dealFee")},trades:void 0},r)}sign(e,t="public",i="GET",r={},o,n){let d=this.safeString(this.urls.api,t);if(void 0===d)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let h=d+"/"+this.implodeParams(e,r),c=this.omit(r,this.extractParams(e));if("GET"===i&&Object.keys(c).length>0&&(h+="?"+this.urlencode(c)),"private"===t){c.request="/api/v2/"+e,c.nonce=this.incrementingNonce().toString();let t=this.stringToBase64(this.json(c)),r={"Content-Type":"application/json","X-TXC-APIKEY":this.apiKey,"X-TXC-PAYLOAD":t,"X-TXC-SIGNATURE":this.hmac(this.encode(t),this.encode(this.secret),s.Zf)};return{url:h,method:i,body:this.json(c),headers:r}}return{url:h,method:i,body:n,headers:o}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0!==n&&!0!==this.safeBool(n,"success",!0)){let t=this.safeString(n,"errorCode"),i=this.id+" "+o;this.throwExactlyMatchedException(this.exceptions.exact,t,i);let s=e.toString();if(e<400||!(s in this.httpExceptions))throw new a.ExchangeError(i)}}}i.d(t,{A:()=>o})},5016(e,t,i){"use strict";var s=i(7468),r=i(7313),a=i(1453),o=i(7749),n=i(1093);class d extends r.A{describe(){return this.deepExtend(super.describe(),{id:"pacifica",name:"Pacifica",countries:[],version:"v1",isSandboxModeEnabled:!1,rateLimit:600,certified:!1,pro:!0,dex:!0,has:{CORS:void 0,spot:!0,margin:!1,swap:!0,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,cancelAllOrders:!0,cancelAllOrdersAfter:!1,cancelOrder:!0,cancelOrders:!0,cancelOrdersForSymbols:void 0,closeAllPositions:!1,closePosition:!1,createMarketBuyOrderWithCost:!1,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createOrderWithTakeProfitAndStopLoss:!0,createReduceOnlyOrder:!0,createStopOrder:!0,editOrder:!0,editOrders:!1,fetchAccounts:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchCanceledAndClosedOrders:!0,fetchCanceledOrders:!0,fetchClosedOrders:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDeposits:!1,fetchDepositWithdrawFee:!1,fetchDepositWithdrawFees:!1,fetchFundingHistory:!0,fetchFundingRate:!1,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLedger:!0,fetchLeverage:!0,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchMarginMode:!0,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyLiquidations:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!1,fetchOpenInterests:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchOrderTrades:!1,fetchPosition:!0,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchStatus:void 0,fetchTicker:"emulated",fetchTickers:!0,fetchTime:void 0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!1,fetchTransfer:!1,fetchTransfers:!1,fetchWithdrawal:!1,fetchWithdrawals:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,sandbox:!0,setLeverage:!0,setMarginMode:!0,setPositionMode:!1,transfer:!0,withdraw:!0},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","8h":"8h","12h":"12h","1d":"1d","1w":"1w","1M":"1M"},hostname:"pacifica.fi",urls:{logo:"https://github.com/user-attachments/assets/03ed021f-cdec-43c8-acb4-941f1282f610",api:{public:"https://api.{hostname}",private:"https://api.{hostname}"},test:{public:"https://test-api.{hostname}",private:"https://test-api.{hostname}"},www:"https://www.pacifica.fi",doc:"https://docs.pacifica.fi/api-documentation/api/rest-api",fees:"https://docs.pacifica.fi/trading-on-pacifica/trading-fees",referral:"https://app.pacifica.fi?referral=ccxt"},api:{public:{get:{info:{cost:1},"info/fees":{cost:1},"info/prices":{cost:1},kline:{cost:12},"kline/mark":{cost:12},book:{cost:1},trades:{cost:1},"funding_rate/history":{cost:1},loan_pool:{cost:1},account:{cost:1},"account/loan":{cost:1},"account/settings":{cost:1},positions:{cost:1},"trades/history":{cost:12},"funding/history":{cost:1},portfolio:{cost:1},"account/balance/history":{cost:12},"account/spot_balance/history":{cost:1},"account/spot_asset/deposit/history":{cost:1},"account/spot_asset/withdraw/history":{cost:1},"account/spot_asset/withdraw/pending":{cost:1},orders:{cost:1},"orders/history":{cost:12},"orders/history_by_id":{cost:1},"orders/twap":{cost:1},"orders/twap/history":{cost:12},"orders/twap/history_by_id":{cost:1},spot_assets:{cost:1},"spot_assets/bridge/info":{cost:1},"spot_assets/bridge/parameters/{symbol}":{cost:1},"lake/list":{cost:1},"account/builder_codes/approvals":{cost:1},"builder/overview":{cost:1},"builder/trades":{cost:1},"leaderboard/builder_code":{cost:1}}},private:{post:{"account/leverage":{cost:1},"account/margin":{cost:1},"account/withdraw":{cost:1},"account/settings/auto_lend_disabled":{cost:1},"account/settings/spot":{cost:1},"account/spot_asset/withdraw":{cost:1},"account/subaccount/create":{cost:1},"account/subaccount/list":{cost:1},"account/subaccount/transfer":{cost:1},"account/subaccount/spot_asset/transfer":{cost:1},"positions/add_isolated_margin":{cost:1},"orders/create":{cost:1},"orders/create_market":{cost:1},"orders/stop/create":{cost:1},"positions/tpsl":{cost:1},"orders/cancel":{cost:.5},"orders/cancel_all":{cost:.5},"orders/stop/cancel":{cost:.5},"orders/edit":{cost:1},"orders/batch":{cost:1},"orders/twap/create":{cost:1},"orders/twap/cancel":{cost:.5},"account/builder_codes/approve":{cost:1},"account/builder_codes/revoke":{cost:1},"builder/update_fee_rate":{cost:1},"referral/user/code/claim":{cost:1},"agent/bind":{cost:1},"agent/list":{cost:1},"agent/revoke":{cost:1},"agent/revoke_all":{cost:1},"agent/ip_whitelist/list":{cost:1},"agent/ip_whitelist/add":{cost:1},"agent/ip_whitelist/remove":{cost:1},"agent/ip_whitelist/toggle":{cost:1},"account/api_keys/create":{cost:1},"account/api_keys/revoke":{cost:1},"account/api_keys":{cost:1},"lake/add_blacklist":{cost:1},"lake/add_max_leverage":{cost:1},"lake/add_whitelist":{cost:1},"lake/claim_manager":{cost:1},"lake/claim_referral_code":{cost:1},"lake/create":{cost:1},"lake/deposit":{cost:1},"lake/remove_blacklist":{cost:1},"lake/remove_max_leverage":{cost:1},"lake/remove_whitelist":{cost:1},"lake/update_deposit_cap":{cost:1},"lake/withdraw":{cost:1}}}},fees:{swap:{taker:this.parseNumber("0.0004"),maker:this.parseNumber("0.00015")},spot:{taker:this.parseNumber("0.0004"),maker:this.parseNumber("0.00015")}},requiredCredentials:{apiKey:!1,secret:!1,walletAddress:!1,privateKey:!0},exceptions:{exact:{0:a.ExchangeError,1:a.ExchangeError,2:a.ExchangeError,3:a.ExchangeError,4:a.InvalidOrder,5:a.InsufficientFunds,6:a.OrderNotFound,7:a.InvalidOrder,8:a.InvalidOrder,9:a.InsufficientFunds,10:a.InvalidOrder,11:a.ExchangeError,12:a.ExchangeError,13:a.ExchangeError,14:a.ExchangeError,15:a.BadRequest,16:a.InvalidOrder,17:a.InvalidOrder,18:a.InvalidOrder,19:a.InvalidOrder,20:a.InvalidOrder,21:a.InvalidOrder,22:a.InvalidOrder,23:a.InvalidOrder,24:a.ExchangeError,25:a.InvalidOrder,26:a.ExchangeError,27:a.ExchangeError,28:a.InvalidOrder,29:a.InvalidOrder,30:a.InvalidOrder,31:a.PermissionDenied,32:a.PermissionDenied,33:a.BadRequest,34:a.PermissionDenied,35:a.PermissionDenied,36:a.InvalidOrder,37:a.InvalidOrder,38:a.PermissionDenied,39:a.BadRequest,40:a.PermissionDenied,41:a.InvalidOrder,42:a.ExchangeError,43:a.InvalidOrder,44:a.InvalidOrder,45:a.InvalidOrder,46:a.InvalidOrder,47:a.OrderNotFound,48:a.InvalidOrder,49:a.InvalidOrder,50:a.BadRequest,51:a.NotSupported,52:a.InvalidOrder,53:a.InvalidOrder,54:a.ExchangeError,55:a.ExchangeError,56:a.ExchangeError,59:a.InvalidOrder,61:a.InsufficientFunds,62:a.InsufficientFunds,63:a.ExchangeError,64:a.BadRequest,65:a.InsufficientFunds,66:a.ExchangeError,67:a.ExchangeError,68:a.InvalidOrder,69:a.InvalidOrder,70:a.InsufficientFunds,71:a.ExchangeError,72:a.PermissionDenied,73:a.PermissionDenied,74:a.PermissionDenied,75:a.InvalidOrder,76:a.PermissionDenied,77:a.BadRequest,78:a.InsufficientFunds,79:a.ExchangeError,80:a.InvalidOrder,81:a.BadRequest,82:a.InvalidOrder,83:a.ExchangeNotAvailable,84:a.BadRequest,85:a.BadRequest,86:a.BadRequest,87:a.PermissionDenied,88:a.BadRequest,89:a.BadRequest,90:a.BadRequest,91:a.ExchangeError,92:a.ExchangeNotAvailable,93:a.BadRequest,94:a.InvalidOrder,95:a.ExchangeError,96:a.ExchangeError,97:a.ExchangeError,99:a.InvalidOrder,100:a.PermissionDenied,101:a.ExchangeNotAvailable,102:a.BadRequest,103:a.PermissionDenied,104:a.InvalidOrder,105:a.InvalidOrder,106:a.NotSupported,107:a.NotSupported,108:a.NotSupported,109:a.NotSupported,110:a.BadRequest,111:a.ExchangeNotAvailable,112:a.InvalidOrder,113:a.ExchangeError,114:a.ExchangeError,115:a.ExchangeError,116:a.ExchangeError,117:a.ExchangeError,118:a.ExchangeError,119:a.ExchangeNotAvailable,120:a.PermissionDenied,121:a.InvalidOrder,400:a.BadRequest,401:a.AuthenticationError,402:a.AuthenticationError,403:a.PermissionDenied,404:a.BadRequest,409:a.ExchangeError,420:a.ExchangeError,422:a.ExchangeError,429:a.RateLimitExceeded,500:a.ExchangeNotAvailable,503:a.ExchangeNotAvailable,504:a.RequestTimeout,signature_verification_failed:a.AuthenticationError,invalid_amount:a.InvalidOrder},broad:{"Invalid signature":a.AuthenticationError,"Invalid public key":a.AuthenticationError,"Verification failed":a.AuthenticationError,"Invalid message":a.BadRequest,UNKNOWN:a.ExchangeError,ACCOUNT_NOT_FOUND:a.ExchangeError,BOOK_NOT_FOUND:a.ExchangeError,INVALID_TICK_LEVEL:a.InvalidOrder,INSUFFICIENT_BALANCE:a.InsufficientFunds,ORDER_NOT_FOUND:a.OrderNotFound,OVER_WITHDRAWAL:a.InsufficientFunds,INVALID_LEVERAGE:a.ExchangeError,CANNOT_UPDATE_MARGIN:a.ExchangeError,POSITION_NOT_FOUND:a.ExchangeError,POSITION_TPSL_LIMIT_EXCEEDED:a.InvalidOrder}},precisionMode:4,commonCurrencies:{},options:{agentAddress:void 0,apiKey:void 0,builderCode:"CCXT",feeRate:"0.01",builderFee:!0,batchOrdersMax:10,defaultType:"swap",defaultSlippage:"0.5",expiryWindow:5e3,maxCostHugeWithApiKey:4,marketHelperProps:[],defaultMarginMode:"cross",builderSupportOperations:{create_market_order:!0,create_limit_order:!0,create_stop_order:!0,set_position_tpsl:!0}},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:{triggerPriceType:{last:!1,mark:!1,index:!1},triggerPrice:!0,type:!0,price:!0},timeInForce:{IOC:!0,FOK:!1,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:{max:10},editOrder:{side:!1,type:!1},fetchMyTrades:{marginMode:!1,limit:100,daysBack:void 0,untilDays:void 0,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:100,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:100,daysBack:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:100,daysBack:void 0,daysBackCanceled:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:3950},fetchLedger:{code:!1}},forPerps:{extends:"default",createOrder:{stopLossPrice:!0,takeProfitPrice:!0,attachedStopLossTakeProfit:void 0}},spot:void 0,swap:{linear:{extends:"forPerps"},inverse:{extends:"forPerps"}},future:{linear:{extends:"forPerps"},inverse:{extends:"forPerps"}}}})}async initializeClient(){try{await this.handleBuilderFeeApproval()}catch(e){return!1}return!0}async handleBuilderFeeApproval(){if(this.isSandboxModeEnabled||!0!==this.safeBool(this.options,"builderFee",!0))return!1;if(!0===this.safeBool(this.options,"approvedBuilderFee",!1))return!0;try{let e=this.safeString(this.options,"builderCode","CCXT"),t=this.safeString(this.options,"feeRate","0.01");await this.approveBuilderCode(e,t),this.options.approvedBuilderFee=!0}catch(e){this.options.builderFee=!1}return!0}async fetchMarkets(e={}){let t=await this.publicGetInfo(e),i=this.safeList(t,"data",[]);return this.parseMarkets(i)}async fetchSwapMarkets(e={}){let t=await this.fetchMarkets(e);return this.filterBy(t,"type","swap")}parseMarket(e){let t,i,s,r,o,n,d,h,c=this.safeString(e,"symbol"),l=this.safeString(e,"base_asset",c),u="spot"===this.safeString(e,"instrument_type"),f=!u,p="USDC",m="spot";if(void 0===c)throw new a.ExchangeError(this.id+" parseMarket() missing id");if(u){let e=c.split("-");p=this.safeString(e,1,p)}let g=this.safeBool(e,"isolated_only",!1);f&&(t=p,m="swap",i=!0,s=!1,r=this.parseNumber("1"),o=1,n=this.safeInteger(e,"max_leverage"),d=!0!==g,h=!0);let v=this.safeCurrencyCode(l),y=this.safeCurrencyCode(p);if(void 0===v||void 0===y)return;let b=this.safeCurrencyCode(t),w=v+"/"+y;f&&(w=w+":"+b);let k=this.safeDict(this.fees,m,{}),S=this.safeNumber(k,"taker"),O=this.safeNumber(k,"maker"),T=this.safeNumber(e,"lot_size"),P=this.safeNumber(e,"tick_size");return this.safeMarketStructure({id:c,symbol:w,base:v,quote:y,settle:b,baseId:l,quoteId:p,settleId:t,type:m,spot:u,margin:!1,swap:f,future:!1,option:!1,active:!0,contract:f,linear:i,inverse:s,taker:S,maker:O,contractSize:r,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:T,price:P},limits:{leverage:{min:o,max:n},amount:{min:void 0,max:void 0},price:{min:this.safeNumber(e,"min_tick"),max:this.safeNumber(e,"max_tick")},cost:{min:this.safeNumber(e,"min_order_size"),max:this.safeNumber(e,"max_order_size")}},created:this.safeInteger(e,"created_at"),marginModes:{cross:d,isolated:h},info:e})}async fetchBalance(e={}){let[t,i]=this.handleOriginAndSingleAddress("fetchBalance",e),s=await this.publicGetAccount(this.extend({account:t},i)),r=this.safeDict(s,"data",{}),a={info:r},o=this.account();o.total=this.safeString(r,"balance"),o.used=this.safeString(r,"total_margin_used"),a.USDC=o;let n=this.safeList(r,"spot_balances",[]);for(let e=0;e<n.length;e++){let t=this.safeDict(n,e),i=this.safeString(t,"symbol"),s=this.safeCurrencyCode(i),r=this.account();r.total=this.safeString(t,"amount"),r.free=this.safeString(t,"available_to_withdraw"),void 0===s||s in a||(a[s]=r)}let d=this.safeInteger(r,"updated_at");return a.timestamp=d,a.datetime=this.iso8601(d),this.safeBalance(a)}async fetchLeverage(e,t={}){let i;await this.loadAccountSettings(),void 0===this.markets&&await this.loadMarkets();let s=this.market(e),[r,a]=this.handleOriginAndSingleAddress("fetchLeverage",t);i=r===this.walletAddress?this.handleOption("fetchLeverage","settings"):await this.fetchAccountSettings(this.extend({account:r},a));let o=this.safeDict(i,e);return void 0===o?this.parseLeverageFromMarket(s):this.parseLeverageFromSetting(e,o)}parseLeverageFromSetting(e,t){let i=this.safeBool(t,"isolated",!1),s=this.safeInteger(t,"leverage"),r="cross";return!0===i&&(r="isolated"),{info:t,symbol:e,marginMode:r,longLeverage:s,shortLeverage:s}}parseLeverageFromMarket(e){let t=this.safeDict(e,"limits",{}),i=this.safeDict(t,"leverage",{});return{info:e,symbol:this.safeString(e,"symbol"),marginMode:this.handleOption("fetchLeverage","defaultMarginMode","cross"),longLeverage:this.safeInteger(i,"max"),shortLeverage:this.safeInteger(i,"max")}}async fetchAccountSettings(e={}){let[t,i]=this.handleOriginAndSingleAddress("fetchAccountSettings",e),s=await this.publicGetAccountSettings(this.extend({account:t},i));return this.parseAccountSettings(this.safeList(s,"data",[]))}async loadAccountSettings(e=!1,t={}){let i=this.handleOption("loadAccountSettings","settings");(void 0===i||!0===e)&&(this.options.settings=this.createSafeDictionary(),i=await this.fetchAccountSettings(t),this.options.settings=i)}parseAccountSettings(e){if(0===e.length)return{};let t={};for(let i=0;i<e.length;i++){let s=e[i].symbol;t[this.safeMarket(s).symbol]=e[i]}return t}async fetchMarginMode(e,t={}){let i;await this.loadAccountSettings();let[s,r]=this.handleOriginAndSingleAddress("fetchMarginMode",t);i=s===this.walletAddress?this.handleOption("fetchMarginMode","settings"):await this.fetchAccountSettings(this.extend({account:s},r));let a=this.safeDict(i,e);return void 0===a?{symbol:e,marginMode:this.handleOption("fetchMarginMode","defaultMarginMode","cross")}:this.parseMarginModeFromSetting(e,a)}parseMarginModeFromSetting(e,t){let i=this.safeBool(t,"isolated",!1),s="cross";return!0===i&&(s="isolated"),{symbol:e,marginMode:s,info:t}}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),[r,a]=this.handleOptionIntegerAndParams(i,"fetchOrderBook","aggLevel",1),o={symbol:s.id,agg_level:r},n=await this.publicGetBook(this.extend(o,a)),d=this.safeDict(n,"data",{}),h=this.safeList(d,"l",[]),c={bids:this.safeList(h,0,[]),asks:this.safeList(h,1,[])},l=this.safeInteger(d,"t");return this.parseOrderBook(c,this.safeSymbol(void 0,s),l,"bids","asks","p","a")}async fetchFundingRates(e,t={}){let i=await this.publicGetInfoPrices(t),s=this.safeList(i,"data",[]);return this.parseFundingRates(s,e)}parseFundingRate(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t).symbol,r=this.safeNumber(e,"funding"),a=this.safeNumber(e,"mark"),o=this.safeNumber(e,"oracle"),n=this.safeNumber(e,"next_funding"),d=this.safeInteger(e,"timestamp"),h=(Math.floor(this.milliseconds()/60/60/1e3)+1)*36e5;return{info:e,symbol:s,markPrice:a,indexPrice:o,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:d,datetime:this.iso8601(d),fundingRate:r,fundingTimestamp:h,fundingDatetime:this.iso8601(h),nextFundingRate:n,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:"1h"}}async fetchOHLCV(e,t="1m",i,s,r={}){if(void 0===i)throw new a.ArgumentsRequired(this.id+' fetchOHLCV() requires a "since" argument');if(void 0===e)throw new a.ArgumentsRequired(this.id+' fetchOHLCV() requires a "symbol" argument');void 0===this.markets&&await this.loadMarkets();let o=this.market(e),[n,d]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(n)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,d,3950);let h=this.safeString(this.timeframes,t,t),c={symbol:o.id,interval:h,start_time:i},[l,u]=this.handleUntilOption("end_time",c,d),f=this.milliseconds(),p=this.safeInteger(l,"end_time");void 0===p&&(void 0!==s&&(p=i+s*(1e3*this.parseTimeframe(h))-1),void 0===p&&(p=i+3950*(1e3*this.parseTimeframe(h))-1),p>f&&(p=f),l.end_time=p);let m=await this.publicGetKline(this.extend(l,u)),g=this.safeList(m,"data",[]);return this.parseOHLCVs(g,o,t,i,s)}parseOHLCV(e,t){return[this.safeInteger(e,"t"),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id},o=await this.publicGetTrades(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parseTrades(n,r,t,i)}async fetchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1),[n,d]=this.handleOriginAndSingleAddress("fetchMyTrades",o);if(a)return await this.fetchPaginatedCallCursor("fetchMyTrades",e,t,i,d,"next_cursor","cursor",void 0,100);let[h,c]=this.handleUntilOption("end_time",{},d);h.account=n,void 0!==e&&(h.symbol=this.safeString(r,"id")),void 0!==i&&(h.limit=i),void 0!==t&&(h.start_time=t);let l=await this.publicGetTradesHistory(this.extend(h,c)),u=this.addPaginationCursorToResult(l);return this.parseTrades(u,r,t,i)}parseTrade(e,t){let i,s=this.safeString(e,"event_type"),r=this.safeInteger(e,"created_at"),a=this.safeString(e,"price"),o=this.safeString(e,"amount"),n=this.safeString(e,"symbol"),d=this.safeMarket(n,t),h=d.symbol,c=this.safeString(e,"history_id"),l=this.safeString(e,"side");"open_long"===l?l="buy":"close_long"===l||"open_short"===l?l="sell":"close_short"===l&&(l="buy");let u=this.safeString(e,"fee"),f=this.safeString(e,"order_id");return void 0!==s&&(i="fulfill_maker"===s?"maker":"taker"),void 0===f&&(i=void 0),this.safeTrade({info:e,timestamp:r,datetime:this.iso8601(r),symbol:h,id:c,order:f,type:void 0,side:l,takerOrMaker:i,price:a,amount:o,cost:void 0,fee:{cost:u,currency:"USDC",rate:void 0}},d)}async createOrder(e,t,i,s,r,a={}){let o,n;void 0===this.markets&&await this.loadMarkets(),await this.initializeClient();let[d,h]=this.createOrderRequest(e,t,i,s,r,a),c=this.omit(a,["reduceOnly","reduce_only","clientOrderId","stopLimitPrice","timeInForce","triggerPrice","stopLossCloid","stopLossPrice","stopLossLimitPrice","takeProfitCloid","takeProfitPrice","takeProfitLimitPrice","expiryWindow","slippage","slippage_percent"]);o="create_market_order"===h?await this.privatePostOrdersCreateMarket(this.extend(d,c)):"create_stop_order"===h?await this.privatePostOrdersStopCreate(this.extend(d,c)):"set_position_tpsl"===h?await this.privatePostPositionsTpsl(this.extend(d,c)):await this.privatePostOrdersCreate(this.extend(d,c)),n=!0!==this.safeBool(o,"success",!1)?"rejected":"open";let l=this.safeDict(o,"data",{}),u=this.safeString(l,"order_id");return this.safeOrder({id:u,status:n,info:o,symbol:e})}createOrderRequest(e,t,i,s,r,o={}){let n;if(void 0===t)throw new a.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new a.ArgumentsRequired(this.id+" requires a side argument");let d={symbol:this.market(e).id,side:this.mapSide(i)},h=this.safeBool2(o,"reduceOnly","reduce_only",!1),c=t.toUpperCase(),l=this.safeString(o,"triggerPrice"),u=this.safeString(o,"stopLossPrice"),f=this.safeString(o,"takeProfitPrice"),p=this.safeStringUpper(o,"timeInForce"),m=void 0!==f,g=void 0!==u,v=void 0!==l,y=this.mapTimeInForce(p);if("MARKET"===c){n="create_market_order",d.reduce_only=h;let e=this.handleOption("createOrder","defaultSlippage","0.5");d.slippage_percent=this.safeString2(o,"slippage","slippage_percent",e)}else if((m||g)&&void 0===r)n="set_position_tpsl";else if(v){n="create_stop_order",d.reduce_only=h;let t=this.safeString(o,"clientOrderId"),i={amount:this.amountToPrecision(e,s),stop_price:this.priceToPrecision(e,l)};void 0!==t&&(i.client_order_id=t),void 0!==r&&(i.limit_price=this.priceToPrecision(e,r)),d.stop_order=i}else n="create_order",d.reduce_only=h,d.tif=y;if(m){let t={stop_price:this.priceToPrecision(e,f)};void 0!==r&&(t.limit_price=this.priceToPrecision(e,r)),d.take_profit=t}if(g){let t={stop_price:this.priceToPrecision(e,u)};void 0!==r&&(t.limit_price=this.priceToPrecision(e,r)),d.stop_loss=t}void 0!==r&&"create_order"===n&&(d.price=this.priceToPrecision(e,r)),void 0!==s&&"create_stop_order"!==n&&"set_position_tpsl"!==n&&(d.amount=this.amountToPrecision(e,s));let b="create_stop_order"===n?this.omit(o,["clientOrderId"]):o,w=this.safeString(b,"clientOrderId");return void 0!==w&&(d.client_order_id=w),[this.postActionRequest(n,d,b),n]}batchOrdersRequest(e){let t=e.length,i=this.handleOption("batchOrdersRequest","batchOrdersMax");if(void 0!==i&&t>i)throw new a.ExchangeError(this.id+" batchOrdersRequest() too many orders to create/cancel. Limit is "+this.numberToString(i));return{actions:e}}createOrdersRequest(e,t={}){let i=[],s=this.milliseconds();for(let t=0;t<e.length;t++){let r=this.safeDict(e,t),o=this.safeString(r,"symbol"),n=this.safeString(r,"side"),d=this.safeString(r,"price"),h=this.safeString(r,"type","limit"),c=this.safeDict(r,"params",{});c.timestamp=s;let l=this.safeString(r,"amount"),u=this.parseNumber(l),f=this.parseNumber(d);if("limit"!==h)throw new a.NotSupported(this.id+' createOrders() supports only type = "limit"! Your value type='+h);let p={type:"Create",data:this.createOrderRequest(o,h,n,u,f,c)[0]};i.push(p)}return this.batchOrdersRequest(i)}async createOrders(e,t={}){void 0===this.markets&&await this.loadMarkets(),await this.initializeClient();let i=this.createOrdersRequest(e),s=await this.privatePostOrdersBatch(this.extend(i,t)),r=this.safeDict(s,"data",{}),a=this.safeList(r,"results",[]),o=[];for(let e=0;e<a.length;e++){let t,i=a[e],s=this.safeString(i,"error"),r=this.safeBool(i,"success",!1);t=void 0!==s||!0!==r?"rejected":"open";let n=this.safeString(i,"order_id");o.push(this.safeOrder({info:i,id:n,status:t}))}return o}async cancelOrders(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),await this.initializeClient(),void 0===t)throw new a.ArgumentsRequired(this.id+' cancelOrders() requires a "symbol" argument!');let s=this.cancelOrdersRequest(e,t,i),r=this.omit(i,["expiryWindow","clientOrderIds"]),o=await this.privatePostOrdersBatch(this.extend(s,r)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"results",[]),h=[];for(let e=0;e<d.length;e++){let i,s=d[e],r=this.safeString(s,"error"),a=this.safeBool(s,"success",!1);i=void 0!==r||!0!==a?"closed":"canceled",h.push(this.safeOrder({info:s,status:i,symbol:t}))}return h}cancelOrdersRequest(e,t,i={}){let s=[];for(let r=0;r<e.length;r++){let a=e[r],o={type:"Cancel",data:this.cancelOrderRequest(a,t,i)};s.push(o)}let r=this.safeList(i,"clientOrderIds",[]),a=this.omit(i,"clientOrderIds");for(let e=0;e<r.length;e++){let i=r[e],o={clientOrderId:i},n={type:"Cancel",data:this.cancelOrderRequest(i,t,this.extend(o,a))};s.push(n)}return this.batchOrdersRequest(s)}async cancelAllOrders(e,t={}){void 0===this.markets&&await this.loadMarkets(),await this.initializeClient();let i=this.cancelAllOrdersRequest(e,t),s=this.omit(t,["excludeReduceOnly","expiryWindow"]),r=await this.privatePostOrdersCancelAll(this.extend(i,s));return[this.safeOrder({info:r})]}cancelAllOrdersRequest(e,t={}){let i={};if(i.exclude_reduce_only=this.safeBool(t,"excludeReduceOnly",!1),void 0!==e){let t=this.market(e);i.all_symbols=!1,i.symbol=t.id}else i.all_symbols=!0;return this.postActionRequest("cancel_all_orders",i,t)}async cancelOrder(e,t,i={}){let s;if(void 0===this.markets&&await this.loadMarkets(),await this.initializeClient(),void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");let r=this.cancelOrderRequest(e,t,i),o=this.safeBool2(i,"trigger","stop",!1),n=this.omit(i,["expiryWindow","trigger","stop","clientOrderId"]);s=!0===o?await this.privatePostOrdersStopCancel(this.extend(r,n)):await this.privatePostOrdersCancel(this.extend(r,n));let d=this.safeBool(s,"success",!1),h="closed";return!0===d&&(h="canceled"),this.safeOrder({id:e,status:h,info:s,symbol:t})}cancelOrderRequest(e,t,i={}){let s,r=this.market(t);s=!0===this.safeBool2(i,"trigger","stop",!1)?"cancel_stop_order":"cancel_order";let a=this.safeString(i,"clientOrderId"),o={symbol:r.id};return void 0!==a?o.client_order_id=a:o.order_id=this.parseToInt(e),this.postActionRequest(s,o,i)}async editOrder(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets(),await this.initializeClient();let n=this.market(t),d=this.editOrderRequest(e,t,i,s,r,a,n,o),h=this.omit(o,["expiryWindow","clientOrderId"]),c=await this.privatePostOrdersEdit(this.extend(d,h)),l=this.safeDict(c,"data",{}),u=this.safeString(l,"order_id");return this.safeOrder({id:u,info:c,symbol:t})}editOrderRequest(e,t,i,s,r,o,n,d={}){if(void 0===s)throw new a.ArgumentsRequired(this.id+" requires a side argument");if(void 0===r)throw new a.ArgumentsRequired(this.id+" editOrder() requires an amount!");if(void 0===o)throw new a.ArgumentsRequired(this.id+" editOrder() requires a price");let h=this.safeString(d,"clientOrderId"),c=this.priceToPrecision(t,o),l=this.amountToPrecision(t,r),u={symbol:this.safeString(n,"id"),price:c,amount:l};if(void 0===h&&void 0===e)throw new a.ArgumentsRequired('this.ideditOrder() requires either "id" or "clientOrderId"');return void 0!==h?u.client_order_id=h:u.order_id=this.parseToInt(e),this.postActionRequest("edit_order",u,d)}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");let r=this.market(e),[o,n]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(o)return await this.fetchPaginatedCallCursor("fetchFundingRateHistory",e,t,i,n,"next_cursor","cursor",void 0,100);let d={symbol:r.id};void 0!==i&&(d.limit=i);let h=await this.publicGetFundingRateHistory(this.extend(d,n)),c=this.addPaginationCursorToResult(h),l=[];for(let e=0;e<c.length;e++){let t=c[e],i=this.safeInteger(t,"created_at");l.push({info:t,symbol:r.symbol,fundingRate:this.safeNumber(t,"funding_rate"),timestamp:i,datetime:this.iso8601(i)})}let u=this.sortBy(l,"timestamp");return this.filterBySinceLimit(u,t,i,"timestamp")}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetInfoPrices(t),r=this.safeList(s,"data",[]),a={};for(let e=0;e<r.length;e++){let t=r[e],i=this.parseTicker(t),s=this.safeString(i,"symbol");void 0!==s&&(a[s]=i)}return this.filterByArrayTickers(a,"symbol",i)}parseTicker(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=s.symbol,a=this.safeInteger(e,"timestamp");return this.safeTicker({symbol:r,timestamp:a,datetime:this.iso8601(a),previousClose:this.safeNumber(e,"yesterday_price"),close:this.safeNumber(e,"mid"),bid:void 0,ask:void 0,quoteVolume:this.safeNumber(e,"volume_24h"),info:e},s)}async fetchClosedOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.fetchOrders(e,void 0,void 0,s),a=this.filterByArray(r,"status",["closed"],!1);return this.filterBySymbolSinceLimit(a,e,t,i)}async fetchCanceledOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.fetchOrders(e,void 0,void 0,s),a=this.filterByArray(r,"status",["canceled"],!1);return this.filterBySymbolSinceLimit(a,e,t,i)}async fetchCanceledAndClosedOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.fetchOrders(e,void 0,void 0,s),a=this.filterByArray(r,"status",["canceled","closed","rejected"],!1);return this.filterBySymbolSinceLimit(a,e,t,i)}async fetchOpenOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOriginAndSingleAddress("fetchOpenOrders",s);void 0!==e&&(r=this.market(e));let n=await this.publicGetOrders(this.extend({account:a},o)),d=this.safeList(n,"data",[]);return this.parseOrders(d,r,t,i)}async fetchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchOrders","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchOrders",e,t,i,o,"next_cursor","cursor",void 0,100);let[n,d]=this.handleOriginAndSingleAddress("fetchOrders",o);void 0!==e&&(r=this.market(e));let h={account:n};void 0!==i&&(h.limit=i);let c=await this.publicGetOrdersHistory(this.extend(h,d)),l=this.addPaginationCursorToResult(c);return this.parseOrders(l,r,t,i)}addPaginationCursorToResult(e){let t=this.safeList(e,"data",[]),i=this.safeString(e,"next_cursor"),s=this.safeBool(e,"has_more",!1),r=t.length;if(!0===s&&void 0!==i&&r>0){let e=t[0];e.next_cursor=i,e.has_more=s,t[0]=e}return t}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(s=this.market(t));let r=await this.publicGetOrdersHistoryById(this.extend({order_id:e},i)),a=this.safeList(r,"data",[]),o=this.sortBy(a,"history_id",!0),n=o.length,d={};return n>0&&(d=o[0]),this.parseOrder(d,s)}parseOrderStatus(e){return this.safeString({open:"open",partially_filled:"open",filled:"closed",cancelled:"canceled",rejected:"failed"},e,e)}mapTimeInForce(e){let t;return void 0!==e&&(t=e.toUpperCase()),this.safeString({GTC:"GTC",IOC:"IOC",PO:"ALO",POST_ONLY:"ALO",PO_TOB:"TOB",TOB:"TOB",ALO:"ALO"},t,"GTC")}mapSide(e){return this.safeString({sell:"ask",buy:"bid"},e,e)}parseOrderType(e){return this.safeString({stop_limit:"limit",stop_market:"market",take_profit_limit:"limit",stop_loss_limit:"limit",take_profit_market:"market",stop_loss_market:"market"},e,e)}parseOrder(e,t){let i=this.safeString2(e,"symbol","s"),s=this.safeMarket(i,t),r=s.symbol,a=this.safeInteger2(e,"created_at","ct"),n=this.safeString2(e,"order_status","os","open"),d=this.safeString(e,"side","d");void 0!==d&&(d="bid"===d?"buy":"sell");let h=this.safeString2(e,"initial_amount","a"),c=this.safeString2(e,"filled_amount","f"),l=o.Y.stringSub(h,c),u=this.safeString2(e,"average_filled_price","p"),f=this.safeString(e,"event_type"),p=this.inArray(f,["fulfill_market","fulfill_limit"]);return void 0===u&&p&&(u=this.safeString(e,"price")),this.safeOrder({info:e,id:this.safeString2(e,"order_id","i"),clientOrderId:this.safeString2(e,"client_order_id","I"),timestamp:a,datetime:this.iso8601(a),lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeInteger2(e,"updated_at","ut"),symbol:r,type:this.parseOrderType(this.safeStringLower2(e,"order_type","ot")),timeInForce:void 0,postOnly:void 0,reduceOnly:this.safeBool2(e,"reduce_only","r"),side:d,price:this.safeString2(e,"price","lp"),triggerPrice:this.safeNumber2(e,"stop_price","sp"),amount:h,cost:void 0,average:u,filled:c,remaining:l,status:this.parseOrderStatus(n),fee:void 0,trades:void 0},s)}async fetchPosition(e,t={}){let i=await this.fetchPositions([e],t);return this.safeDict(i,0,{})}async fetchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOriginAndSingleAddress("fetchPositions",t),r=this.marketSymbols(e),a=await this.publicGetPositions(this.extend({account:i},s)),o=this.safeList(a,"data",[]),n=[];for(let e=0;e<o.length;e++)n.push(this.parsePosition(o[e],void 0));return this.filterByArrayPositions(n,"symbol",r)}parsePosition(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t).symbol,r=this.safeString(e,"margin"),a=void 0!==r&&"0"!==r?"isolated":"cross",o=this.safeString(e,"side");void 0!==o&&(o="bid"===o?"long":"short");let n=this.safeInteger(e,"created_at");return this.safePosition({info:e,id:void 0,symbol:s,timestamp:n,datetime:this.iso8601(n),isolated:"isolated"===a,hedged:void 0,side:o,contracts:this.safeNumber(e,"amount"),contractSize:void 0,entryPrice:this.safeNumber(e,"entry_price"),markPrice:void 0,notional:void 0,leverage:void 0,collateral:r,initialMargin:void 0,maintenanceMargin:void 0,initialMarginPercentage:void 0,maintenanceMarginPercentage:void 0,unrealizedPnl:void 0,liquidationPrice:void 0,marginMode:a,percentage:void 0})}async setMarginMode(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s={symbol:this.market(t).id,is_isolated:"isolated"===e},r=this.postActionRequest("update_margin_mode",s,i);return await this.privatePostAccountMargin(r)}async setLeverage(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s={symbol:this.market(t).id,leverage:e},r=this.postActionRequest("update_leverage",s,i);return await this.privatePostAccountLeverage(r)}async withdraw(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets(),this.checkAddress(i);let a={amount:this.numberToString(t)},o=this.postActionRequest("withdraw",a,r),n=this.omit(r,["expiryWindow"]);return{info:await this.privatePostAccountWithdraw(this.extend(o,n))}}async fetchTradingFee(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOriginAndSingleAddress("fetchTradingFee",t),r=this.market(e),a=await this.publicGetAccount(this.extend({account:i},s)),o=this.safeDict(a,"data",{});return this.parseTradingFee(o,r)}parseTradingFee(e,t){return{info:e,symbol:this.safeSymbol(void 0,t),maker:this.safeNumber(e,"maker_fee"),taker:this.safeNumber(e,"taker_fee"),percentage:void 0,tierBased:void 0}}async fetchOpenInterests(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetInfoPrices(t),r=this.safeList(s,"data",[]);return this.parseOpenInterests(r,i)}async fetchOpenInterest(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.symbol(e),s=await this.fetchOpenInterests([i],t),r=this.safeDict(s,i);if(void 0===r)throw new a.BadSymbol(this.id+" fetchOpenInterest() could not find open interest for "+i);return r}parseOpenInterest(e,t){let i,s,r=this.safeString(e,"symbol"),a=void 0!==r?this.safeMarket(r,t):t;void 0!==r&&(i=this.safeString(a,"symbol"));let n=this.safeString(e,"mark"),d=this.safeString(e,"open_interest");void 0!==d&&void 0!==n&&(s=o.Y.stringMul(d,n));let h=this.safeInteger(e,"timestamp");return this.safeOpenInterest({symbol:this.safeSymbol(i),openInterestAmount:this.parseNumber(d),openInterestValue:this.parseNumber(s),timestamp:h,datetime:this.iso8601(h),info:e},a)}async fetchLedger(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchLedger","paginate",!1),[o,n]=this.handleOriginAndSingleAddress("fetchLedger",a);if(r)return await this.fetchPaginatedCallCursor("fetchLedger",e,t,i,n,"next_cursor","cursor",void 0,100);let d={account:o};void 0!==i&&(d.limit=i);let h=await this.publicGetAccountBalanceHistory(this.extend(d,n)),c=this.addPaginationCursorToResult(h);return this.parseLedger(c,void 0,t,i)}parseLedgerEntry(e,t){let i=this.safeInteger(e,"created_at"),s=this.safeString(e,"event_type"),r=this.safeString(e,"amount"),a=this.safeString(e,"balance");return this.safeLedgerEntry({info:e,id:void 0,direction:void 0,account:void 0,referenceAccount:void 0,referenceId:void 0,type:this.parseLedgerEntryType(s),currency:void 0,amount:this.parseNumber(r),timestamp:i,datetime:this.iso8601(i),before:void 0,after:this.parseNumber(a),status:void 0,fee:void 0},t)}parseLedgerEntryType(e){return this.safeString({subaccount_transfer:"transfer",deposit:"transaction",deposit_release:"transaction",withdraw:"transaction",trade:"trade",market_liquidation:"trade",backstop_liquidation:"trade",adl_liquidation:"trade",funding:"funding",fee:"fee",rebate:"rebate",cashback:"cashback",referral:"referral",airdrop:"airdrop",payout:"payout"},e,e)}async fetchFundingHistory(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let[a,o]=this.handleOptionBoolAndParams(s,"fetchFundingHistory","paginate",!1),[n,d]=this.handleOriginAndSingleAddress("fetchFundingHistory",o),h={account:n};if(void 0!==i&&(h.limit=i),a)return await this.fetchPaginatedCallCursor("fetchFundingHistory",e,t,i,d,"next_cursor","cursor",void 0,100);let c=await this.publicGetFundingHistory(this.extend(h,d)),l=this.addPaginationCursorToResult(c);return this.parseIncomes(l,r,t,i)}parseIncome(e,t){let i=this.safeString(e,"history_id"),s=this.safeInteger(e,"created_at"),r=this.safeString(e,"symbol"),a=this.safeMarket(r,t).symbol,o=this.safeString(e,"amount"),n=this.safeCurrencyCode("USDC"),d=this.safeNumber(e,"rate");return{info:e,symbol:a,code:n,timestamp:s,datetime:this.iso8601(s),id:i,amount:this.parseNumber(o),rate:d}}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(e),o={to_account:s,amount:this.numberToString(t)},n=this.postActionRequest("transfer_funds",o,r),d=this.omit(r,["expiryWindow"]),h=await this.privatePostAccountSubaccountTransfer(this.extend(n,d)),c=this.safeDict(h,"data",{});return this.extend(this.parseTransfer(c,a),{amount:t,fromAccount:this.safeString(n,"account"),toAccount:s})}parseTransfer(e,t){let i,s=this.safeBool(e,"success");return void 0!==s&&(i=!0===s?"ok":"failed"),{info:e,id:void 0,timestamp:void 0,datetime:void 0,currency:this.safeCurrencyCode(void 0,t),amount:void 0,fromAccount:void 0,toAccount:void 0,status:i}}async createSubAccount(e,t={}){let i={},[s,r]=this.handleOptionStringAndParams(t,"createSubAccount","agentAddress"),[o,n]=this.handleOriginAndSingleAddress("createSubAccount",r);if(void 0===o)throw new a.ArgumentsRequired(this.id+' createSubAccount() requires "originAddress" in params or "walletAddress" in requiredCredentials');void 0!==s&&(i.agent_wallet=s);let[d,h]=this.handleOptionStringAndParams(n,"createSubAccount","subAccountAddress"),[c,l]=this.handleOptionStringAndParams(h,"createSubAccount","subAccountPrivateKey");if(void 0===d)throw new a.ArgumentsRequired(this.id+' createSubAccount() requires a "subAccountAddress"!');if(void 0===c)throw new a.ArgumentsRequired(this.id+' createSubAccount() requires a "subAccountPrivateKey"!');let[u,f]=this.handleParamInteger(l,"timestamp",this.milliseconds()),[p,m]=this.handleOptionIntegerAndParams2(f,"createSubAccount","expiryWindow","expiry_window",5e3),g=this.signMessage({timestamp:u,expiry_window:p,type:"subaccount_initiate"},{account:o},c),v=this.signMessage({timestamp:u,expiry_window:p,type:"subaccount_confirm"},{signature:g},this.privateKey);return i.main_account=o,i.subaccount=d,i.sub_signature=g,i.main_signature=v,i.timestamp=u,i.expiry_window=p,await this.privatePostAccountSubaccountCreate(this.extend(i,m))}async bindAgentWallet(e,t={}){let i=this.postActionRequest("bind_agent_wallet",{agent_wallet:e},t);return await this.privatePostAgentBind(this.extend(i,t))}async createApiKey(e={}){let t=this.postActionRequest("create_api_key",{},e);return await this.privatePostAccountApiKeysCreate(this.extend(t,e))}async revokeApiKey(e,t={}){let i=this.postActionRequest("revoke_api_key",{api_key:e},t);return await this.privatePostAccountApiKeysRevoke(this.extend(i,t))}async fetchApiKeys(e={}){let t=this.postActionRequest("list_api_keys",{},e);return await this.privatePostAccountApiKeys(this.extend(t,e))}async approveBuilderCode(e,t,i={}){let s=this.postActionRequest("approve_builder_code",{builder_code:e,max_fee_rate:t},i);return await this.privatePostAccountBuilderCodesApprove(this.extend(s,i))}async fetchBuilderApprovals(e){return await this.publicGetAccountBuilderCodesApprovals(this.extend({account:e}))}async revokeBuilderCode(e,t={}){let i=this.postActionRequest("revoke_builder_code",{builder_code:e},t);return await this.privatePostAccountBuilderCodesRevoke(this.extend(i,t))}handleOriginAndSingleAddress(e,t){let[i,s]=this.handleParamString2(t,"account","address",void 0);if(void 0!==i)return[i,s];let r=this.walletAddress;if(void 0!==r)return[r,s];throw new a.ArgumentsRequired(this.id+" "+e+'() requires address either as "exchange.walletAddress = ..." or as parameter or "address" in params')}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"code"),l=this.safeString(n,"error_id"),u=this.safeString(n,"error"),f=void 0!==u&&""!==u;if(void 0!==c&&"200"!==c||f){let t=this.id+" "+o;this.throwExactlyMatchedException(this.exceptions.exact,l,t),this.throwBroadlyMatchedException(this.exceptions.broad,u,t),this.throwExactlyMatchedException(this.exceptions.exact,c,t);let i=e.toString();if(e<400||!(i in this.httpExceptions))throw new a.ExchangeError(t)}}sign(e,t="public",i="GET",s={},r,o){let n=o,d=this.isSandboxModeEnabled,h="api";d&&(h="test");let c=this.safeString(this.urls[h],t);if(void 0===c)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let l=this.implodeHostname(c)+"/api/"+this.version+"/"+this.implodeParams(e,s),u=this.omit(s,this.extractParams(e)),f=Object.keys(u).length,p={"Content-Type":"application/json"};return"GET"===i&&f>0&&(l+="?"+this.urlencode(u),p.Accept="*/*"),"POST"===i&&(n=this.json(u)),void 0!==this.handleOption("sign","apiKey")&&(p["PF-API-KEY"]=this.options.apiKey),{url:l,method:i,body:n,headers:p}}calculateRateLimiterCost(e,t,i,s,r={}){let a=this.safeString(r,"cost","1"),o=this.parseNumber(a);return o>1&&void 0!==this.handleOption(t,"apiKey")?this.handleOption(t,"maxCostHugeWithApiKey",3):o}sortJsonKeys(e){if(this.isDictionary(e)){let t={},i=Object.keys(e),s=this.sort(i);for(let i=0;i<s.length;i++){let r=s[i];t[r]=this.sortJsonKeys(e[r])}return t}if(!Array.isArray(e))return e;{let t=[];for(let i=0;i<e.length;i++)t.push(this.sortJsonKeys(e[i]));return t}}prepareMessage(e,t){if(void 0===e.type||void 0===e.timestamp||void 0===e.expiry_window)throw new a.ArgumentsRequired(this.id+" prepareMessage() requires type, timestamp, expiry_window in header");let i=this.extend(e,{data:t}),s=this.sortJsonKeys(i);return this.json(s)}signMessage(e,t,i){let r=this.prepareMessage(e,t),a=this.encode(r),o=this.base58ToBinary(i),d=this.arraySlice(o,0,32),h=(0,n.q4)(a,d,s.ev),c=this.base64ToBinary(h);return this.binaryToBase58(c)}postActionRequest(e,t,i){if(this.checkRequiredCredentials(),"undefined"===e)throw new a.ArgumentsRequired(this.id+" action: "+e+' postActionRequest() requires "operationType"');if(!this.isSandboxModeEnabled){let i;!0===this.handleOption("postActionRequest","builderFee",!0)&&(i=this.handleOption("postActionRequest","builderCode")),void 0!==i&&!0===this.safeBool(this.options.builderSupportOperations,e,!1)&&(t.builder_code=i)}let[s,r]=this.handleOptionIntegerAndParams2(i,"postActionRequest","expiryWindow","expiry_window",5e3),o={timestamp:this.safeInteger(r,"timestamp",this.milliseconds()),expiry_window:s,type:e},n=this.signMessage(o,t,this.privateKey),d={},[h,c]=this.handleOptionStringAndParams(r,"postActionRequest","agentAddress"),l=this.handleOriginAndSingleAddress("postActionRequest",c)[0];if(void 0===l)throw new a.ArgumentsRequired(this.id+" action: "+e+' postActionRequest() requires "originAddress" in params or "walletAddress" in requiredCredentials');return d.account=l,void 0!==h&&(d.agent_wallet=h),d.signature=n,d.timestamp=this.safeInteger(o,"timestamp"),d.expiry_window=this.safeInteger(o,"expiry_window"),this.extend(d,t)}}i.d(t,{A:()=>d})},3651(e,t,i){"use strict";var s=i(6834),r=i(6885),a=i(7749),o=i(3496),n=i(1453),d=i(1093);class h extends o.A{describe(){return this.deepExtend(super.describe(),{id:"paradex",name:"Paradex",countries:[],version:"v1",rateLimit:50,certified:!1,pro:!0,dex:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,cancelAllOrders:!0,cancelAllOrdersAfter:!1,cancelOrder:!0,cancelOrders:!0,cancelOrdersForSymbols:!1,closeAllPositions:!1,closePosition:!1,createMarketBuyOrderWithCost:!1,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:!0,createReduceOnlyOrder:!1,createStopOrder:!0,createTriggerOrder:!0,editOrder:!0,fetchAccounts:!1,fetchAllGreeks:!0,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchCanceledOrders:!1,fetchClosedOrders:!1,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDepositAddress:!1,fetchDepositAddresses:!1,fetchDeposits:!0,fetchDepositWithdrawFee:!1,fetchDepositWithdrawFees:!1,fetchFundingHistory:!0,fetchFundingRate:!0,fetchFundingRateHistory:!0,fetchFundingRates:!0,fetchGreeks:!0,fetchIndexOHLCV:!0,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLedger:!1,fetchLeverage:!0,fetchLeverageTiers:!1,fetchLiquidations:!1,fetchMarginMode:!0,fetchMarketLeverageTiers:!1,fetchMarkets:!0,fetchMarkOHLCV:!0,fetchMyLiquidations:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenInterestHistory:!1,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchOrderTrades:!1,fetchPosition:!0,fetchPositionMode:!1,fetchPositions:!0,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchTradingFees:!0,fetchTransfer:!1,fetchTransfers:!0,fetchWithdrawal:!1,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,sandbox:!0,setLeverage:!0,setMarginMode:!0,setPositionMode:!1,transfer:!1,withdraw:!1},timeframes:{"1m":1,"3m":3,"5m":5,"15m":15,"30m":30,"1h":60},hostname:"paradex.trade",urls:{logo:"https://github.com/user-attachments/assets/84628770-784e-4ec4-a759-ec2fbb2244ea",api:{v1:"https://api.prod.{hostname}/v1",v2:"https://api.prod.{hostname}/v2"},test:{v1:"https://api.testnet.{hostname}/v1",v2:"https://api.testnet.{hostname}/v2"},www:"https://www.paradex.trade/",doc:"https://docs.api.testnet.paradex.trade/",fees:"https://docs.paradex.trade/getting-started/trading-fees",referral:"https://app.paradex.trade/r/ccxt24"},api:{public:{get:{"bbo/{market}":{cost:1},"bbo/{market}/interactive":{cost:1},"funding/data":{cost:1},markets:{cost:1},"markets/history":{cost:1},"markets/klines":{cost:1},"markets/settlement-price":{cost:1},"markets/summary":{cost:1},"orderbook/{market}":{cost:1},"orderbook/{market}/impact-price":{cost:1},"orderbook/{market}/interactive":{cost:1},insurance:{cost:1},"jwks.json":{cost:1},onboarding:{cost:1},"referrals/config":{cost:1},"staking/balance/history/global":{cost:1},"staking/config":{cost:1},"system/announcements":{cost:1},"system/config":{cost:1},"system/portfolio-margin-config":{cost:1},"system/state":{cost:1},"system/time":{cost:1},"system/volume-tiers":{cost:1},trades:{cost:1},vaults:{cost:1},"vaults/analytics":{cost:1},"vaults/balance":{cost:1},"vaults/config":{cost:1},"vaults/history":{cost:1},"vaults/positions":{cost:1},"vaults/summary":{cost:1},"vaults/transfers":{cost:1},"xp/fee-config":{cost:1},"xp/public-transfers":{cost:1},"xp/transfer/{transfer_id}":{cost:1}}},private:{get:{account:{cost:1},"account/compliance":{cost:1},"account/history":{cost:1},"account/info":{cost:1},"account/margin":{cost:1},"account/profile":{cost:1},"account/settings":{cost:1},"account/subaccounts":{cost:1},"account/summary":{cost:1},balance:{cost:1},fills:{cost:1},"funding/payments":{cost:1},positions:{cost:1},tradebusts:{cost:1},transactions:{cost:1},"account/keys/subkeys":{cost:1},"account/keys/subkeys/{public_key}":{cost:1},"account/tokens":{cost:1},"algo/orders":{cost:1},"algo/orders-history":{cost:1},"algo/orders/{algo_id}":{cost:1},"block-trades":{cost:1},"block-trades/{block_trade_id}":{cost:1},"block-trades/{block_trade_id}/offers":{cost:1},"block-trades/{block_trade_id}/offers/{offer_id}":{cost:1},liquidations:{cost:1},orders:{cost:1},"orders-history":{cost:1},"orders/by_client_id/{client_id}":{cost:1},"orders/{order_id}":{cost:1},"referrals/qr-code":{cost:1},"referrals/summary":{cost:1},rfqs:{cost:1},"rfqs/drafts":{cost:1},"rfqs/markets":{cost:1},"rfqs/{rfq_id}/bbo":{cost:1},"staking/balance/history":{cost:1},"staking/history":{cost:1},"staking/summary":{cost:1},transfers:{cost:1},"vaults/account-summary":{cost:1},"vaults/mine":{cost:1},"xp/account-balance":{cost:1},"xp/transfers":{cost:1}},post:{"account/compliance":{cost:1},"account/margin/{market}":{cost:1},"account/profile/market_max_slippage/{market}":{cost:1},"account/profile/notifications":{cost:1},"account/profile/notifications/last_seen":{cost:1},"account/profile/referral_code":{cost:1},"account/profile/refresh_inventory":{cost:1},"account/profile/size_currency_display":{cost:1},"account/profile/username":{cost:1},"account/referrer":{cost:1},"account/settings/trading_value_display":{cost:1},"account/paradigm/enable":{cost:1},"account/terminal-token":{cost:1},"account/keys/subkeys/activate":{cost:1},"account/keys/subkeys":{cost:1},"account/tokens":{cost:1},"algo/orders":{cost:1},auth:{cost:1},"block-trades":{cost:1},"block-trades/{block_trade_id}/execute":{cost:1},"block-trades/{block_trade_id}/offers":{cost:1},"block-trades/{block_trade_id}/offers/{offer_id}/execute":{cost:1},onboarding:{cost:1},orders:{cost:1},"orders/batch":{cost:1},rfqs:{cost:1},"rfqs/drafts":{cost:1},"rfqs/{rfq_id}/execute":{cost:1},"v2/auth":{cost:1},"v2/onboarding":{cost:1},vaults:{cost:1},"xp/transfer":{cost:1}},put:{"account/profile":{cost:1},"account/keys/subkeys/{public_key}":{cost:1},"account/keys/subkeys/{public_key}/allowed-cidrs":{cost:1},"account/tokens/{lookup_id}/allowed-cidrs":{cost:1},"orders/{order_id}":{cost:1}},delete:{"account/keys/subkeys/{public_key}":{cost:1},"account/tokens/{lookup_id}":{cost:1},"algo/orders/{algo_id}":{cost:1},"block-trades/{block_trade_id}":{cost:1},"block-trades/{block_trade_id}/offers/{offer_id}":{cost:1},orders:{cost:1},"orders/batch":{cost:1},"orders/by_client_id/{client_id}":{cost:1},"orders/{order_id}":{cost:1},"rfqs/drafts/{draft_id}":{cost:1},"rfqs/{rfq_id}":{cost:1}}}},fees:{swap:{taker:this.parseNumber("0.0002"),maker:this.parseNumber("0.0002")},spot:{taker:this.parseNumber("0.0002"),maker:this.parseNumber("0.0002")}},requiredCredentials:{apiKey:!1,secret:!1,walletAddress:!0,privateKey:!0},exceptions:{exact:{VALIDATION_ERROR:n.AuthenticationError,BINDING_ERROR:n.OperationRejected,INTERNAL_ERROR:n.ExchangeError,NOT_FOUND:n.BadRequest,SERVICE_UNAVAILABLE:n.ExchangeError,INVALID_REQUEST_PARAMETER:n.BadRequest,ORDER_ID_NOT_FOUND:n.InvalidOrder,ORDER_IS_CLOSED:n.InvalidOrder,ORDER_IS_NOT_OPEN_YET:n.InvalidOrder,CLIENT_ORDER_ID_NOT_FOUND:n.InvalidOrder,DUPLICATED_CLIENT_ID:n.InvalidOrder,INVALID_PRICE_PRECISION:n.OperationRejected,INVALID_SYMBOL:n.OperationRejected,INVALID_TOKEN:n.OperationRejected,INVALID_ETHEREUM_ADDRESS:n.OperationRejected,INVALID_ETHEREUM_SIGNATURE:n.OperationRejected,INVALID_STARKNET_ADDRESS:n.OperationRejected,INVALID_STARKNET_SIGNATURE:n.OperationRejected,STARKNET_SIGNATURE_VERIFICATION_FAILED:n.AuthenticationError,BAD_STARKNET_REQUEST:n.BadRequest,ETHEREUM_SIGNER_MISMATCH:n.BadRequest,ETHEREUM_HASH_MISMATCH:n.BadRequest,NOT_ONBOARDED:n.BadRequest,INVALID_TIMESTAMP:n.BadRequest,INVALID_SIGNATURE_EXPIRATION:n.AuthenticationError,ACCOUNT_NOT_FOUND:n.AuthenticationError,INVALID_ORDER_SIGNATURE:n.AuthenticationError,PUBLIC_KEY_INVALID:n.BadRequest,UNAUTHORIZED_ETHEREUM_ADDRESS:n.BadRequest,ETHEREUM_ADDRESS_ALREADY_ONBOARDED:n.BadRequest,MARKET_NOT_FOUND:n.BadRequest,ALLOWLIST_ENTRY_NOT_FOUND:n.BadRequest,USERNAME_IN_USE:n.AuthenticationError,GEO_IP_BLOCK:n.PermissionDenied,ETHEREUM_ADDRESS_BLOCKED:n.PermissionDenied,PROGRAM_NOT_FOUND:n.BadRequest,INVALID_DASHBOARD:n.OperationRejected,MARKET_NOT_OPEN:n.BadRequest,INVALID_REFERRAL_CODE:n.OperationRejected,PARENT_ADDRESS_ALREADY_ONBOARDED:n.BadRequest,INVALID_PARENT_ACCOUNT:n.OperationRejected,INVALID_VAULT_OPERATOR_CHAIN:n.OperationRejected,VAULT_OPERATOR_ALREADY_ONBOARDED:n.OperationRejected,VAULT_NAME_IN_USE:n.OperationRejected,BATCH_SIZE_OUT_OF_RANGE:n.OperationRejected,ISOLATED_MARKET_ACCOUNT_MISMATCH:n.OperationRejected,POINTS_SUMMARY_NOT_FOUND:n.OperationRejected,"-32700":n.BadRequest,"-32600":n.BadRequest,"-32601":n.BadRequest,"-32602":n.BadRequest,"-32603":n.ExchangeError,100:n.BadRequest,40110:n.AuthenticationError,40111:n.AuthenticationError,40112:n.PermissionDenied},broad:{"missing or malformed jwt":n.AuthenticationError}},precisionMode:4,commonCurrencies:{},options:{paradexAccount:void 0,broker:"CCXT"},features:{spot:void 0,forSwap:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerDirection:!0,triggerPriceType:void 0,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!1,PO:!0,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!1,marketBuyRequiresPrice:!1,selfTradePrevention:!0,iceberg:!1},createOrders:{max:10},fetchMyTrades:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:100,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:100,daysBack:1e5,untilDays:1e5,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:void 0,fetchOHLCV:{limit:void 0}},swap:{linear:{extends:"forSwap"},inverse:void 0},future:{linear:void 0,inverse:void 0}}})}async fetchTime(e={}){let t=await this.publicGetSystemTime(e);return this.safeInteger(t,"server_time")}async fetchStatus(e={}){let t=await this.publicGetSystemState(e);return{status:"ok"===this.safeString(t,"status")?"ok":"maintenance",updated:void 0,eta:void 0,url:void 0,info:t}}async fetchMarkets(e={}){let t=await this.publicGetMarkets(e),i=this.safeList(t,"results");return this.parseMarkets(i)}parseMarket(e){let t=this.safeString(e,"asset_kind"),i="PERP_OPTION"===t||"OPTION"===t,s="swap";i&&(s="option");let r="swap"===s,a=this.safeString(e,"symbol"),o=this.safeString(e,"quote_currency"),n=this.safeString(e,"base_currency"),d=this.safeCurrencyCode(o),h=this.safeCurrencyCode(n);if(void 0===h||void 0===d)return;let c=this.safeString(e,"settlement_currency"),l=this.safeCurrencyCode(c),u=h+"/"+d+":"+l,f=this.safeInteger(e,"expiry_at"),p=this.safeString(e,"option_type"),m=this.safeString(e,"strike_price"),g=this.parseNumber("0.0003"),v=this.parseNumber("-0.00005");i?(u=u+"-"+(0===f?"":this.yymmdd(f)+"-")+m+"-"+("CALL"===p?"C":"P"),v=this.parseNumber("0.0003")):f=void 0;let y=0===f?void 0:this.iso8601(f);return this.safeMarketStructure({id:a,symbol:u,base:h,quote:d,settle:l,baseId:n,quoteId:o,settleId:c,type:s,spot:!1,margin:void 0,swap:r,future:!1,option:i,active:this.safeBool(e,"enableTrading"),contract:!0,linear:!0,inverse:!1,taker:g,maker:v,contractSize:this.parseNumber("1"),expiry:f,expiryDatetime:y,strike:this.parseNumber(m),optionType:this.safeStringLower(e,"option_type"),precision:{amount:this.safeNumber(e,"order_size_increment"),price:this.safeNumber(e,"price_tick_size")},limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:this.safeNumber(e,"max_order_size")},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(e,"min_notional"),max:void 0}},created:void 0,info:e})}parseTradingFee(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeDict(e,"fee_config",{}),a=this.safeDict(r,"api_fee",{}),o=this.safeDict(a,"maker_fee",{}),n=this.safeDict(a,"taker_fee",{});return{info:e,symbol:s.symbol,maker:this.safeNumber(o,"fee",this.safeNumber(s,"maker")),taker:this.safeNumber(n,"fee",this.safeNumber(s,"taker")),percentage:!0,tierBased:!1}}async fetchTradingFee(e,t={}){if(void 0===e)throw new n.ArgumentsRequired(this.id+" fetchTradingFee() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={market:i.id},r=await this.publicGetMarkets(this.extend(s,t)),a=this.safeList(r,"results",[]),o=this.safeDict(a,0,{});return this.parseTradingFee(o,i)}async fetchTradingFees(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.publicGetMarkets(e),i=this.safeList(t,"results",[]),s={};for(let e=0;e<i.length;e++){let t=this.parseTradingFee(i[e]);s[t.symbol]=t}return s}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={resolution:this.safeString(this.timeframes,t,t),symbol:a.id},n=this.milliseconds(),d=this.parseTimeframe(t),h=this.safeInteger2(r,"until","till",n),c=this.safeString(r,"price");void 0!==c&&(o.price_kind=c);let l=this.omit(r,["until","till","price"]);void 0!==i?(o.start_at=i,void 0!==s?o.end_at=i+d*(s+1)*1e3-1:o.end_at=h):(o.end_at=h,void 0!==s?o.start_at=h-d*(s+1)*1e3+1:o.start_at=h-101*d*1e3+1);let u=await this.publicGetMarketsKlines(this.extend(o,l)),f=this.safeList(u,"results",[]);return this.parseOHLCVs(f,a,t,i,s)}parseOHLCV(e,t){return[this.safeInteger(e,0),this.safeNumber(e,1),this.safeNumber(e,2),this.safeNumber(e,3),this.safeNumber(e,4),this.safeNumber(e,5)]}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.publicGetMarketsSummary(this.extend({market:"ALL"},t)),r=this.safeList(s,"results",[]);return this.parseTickers(r,i)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={market:i.id},r=await this.publicGetMarketsSummary(this.extend(s,t)),a=this.safeList(r,"results",[]),o=this.safeDict(a,0,{});return this.parseTicker(o,i)}parseTicker(e,t){let i=this.safeString(e,"price_change_rate_24h");void 0!==i&&(i=a.Y.stringMul(i,"100"));let s=this.safeString(e,"last_traded_price"),r=this.safeString(e,"symbol"),o=this.safeMarket(r,t),n=o.symbol,d=this.safeInteger(e,"created_at");return this.safeTicker({symbol:n,timestamp:d,datetime:this.iso8601(d),high:void 0,low:void 0,bid:this.safeString(e,"bid"),bidVolume:void 0,ask:this.safeString(e,"ask"),askVolume:void 0,vwap:void 0,open:void 0,close:s,last:s,previousClose:void 0,change:void 0,percentage:i,average:void 0,baseVolume:void 0,quoteVolume:this.safeString(e,"volume_24h"),markPrice:this.safeString(e,"mark_price"),info:e},o)}async fetchFundingRates(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s="ALL";void 0!==i&&1===i.length&&(s=this.market(i[0]).id);let r={market:s},a=await this.publicGetMarketsSummary(this.extend(r,t)),o=this.safeList(a,"results",[]);return this.parseFundingRates(o,i)}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=await this.fetchFundingRates([i.symbol],t),r=this.safeDict(s,i.symbol);if(void 0===r)throw new n.BadSymbol(this.id+" fetchFundingRate() could not find a funding rate for "+e);return r}parseFundingRate(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t,void 0,"swap"),o=this.safeInteger(e,"created_at"),n=this.safeString(e,"funding_rate"),d=!0===r.swap&&void 0!==n&&""!==n,h=this.safeString(this.safeDict(r,"info",{}),"funding_period_hours");return void 0!==h&&a.Y.stringGt(h,"0")&&(i=h+"h"),{info:e,symbol:d?r.symbol:void 0,markPrice:this.safeNumber(e,"mark_price"),indexPrice:this.safeNumber(e,"underlying_price"),interestRate:void 0,estimatedSettlePrice:void 0,timestamp:o,datetime:this.iso8601(o),fundingRate:this.safeNumber(e,"funding_rate"),fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:i}}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={market:s.id},a=await this.publicGetOrderbookMarket(this.extend(r,i));void 0!==t&&(r.depth=t);let o=this.safeInteger(a,"last_updated_at"),n=this.parseOrderBook(a,s.symbol,o);return n.nonce=this.safeInteger(a,"seq_no"),n}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchTrades","paginate",!1);if(r)return await this.fetchPaginatedCallCursor("fetchTrades",e,t,i,a,"next","cursor",void 0,100);let o=this.market(e),n={market:o.id};void 0!==i&&(n.page_size=Math.min(i,1e3)),void 0!==t&&(n.start_at=t);let[d,h]=this.handleUntilOption("end_at",n,a),c=await this.publicGetTrades(this.extend(d,h)),l=this.safeList(c,"results",[]);for(let e=0;e<l.length;e++)l[e].next=this.safeString(c,"next");return this.parseTrades(l,o,t,i)}parseTrade(e,t){let i=this.safeString(e,"market"),s=this.safeMarket(i,t),r=this.safeString(e,"id"),a=this.safeInteger(e,"created_at"),o=this.safeString(e,"price"),n=this.safeString(e,"size"),d=this.safeStringLower(e,"side"),h=this.safeStringLower(e,"liquidity","taker"),c="maker";"taker"===h&&(c="taker");let l=this.safeString(e,"fee_currency"),u=this.safeCurrencyCode(l);return this.safeTrade({info:e,id:r,order:this.safeString(e,"order_id"),timestamp:a,datetime:this.iso8601(a),symbol:s.symbol,type:void 0,takerOrMaker:c,side:d,price:o,amount:n,cost:void 0,fee:{cost:this.safeString(e,"fee"),currency:u,rate:void 0}},s)}async fetchOpenInterest(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.contract)throw new n.BadRequest(this.id+" fetchOpenInterest() supports contract markets only");let s={market:i.id},r=await this.publicGetMarketsSummary(this.extend(s,t)),a=this.safeList(r,"results",[]),o=this.safeDict(a,0,{});return this.parseOpenInterest(o,i)}parseOpenInterest(e,t){let i=this.safeInteger(e,"created_at"),s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=r.symbol;return this.safeOpenInterest({symbol:a,openInterestAmount:this.safeString(e,"open_interest"),openInterestValue:void 0,timestamp:i,datetime:this.iso8601(i),info:e},r)}hashMessage(e){return"0x"+this.hash(e,s.lY,"hex")}signHash(e,t){let i=(0,d.h1)(e.slice(-64),t.slice(-64),r.bI,void 0),s=i.r,a=i.s,o=this.intToBase16(this.sum(27,i.v));return"0x"+s.padStart(64,"0")+a.padStart(64,"0")+o}signMessage(e,t){return this.signHash(this.hashMessage(e),t.slice(-64))}async getSystemConfig(){let e=this.safeDict(this.options,"systemConfig");if(void 0!==e)return e;let t=await this.publicGetSystemConfig();return this.options.systemConfig=t,this.safeDict(this.options,"systemConfig",{})}async prepareParadexDomain(e=!1){let t=await this.getSystemConfig();return!0===e?{name:"Paradex",chainId:t.l1_chain_id,version:"1"}:{name:"Paradex",chainId:t.starknet_chain_id,version:1}}async retrieveAccount(){let e=this.safeDict(this.options,"paradexAccount");if(void 0!==e)return e;this.checkRequiredCredentials();let t=await this.getSystemConfig(),i=await this.prepareParadexDomain(!0),s=this.ethEncodeStructuredData(i,{Constant:[{name:"action",type:"string"}]},{action:"STARK Key"}),r=this.signMessage(s,this.privateKey),a=this.retrieveStarkAccount(r,t.paraclear_account_hash,t.paraclear_account_proxy_hash);return this.options.paradexAccount=a,a}async onboarding(e={}){let t=await this.retrieveAccount(),i=await this.prepareParadexDomain(),s=this.starknetEncodeStructuredData(i,{Constant:[{name:"action",type:"felt"}]},{action:"Onboarding"},t.address);return e.signature=this.starknetSign(s,t.privateKey),e.account=t.address,e.public_key=t.publicKey,await this.privatePostOnboarding(e)}async authenticateRest(e={}){let t=this.safeString(this.options,"authToken"),i=this.nonce();if(void 0!==t){let e=this.safeInteger(this.options,"expires");if(void 0===e)throw new n.ExchangeError(this.id+" authenticateRest() missing cachedExpires");if(i<e)return t}let s=await this.retrieveAccount(),r=i+180,a={method:"POST",path:"/v1/auth",body:"",timestamp:i,expiration:r},o=await this.prepareParadexDomain(),d=this.starknetEncodeStructuredData(o,{Request:[{name:"method",type:"felt"},{name:"path",type:"felt"},{name:"body",type:"felt"},{name:"timestamp",type:"felt"},{name:"expiration",type:"felt"}]},a,s.address);e.signature=this.starknetSign(d,s.privateKey),e.account=s.address,e.timestamp=a.timestamp,e.expiration=a.expiration;let h=await this.privatePostAuth(e),c=this.safeString(h,"jwt_token");return this.options.authToken=c,this.options.expires=r,c}parseOrder(e,t){let i,s=this.safeInteger(e,"created_at"),r=this.safeString(e,"id"),a=this.omitZero(this.safeString(e,"client_id")),o=this.safeString(e,"market"),n=this.safeMarket(o,t),d=n.symbol,h=this.safeString(e,"price"),c=this.safeString(e,"size"),l=this.safeString(e,"type"),u=this.safeString(e,"cancel_reason"),f=this.safeString(e,"status");void 0!==u&&(f="NOT_ENOUGH_MARGIN"===u||"ORDER_EXCEEDS_POSITION_LIMIT"===u?"rejected":"canceled");let p=this.safeStringLower(e,"side"),m=this.omitZero(this.safeString(e,"avg_fill_price")),g=this.omitZero(this.safeString(e,"remaining_size")),v=this.omitZero(this.safeString(e,"trigger_price")),y=this.safeInteger(e,"last_updated_at"),b=this.safeList(e,"flags");return void 0!==b&&(i=this.inArray("REDUCE_ONLY",b)),this.safeOrder({id:r,clientOrderId:a,timestamp:s,datetime:this.iso8601(s),lastTradeTimestamp:void 0,lastUpdateTimestamp:y,status:this.parseOrderStatus(f),symbol:d,type:this.parseOrderType(l),timeInForce:this.parseTimeInForce(this.safeString(e,"instruction")),postOnly:void 0,reduceOnly:i,side:p,price:h,triggerPrice:v,takeProfitPrice:void 0,stopLossPrice:void 0,average:m,amount:c,filled:void 0,remaining:g,cost:void 0,trades:void 0,fee:{cost:void 0,currency:void 0},info:e},n)}parseTimeInForce(e){return this.safeString({IOC:"IOC",GTC:"GTC",POST_ONLY:"PO"},e)}parseOrderStatus(e){if(void 0!==e)return this.safeString({NEW:"open",UNTRIGGERED:"open",OPEN:"open",CLOSED:"closed"},e,e)}parseOrderType(e){return this.safeStringLower({LIMIT:"limit",MARKET:"market",STOP_LIMIT:"limit",STOP_MARKET:"market"},e,e)}scaleNumber(e){return a.Y.stringMul(e,"100000000")}createOrderRequest(e,t,i,s,r,a={}){let o;if(void 0===t)throw new n.ArgumentsRequired(this.id+" requires a type argument");if(void 0===i)throw new n.ArgumentsRequired(this.id+" requires a side argument");let d=this.market(e),h=this.safeBool2(a,"reduceOnly","reduce_only"),c=t.toUpperCase(),l=i.toUpperCase(),u={market:d.id,side:l,type:c,instruction:"GTC"},f=this.safeString2(a,"triggerPrice","stopPrice"),p=this.safeString(a,"stopLossPrice"),m=this.safeString(a,"takeProfitPrice"),g="MARKET"===c,v=void 0!==m,y=void 0!==p,b=void 0!==f||v||y,w=this.safeStringUpper(a,"timeInForce"),k=this.isPostOnly(g,void 0,a);g||(k?u.instruction="POST_ONLY":"IOC"===w&&(u.instruction="IOC")),void 0!==r&&(u.price=this.priceToPrecision(e,r));let S=this.safeStringN(a,["clOrdID","clientOrderId","client_order_id"]);void 0!==S&&(u.client_id=S);let O="0";b?g?y?(o=this.priceToPrecision(e,p),h=!0,u.type="STOP_LOSS_MARKET"):v?(o=this.priceToPrecision(e,m),h=!0,u.type="TAKE_PROFIT_MARKET"):(o=this.priceToPrecision(e,f),O=this.amountToPrecision(e,s),u.type="STOP_MARKET"):y?(o=this.priceToPrecision(e,p),h=!0,u.type="STOP_LOSS_LIMIT"):v?(o=this.priceToPrecision(e,m),h=!0,u.type="TAKE_PROFIT_LIMIT"):(o=this.priceToPrecision(e,f),O=this.amountToPrecision(e,s),u.type="STOP_LIMIT"):O=this.amountToPrecision(e,s),void 0!==o&&(u.trigger_price=o),u.size=O,!0===h&&(u.flags=["REDUCE_ONLY"]);let T=this.omit(a,["reduceOnly","reduce_only","clOrdID","clientOrderId","client_order_id","postOnly","timeInForce","stopPrice","triggerPrice","stopLossPrice","takeProfitPrice"]);return this.extend(u,T)}async signOrderRequest(e,t=!1){let i=await this.retrieveAccount(),s=this.nonce(),r=this.safeString(e,"type");if(void 0===r)throw new n.ExchangeError(this.id+" signOrderRequest() missing orderType");let a=r.indexOf("MARKET")>=0,o={timestamp:1e3*s,market:this.stringToBase16(e.market),side:"BUY"===this.safeString(e,"side")?"1":"2",orderType:this.stringToBase16(e.type),size:this.scaleNumber(e.size),price:a?"0":this.scaleNumber(e.price)},d=[{name:"timestamp",type:"felt"},{name:"market",type:"felt"},{name:"side",type:"felt"},{name:"orderType",type:"felt"},{name:"size",type:"felt"},{name:"price",type:"felt"}],h={};t?(o.id=e.id,d.push({name:"id",type:"felt"}),h={ModifyOrder:d}):h={Order:d};let c=await this.prepareParadexDomain(),l=this.starknetEncodeStructuredData(c,h,o,i.address);return e.signature=this.starknetSign(l,i.privateKey),e.signature_timestamp=o.timestamp,e}async createOrder(e,t,i,s,r,a={}){await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=this.createOrderRequest(e,t,i,s,r,a);n=await this.signOrderRequest(n);let d=await this.privatePostOrders(n);return this.parseOrder(d,o)}async editOrder(e,t,i,s,r,a,o={}){if(void 0===r)throw new n.ArgumentsRequired(this.id+" editOrder() requires an amount argument");if(void 0===a)throw new n.ArgumentsRequired(this.id+" editOrder() requires a price argument");await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let d=this.market(t),h=this.createOrderRequest(t,i,s,r,a,o);(h=this.omit(h,["instruction","client_id","flags"])).order_id=e,h.id=e,h=await this.signOrderRequest(h,!0);let c=await this.privatePutOrdersOrderId(h);return this.parseOrder(c,d)}async createOrders(e,t={}){await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let i=[];for(let s=0;s<e.length;s++){let r=this.safeDict(e,s),a=this.safeString(r,"symbol"),o=this.safeString(r,"type"),n=this.safeString(r,"side"),d=this.safeNumber(r,"amount"),h=this.safeNumber(r,"price"),c=this.safeDict(r,"params",{}),l=this.extend(t,c),u=this.createOrderRequest(a,o,n,d,h,l);u=await this.signOrderRequest(u),i.push(u)}let s=await this.privatePostOrdersBatch(i),r=this.safeList(s,"orders",[]),a=this.parseOrders(r),o=this.safeList(s,"errors",[]);for(let e=0;e<o.length;e++){let t=o[e];a.push(this.safeOrder({info:t,status:"rejected"}))}return a}async cancelOrder(e,t,i={}){let s;await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let r={},a=this.safeStringN(i,["clOrdID","clientOrderId","client_order_id"]);return void 0!==a?(r.client_id=a,s=await this.privateDeleteOrdersByClientIdClientId(this.extend(r,i))):(r.order_id=e,s=await this.privateDeleteOrdersOrderId(this.extend(r,i))),this.parseOrder(s)}async cancelOrders(e,t,i={}){await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let s=this.safeListN(i,["clOrdIDs","clientOrderIds","client_order_ids"]),r=this.omit(i,["clOrdIDs","clientOrderIds","client_order_ids"]),a=void 0!==e&&Array.isArray(e),o=void 0!==s&&Array.isArray(s);if(!a&&!o)throw new n.ArgumentsRequired(this.id+" cancelOrders() requires a non-empty ids argument or a non-empty clientOrderIds parameter");let d={};a&&(d.order_ids=e),o&&(d.client_order_ids=s);let h=await this.privateDeleteOrdersBatch(this.extend(d,r)),c=this.safeList(h,"results",[]),l=[];for(let e=0;e<c.length;e++){let t,i=c[e],s=this.safeString(i,"market"),r=this.safeMarket(s),a=this.safeString(i,"status");"QUEUED_FOR_CANCELLATION"===a?t="canceled":"ALREADY_CLOSED"===a?t="closed":"NOT_FOUND"===a&&(t="rejected"),l.push(this.safeOrder({info:i,id:this.safeString(i,"id"),clientOrderId:this.safeString(i,"client_id"),status:t,symbol:r.symbol},r))}return l}async cancelAllOrders(e,t={}){if(void 0===e)throw new n.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument");await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let i={market:this.market(e).id},s=await this.privateDeleteOrders(this.extend(i,t));return[this.safeOrder({info:s})]}async fetchOrder(e,t,i={}){let s;await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let r={},a=this.safeStringN(i,["clOrdID","clientOrderId","client_order_id"]),o=this.omit(i,["clOrdID","clientOrderId","client_order_id"]);return void 0!==a?(r.client_id=a,s=await this.privateGetOrdersByClientIdClientId(this.extend(r,o))):(r.order_id=e,s=await this.privateGetOrdersOrderId(this.extend(r,o))),this.parseOrder(s)}async fetchOrders(e,t,i,s={}){let r;await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchOrders","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchOrders",e,t,i,o,"next","cursor",void 0,50);let n={};void 0!==e&&(n.market=(r=this.market(e)).id),void 0!==t&&(n.start_at=t),void 0!==i&&(n.page_size=i);let[d,h]=this.handleUntilOption("end_at",n,o),c=await this.privateGetOrdersHistory(this.extend(d,h)),l=this.safeList(c,"results",[]),u=this.safeString(c,"next"),f=l.length;if(void 0!==u&&f>0){let e=l[0];e.next=u,l[0]=e}return this.parseOrders(l,r,t,i)}async fetchOpenOrders(e,t,i,s={}){let r;await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.market=(r=this.market(e)).id);let o=await this.privateGetOrders(this.extend(a,s)),n=this.safeList(o,"results",[]);return this.parseOrders(n,r,t,i)}async fetchBalance(e={}){await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetBalance(),i=this.safeList(t,"results",[]);return this.parseBalance(i)}parseBalance(e){let t={info:e};for(let i=0;i<e.length;i++){let s=this.safeDict(e,i,{}),r=this.safeString(s,"token"),a=this.safeCurrencyCode(r),o=this.account();o.total=this.safeString(s,"size"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}async fetchMyTrades(e,t,i,s={}){let r;await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchMyTrades",e,t,i,o,"next","cursor",void 0,100);let n={};void 0!==e&&(n.market=(r=this.market(e)).id),void 0!==i&&(n.page_size=i),void 0!==t&&(n.start_at=t);let[d,h]=this.handleUntilOption("end_at",n,o),c=await this.privateGetFills(this.extend(d,h)),l=this.safeList(c,"results",[]);for(let e=0;e<l.length;e++)l[e].next=this.safeString(c,"next");return this.parseTrades(l,r,t,i)}async fetchPosition(e,t={}){await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=await this.fetchPositions([i.symbol],t);return this.safeDict(s,0,{})}async fetchPositions(e,t={}){await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=await this.privateGetPositions(),r=this.safeList(s,"results",[]);return this.parsePositions(r,i)}parsePosition(e,t){let i=this.safeString(e,"market"),s=this.safeMarket(i,t).symbol,r=this.safeStringLower(e,"side"),o=this.safeString(e,"size");"long"!==r&&(o=a.Y.stringMul("-1",o));let n=this.safeInteger(e,"time"),d=this.parseNumber(this.omitZero(this.safeString(e,"liquidation_price")));return this.safePosition({info:e,id:this.safeString(e,"id"),symbol:s,entryPrice:this.safeNumber(e,"average_entry_price"),markPrice:void 0,notional:void 0,collateral:this.safeNumber(e,"cost"),unrealizedPnl:this.safeNumber(e,"unrealized_pnl"),side:r,contracts:this.parseNumber(o),contractSize:void 0,timestamp:n,datetime:this.iso8601(n),hedged:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,initialMargin:void 0,initialMarginPercentage:void 0,leverage:void 0,liquidationPrice:d,marginRatio:void 0,marginMode:void 0,percentage:void 0})}async fetchMyLiquidations(e,t,i,s={}){let r;await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let a={};void 0!==t?a.from=t:a.from=1,void 0!==e&&(r=this.market(e));let[o,n]=this.handleUntilOption("to",a,s),d=await this.privateGetLiquidations(this.extend(o,n)),h=this.safeList(d,"results",[]);return this.parseLiquidations(h,r,t,i)}parseLiquidation(e,t){let i=this.safeInteger(e,"created_at");return this.safeLiquidation({info:e,symbol:this.safeString(t,"symbol"),contracts:void 0,contractSize:void 0,price:void 0,side:void 0,baseValue:void 0,quoteValue:void 0,timestamp:i,datetime:this.iso8601(i)})}async fetchDeposits(e,t,i,s={}){await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchDeposits","paginate",!1);if(r)return await this.fetchPaginatedCallCursor("fetchDeposits",e,t,i,a,"next","cursor",void 0,100);let o={};void 0!==i&&(o.page_size=i),void 0!==t&&(o.start_at=t);let[n,d]=this.handleUntilOption("end_at",o,a),h=await this.privateGetTransfers(this.extend(n,d)),c=this.safeList(h,"results",[]),l=[];for(let e=0;e<c.length;e++){let t=c[e];"DEPOSIT"===this.safeString(t,"kind")&&l.push(t)}return this.parseTransactions(l,void 0,t,i)}async fetchWithdrawals(e,t,i,s={}){await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchWithdrawals","paginate",!1);if(r)return await this.fetchPaginatedCallCursor("fetchWithdrawals",e,t,i,a,"next","cursor",void 0,100);let o={};void 0!==i&&(o.page_size=i),void 0!==t&&(o.start_at=t);let[n,d]=this.handleUntilOption("end_at",o,a),h=await this.privateGetTransfers(this.extend(n,d)),c=this.safeList(h,"results",[]),l=[];for(let e=0;e<c.length;e++){let t=c[e];"WITHDRAWAL"===this.safeString(t,"kind")&&l.push(t)}return this.parseTransactions(l,void 0,t,i)}async fetchTransfers(e,t,i,s={}){let r;await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchTransfers","paginate",!1);if(a)return await this.fetchPaginatedCallCursor("fetchTransfers",e,t,i,o,"next","cursor",void 0,100);let n={};void 0!==e&&(r=this.safeCurrency(e)),void 0!==i&&(n.page_size=i),void 0!==t&&(n.start_at=t);let[d,h]=this.handleUntilOption("end_at",n,o),c=await this.privateGetTransfers(this.extend(d,h)),l=this.safeList(c,"results",[]);return this.parseTransfers(l,r,t,i)}parseTransfer(e,t){let i,s,r=this.safeString(e,"token"),a=this.safeCurrencyCode(r,t),o=this.safeInteger(e,"created_at"),n=this.safeString(e,"kind");return"DEPOSIT"===n?(i="external",s="account"):"WITHDRAWAL"===n&&(i="account",s="external"),{info:e,id:this.safeString(e,"id"),timestamp:o,datetime:this.iso8601(o),currency:a,amount:this.safeNumber(e,"amount"),fromAccount:i,toAccount:s,status:this.parseTransactionStatus(this.safeString(e,"status"))}}parseTransaction(e,t){let i=this.safeString(e,"id"),s=this.safeString(e,"account"),r=this.safeString(e,"txn_hash"),a=this.safeString(e,"token"),o=this.safeCurrencyCode(a,t),n=this.safeInteger(e,"created_at"),d=this.safeInteger(e,"last_updated_at"),h=this.safeString(e,"kind");h="DEPOSIT"===h?"deposit":"withdrawal";let c=this.parseTransactionStatus(this.safeString(e,"status")),l=this.safeNumber(e,"amount");return{info:e,id:i,txid:r,timestamp:n,datetime:this.iso8601(n),network:void 0,address:s,addressTo:s,addressFrom:void 0,tag:void 0,tagTo:void 0,tagFrom:void 0,type:h,amount:l,currency:o,status:c,updated:d,internal:void 0,comment:void 0,fee:void 0}}parseTransactionStatus(e){return this.safeString({PENDING:"pending",AVAILABLE:"pending",COMPLETED:"ok",FAILED:"failed"},e,e)}async fetchMarginMode(e,t={}){await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={market:i.id},r=await this.privateGetAccountMargin(this.extend(s,t)),a=this.safeList(r,"configs");return this.parseMarginMode(this.safeDict(a,0),i)}parseMarginMode(e,t){let i=this.safeString(e,"market"),s=this.safeMarket(i,t),r=this.safeStringLower(e,"margin_type");return{info:e,symbol:this.safeString(s,"symbol"),marginMode:r}}async setMarginMode(e,t,i={}){this.checkRequiredArgument("setMarginMode",t,"symbol"),await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let s=this.market(t),[r,a]=this.handleOptionAndParams(i,"setMarginMode","leverage",1),o={market:s.id,leverage:r,margin_type:this.encodeMarginMode(e)};return await this.privatePostAccountMarginMarket(this.extend(o,a))}async fetchLeverage(e,t={}){await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={market:i.id},r=await this.privateGetAccountMargin(this.extend(s,t)),a=this.safeList(r,"configs");return this.parseLeverage(this.safeDict(a,0),i)}parseLeverage(e,t){let i=this.safeString(e,"market"),s=this.safeMarket(i,t),r=this.safeStringLower(e,"margin_type");return{info:e,symbol:this.safeSymbol(i,s),marginMode:r,longLeverage:this.safeInteger(e,"leverage"),shortLeverage:this.safeInteger(e,"leverage")}}encodeMarginMode(e){return this.safeString({cross:"CROSS",isolated:"ISOLATED"},e,e)}async setLeverage(e,t,i={}){this.checkRequiredArgument("setLeverage",t,"symbol"),await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let s=this.market(t),[r,a]=this.handleMarginModeAndParams("setLeverage",i,"cross"),o={market:s.id,leverage:e,margin_type:this.encodeMarginMode(r)};return await this.privatePostAccountMarginMarket(this.extend(o,a))}async fetchGreeks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={market:i.id},r=await this.publicGetMarketsSummary(this.extend(s,t)),a=this.safeList(r,"results",[]),o=this.safeDict(a,0,{});return this.parseGreeks(o,i)}async fetchAllGreeks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s=await this.publicGetMarketsSummary(this.extend({market:"ALL"},t)),r=this.safeList(s,"results",[]);return this.parseAllGreeks(r,i)}parseGreeks(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t,void 0,"option").symbol,r=this.safeInteger(e,"created_at"),a=this.safeDict(e,"greeks",{});return{symbol:s,timestamp:r,datetime:this.iso8601(r),delta:this.safeNumber(a,"delta"),gamma:this.safeNumber(a,"gamma"),theta:void 0,vega:this.safeNumber(a,"vega"),rho:this.safeNumber(a,"rho"),vanna:this.safeNumber(a,"vanna"),volga:this.safeNumber(a,"volga"),bidSize:void 0,askSize:void 0,bidImpliedVolatility:this.safeNumber(e,"bid_iv"),askImpliedVolatility:this.safeNumber(e,"ask_iv"),markImpliedVolatility:this.safeNumber(e,"mark_iv"),bidPrice:this.safeNumber(e,"bid"),askPrice:this.safeNumber(e,"ask"),markPrice:this.safeNumber(e,"mark_price"),lastPrice:this.safeNumber(e,"last_traded_price"),underlyingPrice:this.safeNumber(e,"underlying_price"),info:e}}async fetchFundingHistory(e,t,i,s={}){if(void 0===e)throw new n.ArgumentsRequired(this.id+" fetchFundingHistory() requires a symbol argument");await this.authenticateRest(),void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"fetchFundingHistory","paginate",!1);if(r)return await this.fetchPaginatedCallCursor("fetchFundingHistory",e,t,i,a,"next","cursor",void 0,100);let o=this.market(e),d={market:o.id};void 0!==i?d.page_size=Math.min(i,5e3):d.page_size=100,void 0!==t&&(d.start_at=t);let[h,c]=this.handleUntilOption("end_at",d,a),l=await this.privateGetFundingPayments(this.extend(h,c)),u=this.safeList(l,"results",[]);return this.parseIncomes(u,o,t,i)}parseIncome(e,t){let i=this.safeString(e,"market"),s=this.safeMarket(i,t),r=this.safeInteger(e,"created_at");return{info:e,symbol:s.symbol,code:s.settle,timestamp:r,datetime:this.iso8601(r),id:this.safeString(e,"id"),amount:this.safeNumber(e,"payment")}}async fetchFundingRateHistory(e,t,i,s={}){if(void 0===e)throw new n.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={market:r.id};void 0!==i?a.page_size=Math.min(i,5e3):a.page_size=1e3,void 0!==t&&(a.start_at=t);let o=this.safeInteger(s,"until"),d=void 0!==o?this.omit(s,"until"):s;void 0!==o&&(a.end_at=o);let h=await this.publicGetFundingData(this.extend(a,d)),c=this.safeList(h,"results",[]),l=[];for(let e=0;e<c.length;e++){let t=c[e],i=this.safeInteger(t,"created_at"),s=this.iso8601(i);l.push({info:t,symbol:r.symbol,fundingRate:this.safeNumber(t,"funding_rate"),timestamp:i,datetime:s})}let u=this.sortBy(l,"timestamp");return this.filterBySymbolSinceLimit(u,this.safeString(r,"symbol"),t,i)}sign(e,t="public",i="GET",s={},r,a){let o=this.version,d=e;0===e.indexOf("v2/")&&(d=e.replace("v2/","")),0===e.indexOf("v2/")&&(o="v2");let h=this.safeString(this.urls.api,o);if(void 0===h)throw new n.ExchangeError(this.id+" sign() has no API URL for this endpoint");let c=this.implodeHostname(h)+"/"+this.implodeParams(d,s),l=this.omit(s,this.extractParams(d));if("public"===t)Object.keys(l).length>0&&(c+="?"+this.urlencode(l));else if("private"===t){let e,t={Accept:"application/json","PARADEX-PARTNER":this.safeString(this.options,"broker","CCXT")};if("auth"===d)t["PARADEX-STARKNET-ACCOUNT"]=l.account,t["PARADEX-STARKNET-SIGNATURE"]=l.signature,t["PARADEX-TIMESTAMP"]=l.timestamp.toString(),t["PARADEX-SIGNATURE-EXPIRATION"]=l.expiration.toString();else if("onboarding"===d)t["PARADEX-ETHEREUM-ACCOUNT"]=this.walletAddress,t["PARADEX-STARKNET-ACCOUNT"]=l.account,t["PARADEX-STARKNET-SIGNATURE"]=l.signature,t["PARADEX-TIMESTAMP"]=this.nonce().toString(),t["Content-Type"]="application/json",e=this.json({public_key:l.public_key});else{let s=this.safeString(this.options,"authToken");if(void 0===s)throw new n.AuthenticationError(this.id+" sign() requires an authToken, call authenticateRest() first");t.Authorization="Bearer "+s,"POST"===i||"PUT"===i||"DELETE"===i&&"orders/batch"===d?(t["Content-Type"]="application/json",e=this.json(l)):c=c+"?"+this.urlencode(l)}return{url:c,method:i,body:void 0!==e?e:a,headers:t}}return{url:c,method:i,body:a,headers:r}}handleErrors(e,t,i,s,r,a,o,d,h){if(void 0===o)return;let c=this.safeString(o,"error");if(void 0!==c){let e=this.id+" "+a;throw this.throwBroadlyMatchedException(this.exceptions.broad,a,e),this.throwExactlyMatchedException(this.exceptions.exact,c,e),new n.ExchangeError(e)}}}i.d(t,{A:()=>h})},8686(e,t,i){"use strict";var s=i(4721),r=i(7113),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"paymium",name:"Paymium",countries:["FR","EU"],rateLimit:2e3,version:"v1",has:{CORS:!0,spot:!0,margin:void 0,swap:!1,future:!1,option:!1,cancelOrder:!0,createDepositAddress:!0,createOrder:!0,fetchBalance:!0,fetchDepositAddress:!0,fetchDepositAddresses:!0,fetchDepositAddressesByNetwork:!1,fetchFundingHistory:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchIndexOHLCV:!1,fetchMarkOHLCV:!1,fetchOpenInterestHistory:!1,fetchOrderBook:!0,fetchPremiumIndexOHLCV:!1,fetchTicker:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,transfer:!0},urls:{logo:"https://user-images.githubusercontent.com/51840849/87153930-f0f02200-c2c0-11ea-9c0a-40337375ae89.jpg",api:{rest:"https://paymium.com/api"},www:"https://www.paymium.com",fees:"https://www.paymium.com/page/help/fees",doc:["https://github.com/Paymium/api-documentation","https://www.paymium.com/page/developers","https://paymium.github.io/api-documentation/"],referral:"https://www.paymium.com/page/sign-up?referral=eDAzPoRQFMvaAB8sf-qj"},api:{public:{get:{countries:{cost:1},currencies:{cost:1},"data/{currency}/ticker":{cost:1},"data/{currency}/trades":{cost:1},"data/{currency}/depth":{cost:1},"bitcoin_charts/{id}/trades":{cost:1},"bitcoin_charts/{id}/depth":{cost:1}}},private:{get:{user:{cost:1},"user/addresses":{cost:1},"user/addresses/{address}":{cost:1},"user/orders":{cost:1},"user/orders/{uuid}":{cost:1},"user/price_alerts":{cost:1},"user/withdrawals":{cost:1},"merchant/get_payment/{uuid}":{cost:1}},post:{"user/addresses":{cost:1},"user/orders":{cost:1},"user/withdrawals":{cost:1},"user/email_transfers":{cost:1},"user/payment_requests":{cost:1},"user/price_alerts":{cost:1},"merchant/create_payment":{cost:1}},delete:{"user/orders/{uuid}":{cost:1},"user/orders/{uuid}/cancel":{cost:1},"user/price_alerts/{id}":{cost:1}}}},markets:{"BTC/EUR":this.safeMarketStructure({id:"eur",symbol:"BTC/EUR",base:"BTC",quote:"EUR",baseId:"btc",quoteId:"eur",type:"spot",spot:!0})},fees:{trading:{maker:this.parseNumber("-0.001"),taker:this.parseNumber("0.005")}},precisionMode:4,features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerDirection:!1,triggerPriceType:void 0,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!1,FOK:!1,PO:!1,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:void 0,fetchOrder:void 0,fetchOpenOrders:void 0,fetchOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:void 0},swap:{linear:void 0,inverse:void 0},future:{linear:void 0,inverse:void 0}}})}parseBalance(e){let t={info:e},i=Object.keys(this.currencies);for(let s=0;s<i.length;s++){let r=i[s],a=this.currency(r).id,o="balance_"+a;if(o in e){let i=this.account(),s="locked_"+a;i.free=this.safeString(e,o),i.used=this.safeString(e,s),t[r]=i}}return this.safeBalance(t)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGetUser(e);return this.parseBalance(t)}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={currency:s.id},a=await this.publicGetDataCurrencyDepth(this.extend(r,i));return this.parseOrderBook(a,s.symbol,void 0,"bids","asks","price","amount")}parseTicker(e,t){let i=this.safeSymbol(void 0,t),s=this.safeTimestamp(e,"at"),r=this.safeString(e,"vwap"),a=this.safeString(e,"volume"),n=o.Y.stringMul(a,r),d=this.safeString(e,"price");return this.safeTicker({symbol:i,timestamp:s,datetime:this.iso8601(s),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"bid"),bidVolume:void 0,ask:this.safeString(e,"ask"),askVolume:void 0,vwap:r,open:this.safeString(e,"open"),close:d,last:d,previousClose:void 0,change:void 0,percentage:this.safeString(e,"variation"),average:void 0,baseVolume:a,quoteVolume:n,info:e},t)}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={currency:i.id},r=await this.publicGetDataCurrencyTicker(this.extend(s,t));return this.parseTicker(r,i)}parseTrade(e,t){let i=this.safeTimestamp(e,"created_at_int"),s=this.safeString(e,"uuid"),r=this.safeMarket(void 0,t),a=this.safeString(e,"side"),o=this.safeString(e,"price"),n="traded_"+r.base.toLowerCase(),d=this.safeString(e,n);return this.safeTrade({info:e,id:s,order:void 0,timestamp:i,datetime:this.iso8601(i),symbol:r.symbol,type:void 0,side:a,takerOrMaker:void 0,price:o,amount:d,cost:void 0,fee:void 0},r)}async fetchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={currency:r.id},o=await this.publicGetDataCurrencyTrades(this.extend(a,s));return this.parseTrades(o,r,t,i)}async createDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privatePostUserAddresses(t);return this.parseDepositAddress(i)}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privateGetUserAddressesAddress(this.extend({address:e},t));return this.parseDepositAddress(i)}async fetchDepositAddresses(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.privateGetUserAddresses(t);return this.parseDepositAddresses(i,e,!1)}parseDepositAddress(e,t){let i=this.safeString(e,"address"),s=this.safeString(e,"currency");return{info:e,currency:this.safeCurrencyCode(s,t),network:void 0,address:i,tag:void 0}}async createOrder(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={type:this.capitalize(t)+"Order",currency:o.id,direction:i,amount:s};"market"!==t&&(n.price=r);let d=await this.privatePostUserOrders(this.extend(n,a));return this.safeOrder({info:d,id:this.safeString(d,"uuid")},o)}async cancelOrder(e,t,i={}){let s=await this.privateDeleteUserOrdersUuidCancel(this.extend({uuid:e},i));return this.safeOrder({info:s})}async transfer(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let o=this.currency(e);if(0>s.indexOf("@"))throw new a.ExchangeError(this.id+" transfer() only allows transfers to an email address");if("BTC"!==e&&"EUR"!==e)throw new a.ExchangeError(this.id+" transfer() only allows BTC or EUR");let n={currency:o.id,amount:this.currencyToPrecision(e,t),email:s},d=await this.privatePostUserEmailTransfers(this.extend(n,r));return this.parseTransfer(d,o)}parseTransfer(e,t){let i=this.safeString(e,"currency"),s=this.safeString(e,"updated_at"),r=this.parseDate(s),a=this.safeList(e,"account_operations"),o=this.safeDict(a,0,{}),n=this.safeString(e,"state");return{info:e,id:this.safeString(e,"uuid"),timestamp:r,datetime:this.iso8601(r),currency:this.safeCurrencyCode(i,t),amount:this.safeNumber(e,"amount"),fromAccount:void 0,toAccount:this.safeString(o,"address"),status:this.parseTransferStatus(n)}}parseTransferStatus(e){return this.safeString({executed:"ok"},e,e)}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},o,n){let d=this.safeString(this.urls.api,"rest");if(void 0===d)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let h=d+"/"+this.version+"/"+this.implodeParams(e,r),c=this.omit(r,this.extractParams(e));if("public"===t)Object.keys(c).length>0&&(h+="?"+this.urlencode(c));else{this.checkRequiredCredentials();let e=this.incrementingNonce().toString(),t=e+h,r={"Api-Key":this.apiKey,"Api-Nonce":e},a=Object.keys(c).length>0,o=n;if("POST"===i&&a&&(o=this.json(c)),"POST"===i)a&&(t+=o,r["Content-Type"]="application/json");else if(a){let e=this.urlencode(c);t+=e,h+="?"+e}return r["Api-Signature"]=this.hmac(this.encode(t),this.encode(this.secret),s.sc),{url:h,method:i,body:o,headers:r}}return{url:h,method:i,body:n,headers:o}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0!==n&&void 0!==this.safeValue(n,"errors"))throw new a.ExchangeError(this.id+" "+this.json(n))}}i.d(t,{A:()=>n})},5653(e,t,i){"use strict";var s=i(4721),r=i(2400),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"phemex",name:"Phemex",countries:["CN"],rateLimit:120.5,version:"v1",certified:!1,pro:!0,hostname:"api.phemex.com",has:{CORS:void 0,spot:!0,margin:!1,swap:!0,future:!1,option:!1,addMargin:!1,borrowCrossMargin:!1,borrowIsolatedMargin:!1,borrowMargin:!1,cancelAllOrders:!0,cancelOrder:!0,closePosition:!1,createConvertTrade:!0,createOrder:!0,createReduceOnlyOrder:!0,createStopLimitOrder:!0,createStopMarketOrder:!0,createStopOrder:!0,editOrder:!0,fetchAllGreeks:!1,fetchBalance:!0,fetchBorrowInterest:!1,fetchBorrowRate:!1,fetchBorrowRateHistories:!1,fetchBorrowRateHistory:!1,fetchBorrowRates:!1,fetchBorrowRatesPerSymbol:!1,fetchClosedOrders:!0,fetchConvertQuote:!0,fetchConvertTrade:!1,fetchConvertTradeHistory:!0,fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchFundingHistory:!0,fetchFundingRate:!0,fetchFundingRateHistories:!1,fetchFundingRateHistory:!0,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchLeverage:!1,fetchLeverageTiers:!0,fetchMarketLeverageTiers:"emulated",fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPositionADLRank:!0,fetchPositionHistory:!0,fetchPositions:!0,fetchPositionsADLRank:!0,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTransfers:!0,fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,sandbox:!0,setLeverage:!0,setMargin:!0,setMarginMode:!0,setPositionMode:!0,transfer:!0,withdraw:!0},urls:{logo:"https://user-images.githubusercontent.com/1294454/85225056-221eb600-b3d7-11ea-930d-564d2690e3f6.jpg",test:{v1:"https://testnet-api.phemex.com/v1",v2:"https://testnet-api.phemex.com",public:"https://testnet-api.phemex.com/exchange/public",private:"https://testnet-api.phemex.com"},api:{v1:"https://{hostname}/v1",v2:"https://{hostname}",public:"https://{hostname}/exchange/public",private:"https://{hostname}"},www:"https://phemex.com",doc:"https://phemex-docs.github.io/#overview",fees:"https://phemex.com/fees-conditions",referral:{url:"https://phemex.com/register?referralCode=EDNVJ",discount:.1}},timeframes:{"1m":"60","3m":"180","5m":"300","15m":"900","30m":"1800","1h":"3600","2h":"7200","3h":"10800","4h":"14400","6h":"21600","12h":"43200","1d":"86400","1w":"604800","1M":"2592000","3M":"7776000","1Y":"31104000"},api:{public:{get:{"cfg/v2/products":{cost:5},"cfg/fundingRates":{cost:5},products:{cost:5},"nomics/trades":{cost:5},"md/kline":{cost:5},"md/v2/kline/list":{cost:5},"md/v2/kline":{cost:5},"md/v2/kline/last":{cost:5},"md/orderbook":{cost:5},"md/trade":{cost:5},"md/spot/ticker/24hr":{cost:5},"exchange/public/cfg/chain-settings":{cost:5}}},v1:{get:{"md/fullbook":{cost:5},"md/orderbook":{cost:5},"md/trade":{cost:5},"md/ticker/24hr":{cost:5},"md/ticker/24hr/all":{cost:5},"md/spot/ticker/24hr":{cost:5},"md/spot/ticker/24hr/all":{cost:5},"exchange/public/products":{cost:5},"api-data/public/data/funding-rate-history":{cost:5}}},v2:{get:{"public/products":{cost:5},"public/products-plus":{cost:5},"public/index-sources":{cost:5},"md/v2/orderbook":{cost:5},"md/v2/trade":{cost:5},"md/v2/ticker/24hr":{cost:5},"md/v2/ticker/24hr/all":{cost:5},"api-data/public/data/funding-rate-history":{cost:5}}},private:{get:{"spot/orders/active":{cost:1},"spot/orders":{cost:1},"spot/wallets":{cost:5},"exchange/spot/order":{cost:5},"exchange/spot/order/trades":{cost:5},"exchange/order/v2/orderList":{cost:5},"exchange/order/v2/tradingList":{cost:5},"accounts/accountPositions":{cost:1},"g-accounts/accountPositions":{cost:1},"g-accounts/positions":{cost:25},"g-accounts/risk-unit":{cost:1},"api-data/futures/funding-fees":{cost:5},"api-data/g-futures/funding-fees":{cost:5},"api-data/futures/orders":{cost:5},"api-data/g-futures/orders":{cost:5},"api-data/futures/orders/by-order-id":{cost:5},"api-data/g-futures/orders/by-order-id":{cost:5},"api-data/futures/trades":{cost:5},"api-data/g-futures/trades":{cost:5},"api-data/futures/trading-fees":{cost:5},"api-data/g-futures/trading-fees":{cost:5},"api-data/futures/v2/tradeAccountDetail":{cost:5},"api-data/g-futures/closedPosition":{cost:5},"g-orders/activeList":{cost:1},"orders/activeList":{cost:1},"exchange/order/list":{cost:5},"exchange/order":{cost:5},"exchange/order/trade":{cost:5},"phemex-user/users/children":{cost:5},"phemex-user/wallets/v2/depositAddress":{cost:5},"phemex-user/wallets/tradeAccountDetail":{cost:5},"phemex-deposit/wallets/api/depositAddress":{cost:5},"phemex-deposit/wallets/api/depositHist":{cost:5},"phemex-deposit/wallets/api/chainCfg":{cost:5},"phemex-withdraw/wallets/api/withdrawHist":{cost:5},"phemex-withdraw/wallets/api/asset/info":{cost:5},"phemex-user/order/closedPositionList":{cost:5},"exchange/margins/transfer":{cost:5},"exchange/wallets/confirm/withdraw":{cost:5},"exchange/wallets/withdrawList":{cost:5},"exchange/wallets/depositList":{cost:5},"exchange/wallets/v2/depositAddress":{cost:5},"api-data/spots/funds":{cost:5},"api-data/spots/orders":{cost:5},"api-data/spots/orders/by-order-id":{cost:5},"api-data/spots/pnls":{cost:5},"api-data/spots/trades":{cost:5},"api-data/spots/trades/by-order-id":{cost:5},"assets/convert":{cost:5},"assets/transfer":{cost:5},"assets/spots/sub-accounts/transfer":{cost:5},"assets/futures/sub-accounts/transfer":{cost:5},"assets/quote":{cost:5},"phemex-lb/public/api/trader/performance-info":{cost:5},"uta-api/risk/risk-mode":{cost:5},"uta-api/risk/risk-units":{cost:5},"uta-biz/assets":{cost:5},"uta-funds/contract/borrow":{cost:5},"uta-funds/contract/payback":{cost:5},"uta-funds/contract/borrow/interests":{cost:5},"uta-exchanger/assets/convert":{cost:5}},post:{"spot/orders":{cost:1},orders:{cost:1},"g-orders":{cost:1},"positions/assign":{cost:5},"exchange/wallets/transferOut":{cost:5},"exchange/wallets/transferIn":{cost:5},"exchange/margins":{cost:5},"exchange/wallets/createWithdraw":{cost:5},"exchange/wallets/cancelWithdraw":{cost:5},"exchange/wallets/createWithdrawAddress":{cost:5},"assets/transfer":{cost:5},"assets/spots/sub-accounts/transfer":{cost:5},"assets/futures/sub-accounts/transfer":{cost:5},"assets/universal-transfer":{cost:5},"assets/convert":{cost:5},"phemex-withdraw/wallets/api/createWithdraw":{cost:5},"phemex-withdraw/wallets/api/cancelWithdraw":{cost:5},"uta-account/switch-mode":{cost:5},"uta-funds/contract/payback":{cost:5}},put:{"spot/orders/create":{cost:1},"spot/orders":{cost:1},"orders/replace":{cost:1},"g-orders/replace":{cost:1},"g-orders/create":{cost:1},"positions/leverage":{cost:5},"g-positions/leverage":{cost:5},"g-positions/switch-pos-mode-sync":{cost:5},"positions/riskLimit":{cost:5}},delete:{"spot/orders":{cost:2},"spot/orders/all":{cost:2},"orders/cancel":{cost:1},orders:{cost:1},"orders/all":{cost:3},"g-orders/cancel":{cost:1},"g-orders":{cost:1},"g-orders/all":{cost:3}}}},precisionMode:4,fees:{trading:{tierBased:!1,percentage:!0,taker:this.parseNumber("0.001"),maker:this.parseNumber("0.001")}},features:{default:{sandbox:!0,createOrder:{marginMode:!1,triggerPrice:!0,triggerPriceType:{mark:!0,last:!0,index:!0},triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,selfTradePrevention:!1,trailing:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:200,daysBack:1e5,untilDays:2,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!0},fetchOpenOrders:{marginMode:!1,limit:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchOrders:{marginMode:!1,limit:void 0,daysBack:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!0},fetchClosedOrders:{marginMode:!1,limit:200,daysBack:1e5,daysBackCanceled:1e5,untilDays:2,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:1e3}},spot:{extends:"default"},forDerivatives:{extends:"default",createOrder:{triggerDirection:!0,attachedStopLossTakeProfit:{triggerPriceType:{mark:!0,last:!0,index:!0},price:!0},hedged:!0},fetchOHLCV:{limit:2e3}},swap:{linear:{extends:"forDerivatives"},inverse:{extends:"forDerivatives"}},future:{linear:void 0,inverse:void 0}},requiredCredentials:{apiKey:!0,secret:!0},exceptions:{exact:{401:a.AuthenticationError,412:a.BadRequest,6001:a.BadRequest,19999:a.BadRequest,10001:a.DuplicateOrderId,10002:a.OrderNotFound,10003:a.CancelPending,10004:a.CancelPending,10005:a.CancelPending,11001:a.InsufficientFunds,11002:a.InvalidOrder,11003:a.InsufficientFunds,11004:a.InvalidOrder,11005:a.InsufficientFunds,11006:a.ExchangeError,11007:a.ExchangeError,11008:a.ExchangeError,11009:a.ExchangeError,11010:a.InsufficientFunds,11011:a.InvalidOrder,11012:a.InvalidOrder,11013:a.InvalidOrder,11014:a.InvalidOrder,11015:a.InvalidOrder,11016:a.BadRequest,11017:a.ExchangeError,11018:a.ExchangeError,11019:a.ExchangeError,11020:a.ExchangeError,11021:a.ExchangeError,11022:a.AccountSuspended,11023:a.ExchangeError,11024:a.ExchangeError,11025:a.BadRequest,11026:a.ExchangeError,11027:a.BadSymbol,11028:a.BadSymbol,11029:a.ExchangeError,11030:a.ExchangeError,11031:a.InvalidOrder,11032:a.InvalidOrder,11033:a.DuplicateOrderId,11034:a.InvalidOrder,11035:a.InvalidOrder,11036:a.InvalidOrder,11037:a.InvalidOrder,11038:a.InvalidOrder,11039:a.InvalidOrder,11040:a.InvalidOrder,11041:a.InvalidOrder,11042:a.InvalidOrder,11043:a.InvalidOrder,11044:a.InvalidOrder,11045:a.InvalidOrder,11046:a.InvalidOrder,11047:a.InvalidOrder,11048:a.InvalidOrder,11049:a.InvalidOrder,11050:a.InvalidOrder,11051:a.InvalidOrder,11052:a.InvalidOrder,11053:a.InvalidOrder,11054:a.InvalidOrder,11055:a.InvalidOrder,11056:a.InvalidOrder,11057:a.InvalidOrder,11058:a.InvalidOrder,11059:a.InvalidOrder,11060:a.InvalidOrder,11061:a.CancelPending,11062:a.InvalidOrder,11063:a.InvalidOrder,11064:a.InvalidOrder,11065:a.InvalidOrder,11066:a.InvalidOrder,11067:a.InvalidOrder,11068:a.InvalidOrder,11069:a.ExchangeError,11070:a.BadSymbol,11071:a.InvalidOrder,11072:a.InvalidOrder,11073:a.InvalidOrder,11074:a.InvalidOrder,11075:a.InvalidOrder,11076:a.InvalidOrder,11077:a.InvalidOrder,11078:a.InvalidOrder,11079:a.InvalidOrder,11080:a.InvalidOrder,11081:a.InvalidOrder,11082:a.InsufficientFunds,11083:a.InvalidOrder,11084:a.InvalidOrder,11085:a.DuplicateOrderId,11086:a.InvalidOrder,11087:a.InvalidOrder,11088:a.InvalidOrder,11089:a.InvalidOrder,11090:a.InvalidOrder,11091:a.InvalidOrder,11092:a.InvalidOrder,11093:a.InvalidOrder,11094:a.InvalidOrder,11095:a.InvalidOrder,11096:a.InvalidOrder,11097:a.BadRequest,11098:a.BadRequest,11099:a.ExchangeError,11100:a.InsufficientFunds,11101:a.InsufficientFunds,11102:a.BadRequest,11103:a.BadRequest,11104:a.BadRequest,11105:a.InsufficientFunds,11106:a.InsufficientFunds,11107:a.ExchangeError,11108:a.InvalidOrder,11109:a.InvalidOrder,11110:a.InvalidOrder,11111:a.InvalidOrder,11112:a.InvalidOrder,11113:a.BadRequest,11114:a.InvalidOrder,11115:a.InvalidOrder,11116:a.InvalidOrder,11117:a.InvalidOrder,11118:a.InvalidOrder,11119:a.InvalidOrder,11120:a.InvalidOrder,11121:a.InvalidOrder,11122:a.InvalidOrder,11123:a.InvalidOrder,11124:a.InvalidOrder,11125:a.InvalidOrder,11126:a.InvalidOrder,11128:a.InvalidOrder,11129:a.InvalidOrder,11130:a.InvalidOrder,11131:a.InvalidOrder,11132:a.InvalidOrder,11133:a.InvalidOrder,11134:a.InvalidOrder,3e4:a.BadRequest,30018:a.BadRequest,34003:a.PermissionDenied,35104:a.InsufficientFunds,39995:a.RateLimitExceeded,39996:a.PermissionDenied,39997:a.BadSymbol},broad:{"401 Insufficient privilege":a.PermissionDenied,"401 Request IP mismatch":a.PermissionDenied,"Failed to find api-key":a.AuthenticationError,"Missing required parameter":a.BadRequest,"API Signature verification failed":a.AuthenticationError,"Api key not found":a.AuthenticationError}},options:{brokerId:"CCXT123456","x-phemex-request-expiry":60,createOrderByQuoteRequiresPrice:!0,networks:{TRC20:"TRX",ERC20:"ETH",BEP20:"BNB"},defaultNetworks:{USDT:"ETH",MKR:"ETH"},defaultSubType:"linear",accountsByType:{spot:"spot",swap:"future"},stableCoins:["BUSD","FEI","TUSD","USD","USDC","USDD","USDP","USDT"],transfer:{fillResponseFromRequest:!0},triggerPriceTypesMap:{last:"ByLastPrice",mark:"ByMarkPrice",index:"ByIndexPrice",ask:"ByAskPrice",bid:"ByBidPrice"}}})}parseSafeNumber(e){if(void 0===e)return e;let t=e.split(",");return t=t.join("").split(" "),this.safeNumber(t,0)}parseSwapMarket(e){let t,i=this.safeString(e,"symbol"),s=this.safeString(e,"contractUnderlyingAssets"),r=this.safeString(e,"baseCurrency",s),a=this.safeString(e,"quoteCurrency"),o=this.safeString(e,"settleCurrency"),n=this.safeCurrencyCode(r),d=this.safeCurrencyCode(a);if(void 0===n||void 0===d)return;n=n.replace(" ","");let h=this.safeCurrencyCode(o),c=!1;o!==a&&(c=!0,"baseCurrency"in e||n!==d||(n=h));let l=this.safeInteger(e,"priceScale"),u=this.safeInteger(e,"ratioScale"),f=this.safeInteger(e,"valueScale"),p=this.safeString(e,"minPriceEp"),m=this.safeString(e,"maxPriceEp"),g=this.safeString(e,"makerFeeRateEr"),v=this.safeString(e,"takerFeeRateEr"),y=this.safeString(e,"status"),b=this.safeString(e,"contractSize"," ");if("USDT"===h)t=this.parseNumber("1");else if(-1!==b.indexOf(" ")){let e=b.split(" ");t=this.parseNumber(e[0])}else t=this.parseNumber(b);let w=!c;return this.safeMarketStructure({id:i,symbol:n+"/"+d+":"+h,base:n,quote:d,settle:h,baseId:r,quoteId:a,settleId:o,type:"swap",spot:!1,margin:!1,swap:!0,future:!1,option:!1,active:"Listed"===y,contract:!0,linear:w,inverse:c,taker:this.parseNumber(this.fromEn(v,u)),maker:this.parseNumber(this.fromEn(g,u)),contractSize:t,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,priceScale:l,valueScale:f,ratioScale:u,precision:{amount:this.safeNumber2(e,"lotSize","qtyStepSize"),price:this.safeNumber(e,"tickSize")},limits:{leverage:{min:this.parseNumber("1"),max:this.safeNumber(e,"maxLeverage")},amount:{min:void 0,max:void 0},price:{min:this.parseNumber(this.fromEn(p,l)),max:this.parseNumber(this.fromEn(m,l))},cost:{min:void 0,max:this.parseNumber(this.safeString(e,"maxOrderQty"))}},created:void 0,info:e})}parseSpotMarket(e){let t=this.safeStringLower(e,"type"),i=this.safeString(e,"symbol"),s=this.safeString(e,"quoteCurrency"),r=this.safeString(e,"baseCurrency"),a=this.safeCurrencyCode(r),o=this.safeCurrencyCode(s);if(void 0===a||void 0===o)return;let n=this.safeString(e,"status"),d=this.parseSafeNumber(this.safeString(e,"baseTickSize")),h=this.parseSafeNumber(this.safeString(e,"quoteTickSize"));return this.safeMarketStructure({id:i,symbol:a+"/"+o,base:a,quote:o,settle:void 0,baseId:r,quoteId:s,settleId:void 0,type:t,spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:"Listed"===n,contract:!1,linear:void 0,inverse:void 0,taker:this.safeNumber(e,"defaultTakerFee"),maker:this.safeNumber(e,"defaultMakerFee"),contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,priceScale:this.safeInteger(e,"priceScale"),valueScale:this.safeInteger(e,"valueScale"),ratioScale:this.safeInteger(e,"ratioScale"),precision:{amount:d,price:h},limits:{leverage:{min:void 0,max:void 0},amount:{min:d,max:this.parseSafeNumber(this.safeString(e,"maxBaseOrderSize"))},price:{min:h,max:void 0},cost:{min:this.parseSafeNumber(this.safeString(e,"minOrderValue")),max:this.parseSafeNumber(this.safeString(e,"maxOrderValue"))}},created:this.safeInteger(e,"listTime"),info:e})}async fetchMarkets(e={}){let t=this.v2GetPublicProducts(e),i=this.v1GetExchangePublicProducts(e),[s,r]=await Promise.all([t,i]),a=this.safeList(r,"data",[]),o=this.safeDict(s,"data",{}),n=this.safeList(o,"products",[]),d=this.safeList(o,"perpProductsV2",[]);n=this.arrayConcat(n,d);let h=this.safeList(o,"riskLimits",[]),c=this.safeList(o,"riskLimitsV2",[]);h=this.arrayConcat(h,c);let l=this.safeList(o,"currencies",[]),u=this.indexBy(h,"symbol"),f=this.indexBy(a,"symbol"),p=this.indexBy(l,"currency"),m=[];for(let e=0;e<n.length;e++){let t=n[e],i=this.safeStringLower(t,"type");if("perpetual"===i||"perpetualv2"===i||"perpetualpilot"===i){let e=this.safeString(t,"symbol"),i=this.safeDict(u,e,{});t=this.extend(t,i);let s=this.safeDict(f,e,{});t=this.extend(t,s),t=this.parseSwapMarket(t)}else{let e=this.safeString(t,"baseCurrency"),i=this.safeDict(p,e,{}),s=this.safeString(i,"valueScale","8");t=this.extend(t,{valueScale:s}),t=this.parseSpotMarket(t)}void 0!==t&&m.push(t)}return m}async fetchCurrencies(e={}){let t=await this.v2GetPublicProducts(e),i=this.safeDict(t,"data",{}),s=this.safeList(i,"currencies",[]);return this.parseCurrencies(s)}parseCurrency(e){let t,i,s,r=this.safeString(e,"currency"),a=this.safeCurrencyCode(r),n=this.safeString(e,"valueScale"),d=parseInt(n),h=this.safeString(e,"minValueEv"),c=this.safeString(e,"maxValueEv");if(void 0!==n){let e=this.parsePrecision(n);s=this.parseNumber(e),t=this.parseNumber(o.Y.stringMul(h,e)),i=this.parseNumber(o.Y.stringMul(c,e))}return this.safeCurrencyStructure({id:r,info:e,code:a,name:this.safeString(e,"name"),active:"Listed"===this.safeString(e,"status"),deposit:void 0,withdraw:void 0,fee:void 0,precision:s,limits:{amount:{min:t,max:i},withdraw:{min:void 0,max:void 0}},valueScale:d,networks:void 0,type:"crypto"})}customParseBidAsk(e,t=0,i=1,s){if(void 0===s)throw new a.ArgumentsRequired(this.id+" customParseBidAsk() requires a market argument");let r=this.safeString(e,i);return!0===s.spot&&(r=this.fromEv(r,s)),[this.parseNumber(this.fromEp(this.safeString(e,t),s)),this.parseNumber(r)]}customParseOrderBook(e,t,i,s="bids",r="asks",a=0,o=1,n){let d={symbol:t,timestamp:i,datetime:this.iso8601(i),nonce:void 0},h=[s,r];for(let t=0;t<h.length;t++){let i=h[t],s=[],r=this.safeValue(e,i);for(let e=0;e<r.length;e++)s.push(this.customParseBidAsk(r[e],a,o,n));d[i]=s}return d[s]=this.sortBy(d[s],0,!0),d[r]=this.sortBy(d[r],0),d}async fetchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={symbol:r.id},o="USDT"===r.settle||"USDC"===r.settle;s=!0===r.linear&&o?await this.v2GetMdV2Orderbook(this.extend(a,i)):void 0!==t&&t<=30?await this.v1GetMdOrderbook(this.extend(a,i)):await this.v1GetMdFullbook(this.extend(a,i));let n=this.safeDict(s,"result",{}),d=this.safeDict2(n,"book","orderbook_p",{}),h=this.safeIntegerProduct(n,"timestamp",1e-6),c=this.customParseOrderBook(d,e,h,"bids","asks",0,1,r),l=this.safeInteger(n,"sequence");return this.extend(c,{nonce:l})}toEn(e,t){if(void 0===e||void 0===t)return;let i=this.numberToString(e),s=new o.Y(i);s.decimals=s.decimals-t,s.reduce();let r=s.toString();return this.parseToNumeric(r)}toEv(e,t){return void 0===e||void 0===t?e:this.toEn(e,this.safeInteger(t,"valueScale"))}toEp(e,t){return void 0===e||void 0===t?e:this.toEn(e,this.safeInteger(t,"priceScale"))}fromEn(e,t){if(void 0===e||void 0===t)return;let i=new o.Y(e);return i.decimals=this.sum(i.decimals,t),i.reduce(),i.toString()}fromEp(e,t){return void 0===e||void 0===t?e:this.fromEn(e,this.safeInteger(t,"priceScale"))}fromEv(e,t){return void 0===e||void 0===t?e:this.fromEn(e,this.safeInteger(t,"valueScale"))}fromEr(e,t){return void 0===e||void 0===t?e:this.fromEn(e,this.safeInteger(t,"ratioScale"))}parseOHLCV(e,t){let i;return i=void 0!==t&&!0===t.spot?this.parseNumber(this.fromEv(this.safeString(e,7),t)):this.safeNumber(e,7),[this.safeTimestamp(e,0),this.parseNumber(this.fromEp(this.safeString(e,3),t)),this.parseNumber(this.fromEp(this.safeString(e,4),t)),this.parseNumber(this.fromEp(this.safeString(e,5),t)),this.parseNumber(this.fromEp(this.safeString(e,6),t)),i]}async fetchOHLCV(e,t="1m",i,s,r={}){let a,o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d={symbol:n.id,resolution:this.safeString(this.timeframes,t,t)},h=this.safeInteger2(r,"until","to"),c=this.omit(r,["until"]),l="USDT"===n.settle||"USDC"===n.settle,u=(!0===n.linear||l)&&(void 0!==i||void 0!==h),f=1e3;if(u&&(f=2e3),d.limit=Math.min(void 0===s?f:s,f),!0===n.linear||l)if(void 0!==h||void 0!==i){let e=this.parseTimeframe(t);if(d.from=o=void 0!==i?Math.round(i/1e3):Math.round(h/1e3)-f*e,void 0!==h)d.to=Math.round(h/1e3);else{let t=o+f*e,i=this.seconds();t>i&&(t=i),d.to=t}a=await this.publicGetMdV2KlineList(this.extend(d,c))}else a=await this.publicGetMdV2KlineLast(this.extend(d,c));else a=await this.publicGetMdV2Kline(this.extend(d,c));let p=this.safeDict(a,"data",{}),m=this.safeList(p,"rows",[]),g=i;return u&&(g=o),this.parseOHLCVs(m,n,t,g,s)}parseTicker(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=s.symbol,a=this.safeIntegerProduct(e,"timestamp",1e-6),o=this.fromEp(this.safeString2(e,"lastEp","closeRp"),s),n=this.fromEr(this.safeString2(e,"turnoverEv","turnoverRv"),s),d=this.safeString(e,"volume");void 0===d&&(d=this.fromEv(this.safeString2(e,"volumeEv","volumeRq"),s));let h=this.fromEp(this.safeString(e,"openEp"),s);return this.safeTicker({symbol:r,timestamp:a,datetime:this.iso8601(a),high:this.fromEp(this.safeString2(e,"highEp","highRp"),s),low:this.fromEp(this.safeString2(e,"lowEp","lowRp"),s),bid:this.fromEp(this.safeString(e,"bidEp"),s),bidVolume:void 0,ask:this.fromEp(this.safeString(e,"askEp"),s),askVolume:void 0,vwap:void 0,open:h,close:o,last:o,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:d,quoteVolume:n,info:e},s)}async fetchTicker(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};i=!0===s.swap?!0===s.inverse||"USD"===s.settle?await this.v1GetMdTicker24hr(this.extend(r,t)):await this.v2GetMdV2Ticker24hr(this.extend(r,t)):await this.v1GetMdSpotTicker24hr(this.extend(r,t));let a=this.safeDict(i,"result",{});return this.parseTicker(a,s)}async fetchTickers(e,t={}){let i,s;if(void 0===this.markets&&await this.loadMarkets(),void 0!==e){let t=this.safeString(e,0);s=this.market(t)}let[r,a]=this.handleMarketTypeAndParams("fetchTickers",s,t),[o,n]=this.handleSubTypeAndParams("fetchTickers",s,a),d=this.omit(n,"type");i="spot"===r?await this.v1GetMdSpotTicker24hrAll(d):"inverse"===o||"USD"===this.safeString(s,"settle")?await this.v1GetMdTicker24hrAll(d):await this.v2GetMdV2Ticker24hrAll(d);let h=this.safeList(i,"result",[]);return this.parseTickers(h,e)}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={symbol:a.id},n="USDT"===a.settle||"USDC"===a.settle;r=!0===a.linear&&n?await this.v2GetMdV2Trade(this.extend(o,s)):await this.v1GetMdTrade(this.extend(o,s));let d=this.safeDict(r,"result",{}),h=this.safeList2(d,"trades","trades_p",[]);return this.parseTrades(h,a,t,i)}parseTrade(e,t){let i,s,r,a,o,n,d,h,c,l,u,f,p,m=this.safeString(e,"symbol"),g=this.safeMarket(m,t),v=g.symbol;if(Array.isArray(e)){let t=e.length;r=this.safeIntegerProduct(e,0,1e-6),t>4&&(a=this.safeString(e,t-4)),o=this.safeStringLower(e,t-3),i=this.safeString(e,t-2),s=this.safeString(e,t-1),"number"==typeof e[t-2]&&(i=this.fromEp(i,g),s=this.fromEv(s,g))}else{if(void 0===(r=this.safeIntegerProduct(e,"transactTimeNs",1e-6))&&(r=this.safeInteger(e,"createdAt")),a=this.safeString2(e,"execId","execID"),f=this.safeString(e,"orderID"),"USDT"===g.settle||"USDC"===g.settle){let t=this.safeStringLower(e,"side");"buy"===t||"sell"===t?o=t:void 0!==t&&(o="1"===t?"buy":"sell");let r=this.safeString(e,"ordType");if("1"===r?d="market":"2"===r&&(d="limit"),i=this.safeString(e,"execPriceRp"),s=this.safeString(e,"execQtyRq"),n=this.safeString(e,"execValueRv"),c=this.omitZero(this.safeString(e,"execFeeRv")),l=this.safeString(e,"feeRateRr"),void 0!==c){let t=this.safeString(e,"currency");u=this.safeCurrencyCode(t)}else{let t=this.omitZero(this.safeString(e,"ptFeeRv"));void 0!==t&&(c=t,u="PT")}}else if(o=this.safeStringLower(e,"side"),d=this.parseOrderType(this.safeString(e,"ordType")),"MakerFill"===this.safeString(e,"execStatus")&&(p="maker"),i=this.fromEp(this.safeString(e,"execPriceEp"),g),s=this.fromEv(this.safeString(e,"execBaseQtyEv"),g),s=this.safeString(e,"execQty",s),n=this.fromEr(this.safeString2(e,"execQuoteQtyEv","execValueEv"),g),void 0!==(c=this.fromEr(this.omitZero(this.safeString(e,"execFeeEv")),g)))if(l=this.fromEr(this.safeString(e,"feeRateEr"),g),!0===g.spot)u=this.safeCurrencyCode(this.safeString(e,"feeCurrency"));else{let e=this.safeDict(g,"info");if(void 0!==e){let t=this.safeString(e,"settlementCurrency");u=this.safeCurrencyCode(t)}}else void 0!==(c=this.safeString(e,"ptFeeRv"))&&(u="PT");h={cost:c,rate:l,currency:u}}return this.safeTrade({info:e,id:a,symbol:v,timestamp:r,datetime:this.iso8601(r),order:f,type:d,side:o,takerOrMaker:p,price:i,amount:s,cost:n,fee:h},g)}parseSpotBalance(e){let t,i={info:e},s=this.safeList(e,"data",[]);for(let e=0;e<s.length;e++){let r=this.safeDict(s,e),a=this.safeString(r,"currency"),n=this.safeCurrencyCode(a),d=this.safeDict(this.currencies,n,{}),h=this.safeInteger(d,"valueScale",8),c=this.account(),l=this.safeString(r,"balanceEv"),u=this.safeString(r,"lockedTradingBalanceEv"),f=this.safeString(r,"lockedWithdrawEv"),p=this.fromEn(l,h),m=this.fromEn(u,h),g=this.fromEn(f,h),v=o.Y.stringAdd(m,g),y=this.safeIntegerProduct(r,"lastUpdateTimeNs",1e-6);t=void 0===t?y:Math.max(t,y),c.total=p,c.used=v,i[n]=c}return i.timestamp=t,i.datetime=this.iso8601(t),this.safeBalance(i)}parseSwapBalance(e){let t={info:e},i=this.safeDict(e,"data",{}),s=this.safeDict(i,"account",{}),r=this.safeString(s,"currency"),a=this.safeCurrencyCode(r),o=this.currency(a),n=this.safeInteger(o,"valueScale",8),d=this.account(),h=this.safeString2(s,"accountBalanceEv","accountBalanceRv"),c=this.safeString2(s,"totalUsedBalanceEv","totalUsedBalanceRv"),l="USDT"!==a;return d.total=l?this.fromEn(h,n):h,d.used=l?this.fromEn(c,n):c,t[a]=d,this.safeBalance(t)}async fetchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleMarketTypeAndParams("fetchBalance",void 0,e),r=this.safeString(s,"code"),o=this.omit(s,["code"]),n={};if("spot"!==i&&"swap"!==i)throw new a.BadRequest(this.id+" does not support "+i+" markets, only spot and swap");if("swap"===i){let[e,s]=this.handleOptionStringAndParams(o,"fetchBalance","settle","USDT");if(void 0!==r||void 0!==e){let i=this.currency(void 0!==r?r:e);n.currency=i.id,t="USDT"===i.id?await this.privateGetGAccountsAccountPositions(this.extend(n,s)):await this.privateGetAccountsAccountPositions(this.extend(n,s))}else{if(void 0===this.safeString(s,"currency"))throw new a.ArgumentsRequired(this.id+" fetchBalance() requires a code parameter or a currency or settle parameter for "+i+" type");t=await this.privateGetSpotWallets(this.extend(n,s))}}else t=await this.privateGetSpotWallets(this.extend(n,o));return"swap"===i?this.parseSwapBalance(t):this.parseSpotBalance(t)}parseOrderStatus(e){return this.safeString({Created:"open",Untriggered:"open",Deactivated:"closed",Triggered:"open",Rejected:"rejected",New:"open",PartiallyFilled:"open",Filled:"closed",Canceled:"canceled",Suspended:"canceled",1:"open",2:"canceled",3:"closed",4:"canceled",5:"open",6:"open",7:"closed",8:"canceled"},e,e)}parseOrderType(e){return this.safeString({1:"market",2:"limit",3:"stop",4:"stopLimit",5:"market",6:"limit",7:"market",8:"market",9:"stopLimit",10:"market",Limit:"limit",Market:"market"},e,e)}parseTimeInForce(e){return this.safeString({GoodTillCancel:"GTC",PostOnly:"PO",ImmediateOrCancel:"IOC",FillOrKill:"FOK"},e,e)}parseSpotOrder(e,t){let i,s=this.safeString(e,"orderID"),r=this.safeString(e,"clOrdID");void 0!==r&&r.length<1&&(r=void 0);let a=this.safeString(e,"symbol"),o=this.safeMarket(a,t),n=o.symbol,d=this.fromEp(this.safeString(e,"priceEp"),o),h=this.fromEv(this.safeString(e,"baseQtyEv"),o),c=this.omitZero(this.fromEv(this.safeString(e,"leavesBaseQtyEv"),o)),l=this.fromEv(this.safeString2(e,"cumBaseQtyEv","cumBaseValueEv"),o),u=this.fromEr(this.safeString2(e,"cumQuoteValueEv","quoteQtyEv"),o),f=this.fromEp(this.safeString(e,"avgPriceEp"),o),p=this.parseOrderStatus(this.safeString(e,"ordStatus")),m=this.safeStringLower(e,"side"),g=this.parseOrderType(this.safeString(e,"ordType")),v=this.safeIntegerProduct2(e,"actionTimeNs","createTimeNs",1e-6),y=this.fromEv(this.safeString(e,"cumFeeEv"),o);void 0!==y&&(i={cost:y,currency:this.safeCurrencyCode(this.safeString(e,"feeCurrency"))});let b=this.parseTimeInForce(this.safeString(e,"timeInForce")),w=this.parseNumber(this.omitZero(this.fromEp(this.safeString(e,"stopPxEp"),o)));return this.safeOrder({info:e,id:s,clientOrderId:r,timestamp:v,datetime:this.iso8601(v),lastTradeTimestamp:void 0,symbol:n,type:g,timeInForce:b,postOnly:"PO"===b,side:m,price:d,triggerPrice:w,amount:h,cost:u,average:f,filled:l,remaining:c,status:p,fee:i,trades:void 0},o)}parseOrderSide(e){return this.safeString({1:"buy",2:"sell"},e,e)}parseSwapOrder(e,t){let i,s=this.safeString2(e,"orderID","orderId"),r=this.safeString2(e,"clOrdID","clOrdId");void 0!==r&&r.length<1&&(r=void 0);let a=this.safeString(e,"symbol"),o=this.safeSymbol(a,t),n=this.safeMarket(a,t),d=this.parseOrderStatus(this.safeString(e,"ordStatus")),h=this.parseOrderSide(this.safeStringLower(e,"side")),c=this.parseOrderType(this.safeString(e,"orderType")),l=this.safeString(e,"priceRp");void 0===l&&(l=this.fromEp(this.safeString(e,"priceEp"),n));let u=this.safeNumber2(e,"orderQty","orderQtyRq"),f=this.safeNumber2(e,"cumQty","cumQtyRq"),p=this.safeNumber2(e,"leavesQty","leavesQtyRq");"Untriggered"===this.safeString(e,"ordStatus")&&(p=void 0);let m=this.safeIntegerProduct(e,"actionTimeNs",1e-6);void 0===m&&(m=this.safeInteger(e,"createdAt"));let g=this.safeNumber2(e,"cumValue","cumValueRv"),v=this.safeIntegerProduct(e,"transactTimeNs",1e-6);0===v&&(v=void 0);let y=this.parseTimeInForce(this.safeString(e,"timeInForce")),b=this.omitZero(this.safeString2(e,"stopPx","stopPxRp")),w=this.safeValue(e,"reduceOnly");"ReduceOnly"===this.safeString(e,"execInst")&&(w=!0);let k=this.safeString(e,"takeProfitRp"),S=this.safeString(e,"stopLossRp"),O=this.omitZero(this.safeString(e,"execFeeRv")),T=this.omitZero(this.safeString(e,"ptFeeRv"));return void 0!==O?i={cost:O,currency:n.quote}:void 0!==T&&(i={cost:T,currency:"PT"}),this.safeOrder({info:e,id:s,clientOrderId:r,datetime:this.iso8601(m),timestamp:m,lastTradeTimestamp:v,symbol:o,type:c,timeInForce:y,postOnly:"PO"===y,reduceOnly:w,side:h,price:l,triggerPrice:b,takeProfitPrice:k,stopLossPrice:S,amount:u,filled:f,remaining:p,cost:g,average:void 0,status:d,fee:i,trades:void 0})}parseOrder(e,t){let i=this.safeBool(t,"swap",!1),s="closedPnl"in e||"closedPnlRv"in e||"totalPnlRv"in e;return!0===i||s?this.parseSwapOrder(e,t):this.parseSpotOrder(e,t)}async createOrder(e,t,i,s,r,n={}){let d;void 0===this.markets&&await this.loadMarkets();let h=this.market(e),c=this.capitalize(i),l=this.capitalize(t),u={symbol:h.id,side:c,ordType:l},f=this.safeString2(n,"clOrdID","clientOrderId"),p=this.safeDict(n,"stopLoss"),m=this.safeDict(n,"takeProfit"),g=void 0!==p,v=void 0!==m,y="USDT"===h.settle||"USDC"===h.settle;if(void 0===f){let e=this.safeString(this.options,"brokerId","CCXT123456");void 0!==e&&(u.clOrdID=e+this.uuid16())}else u.clOrdID=f;let b=void 0!==f?this.omit(n,["clOrdID","clientOrderId"]):n,w=this.safeStringN(b,["stopPx","stopPrice","triggerPrice"]);void 0!==w&&(y?u.stopPxRp=this.priceToPrecision(e,w):u.stopPxEp=this.toEp(w,h));let k=this.omit(b,["stopPx","stopPrice","stopLoss","takeProfit","triggerPrice"]);if(!0===h.spot){let t=this.safeString(k,"qtyType","ByBase");if(("Market"===l||"Stop"===l||"MarketIfTouched"===l)&&void 0!==r&&(t="ByQuote"),void 0!==w&&("Limit"===l?u.ordType="StopLimit":"Market"===l&&(u.ordType="Stop"),u.trigger="ByLastPrice"),u.qtyType=t,"ByQuote"===t){let i=this.safeNumber(k,"cost");if(k=this.omit(k,"cost"),this.safeBool(this.options,"createOrderByQuoteRequiresPrice",!1)){if(void 0!==r){let e=this.numberToString(s),t=this.numberToString(r),a=o.Y.stringMul(e,t);i=this.parseNumber(a)}else if(void 0===i)throw new a.ArgumentsRequired(this.id+" createOrder() "+t+" requires a price argument or a cost parameter")}i=void 0===i?s:i;let n=this.costToPrecision(e,i);u.quoteQtyEv=this.toEv(n,h)}else{let t=this.amountToPrecision(e,s);u.baseQtyEv=this.toEv(t,h)}}else if(!0===h.swap){let t=this.safeBool(k,"hedged",!1);k=this.omit(k,"hedged");let r=this.safeStringLower(k,"posSide"),o=void 0===r&&!0===t&&this.safeBool(k,"reduceOnly",!1),n="buy"===i?"sell":"buy",d=i;if(o&&(d=n),void 0===r&&(!0===t?(o&&(k=this.omit(k,"reduceOnly")),r="buy"===d?"Long":"Short"):r="Merged"),u.posSide=r=this.capitalize(r),y?u.orderQtyRq=this.amountToPrecision(e,s):u.orderQty=this.parseToInt(this.amountToPrecision(e,s)),void 0!==w){u.triggerType=this.safeString(k,"triggerType","ByMarkPrice");let[e,t]=this.handleParamString(k,"triggerDirection");if(k=t,void 0===e)throw new a.ArgumentsRequired(this.id+" createOrder() also requires a 'triggerDirection' parameter with either 'ascending' or 'descending' value");"ascending"===e||"up"===e?"sell"===d?u.ordType="Market"===l?"MarketIfTouched":"LimitIfTouched":"buy"===d&&(u.ordType="Market"===l?"Stop":"StopLimit"):("descending"===e||"down"===e)&&("sell"===d?u.ordType="Market"===l?"Stop":"StopLimit":"buy"===d&&(u.ordType="Market"===l?"MarketIfTouched":"LimitIfTouched"))}if(g||v){if(g){let t=this.safeNumber2(p,"triggerPrice","stopPrice");if(void 0===t)throw new a.InvalidOrder(this.id+' createOrder() requires a trigger price in params["stopLoss"]["triggerPrice"] for a stop loss order');y?u.stopLossRp=this.priceToPrecision(e,t):u.stopLossEp=this.toEp(t,h);let i=this.safeString2(p,"triggerPriceType","slTrigger");void 0!==i&&(u.slTrigger=this.safeString(this.options.triggerPriceTypesMap,i,i));let s=this.safeString(p,"price");void 0!==s&&(u.slPxRp=this.priceToPrecision(e,s))}if(v){let t=this.safeNumber2(m,"triggerPrice","stopPrice");if(void 0===t)throw new a.InvalidOrder(this.id+' createOrder() requires a trigger price in params["takeProfit"]["triggerPrice"] for a take profit order');y?u.takeProfitRp=this.priceToPrecision(e,t):u.takeProfitEp=this.toEp(t,h);let i=this.safeString2(m,"triggerPriceType","tpTrigger");void 0!==i&&(u.tpTrigger=this.safeString(this.options.triggerPriceTypesMap,i,i));let s=this.safeString(m,"price");void 0!==s&&(u.tpPxRp=this.priceToPrecision(e,s))}}}if("Limit"===l||"StopLimit"===l||"LimitIfTouched"===l)if(y)u.priceRp=this.priceToPrecision(e,r);else{let e=this.numberToString(r);u.priceEp=this.toEp(e,h)}let S=this.safeString(k,"takeProfitPrice");void 0!==S&&(y?u.takeProfitRp=this.priceToPrecision(e,S):u.takeProfitEp=this.toEp(S,h),k=this.omit(k,"takeProfitPrice"));let O=this.safeString(k,"stopLossPrice");void 0!==O&&(y?u.stopLossRp=this.priceToPrecision(e,O):u.stopLossEp=this.toEp(O,h),k=this.omit(k,"stopLossPrice")),d=y?await this.privatePostGOrders(this.extend(u,k)):!0===h.contract?await this.privatePostOrders(this.extend(u,k)):await this.privatePostSpotOrders(this.extend(u,k));let T=this.safeDict(d,"data",{});return this.parseOrder(T,h)}async editOrder(e,t,i,s,r,a,o={}){let n;void 0===this.markets&&await this.loadMarkets();let d=this.market(t),h={symbol:d.id},c=this.safeString2(o,"clientOrderId","clOrdID"),l=this.omit(o,["clientOrderId","clOrdID"]),u="USDT"===d.settle||"USDC"===d.settle;void 0!==c?h.clOrdID=c:h.orderID=e,void 0!==a&&(u?h.priceRp=this.priceToPrecision(d.symbol,a):h.priceEp=this.toEp(a,d));let f=this.safeString(l,"baseQtyEv"),p=this.omit(l,["baseQtyEv"]);void 0!==f?h.baseQtyEV=f:void 0!==r&&(u?h.orderQtyRq=this.amountToPrecision(d.symbol,r):h.baseQtyEV=this.toEv(r,d));let m=this.safeStringN(p,["triggerPrice","stopPx","stopPrice"]);void 0!==m&&(u?h.stopPxRp=this.priceToPrecision(t,m):h.stopPxEp=this.toEp(m,d));let g=this.omit(p,["triggerPrice","stopPx","stopPrice"]);u?(void 0===this.safeString(g,"posSide")&&(h.posSide="Merged"),n=await this.privatePutGOrdersReplace(this.extend(h,g))):n=!0===d.swap?await this.privatePutOrdersReplace(this.extend(h,g)):await this.privatePutSpotOrders(this.extend(h,g));let v=this.safeDict(n,"data",{});return this.parseOrder(v,d)}async cancelOrder(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),o={symbol:r.id},n=this.safeString2(i,"clientOrderId","clOrdID"),d=this.omit(i,["clientOrderId","clOrdID"]);void 0!==n?o.clOrdID=n:o.orderID=e,"USDT"===r.settle||"USDC"===r.settle?(void 0===this.safeString(d,"posSide")&&(o.posSide="Merged"),s=await this.privateDeleteGOrdersCancel(this.extend(o,d))):s=!0===r.swap?await this.privateDeleteOrdersCancel(this.extend(o,d)):await this.privateDeleteSpotOrders(this.extend(o,d));let h=this.safeDict(s,"data",{});return this.parseOrder(h,r)}async cancelAllOrders(e,t={}){let i;if(void 0===e)throw new a.ArgumentsRequired(this.id+" cancelAllOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=this.safeBool2(t,"stop","trigger",!1),o=this.omit(t,["stop","trigger"]),n={symbol:s.id};return!0===r&&(n.untriggerred=r),i="USDT"===s.settle||"USDC"===s.settle?await this.privateDeleteGOrdersAll(this.extend(n,o)):!0===s.swap?await this.privateDeleteOrdersAll(this.extend(n,o)):await this.privateDeleteSpotOrdersAll(this.extend(n,o)),[this.safeOrder({info:i})]}async fetchOrder(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.market(t),o={symbol:r.id},n=this.safeString2(i,"clientOrderId","clOrdID"),d=this.omit(i,["clientOrderId","clOrdID"]);void 0!==n?o.clOrdID=n:o.orderID=e,s="USDT"===r.settle||"USDC"===r.settle?await this.privateGetApiDataGFuturesOrdersByOrderId(this.extend(o,d)):!0===r.spot?await this.privateGetApiDataSpotsOrdersByOrderId(this.extend(o,d)):await this.privateGetExchangeOrder(this.extend(o,d));let h=this.safeValue(s,"data",{}),c=h;if(Array.isArray(h)){if(h.length<1)if(void 0!==n)throw new a.OrderNotFound(this.id+" fetchOrder() "+t+" order with clientOrderId "+n+" not found");else throw new a.OrderNotFound(this.id+" fetchOrder() "+t+" order with id "+e+" not found");c=this.safeDict(h,0,{})}else if(!0===r.spot){let i=this.safeList(h,"rows",[]);if(i.length<1)if(void 0!==n)throw new a.OrderNotFound(this.id+" fetchOrder() "+t+" order with clientOrderId "+n+" not found");else throw new a.OrderNotFound(this.id+" fetchOrder() "+t+" order with id "+e+" not found");c=this.safeDict(i,0,{})}return this.parseOrder(c,r)}async fetchOrders(e,t,i,s={}){let r;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={symbol:o.id};void 0!==t&&(n.start=t),void 0!==i&&(n.limit=i),"USDT"===o.settle||"USDC"===o.settle?(n.currency=o.settle,r=await this.privateGetExchangeOrderV2OrderList(this.extend(n,s))):r=!0===o.swap?await this.privateGetExchangeOrderList(this.extend(n,s)):await this.privateGetApiDataSpotsOrders(this.extend(n,s));let d=this.safeValue(r,"data",{}),h=this.safeList(d,"rows",d);return this.parseOrders(h,o,t,i)}async fetchOpenOrders(e,t,i,s={}){let r;if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOpenOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={symbol:o.id};try{r="USDT"===o.settle||"USDC"===o.settle?await this.privateGetGOrdersActiveList(this.extend(n,s)):!0===o.swap?await this.privateGetOrdersActiveList(this.extend(n,s)):await this.privateGetSpotOrders(this.extend(n,s))}catch(e){if(e instanceof a.OrderNotFound)return[];throw e}let d=this.safeValue(r,"data",{});if(Array.isArray(d))return this.parseOrders(d,o,t,i);{let e=this.safeList(d,"rows",[]);return this.parseOrders(e,o,t,i)}}async fetchClosedOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(a=this.market(e));let o={};void 0!==a&&(o.symbol=a.id),void 0!==t&&(o.start=t),void 0!==i&&(o.limit=i),void 0===e||"USDT"===this.safeString(a,"settle")?(o.currency=this.safeString(s,"settle","USDT"),r=await this.privateGetExchangeOrderV2OrderList(this.extend(o,s))):r=void 0!==a&&!0===a.swap?await this.privateGetExchangeOrderList(this.extend(o,s)):await this.privateGetExchangeSpotOrder(this.extend(o,s));let n=this.safeValue(r,"data",{});if(Array.isArray(n))return this.parseOrders(n,a,t,i);{let e=this.safeList(n,"rows",[]);return this.parseOrders(e,a,t,i)}}async fetchMyTrades(e,t,i,s={}){let r,a,o;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(o=this.market(e));let[n,d]=this.handleMarketTypeAndParams("fetchMyTrades",o,s),h={},c=void 0===i?void 0:Math.min(200,i);void 0!==c&&(h.limit=c);let l="spot"!==n&&(void 0===e||"USDT"===this.safeString(o,"settle"));return l?(h.currency="USDT",h.offset=0,void 0===c&&(h.limit=200)):void 0!==e&&void 0!==o&&(h.symbol=o.id),void 0!==t&&(h.start=t),l?r=await this.privateGetExchangeOrderV2TradingList(this.extend(h,d)):"swap"===n?(h.tradeType="Trade",r=await this.privateGetExchangeOrderTrade(this.extend(h,d))):r=await this.privateGetExchangeSpotOrderTrades(this.extend(h,d)),l?a=this.safeList(r,"data",[]):(a=this.safeValue(r,"data",{}),a=this.safeList(a,"rows",[])),this.parseTrades(a,o,t,c)}async fetchDepositAddress(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={currency:this.currency(e).id},s=this.safeDict(this.options,"defaultNetworks"),r=this.safeStringUpper(s,e),o=this.safeDict(this.options,"networks",{}),n=this.safeStringUpper2(t,"network","chainName",r),d=this.omit(t,"network");if(void 0===(n=this.safeString(o,n,n)))throw new a.ArgumentsRequired(this.id+" fetchDepositAddress() requires a network parameter");i.chainName=n;let h=await this.privateGetExchangeWalletsV2DepositAddress(this.extend(i,d)),c=this.safeDict(h,"data",{}),l=this.safeString(c,"address"),u=this.safeString(c,"tag");return this.checkAddress(l),{info:h,currency:e,network:void 0,address:l,tag:u}}async fetchDeposits(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.currency(e));let a=await this.privateGetExchangeWalletsDepositList(s),o=this.safeList(a,"data",[]);return this.parseTransactions(o,r,t,i)}async fetchWithdrawals(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.currency(e));let a=await this.privateGetExchangeWalletsWithdrawList(s),o=this.safeList(a,"data",[]);return this.parseTransactions(o,r,t,i)}parseTransactionStatus(e){return this.safeString({Success:"ok",Succeed:"ok",Rejected:"failed","Security check failed":"failed",SecurityCheckFailed:"failed",Expired:"failed","Address Risk":"failed","Security Checking":"pending",SecurityChecking:"pending","Pending Review":"pending","Pending Transfer":"pending",AmlCsApporve:"pending",New:"pending",Confirmed:"pending",Cancelled:"canceled"},e,e)}parseTransaction(e,t){let i,s=this.safeString(e,"id"),r=this.safeString(e,"address"),a,o=this.safeString(e,"txHash"),n=this.safeString(e,"currency"),d=this.safeCurrency(n,t),h=d.code,c=this.safeString(e,"chainName"),l=this.safeIntegerN(e,["createdAt","submitedAt","submittedAt"]),u=this.safeStringLower(e,"type"),f=this.parseNumber(this.fromEn(this.safeString(e,"feeEv"),this.safeInteger(d,"valueScale")));void 0===f&&(f=this.safeNumber(e,"feeRv")),void 0!==f&&(u="withdrawal",i={cost:f,currency:h});let p=this.parseTransactionStatus(this.safeString(e,"status")),m=this.parseNumber(this.fromEn(this.safeString(e,"amountEv"),this.safeInteger(d,"valueScale")));return void 0===m&&(m=this.safeNumber(e,"amountRv")),{info:e,id:s,txid:o,timestamp:l,datetime:this.iso8601(l),network:this.networkIdToCode(c,h),address:r,addressTo:r,addressFrom:void 0,tag:a,tagTo:a,tagFrom:void 0,type:u,amount:m,currency:h,status:p,updated:void 0,comment:void 0,internal:void 0,fee:i}}async fetchPositions(e,t={}){let i,s,r;void 0===this.markets&&await this.loadMarkets();let a=this.marketSymbols(e),o=this.safeString2(t,"currency","code","USDT"),n=this.omit(t,["currency","code"]),d=n,h=this.safeString(a,0);void 0!==h?(r=this.market(h),s=this.safeString(r,"settle"),o=r.settle):[s,d]=this.handleOptionStringAndParams(n,"fetchPositions","settle",o);let[c,l]=this.handleSubTypeAndParams("fetchPositions",r,d),u="USDT"===s;u?o="USDT":"BTC"===s?o="BTC":void 0===o&&(o="linear"===c?"USD":"BTC");let f={currency:this.currency(o).id};if(u){let[e,t]=this.handleOptionStringAndParams(l,"fetchPositions","method","privateGetGAccountsAccountPositions");i="privateGetGAccountsAccountPositions"===e?await this.privateGetGAccountsAccountPositions(this.extend(f,t)):await this.privateGetGAccountsPositions(this.extend(f,t))}else i=await this.privateGetAccountsAccountPositions(this.extend(f,l));let p=this.safeDict(i,"data",{}),m=this.safeList(p,"positions",[]),g=[];for(let e=0;e<m.length;e++){let t=m[e];g.push(this.parsePosition(t))}return this.filterByArrayPositions(g,"symbol",a)}async fetchPositionHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o={symbol:r.id};void 0!==i&&(o.limit=Math.min(200,i));let n=await this.privateGetApiDataGFuturesClosedPosition(this.extend(o,s)),d=this.safeList(n,"data",[]),h=this.parsePositions(d,[a]);return this.filterBySymbolSinceLimit(h,a,t,i)}parsePosition(e,t){let i,s,r=this.safeString(e,"symbol"),a=this.safeMarket(r,t),n=a.symbol,d=this.safeString2(e,"positionMargin","positionMarginRv"),h=this.safeString2(e,"value","valueRv"),c=this.safeString2(e,"maintMarginReq","maintMarginReqRr"),l=o.Y.stringMul(h,c),u=this.safeString2(e,"assignedPosBalance","assignedPosBalanceRv"),f=o.Y.stringDiv(u,h),p=this.safeNumber2(e,"liquidationPrice","liquidationPriceRp"),m=this.safeString2(e,"markPrice","markPriceRp"),g=this.safeStringN(e,["size","sizeRq","closedSizeRq"]),v=this.safeNumber(a,"contractSize"),y=this.numberToString(v),b=this.parseNumber(o.Y.stringAbs(this.safeString2(e,"leverage","leverageRr"))),w=this.safeStringN(e,["avgEntryPrice","avgEntryPriceRp","openPrice"]),k=this.safeString(e,"side");void 0!==k&&(i="Buy"===k||"1"===k?"long":"short"),s=!0===a.linear?"long"===i?o.Y.stringSub(m,w):o.Y.stringSub(w,m):"long"===i?o.Y.stringSub(o.Y.stringDiv("1",w),o.Y.stringDiv("1",m)):o.Y.stringSub(o.Y.stringDiv("1",m),o.Y.stringDiv("1",w));let S=o.Y.stringMul(o.Y.stringMul(s,g),y),O=this.safeString(e,"unRealisedPnlRv",S),T=o.Y.stringDiv(l,d),P=this.safeBool(e,"crossMargin"),I=this.safeInteger(e,"openedTimeNs"),A=this.safeInteger(e,"updatedTimeNs",this.safeIntegerProduct(e,"transactTimeNs",1e-6));return this.safePosition({info:e,id:this.safeString(e,"execSeq"),symbol:n,contracts:this.parseNumber(g),contractSize:v,realizedPnl:this.safeNumber2(e,"curTermRealisedPnlRv","realizedPnlRv"),unrealizedPnl:this.parseNumber(O),leverage:b,liquidationPrice:p,collateral:this.parseNumber(d),notional:this.parseNumber(h),markPrice:this.parseNumber(m),lastPrice:void 0,entryPrice:this.parseNumber(w),exitPrice:this.safeNumber(e,"closePrice"),lastUpdateTimestamp:A,initialMargin:this.parseNumber(u),initialMarginPercentage:this.parseNumber(f),maintenanceMargin:this.parseNumber(l),maintenanceMarginPercentage:this.parseNumber(c),marginRatio:this.parseNumber(T),timestamp:I,datetime:this.iso8601(I),marginMode:!0===P?"cross":"isolated",side:i,hedged:"Hedged"===this.safeString(e,"posMode"),percentage:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}async fetchFundingHistory(e,t,i,s={}){let r;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n={symbol:o.id};if(void 0!==i){if(i>200)throw new a.BadRequest(this.id+" fetchFundingHistory() limit argument cannot exceed 200");n.limit=i}r="USDT"===o.settle||"USDC"===o.settle?await this.privateGetApiDataGFuturesFundingFees(this.extend(n,s)):await this.privateGetApiDataFuturesFundingFees(this.extend(n,s));let d=this.safeDict(r,"data",{}),h=this.safeList(d,"rows",[]),c=[];for(let e=0;e<h.length;e++){let t=h[e],i=this.safeInteger(t,"createTime"),s=this.safeString2(t,"execFeeEv","execFeeRv"),r=this.safeCurrencyCode(this.safeString(t,"currency"));c.push({info:t,symbol:this.safeString(t,"symbol"),code:r,timestamp:i,datetime:this.iso8601(i),id:void 0,amount:this.parseFundingFeeToPrecision(s,o,r)})}return c}parseFundingFeeToPrecision(e,t,i){if(void 0===e||void 0===i||void 0===t||"USDT"===t.settle||"USDC"===t.settle)return e;let s=this.safeCurrency(i),r=this.safeString(s.info,"valueScale"),a=this.parsePrecision(r);return o.Y.stringMul(e,a)}async fetchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new a.BadSymbol(this.id+" fetchFundingRate() supports swap contracts only");let s={symbol:i.id},r={};r=!0!==i.linear?await this.v1GetMdTicker24hr(this.extend(s,t)):await this.v2GetMdV2Ticker24hr(this.extend(s,t));let o=this.safeDict(r,"result",{});return this.parseFundingRate(o,i)}parseFundingRate(e,t){let i=this.safeString(e,"symbol"),s=this.safeSymbol(i,t),r=this.safeIntegerProduct(e,"timestamp",1e-6),a=this.fromEp(this.safeString(e,"markEp"),t),o=this.fromEp(this.safeString(e,"indexEp"),t),n=this.fromEr(this.safeString(e,"fundingRateEr"),t),d=this.fromEr(this.safeString(e,"predFundingRateEr"),t);return{info:e,symbol:s,markPrice:this.safeNumber(e,"markPriceRp",a),indexPrice:this.safeNumber(e,"indexPriceRp",o),interestRate:void 0,estimatedSettlePrice:void 0,timestamp:r,datetime:this.iso8601(r),fundingRate:this.safeNumber(e,"fundingRateRr",n),fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:this.safeNumber(e,"predFundingRateRr",d),nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:void 0}}async setMargin(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id,posBalanceEv:this.toEv(t,s)},a=await this.privatePostPositionsAssign(this.extend(r,i));return this.extend(this.parseMarginModification(a,s),{amount:t})}parseMarginStatus(e){return this.safeString({0:"ok"},e,e)}parseMarginModification(e,t){let i=this.safeMarket(void 0,t),s=this.safeBool(i,"inverse");return{info:e,symbol:this.safeSymbol(void 0,i),type:"set",marginMode:"isolated",amount:void 0,total:void 0,code:i[!0===s?"base":"quote"],status:this.parseMarginStatus(this.safeString(e,"code")),timestamp:void 0,datetime:void 0}}async setMarginMode(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setMarginMode() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let s=this.market(t);if(!0!==s.swap)throw new a.BadSymbol(this.id+" setMarginMode() supports swap contracts only");let r=e.toLowerCase();if("isolated"!==r&&"cross"!==r)throw new a.BadRequest(this.id+" setMarginMode() marginMode argument should be isolated or cross");let n={symbol:s.id};if(this.inArray(s.settle,["USDT","USDC"])){let e=this.safeString(i,"leverage");if(void 0===e)throw new a.ArgumentsRequired(this.id+' setMarginMode() requires a "leverage" parameter for USDT markets');return n.leverageRr="cross"===r?o.Y.stringNeg(o.Y.stringAbs(e)):o.Y.stringAbs(e),await this.privatePutGPositionsLeverage(this.extend(n,i))}let d=this.safeInteger(i,"leverage");if("cross"===r&&(d=0),void 0===d)throw new a.ArgumentsRequired(this.id+" setMarginMode() requires a leverage parameter");return n.leverage=d,await this.privatePutPositionsLeverage(this.extend(n,i))}async setPositionMode(e,t,i={}){this.checkRequiredArgument("setPositionMode",t,"symbol"),void 0===this.markets&&await this.loadMarkets();let s=this.market(t);if("USDT"!==s.settle)throw new a.BadSymbol(this.id+" setPositionMode() supports USDT settled markets only");let r={symbol:s.id};return e?r.targetPosMode="Hedged":r.targetPosMode="OneWay",await this.privatePutGPositionsSwitchPosModeSync(this.extend(r,i))}async fetchLeverageTiers(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0!==e){let t=this.safeString(e,0);if("USD"!==this.market(t).settle)throw new a.BadSymbol(this.id+" fetchLeverageTiers() supports USD settled markets only")}let i=await this.publicGetCfgV2Products(t),s=this.safeDict(i,"data",{}),r=this.safeList(s,"riskLimits");return this.parseLeverageTiers(r,e,"symbol")}parseMarketLeverageTiers(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=s.info.riskLimits,a=[],o=0;for(let e=0;e<r.length;e++){let t=this.safeDict(r,e),n=this.safeInteger(t,"limit"),d=o;a.push({tier:this.sum(e,1),symbol:this.safeSymbol(i,s),currency:s.settle,minNotional:d,maxNotional:n,maintenanceMarginRate:this.safeNumber(t,"maintenanceMargin"),maxLeverage:void 0,info:t}),o=n}return a}sign(e,t="public",i="GET",r={},o,n){let d,h,c=this.omit(r,this.extractParams(e)),l="/"+this.implodeParams(e,r),u=l,f="";if(("GET"===i||"DELETE"===i||"PUT"===i||"/positions/assign"===u)&&Object.keys(c).length>0&&(u+="?"+(f=this.urlencodeWithArrayRepeat(c))),"private"===t){this.checkRequiredCredentials();let t=this.seconds(),a=this.safeInteger(this.options,"x-phemex-request-expiry",60),o=this.sum(t,a).toString();h={"x-phemex-access-token":this.apiKey,"x-phemex-request-expiry":o};let n="";"POST"===i&&(("g-orders"===e||"spot/orders"===e||"orders"===e)&&void 0===this.safeString(r,"clOrdID")&&(r.clOrdID=this.safeString(this.options,"brokerId","CCXT123456")+this.uuid16()),d=n=this.json(r),h["Content-Type"]="application/json");let c=l+f+o+n;h["x-phemex-request-signature"]=this.hmac(this.encode(c),this.encode(this.secret),s.sc)}let p=this.safeString(this.urls.api,t);if(void 0===p)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");u=this.implodeHostname(p)+u;let m=n;return"private"===t&&"POST"===i&&(m=d),{url:u,method:i,body:m,headers:"private"===t?h:o}}async setLeverage(e,t,i={}){let s;if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");if(e<-100||e>100)throw new a.BadRequest(this.id+" setLeverage() leverage should be between -100 and 100");void 0===this.markets&&await this.loadMarkets();let r=this.safeBool(i,"hedged",!1),o=this.safeInteger(i,"longLeverageRr"),n=this.safeInteger(i,"shortLeverageRr"),d=this.market(t),h={symbol:d.id};return"USDT"===d.settle||"USDC"===d.settle?(!0!==r&&void 0===o&&void 0===n?h.leverageRr=e:(h.longLeverageRr=void 0!==o?o:e,h.shortLeverageRr=void 0!==n?n:e),s=await this.privatePutGPositionsLeverage(this.extend(h,i))):(h.leverage=e,s=await this.privatePutPositionsLeverage(this.extend(h,i))),s}async transfer(e,t,i,s,r={}){let a,o;void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d=this.safeDict(this.options,"accountsByType",{}),h=this.safeString(d,i,i),c=this.safeString(d,s,s),l=this.toEv(t,n);if("spot"===h&&"future"===c?a=2:"future"===h&&"spot"===c&&(a=1),void 0!==a){let e={currency:n.id,moveOp:a,amountEv:l},t=await this.privatePostAssetsTransfer(this.extend(e,r)),i=this.safeDict(t,"data",{});o=this.parseTransfer(i,n)}else{let e={fromUserId:h,toUserId:c,amountEv:l,currency:n.id,bizType:this.safeString(r,"bizType","SPOT")},t=await this.privatePostAssetsUniversalTransfer(this.extend(e,r));o=this.parseTransfer(t)}let u=this.safeDict(this.options,"transfer",{});return!0===this.safeBool(u,"fillResponseFromRequest",!0)&&(void 0===o.fromAccount&&(o.fromAccount=i),void 0===o.toAccount&&(o.toAccount=s),void 0===o.amount&&(o.amount=t),void 0===o.currency&&(o.currency=e)),o}async fetchTransfers(e,t,i,s={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ArgumentsRequired(this.id+" fetchTransfers() requires a code argument");let r=this.currency(e),o={currency:r.id};void 0!==t&&(o.start=t),void 0!==i&&(o.limit=i);let n=await this.privateGetAssetsTransfer(this.extend(o,s)),d=this.safeDict(n,"data",{}),h=this.safeList(d,"rows",[]);return this.parseTransfers(h,r,t,i)}parseTransfer(e,t){let i,s,r=this.safeString(e,"linkKey"),a=this.safeString(e,"status"),o=this.safeString(e,"amountEv"),n=this.fromEv(o),d=this.safeString(e,"currency"),h=this.safeCurrencyCode(d,t),c=this.safeInteger(e,"side");1===c?(i="swap",s="spot"):2===c&&(i="spot",s="swap");let l=this.safeInteger(e,"createTime");return{info:e,id:r,timestamp:l,datetime:this.iso8601(l),currency:h,amount:n,fromAccount:i,toAccount:s,status:this.parseTransferStatus(a)}}parseTransferStatus(e){return this.safeString({3:"rejected",6:"canceled",10:"ok",11:"failed"},e,e)}async fetchFundingRateHistory(e,t,i,s={}){let r;if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchFundingRateHistory() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n="USDT"===o.settle||"USDC"===o.settle;if(!0!==o.swap)throw new a.BadRequest(this.id+" fetchFundingRateHistory() supports swap contracts only");let[d,h]=this.handleOptionBoolAndParams(s,"fetchFundingRateHistory","paginate",!1);if(d)return await this.fetchPaginatedCallDeterministic("fetchFundingRateHistory",e,t,i,"8h",h,100);let c={symbol:n?"."+o.id+"FR8H":"."+o.baseId+"FR8H"};void 0!==t&&(c.start=t),void 0!==i&&(c.limit=i);let[l,u]=this.handleUntilOption("end",c,h);r=n?await this.v2GetApiDataPublicDataFundingRateHistory(this.extend(l,u)):await this.v1GetApiDataPublicDataFundingRateHistory(this.extend(l,u));let f=this.safeDict(r,"data",{}),p=this.safeValue(f,"rows"),m=[];for(let t=0;t<p.length;t++){let i=p[t],s=this.safeInteger(i,"fundingTime");m.push({info:i,symbol:e,fundingRate:this.safeNumber(i,"fundingRate"),timestamp:s,datetime:this.iso8601(s)})}let g=this.sortBy(m,"timestamp");return this.filterBySymbolSinceLimit(g,e,t,i)}async withdraw(e,t,i,s,r={}){let o,[n,d]=this.handleWithdrawTagAndParams(s,r);void 0===this.markets&&await this.loadMarkets(),this.checkAddress(i);let h=this.currency(e),[c,l]=this.handleNetworkCodeAndParams(d);void 0!==c&&(o=this.networkCodeToId(c,e));let u=this.safeValue(this.options,"stableCoins");if(void 0===o)if(this.inArray(e,u))throw new a.ArgumentsRequired(this.id+' withdraw () requires an extra argument params["network"]');else o=h.id;let f={currency:h.id,address:i,amount:t,chainName:o.toUpperCase()};void 0!==n&&(f.addressTag=n);let p=await this.privatePostPhemexWithdrawWalletsApiCreateWithdraw(this.extend(f,l)),m=this.safeDict(p,"data",{});return this.parseTransaction(m,h)}async fetchOpenInterest(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.contract)throw new a.BadRequest(this.id+" fetchOpenInterest is only supported for contract markets.");let s={symbol:i.id},r=await this.v2GetMdV2Ticker24hr(this.extend(s,t)),o=this.safeDict(r,"result");return this.parseOpenInterest(o,i)}parseOpenInterest(e,t){let i=this.safeInteger(e,"timestamp")/1e6,s=this.safeString(e,"symbol");return this.safeOpenInterest({info:e,symbol:this.safeSymbol(s,t),baseVolume:this.safeString(e,"volumeRq"),quoteVolume:void 0,openInterestAmount:this.safeString(e,"openInterestRv"),openInterestValue:void 0,timestamp:i,datetime:this.iso8601(i)},t)}async fetchConvertQuote(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.currency(e),a=this.currency(t),o=this.safeInteger(r,"valueScale"),n={fromCurrency:e,toCurrency:t,fromAmountEv:this.toEn(i,o)},d=await this.privateGetAssetsQuote(this.extend(n,s)),h=this.safeDict(d,"data",{});return this.parseConversion(h,r,a)}async createConvertTrade(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.currency(t),o=this.currency(i),n=this.safeInteger(a,"valueScale"),d={code:e,fromCurrency:t,toCurrency:i};void 0!==s&&(d.fromAmountEv=this.toEn(s,n));let h=await this.privatePostAssetsConvert(this.extend(d,r)),c=this.safeDict(h,"data",{}),l=this.safeString(c,"fromCurrency"),u=this.safeCurrency(l,a),f=this.safeString(c,"toCurrency"),p=this.safeCurrency(f,o);return this.parseConversion(c,u,p)}async fetchConvertTradeHistory(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={};void 0!==e&&(r.fromCurrency=e),void 0!==t&&(r.startTime=t),void 0!==i&&(r.limit=i);let[a,o]=this.handleUntilOption("endTime",r,s),n=await this.privateGetAssetsConvert(this.extend(a,o)),d=this.safeDict(n,"data",{}),h=this.safeList(d,"rows",[]);return this.parseConversions(h,e,"fromCurrency","toCurrency",t,i)}parseConversion(e,t,i){let s=this.safeDict(e,"quoteArgs",{}),r=this.safeInteger(s,"requestAt"),a=this.safeInteger(e,"createTime",r),o=this.safeString(e,"fromCurrency",this.safeString(t,"code")),n=this.safeCurrencyCode(o,t),d=this.safeString(e,"toCurrency",this.safeString(i,"code")),h=this.safeCurrencyCode(d,i),c=this.safeInteger(t,"valueScale"),l=this.safeInteger(i,"valueScale"),u=this.fromEn(this.safeString(e,"fromAmountEv"),c);void 0===u&&void 0!==s&&(u=this.fromEn(this.safeString(s,"origin"),c));let f=this.fromEn(this.safeString(e,"toAmountEv"),l);return void 0===f&&void 0!==s&&(f=this.fromEn(this.safeString(s,"proceeds"),l)),{info:e,timestamp:a,datetime:this.iso8601(a),id:this.safeString(e,"code"),fromCurrency:n,fromAmount:this.parseNumber(u),toCurrency:h,toAmount:this.parseNumber(f),price:this.safeNumber(s,"price"),fee:void 0}}async fetchPositionsADLRank(e,t={}){let i,s,r;void 0===this.markets&&await this.loadMarkets();let a=this.marketSymbols(e,void 0,!0,!0,!0),o=this.safeString2(t,"currency","code","USDT"),n=this.omit(t,["currency","code"]),d=n,h=this.safeString(a,0);void 0!==h?(r=this.market(h),s=this.safeString(r,"settle"),o=r.settle):[s,d]=this.handleOptionStringAndParams(n,"fetchPositionsADLRank","settle",o);let[c,l]=this.handleSubTypeAndParams("fetchPositionsADLRank",r,d),u="USDT"===s;u?o="USDT":"BTC"===s?o="BTC":void 0===o&&(o="linear"===c?"USD":"BTC");let f={currency:this.currency(o).id};if(u){let[e,t]=this.handleOptionStringAndParams(l,"fetchPositionsADLRank","method","privateGetGAccountsAccountPositions");i="privateGetGAccountsAccountPositions"===e?await this.privateGetGAccountsAccountPositions(this.extend(f,t)):await this.privateGetGAccountsPositions(this.extend(f,t))}else i=await this.privateGetAccountsAccountPositions(this.extend(f,l));let p=this.safeDict(i,"data",{}),m=this.safeList(p,"positions",[]),g=[];for(let e=0;e<m.length;e++){let t=m[e];g.push(this.parseADLRank(t))}return this.filterByArrayADLRanks(g,"symbol",a,!1)}parseADLRank(e,t){let i=this.safeString(e,"symbol");return{info:e,symbol:this.safeSymbol(i,t,void 0,"contract"),rank:void 0,rating:void 0,percentage:this.safeNumber2(e,"deleveragePercentileRr","deleveragePercentileEr"),timestamp:void 0,datetime:void 0}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeDict(n,"error",n),l=this.safeString(c,"code"),u=this.safeString(c,"msg");if(void 0!==l&&"0"!==l){let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,l,e),this.throwBroadlyMatchedException(this.exceptions.broad,u,e),new a.ExchangeError(e)}}}i.d(t,{A:()=>n})},2406(e,t,i){"use strict";var s=i(4721),r=i(2819),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"poloniex",name:"Poloniex",countries:["US"],rateLimit:5,certified:!1,pro:!0,has:{CORS:void 0,spot:!0,margin:void 0,swap:!0,future:!1,option:!1,addMargin:!0,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:void 0,createDepositAddress:!0,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createOrders:void 0,createStopOrder:!0,createTriggerOrder:!0,editOrder:!0,fetchAllGreeks:!1,fetchBalance:!0,fetchClosedOrder:!1,fetchClosedOrders:!0,fetchCurrencies:!0,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!0,fetchDepositWithdrawFee:"emulated",fetchDepositWithdrawFees:!0,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:void 0,fetchGreeks:!1,fetchLedger:void 0,fetchLeverage:!0,fetchLiquidations:void 0,fetchMarginMode:!1,fetchMarkets:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterestHistory:!1,fetchOpenOrder:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrderTrades:!0,fetchPosition:!1,fetchPositionMode:!0,fetchPositions:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!0,fetchTransactions:"emulated",fetchTransfer:!1,fetchTransfers:!1,fetchVolatilityHistory:!1,fetchWithdrawals:!0,reduceMargin:!0,sandbox:!0,setLeverage:!0,setPositionMode:!0,transfer:!0,withdraw:!0},timeframes:{"1m":"MINUTE_1","5m":"MINUTE_5","10m":"MINUTE_10","15m":"MINUTE_15","30m":"MINUTE_30","1h":"HOUR_1","2h":"HOUR_2","4h":"HOUR_4","6h":"HOUR_6","12h":"HOUR_12","1d":"DAY_1","3d":"DAY_3","1w":"WEEK_1","1M":"MONTH_1"},urls:{logo:"https://user-images.githubusercontent.com/1294454/27766817-e9456312-5ee6-11e7-9b3c-b628ca5626a5.jpg",api:{spot:"https://api.poloniex.com",swap:"https://api.poloniex.com"},test:{spot:"https://sand-spot-api-gateway.poloniex.com"},www:"https://www.poloniex.com",doc:"https://api-docs.poloniex.com/spot/",fees:"https://poloniex.com/fees",referral:"https://poloniex.com/signup?c=UBFZJRPJ"},api:{public:{get:{markets:{cost:20},"markets/{symbol}":{cost:1},currencies:{cost:20},"currencies/{currency}":{cost:20},"v2/currencies":{cost:20},"v2/currencies/{currency}":{cost:20},timestamp:{cost:1},"markets/price":{cost:1},"markets/{symbol}/price":{cost:1},"markets/markPrice":{cost:1},"markets/{symbol}/markPrice":{cost:1},"markets/{symbol}/markPriceComponents":{cost:1},"markets/{symbol}/orderBook":{cost:1},"markets/{symbol}/candles":{cost:1},"markets/{symbol}/trades":{cost:20},"markets/ticker24h":{cost:20},"markets/{symbol}/ticker24h":{cost:20},"markets/collateralInfo":{cost:1},"markets/{currency}/collateralInfo":{cost:1},"markets/borrowRatesInfo":{cost:1}}},private:{get:{accounts:{cost:4},"accounts/balances":{cost:4},"accounts/{id}/balances":{cost:4},"accounts/activity":{cost:20},"accounts/transfer":{cost:20},"accounts/transfer/{id}":{cost:4},feeinfo:{cost:20},"accounts/interest/history":{cost:1},subaccounts:{cost:4},"subaccounts/balances":{cost:20},"subaccounts/{id}/balances":{cost:4},"subaccounts/transfer":{cost:20},"subaccounts/transfer/{id}":{cost:4},"wallets/addresses":{cost:20},"wallets/addresses/{currency}":{cost:20},"wallets/activity":{cost:20},"margin/accountMargin":{cost:4},"margin/borrowStatus":{cost:4},"margin/maxSize":{cost:4},orders:{cost:20},"orders/{id}":{cost:4},"orders/killSwitchStatus":{cost:4},smartorders:{cost:20},"smartorders/{id}":{cost:4},"orders/history":{cost:20},"smartorders/history":{cost:20},trades:{cost:20},"orders/{id}/trades":{cost:4}},post:{"accounts/transfer":{cost:4},"subaccounts/transfer":{cost:20},"wallets/address":{cost:20},"wallets/withdraw":{cost:20},"v2/wallets/withdraw":{cost:20},orders:{cost:4},"orders/batch":{cost:20},"orders/killSwitch":{cost:4},smartorders:{cost:4}},delete:{"orders/{id}":{cost:4},"orders/cancelByIds":{cost:20},orders:{cost:20},"smartorders/{id}":{cost:4},"smartorders/cancelByIds":{cost:20},smartorders:{cost:20}},put:{"orders/{id}":{cost:20},"smartorders/{id}":{cost:20}}},swapPublic:{get:{"v3/market/allInstruments":{cost:2/3},"v3/market/instruments":{cost:2/3},"v3/market/orderBook":{cost:2/3},"v3/market/candles":{cost:10},"v3/market/indexPriceCandlesticks":{cost:10},"v3/market/premiumIndexCandlesticks":{cost:10},"v3/market/markPriceCandlesticks":{cost:10},"v3/market/trades":{cost:2/3},"v3/market/liquidationOrder":{cost:2/3},"v3/market/tickers":{cost:2/3},"v3/market/markPrice":{cost:2/3},"v3/market/indexPrice":{cost:2/3},"v3/market/indexPriceComponents":{cost:2/3},"v3/market/fundingRate":{cost:2/3},"v3/market/fundingRate/history":{cost:2/3},"v3/market/openInterest":{cost:2/3},"v3/market/insurance":{cost:2/3},"v3/market/riskLimit":{cost:2/3},"v3/market/limitPrice":{cost:2/3}}},swapPrivate:{get:{"v3/account/balance":{cost:4},"v3/account/bills":{cost:20},"v3/trade/order/opens":{cost:20},"v3/trade/order/trades":{cost:20},"v3/trade/order/history":{cost:20},"v3/trade/order/details":{cost:20},"v3/trade/position/opens":{cost:20},"v3/trade/position/history":{cost:20},"v3/position/leverages":{cost:20},"v3/position/mode":{cost:20},"v3/position/riskLimit":{cost:20}},post:{"v3/trade/order":{cost:4},"v3/trade/orders":{cost:40},"v3/trade/position":{cost:20},"v3/trade/positionAll":{cost:100},"v3/position/leverage":{cost:20},"v3/position/mode":{cost:20},"v3/trade/position/margin":{cost:20}},delete:{"v3/trade/order":{cost:2},"v3/trade/batchOrders":{cost:20},"v3/trade/allOrders":{cost:20}}}},fees:{trading:{feeSide:"get",maker:this.parseNumber("0.0009"),taker:this.parseNumber("0.0009")},funding:{}},commonCurrencies:{AIR:"AirCoin",APH:"AphroditeCoin",BCC:"BTCtalkcoin",BCHABC:"BCHABC",BDG:"Badgercoin",BTM:"Bitmark",CON:"Coino",ETHTRON:"ETH",GOLD:"GoldEagles",GPUC:"GPU",HOT:"Hotcoin",ITC:"Information Coin",KEY:"KEYCoin",MASK:"NFTX Hashmasks Index",MEME:"Degenerator Meme",PLX:"ParallaxCoin",REPV2:"REP",STR:"XLM",SOC:"SOCC",TRADE:"Unitrade",TRXETH:"TRX",XAP:"API Coin",USDTBSC:"USDT",USDTTRON:"USDT",USDTETH:"USDT",UST:"USTC"},options:{defaultType:"spot",createMarketBuyOrderRequiresPrice:!0,networks:{BEP20:"BSC",ERC20:"ETH",TRC20:"TRX",TRX:"TRX"},networksById:{TRX:"TRC20",TRON:"TRC20"},limits:{cost:{min:{BTC:1e-4,ETH:1e-4,USDT:1,TRX:100,BNB:.06,USDC:1,USDJ:1,TUSD:1e-4,DAI:1,PAX:1,BUSD:1}}},accountsByType:{spot:"spot",future:"futures"},accountsById:{exchange:"spot",futures:"future"}},features:{default:{sandbox:!0,createOrder:{marginMode:!0,triggerPrice:!0,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{IOC:!0,FOK:!0,PO:!0,GTD:!1},hedged:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,selfTradePrevention:!0,trailing:!1,iceberg:!1},createOrders:{max:20},fetchMyTrades:{marginMode:!1,limit:1e3,daysBack:1e5,untilDays:1e5,symbolRequired:!1},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:2e3,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:void 0,fetchClosedOrders:void 0,fetchOHLCV:{limit:500}},spot:{extends:"default"},forContracts:{extends:"default",createOrder:{marginMode:!0,triggerPrice:!1,hedged:!0,stpMode:!0,marketBuyByCost:!1},createOrders:{max:10},fetchOpenOrders:{limit:100},fetchClosedOrders:{marginMode:!1,limit:100,daysBack:void 0,daysBackCanceled:1/6,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchMyTrades:{limit:100,untilDays:90}},swap:{linear:{extends:"forContracts"},inverse:{extends:"forContracts"}},future:{linear:{extends:"forContracts"},inverse:{extends:"forContracts"}}},precisionMode:4,exceptions:{exact:{500:a.ExchangeNotAvailable,603:a.RequestTimeout,601:a.BadRequest,415:a.ExchangeError,602:a.ArgumentsRequired,21604:a.BadRequest,21600:a.AuthenticationError,21605:a.AuthenticationError,21102:a.ExchangeError,21100:a.AuthenticationError,21704:a.AuthenticationError,21700:a.BadRequest,21705:a.BadRequest,21707:a.ExchangeError,21708:a.BadRequest,21601:a.AccountSuspended,21711:a.ExchangeError,21709:a.InsufficientFunds,25e4:a.ExchangeError,250001:a.BadRequest,250002:a.BadRequest,250003:a.BadRequest,250004:a.BadRequest,250005:a.InsufficientFunds,250008:a.BadRequest,250012:a.ExchangeError,21110:a.BadRequest,10040:a.BadSymbol,10060:a.ExchangeError,10020:a.BadSymbol,10041:a.BadSymbol,21340:a.OnMaintenance,21341:a.InvalidOrder,21342:a.InvalidOrder,21343:a.InvalidOrder,21351:a.AccountSuspended,21352:a.BadSymbol,21353:a.PermissionDenied,21354:a.PermissionDenied,21359:a.OrderNotFound,21360:a.InvalidOrder,24106:a.BadRequest,24201:a.ExchangeNotAvailable,21301:a.OrderNotFound,21302:a.ExchangeError,21304:a.ExchangeError,21305:a.OrderNotFound,21307:a.ExchangeError,21309:a.InvalidOrder,21310:a.InvalidOrder,21311:a.InvalidOrder,21312:a.InvalidOrder,21314:a.InvalidOrder,21315:a.InvalidOrder,21317:a.InvalidOrder,21319:a.InvalidOrder,21320:a.InvalidOrder,21321:a.InvalidOrder,21322:a.InvalidOrder,21324:a.BadRequest,21327:a.InvalidOrder,21328:a.InvalidOrder,21330:a.InvalidOrder,21335:a.InvalidOrder,21336:a.InvalidOrder,21337:a.InvalidOrder,21344:a.InvalidOrder,21345:a.InvalidOrder,21346:a.InvalidOrder,21348:a.InvalidOrder,21347:a.InvalidOrder,21349:a.InvalidOrder,21350:a.InvalidOrder,21355:a.ExchangeError,21356:a.BadRequest,21721:a.InsufficientFunds,24101:a.BadSymbol,24102:a.BadRequest,24103:a.BadRequest,24104:a.BadRequest,24105:a.BadRequest,25020:a.InvalidOrder,25e3:a.InvalidOrder,25001:a.InvalidOrder,25002:a.InvalidOrder,25003:a.ExchangeError,25004:a.InvalidOrder,25005:a.ExchangeError,25006:a.InvalidOrder,25007:a.InvalidOrder,25008:a.InvalidOrder,25009:a.ExchangeError,25010:a.PermissionDenied,25011:a.InvalidOrder,25012:a.ExchangeError,25013:a.OrderNotFound,25014:a.OrderNotFound,25015:a.OrderNotFound,25016:a.ExchangeError,25017:a.ExchangeError,25018:a.BadRequest,25019:a.BadSymbol,820181:a.BadRequest,820201:a.BadRequest,830111:a.BadRequest,250:a.DuplicateOrderId,400:a.BadRequest,403:a.PermissionDenied,404:a.BadRequest,429:a.RateLimitExceeded,503:a.ExchangeNotAvailable,1e3:a.AuthenticationError,1001:a.ExchangeError,1002:a.OnMaintenance,1003:a.AccountSuspended,1e4:a.MarketClosed,10001:a.BadSymbol,10002:a.InvalidOrder,10003:a.InvalidOrder,10004:a.InvalidOrder,10005:a.MarketClosed,10006:a.OperationRejected,10007:a.OperationRejected,10008:a.AccountSuspended,10009:a.OperationRejected,10010:a.InvalidOrder,10011:a.InvalidOrder,10012:a.InvalidOrder,10013:a.InvalidOrder,10014:a.BadRequest,10015:a.OperationRejected,10016:a.BadRequest,10017:a.BadRequest,10018:a.OperationRejected,10019:a.OperationRejected,11003:a.BadRequest,11004:a.OperationRejected,11008:a.OrderNotFound,12004:a.PermissionDenied,21001:a.OperationRejected},broad:{}}})}parseOHLCV(e,t){return 9===e.length?[this.safeInteger(e,7),this.safeNumber(e,2),this.safeNumber(e,1),this.safeNumber(e,0),this.safeNumber(e,3),this.safeNumber(e,5)]:[this.safeInteger(e,12),this.safeNumber(e,2),this.safeNumber(e,1),this.safeNumber(e,0),this.safeNumber(e,3),this.safeNumber(e,5)]}async fetchOHLCV(e,t="1m",i,s,r={}){await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(r,"fetchOHLCV","paginate",!1);if(a)return await this.fetchPaginatedCallDeterministic("fetchOHLCV",e,i,s,t,o,500);let n=this.market(e),d={symbol:n.id,interval:this.safeString(this.timeframes,t,t)},h="sTime";!0===n.spot&&(h="startTime");let c="eTime";!0===n.spot&&(c="endTime"),void 0!==i&&(d[h]=i),void 0!==s&&(d.limit=s);let[l,u]=this.handleUntilOption(c,d,o);if(!0===n.contract){let e=await this.swapPublicGetV3MarketCandles(this.extend(l,u)),r=this.safeList(e,"data");return this.parseOHLCVs(r,n,t,i,s)}let f=await this.publicGetMarketsSymbolCandles(this.extend(l,u)),p=[];return Array.isArray(f)&&(p=f),this.parseOHLCVs(p,n,t,i,s)}async loadMarkets(e=!1,t={}){let i=await super.loadMarkets(e,t);return(void 0===this.safeDict(this.options,"currenciesByNumericId")||e)&&(this.options.currenciesByNumericId=this.indexBy(this.currencies,"numericId")),i}async fetchMarkets(e={}){let t=[this.fetchSpotMarkets(e),this.fetchSwapMarkets(e)],i=await Promise.all(t);return this.arrayConcat(i[0],i[1])}async fetchSpotMarkets(e={}){let t=await this.publicGetMarkets(e);return this.parseMarkets(t)}async fetchSwapMarkets(e={}){let t=await this.swapPublicGetV3MarketAllInstruments(e),i=this.safeList(t,"data");return this.parseMarkets(i)}parseMarket(e){return"ctType"in e?this.parseSwapMarket(e):this.parseSpotMarket(e)}parseSpotMarket(e){let t=this.safeString(e,"symbol"),i=this.safeString(e,"baseCurrencyName"),s=this.safeString(e,"quoteCurrencyName"),r=this.safeCurrencyCode(i),a=this.safeCurrencyCode(s);if(void 0===r||void 0===a)return;let o=this.safeString(e,"state"),n=this.safeDict(e,"symbolTradeLimit");return this.safeMarketStructure({id:t,symbol:r+"/"+a,base:r,quote:a,settle:void 0,baseId:i,quoteId:s,settleId:void 0,type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,active:"NORMAL"===o,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,precision:{amount:this.parseNumber(this.parsePrecision(this.safeString(n,"quantityScale"))),price:this.parseNumber(this.parsePrecision(this.safeString(n,"priceScale")))},limits:{amount:{min:this.safeNumber(n,"minQuantity"),max:void 0},price:{min:void 0,max:void 0},cost:{min:this.safeNumber(n,"minAmount"),max:void 0}},created:this.safeInteger(e,"tradableStartTime"),info:e})}parseSwapMarket(e){let t=this.safeString(e,"symbol"),i=this.safeString(e,"bCcy"),s=this.safeString(e,"qCcy"),r=this.safeString(e,"sCcy"),a=this.safeCurrencyCode(i),o=this.safeCurrencyCode(s);if(void 0===a||void 0===o)return;let n=this.safeCurrencyCode(r),d=this.safeString(e,"status"),h="LINEAR"===this.safeString(e,"ctType"),c=a+"/"+o;h?c+=":"+n:c+=":"+a;let l=this.safeString(e,"alias"),u="swap";void 0!==l&&(u="future");let f="swap";return"future"===u&&(f="future"),this.safeMarketStructure({id:t,symbol:c,base:a,quote:o,settle:n,baseId:i,quoteId:s,settleId:r,type:f,spot:!1,margin:!1,swap:"swap"===u,future:"future"===u,option:!1,active:"OPEN"===d,contract:!0,linear:h,inverse:!h,contractSize:this.safeNumber(e,"ctVal"),expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,taker:this.safeNumber(e,"tFee"),maker:this.safeNumber(e,"mFee"),precision:{amount:this.safeNumber(e,"lotSz"),price:this.safeNumber(e,"tSz")},limits:{amount:{min:this.safeNumber(e,"minSz"),max:this.safeNumber(e,"limitMaxQty")},price:{min:this.safeNumber(e,"minPx"),max:this.safeNumber(e,"maxPx")},cost:{min:void 0,max:void 0},leverage:{max:this.safeNumber(e,"maxLever"),min:void 0}},created:this.safeInteger(e,"oDate"),info:e})}async fetchTime(e={}){let t=await this.publicGetTimestamp(e);return this.safeInteger(t,"serverTime")}parseTicker(e,t){let i=this.safeInteger2(e,"ts","cT"),s=this.safeString2(e,"symbol","s"),r=this.safeMarket(s),a=this.safeString2(e,"quantity","qty");!0===r.contract&&void 0!==r.contractSize&&(a=o.Y.stringMul(a,this.numberToString(r.contractSize)));let n=this.safeString2(e,"dailyChange","dc"),d=o.Y.stringMul(n,"100");return this.safeTicker({symbol:r.symbol,timestamp:i,datetime:this.iso8601(i),high:this.safeString2(e,"high","h"),low:this.safeString2(e,"low","l"),bid:this.safeString2(e,"bid","bPx"),bidVolume:this.safeString2(e,"bidQuantity","bSz"),ask:this.safeString2(e,"ask","aPx"),askVolume:this.safeString2(e,"askQuantity","aSz"),vwap:void 0,open:this.safeString2(e,"open","o"),close:this.safeString2(e,"close","c"),previousClose:void 0,change:void 0,percentage:d,average:void 0,baseVolume:a,quoteVolume:this.safeString2(e,"amount","amt"),markPrice:this.safeString2(e,"markPrice","mPx"),indexPrice:this.safeString(e,"iPx"),info:e},r)}async fetchTickers(e,t={}){let i;await this.loadMarkets();let s={},r=this.marketSymbols(e,void 0,!0,!0,!1);if(void 0!==r){let e=r.length;e>0&&(i=this.market(r[0]),1===e&&(s.symbol=i.id))}let[a,o]=this.handleMarketTypeAndParams("fetchTickers",i,t);if("swap"===a){let e=await this.swapPublicGetV3MarketTickers(this.extend(s,o)),t=this.safeList(e,"data");return this.parseTickers(t,r)}let n=await this.publicGetMarketsTicker24h(o);return this.parseTickers(n,r)}async fetchCurrencies(e={}){let t=await this.publicGetV2Currencies(e);return this.parseCurrencies(t)}parseCurrency(e){let t=this.safeString(e,"coin"),i=this.safeCurrencyCode(t),s={},r=this.safeList(e,"networkList",[]),a=r.length;for(let e=0;e<a;e++){let t=this.safeDict(r,e),a=this.safeString(t,"blockchain"),o=this.networkIdToCode(a,i);void 0!==o&&(s[o]={info:t,id:a,name:void 0,code:o,active:void 0,fee:this.safeNumber(t,"withdrawFee"),deposit:this.safeBool(t,"depositEnable"),withdraw:this.safeBool(t,"withdrawalEnable"),precision:this.parseNumber(this.parsePrecision(this.safeString(t,"decimals"))),limits:{withdraw:{min:this.safeNumber(t,"withdrawMin"),max:void 0},deposit:{min:void 0,max:void 0}}})}return this.safeCurrencyStructure({id:t,name:this.safeString(e,"name"),code:i,type:void 0,precision:void 0,info:e,networks:s,deposit:void 0,withdraw:void 0,active:void 0,fee:void 0,limits:void 0,margin:this.safeBool(e,"supportBorrow")})}async fetchTicker(e,t={}){await this.loadMarkets();let i=this.market(e),s={symbol:i.id};if(!0===i.contract){let s=await this.fetchTickers([i.symbol],t);return this.safeDict(s,e)}let r=await this.publicGetMarketsSymbolTicker24h(this.extend(s,t));return this.parseTicker(r,i)}parseTrade(e,t){let i,s=this.safeStringN(e,["id","tradeID","trdId"]),r=this.safeString2(e,"orderId","ordId"),a=this.safeIntegerN(e,["ts","createTime","cT","cTime"]),o=this.safeString(e,"symbol"),n=this.safeMarket(o,t,"_"),d=n.symbol,h=this.safeStringLower2(e,"side","takerSide"),c=this.safeString2(e,"price","px"),l=this.safeString2(e,"quantity","qty"),u=this.safeString2(e,"amount","amt"),f=this.safeString2(e,"feeCurrency","feeCcy"),p=this.safeString2(e,"feeAmount","feeAmt");return void 0!==p&&(i={cost:p,currency:this.safeCurrencyCode(f)}),this.safeTrade({id:s,info:e,timestamp:a,datetime:this.iso8601(a),symbol:d,order:r,type:this.safeStringLower2(e,"ordType","type"),side:h,takerOrMaker:this.safeStringLower2(e,"matchRole","role"),price:c,amount:l,cost:u,fee:i},n)}async fetchTrades(e,t,i,s={}){await this.loadMarkets();let r=this.market(e),a={symbol:r.id};if(void 0!==i&&(a.limit=i),!0===r.contract){let e=await this.swapPublicGetV3MarketTrades(this.extend(a,s)),o=this.safeList(e,"data",[]);return this.parseTrades(o,r,t,i)}let o=await this.publicGetMarketsSymbolTrades(this.extend(a,s));return this.parseTrades(o,r,t,i)}async fetchMyTrades(e,t,i,s={}){let r;await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);if(a)return await this.fetchPaginatedCallDynamic("fetchMyTrades",e,t,i,o);void 0!==e&&(r=this.market(e));let[n,d]=this.handleMarketTypeAndParams("fetchMyTrades",r,o),h=this.inArray(n,["swap","future"]),c={},l="startTime";h&&(l="sTime");let u="endTime";h&&(u="eTime"),void 0!==t&&(c[l]=t),void 0!==i&&(c.limit=i),h&&void 0!==e&&(c.symbol=this.safeString(r,"id"));let[f,p]=this.handleUntilOption(u,c,d);if(h){let e=await this.swapPrivateGetV3TradeOrderTrades(this.extend(f,p)),s=this.safeList(e,"data",[]);return this.parseTrades(s,r,t,i)}let m=await this.privateGetTrades(this.extend(f,p));return this.parseTrades(m,r,t,i)}parseOrderStatus(e){return this.safeString({NEW:"open",PARTIALLY_FILLED:"open",FILLED:"closed",PENDING_CANCEL:"canceled",PARTIALLY_CANCELED:"canceled",CANCELED:"canceled",FAILED:"canceled"},e,e)}parseOrder(e,t){let i,s,r,a=this.safeIntegerN(e,["timestamp","createTime","cTime"]);void 0===a&&(a=this.parse8601(this.safeString(e,"date")));let o=this.safeString(e,"symbol"),n=this.safeMarket(o,t,"_"),d=n.symbol,h=this.safeValue(e,"resultingTrades");void 0===h||Array.isArray(h)||(h=this.safeValue(h,this.safeString(n,"id",o)));let c=this.safeStringN(e,["price","rate","px"]),l=this.safeString2(e,"quantity","sz"),u=this.safeString2(e,"filledQuantity","execQty"),f=this.parseOrderStatus(this.safeString(e,"state")),p=this.safeStringLower(e,"side"),m=this.safeString(e,"type"),g=this.parseOrderType(m),v=this.safeStringN(e,["orderNumber","id","orderId","ordId"]),y=this.safeString2(e,"tokenFeeCurrency","feeCcy"),b=this.safeString(e,"fee");void 0===y?r="buy"===p?n.base:n.quote:(r=this.safeCurrencyCode(y),s=this.safeString2(e,"tokenFee","feeAmt")),void 0!==s&&(i={rate:b,cost:s,currency:r});let w=this.safeString2(e,"clientOrderId","clOrdId"),k=this.safeStringLower(e,"mgnMode"),S=this.safeBool(e,"reduceOnly"),O=this.safeInteger(e,"lever"),T="BOTH"!==this.safeString(e,"posSide");return this.safeOrder({info:e,id:v,clientOrderId:w,timestamp:a,datetime:this.iso8601(a),lastTradeTimestamp:this.safeInteger(e,"updateTime"),status:f,symbol:d,type:g,timeInForce:this.safeString(e,"timeInForce"),postOnly:"LIMIT_MAKER"===m,side:p,price:c,triggerPrice:this.safeString2(e,"triggerPrice","stopPrice"),cost:this.safeString(e,"execAmt"),average:this.safeString2(e,"avgPrice","avgPx"),amount:l,filled:u,remaining:void 0,trades:h,fee:i,marginMode:k,reduceOnly:S,leverage:O,hedged:T},n)}parseOrderType(e){return this.safeString({MARKET:"market",LIMIT:"limit",LIMIT_MAKER:"limit","STOP-LIMIT":"limit","STOP-MARKET":"market"},e,e)}parseOpenOrders(e,t,i){for(let s=0;s<e.length;s++){let r=e[s],a=this.extend(r,{status:"open",type:"limit",side:r.type,price:r.rate});i.push(this.parseOrder(a,t))}return i}async fetchOpenOrders(e,t,i,s={}){let r;await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id);let[o,n]=this.handleMarketTypeAndParams("fetchOpenOrders",r,s);void 0!==i&&(a.limit=Math.max(i,"spot"===o?2e3:100));let d=this.safeBool2(n,"trigger","stop"),h=this.omit(n,["trigger","stop"]),c=[];if("spot"!==o){let e=await this.swapPrivateGetV3TradeOrderOpens(this.extend(a,h));c=this.safeList(e,"data",[])}else c=!0===d?await this.privateGetSmartorders(this.extend(a,h)):await this.privateGetOrders(this.extend(a,h));return this.parseOrders(c,r,t,i,{status:"open"})}async fetchClosedOrders(e,t,i,s={}){let r;await this.loadMarkets();let o={};void 0!==e&&(o.symbol=(r=this.market(e)).id);let[n,d]=this.handleMarketTypeAndParams("fetchClosedOrders",r,s,"swap");if("spot"===n)throw new a.NotSupported(this.id+" fetchClosedOrders() is not supported for spot markets yet");void 0!==i&&(o.limit=Math.min(200,i)),void 0!==t&&(o.sTime=t);let[h,c]=this.handleUntilOption("eTime",o,d),l=await this.swapPrivateGetV3TradeOrderHistory(this.extend(h,c)),u=this.safeList(l,"data",[]);return this.parseOrders(u,r,t,i)}async createOrder(e,t,i,s,r,a={}){await this.loadMarkets();let o=this.market(e),n={symbol:o.id,side:i.toUpperCase()},d=this.safeNumber2(a,"stopPrice","triggerPrice"),[h,c]=this.orderRequest(e,t,i,s,n,r,a),l={};if(!0===o.swap||!0===o.future){let e=await this.swapPrivatePostV3TradeOrder(this.extend(h,c));l=this.safeDict(e,"data",{})}else l=void 0!==d?await this.privatePostSmartorders(this.extend(h,c)):await this.privatePostOrders(this.extend(h,c));return this.parseOrder(l,o)}orderRequest(e,t,i,s,r,n,d={}){let h=this.safeNumber2(d,"stopPrice","triggerPrice"),c=this.market(e),l=!0===c.contract,[u,f]=this.handleParamString(d,"marginMode"),[p,m]=this.handleParamString(f,"hedged"),g=d;if(l&&(g=m),l&&(void 0!==u&&(this.checkRequiredArgument("createOrder",u,"marginMode",["cross","isolated"]),r.mgnMode=u.toUpperCase()),void 0!==p&&""!==p)){if(void 0===u)throw new a.ArgumentsRequired(this.id+' createOrder() requires a marginMode parameter "cross" or "isolated" for hedged orders');if(!("posSide"in g))throw new a.ArgumentsRequired(this.id+' createOrder() requires a posSide parameter "LONG" or "SHORT" for hedged orders')}let v=t.toUpperCase(),y="MARKET"===v,b=this.isPostOnly(y,"LIMIT_MAKER"===v,g),w=this.omit(g,["postOnly","triggerPrice","stopPrice"]);if(void 0!==h){if(!0!==c.spot)throw new a.InvalidOrder(this.id+" createOrder() does not support trigger orders for "+c.type+" markets");v=void 0===n?"STOP":"STOP_LIMIT",r.stopPrice=h}else b&&(v="LIMIT_MAKER");if(r.type=v,y)if("buy"===i){let t,i=!0;[i,w]=this.handleOptionBoolAndParams(w,"createOrder","createMarketBuyOrderRequiresPrice",!0);let d=this.safeNumber(w,"cost");if(w=this.omit(w,"cost"),void 0!==d)t=this.costToPrecision(e,d);else if(i&&!0===c.spot)if(void 0===n)throw new a.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend (quote quantity) in the amount argument");else{let i=this.numberToString(s),r=this.numberToString(n),a=o.Y.stringMul(i,r);t=this.costToPrecision(e,a)}else t=this.costToPrecision(e,s);let h="sz";!0===c.spot&&(h="amount"),r[h]=t}else{let t="sz";!0===c.spot&&(t="quantity"),r[t]=this.amountToPrecision(e,s)}else{let t="sz";!0===c.spot&&(t="quantity"),r[t]=this.amountToPrecision(e,s);let i="px";!0===c.spot&&(i="price"),r[i]=this.priceToPrecision(e,n)}let k=this.safeString2(w,"clientOrderId","clOrdId");if(void 0!==k){let e="clOrdId";!0===c.spot&&(e="clientOrderId"),r[e]=k,w=this.omit(w,["clientOrderId","clOrdId"])}return[r,w]}async editOrder(e,t,i,s,r,o,n={}){await this.loadMarkets();let d=this.market(t);if(!0!==d.spot)throw new a.NotSupported(this.id+" editOrder() does not support "+d.type+" orders, only spot orders are accepted");let h=this.safeNumber2(n,"stopPrice","triggerPrice"),[c,l]=this.orderRequest(t,i,s,r,{id:e},o,n),u={};return u=void 0!==h?await this.privatePutSmartordersId(this.extend(c,l)):await this.privatePutOrdersId(this.extend(c,l)),u=this.extend(u,{side:s,type:i}),this.parseOrder(u,d)}async cancelOrder(e,t,i={}){if(await this.loadMarkets(),void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrder() requires a symbol argument");let s=this.market(t),r={};if(!0!==s.spot){r.symbol=s.id,r.ordId=e;let t=await this.swapPrivateDeleteV3TradeOrder(this.extend(r,i));return this.parseOrder(this.safeDict(t,"data",{}))}let o=this.safeValue(i,"clientOrderId");r.id=void 0!==o?o:e;let n=this.safeBool2(i,"trigger","stop"),d=this.omit(i,["clientOrderId","trigger","stop"]),h={};return h=!0===n?await this.privateDeleteSmartordersId(this.extend(r,d)):await this.privateDeleteOrdersId(this.extend(r,d)),this.parseOrder(h)}async cancelAllOrders(e,t={}){let i;await this.loadMarkets();let s={symbols:[]};void 0!==e&&(s.symbols=[(i=this.market(e)).id]);let r=[],[a,o]=this.handleMarketTypeAndParams("cancelAllOrders",i,t);if("swap"===a||"future"===a){let e=await this.swapPrivateDeleteV3TradeAllOrders(this.extend(s,o));return r=this.safeList(e,"data",[]),this.parseOrders(r,i)}let n=this.safeBool2(o,"trigger","stop"),d=this.omit(o,["trigger","stop"]);return r=!0===n?await this.privateDeleteSmartorders(this.extend(s,d)):await this.privateDeleteOrders(this.extend(s,d)),this.parseOrders(r,i)}async fetchOrder(e,t,i={}){let s;await this.loadMarkets();let r=e.toString(),o={id:r};void 0!==t&&(o.symbol=(s=this.market(t)).id);let[n,d]=this.handleMarketTypeAndParams("fetchOrder",s,i);if("spot"!==n)throw new a.NotSupported(this.id+" fetchOrder() is not supported for "+n+" markets yet");let h=this.safeBool2(d,"trigger","stop"),c=this.omit(d,["trigger","stop"]),l={};!0===h?(l=await this.privateGetSmartordersId(this.extend(o,c)),l=this.safeValue(l,0)):l=await this.privateGetOrdersId(this.extend(o,c));let u=this.parseOrder(l);return u.id=r,u}async fetchOrderStatus(e,t,i={}){await this.loadMarkets();let s=await this.fetchOpenOrders(t,void 0,void 0,i);return e in this.indexBy(s,"id")?"open":"closed"}async fetchOrderTrades(e,t,i,s,r={}){await this.loadMarkets();let a=await this.privateGetOrdersIdTrades(this.extend({id:e},r));return this.parseTrades(a)}parseBalance(e){let t={info:e,timestamp:void 0,datetime:void 0};if(!Array.isArray(e)){let i=this.safeInteger(e,"uTime");t.timestamp=i,t.datetime=this.iso8601(i);let s=this.safeList(e,"details",[]);for(let e=0;e<s.length;e++){let i=this.safeDict(s,e),r=this.safeString(i,"ccy"),a=this.safeCurrencyCode(r),o=this.account();o.total=this.safeString(i,"avail"),o.used=this.safeString(i,"im"),void 0!==a&&(t[a]=o)}return this.safeBalance(t)}for(let i=0;i<e.length;i++){let s=this.safeDict(e,i,{}),r=this.safeValue(s,"balances");for(let e=0;e<r.length;e++){let i=this.safeDict(r,e),s=this.safeString(i,"currency"),a=this.safeCurrencyCode(s),o=this.account();o.free=this.safeString(i,"available"),o.used=this.safeString(i,"hold"),void 0!==a&&(t[a]=o)}}return this.safeBalance(t)}async fetchBalance(e={}){await this.loadMarkets();let[t,i]=this.handleMarketTypeAndParams("fetchBalance",void 0,e);if("spot"!==t){let e=await this.swapPrivateGetV3AccountBalance(i),t=this.safeDict(e,"data",{});return this.parseBalance(t)}let s=await this.privateGetAccountsBalances(this.extend({accountType:"SPOT"},i));return this.parseBalance(s)}async fetchTradingFees(e={}){await this.loadMarkets();let t=await this.privateGetFeeinfo(e),i={},s=this.symbols;for(let e=0;e<s.length;e++){let r=s[e];i[r]={info:t,symbol:r,maker:this.safeNumber(t,"makerRate"),taker:this.safeNumber(t,"takerRate"),percentage:!0,tierBased:!0}}return i}async fetchOrderBook(e,t,i={}){await this.loadMarkets();let s=this.market(e),r={symbol:s.id};if(void 0!==t&&(r.limit=t,!0===s.contract&&(r.limit=this.findNearestCeiling([5,10,20,100,150],t))),!0===s.contract){let t=await this.swapPublicGetV3MarketOrderBook(this.extend(r,i)),s=this.safeDict(t,"data",{}),a=this.safeInteger(s,"ts");return this.parseOrderBook(s,e,a)}let a=await this.publicGetMarketsSymbolOrderBook(this.extend(r,i)),o=this.safeInteger(a,"time"),n=this.safeValue(a,"asks"),d=this.safeValue(a,"bids"),h=[],c=[];for(let e=0;e<n.length;e++)if(e%2<1){let t=this.safeNumber(n,e),i=this.safeNumber(n,this.sum(e,1));h.push([t,i])}for(let e=0;e<d.length;e++)if(e%2<1){let t=this.safeNumber(d,e),i=this.safeNumber(d,this.sum(e,1));c.push([t,i])}return{symbol:s.symbol,bids:this.sortBy(c,0,!0),asks:this.sortBy(h,0),timestamp:o,datetime:this.iso8601(o),nonce:void 0}}async createDepositAddress(e,t={}){await this.loadMarkets();let[i,s,r,a]=this.prepareRequestForDepositAddress(e,t),o=await this.privatePostWalletsAddress(this.extend(i,s));return this.parseDepositAddressSpecial(o,r,a)}async fetchDepositAddress(e,t={}){await this.loadMarkets();let[i,s,r,o]=this.prepareRequestForDepositAddress(e,t),n=await this.privateGetWalletsAddresses(this.extend(i,s));if(Object.keys(n).length<1)throw new a.ExchangeError(this.id+' fetchDepositAddress() returned an empty response, you might need to try "createDepositAddress" at first and then use "fetchDepositAddress"');return this.parseDepositAddressSpecial(n,r,o)}prepareRequestForDepositAddress(e,t={}){let i,s;if(!(e in this.currencies))throw new a.BadSymbol(this.id+" fetchDepositAddress(): can not recognize "+e+' currency, you might try using unified currency-code and add provide specific "network" parameter, like: fetchDepositAddress("USDT", { "network": "TRC20" })');let r=this.currency(e);if([i,s]=this.handleNetworkCodeAndParams(t),void 0===i)throw new a.ArgumentsRequired(this.id+" fetchDepositAddress requires a network parameter for "+e+".");let o=void 0===(i=this.networkIdToCode(i,e))?void 0:this.safeDict(r.networks,i);return[{currency:void 0!==o?o.id:i},s,r,o]}parseDepositAddressSpecial(e,t,i){let s,r=this.safeString(e,"address");if(void 0===r&&(r=this.safeString(e,i.id)),this.checkAddress(r),void 0!==i){let e=this.safeString(i.info,"depositAddress");void 0!==e&&(s=r,r=e)}return{info:e,currency:t.code,network:this.safeString(i,"network"),address:r,tag:s}}async transfer(e,t,i,s,r={}){await this.loadMarkets();let a=this.currency(e),o=this.safeDict(this.options,"accountsByType",{}),n=this.safeString(o,i,i),d=this.safeString(o,s,i),h={amount:this.currencyToPrecision(e,t),currency:a.id,fromAccount:n,toAccount:d},c=await this.privatePostAccountsTransfer(this.extend(h,r));return this.parseTransfer(c,a)}parseTransfer(e,t){return{info:e,id:this.safeString(e,"transferId"),timestamp:void 0,datetime:void 0,currency:this.safeString(t,"id"),amount:void 0,fromAccount:void 0,toAccount:void 0,status:void 0}}async withdraw(e,t,i,s,r={}){let[o,n]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i);let d=this.currency(e),h={coin:d.id,amount:this.currencyToPrecision(e,t),address:i},[c,l]=this.handleNetworkCodeAndParams(n);if(void 0===c)throw new a.ArgumentsRequired(this.id+" withdraw requires a network parameter for "+e+".");h.network=this.networkCodeToId(c,e),void 0!==o&&(h.paymentId=o);let u=await this.privatePostV2WalletsWithdraw(this.extend(h,l));return this.parseTransaction(u,d)}async fetchTransactionsHelper(e,t,i,s={}){await this.loadMarkets();let r=this.seconds(),a=void 0!==t?this.parseToInt(t/1e3):r-31104e4;return await this.privateGetWalletsActivity(this.extend({start:a,end:r},s))}async fetchDepositsWithdrawals(e,t,i,s={}){let r;await this.loadMarkets();let a=await this.fetchTransactionsHelper(e,t,i,s);void 0!==e&&(r=this.currency(e));let o=this.safeList(a,"withdrawals",[]),n=this.safeList(a,"deposits",[]),d=this.parseTransactions(o,r,t,i),h=this.parseTransactions(n,r,t,i),c=this.arrayConcat(h,d);return this.filterByCurrencySinceLimit(this.sortBy(c,"timestamp"),e,t,i)}async fetchWithdrawals(e,t,i,s={}){let r,a=await this.fetchTransactionsHelper(e,t,i,s);void 0!==e&&(r=this.currency(e));let o=this.safeList(a,"withdrawals",[]),n=this.parseTransactions(o,r,t,i);return this.filterByCurrencySinceLimit(n,e,t,i)}async fetchDepositWithdrawFees(e,t={}){await this.loadMarkets();let i=await this.publicGetCurrencies(this.extend(t,{includeMultiChainCurrencies:!0})),s={},r=[];Array.isArray(i)&&(r=i);for(let e=0;e<r.length;e++){let t=r[e],i=Object.keys(t),a=this.safeString(i,0);s[a]=t[a]}return this.parseDepositWithdrawFees(s,e)}parseDepositWithdrawFees(e,t,i){let s={},r=this.marketCodes(t),a=Object.keys(e);for(let t=0;t<a.length;t++){let i=a[t],o=this.safeCurrencyCode(i),n=e[i];if(void 0!==o&&(void 0===r||this.inArray(o,r))){let t=this.currency(o);s[o]=this.parseDepositWithdrawFee(n,t);let i=this.safeValue(n,"childChains");if(i.length>0)for(let r=0;r<i.length;r++){let a=i[r];a=a.replace(o,"");let n=this.networkIdToCode(a,this.safeString(t,"code")),d=this.safeDict(e,a),h={},c=this.safeNumber(d,"withdrawalFee");void 0!==n&&(h[n]={withdraw:{fee:c,percentage:void 0===c&&void 0},deposit:{fee:void 0,percentage:void 0}}),s[o].networks=this.extend(s[o].networks,h)}}}return s}parseDepositWithdrawFee(e,t){let i=this.depositWithdrawFee({}),s=this.safeString(t,"code");i.info[s]=e;let r=this.safeString(e,"blockchain"),a=this.safeNumber(e,"withdrawalFee"),o={fee:a,percentage:void 0===a&&void 0},n={fee:void 0,percentage:void 0};i.withdraw=o,i.deposit=n;let d=this.networkIdToCode(r,this.safeString(t,"code"));return void 0!==d&&(i.networks[d]={withdraw:o,deposit:n}),i}async fetchDeposits(e,t,i,s={}){let r,a=await this.fetchTransactionsHelper(e,t,i,s);void 0!==e&&(r=this.currency(e));let o=this.safeList(a,"deposits",[]),n=this.parseTransactions(o,r,t,i);return this.filterByCurrencySinceLimit(n,e,t,i)}parseTransactionStatus(e){return this.safeString({COMPLETE:"ok",COMPLETED:"ok","AWAITING APPROVAL":"pending",AWAITING_APPROVAL:"pending",PENDING:"pending",PROCESSING:"pending","COMPLETE ERROR":"failed",COMPLETE_ERROR:"failed"},e,e)}parseTransaction(e,t){let i=e;"withdrawNetworkEntry"in e&&(i=e.response);let s=this.safeTimestamp(i,"timestamp"),r=this.safeString(i,"currency"),a=this.safeCurrencyCode(r),n=this.safeString(i,"status","pending");n=this.parseTransactionStatus(n);let d=this.safeString(i,"txid"),h="deposit";"withdrawalRequestsId"in i&&(h="withdrawal");let c=this.safeString2(i,"withdrawalRequestsId","depositNumber"),l=this.safeString(i,"address"),u=this.safeString(i,"paymentID"),f=this.safeString(i,"amount"),p=this.safeString(i,"fee");return"withdrawal"===h&&(f=o.Y.stringSub(f,p)),{info:i,id:c,currency:a,amount:this.parseNumber(f),network:void 0,address:l,addressTo:void 0,addressFrom:void 0,tag:u,tagTo:void 0,tagFrom:void 0,status:n,type:h,updated:void 0,txid:d,timestamp:s,datetime:this.iso8601(s),comment:void 0,internal:void 0,fee:{currency:a,cost:this.parseNumber(p),rate:void 0}}}async setLeverage(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" setLeverage() requires a symbol argument");await this.loadMarkets();let s=this.market(t),[r,o]=this.handleMarginModeAndParams("setLeverage",i);if(void 0===r)throw new a.ArgumentsRequired(this.id+' setLeverage() requires a marginMode parameter "cross" or "isolated"');let[n,d]=this.handleParamBool(o,"hedged",!1);if(!0===n&&!("posSide"in d))throw new a.ArgumentsRequired(this.id+' setLeverage() requires a posSide parameter for hedged mode: "LONG" or "SHORT"');let h={lever:e,mgnMode:r.toUpperCase(),symbol:s.id};return await this.swapPrivatePostV3PositionLeverage(this.extend(h,d))}async fetchLeverage(e,t={}){await this.loadMarkets();let i=this.market(e),s={symbol:i.id},[r,o]=this.handleMarginModeAndParams("fetchLeverage",t);if(void 0===r)throw new a.ArgumentsRequired(this.id+' fetchLeverage() requires a marginMode parameter "cross" or "isolated"');s.mgnMode=r.toUpperCase();let n=await this.swapPrivateGetV3PositionLeverages(this.extend(s,o));return this.parseLeverage(n,i)}parseLeverage(e,t){let i,s,r,a,o=this.safeList(e,"data",[]);for(let e=0;e<o.length;e++){let t=this.safeDict(o,e);r=this.safeString(t,"symbol"),a=this.safeStringLower(t,"mgnMode");let n=this.safeInteger(t,"lever"),d=this.safeString(t,"posSide");"LONG"===d?s=n:("SHORT"===d||(s=n),i=n)}return{info:e,symbol:this.safeSymbol(r,t),marginMode:a,longLeverage:s,shortLeverage:i}}async fetchPositionMode(e,t={}){let i=await this.swapPrivateGetV3PositionMode(t),s=this.safeDict(i,"data",{});return{info:i,hedged:"HEDGE"===this.safeString(s,"posMode")}}async setPositionMode(e,t,i={}){let s="ONE_WAY";e&&(s="HEDGE");let r={posMode:s};return await this.swapPrivatePostV3PositionMode(this.extend(r,i))}async fetchPositions(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e),s=await this.swapPrivateGetV3TradePositionOpens(t),r=this.safeList(s,"data",[]);return this.parsePositions(r,i)}parsePosition(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeInteger(e,"cTime"),a=this.safeStringLower(e,"mgnMode"),n=this.safeString(e,"lever"),d=this.safeString(e,"im"),h=o.Y.stringMul(n,d),c=this.safeString(e,"qty"),l=this.safeString(e,"openAvgPx"),u=o.Y.stringMul(c,l);return this.safePosition({info:e,id:void 0,symbol:s.symbol,notional:h,marginMode:a,liquidationPrice:this.safeNumber(e,"liqPx"),entryPrice:this.safeNumber(e,"openAvgPx"),unrealizedPnl:this.safeNumber(e,"upl"),percentage:void 0,contracts:this.safeNumber(e,"qty"),contractSize:void 0,markPrice:this.safeNumber(e,"markPx"),lastPrice:void 0,side:this.safeStringLower(e,"posSide"),hedged:void 0,timestamp:r,datetime:this.iso8601(r),lastUpdateTimestamp:void 0,maintenanceMargin:this.safeNumber(e,"mm"),maintenanceMarginPercentage:void 0,collateral:u,initialMargin:d,initialMarginPercentage:void 0,leverage:parseInt(n),marginRatio:this.safeNumber(e,"mgnRatio"),stopLossPrice:this.safeNumber(e,"slTrgPx"),takeProfitPrice:this.safeNumber(e,"tpTrgPx")})}async modifyMarginHelper(e,t,i,s={}){await this.loadMarkets();let r=this.market(e),a=this.amountToPrecision(e,t),n={symbol:r.id,amt:o.Y.stringAbs(a),type:i.toUpperCase()};"posMode"in s||(n.posMode="BOTH");let d=await this.swapPrivatePostV3TradePositionMargin(this.extend(n,s));"reduce"===i&&(a=o.Y.stringAbs(a));let h=this.safeDict(d,"data");return this.parseMarginModification(h,r)}parseMarginModification(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeString(e,"type");return{info:e,symbol:s.symbol,type:"ADD"===r?"add":"reduce",marginMode:void 0,amount:this.safeNumber(e,"amt"),total:void 0,code:void 0,status:"ok",timestamp:void 0,datetime:void 0}}async reduceMargin(e,t,i={}){return await this.modifyMarginHelper(e,-t,"reduce",i)}async addMargin(e,t,i={}){return await this.modifyMarginHelper(e,t,"add",i)}nonce(){return this.milliseconds()}sign(e,t="public",i="GET",r={},a,o){let n,d,h=this.urls.api.spot;this.inArray(t,["swapPublic","swapPrivate"])&&(h=this.urls.api.swap),"GET"===i&&"symbol"in r&&(r.symbol=this.encodeURIComponent(r.symbol));let c=this.omit(r,this.extractParams(e)),l=this.implodeParams(e,r);if("public"===t||"swapPublic"===t)h+="/"+l,Object.keys(c).length>0&&(h+="?"+this.urlencode(c));else{this.checkRequiredCredentials();let e=this.nonce().toString(),t=i+"\n";if(h+="/"+l,t+="/"+l,"POST"===i||"PUT"===i||"DELETE"===i)t+="\n",Object.keys(c).length>0&&(t+="requestBody="+(n=this.json(c))+"&"),t+="signTimestamp="+e;else{let i=this.extend({signTimestamp:e},c);i=this.keysort(i),t+="\n"+this.urlencode(i),Object.keys(c).length>0&&(h+="?"+this.urlencode(c))}let r=this.hmac(this.encode(t),this.encode(this.secret),s.sc,"base64");d={"Content-Type":"application/json",key:this.apiKey,signTimestamp:e,signature:r}}return{url:h,method:i,body:void 0===n?o:n,headers:void 0===d?a:d}}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeString(n,"code");if(void 0!==c&&"200"!==c){let e=this.safeString2(n,"message","msg"),t=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,c,t),this.throwBroadlyMatchedException(this.exceptions.broad,e,t),new a.ExchangeError(t)}}}i.d(t,{A:()=>n})},1538(e,t,i){"use strict";var s=i(4015),r=i(7749),a=i(4721),o=i(1453);class n extends s.A{describe(){return this.deepExtend(super.describe(),{id:"binance",name:"Binance",countries:[],rateLimit:5,version:"v1",certified:!1,pro:!1,has:{CORS:void 0,spot:!1,margin:!1,swap:!1,future:!1,option:!1,cancelOrder:!0,cancelOrders:!0,createMarketOrderWithCost:!0,createOrder:!0,fetchBalance:!0,fetchEvent:!0,fetchEvents:!0,fetchMarkets:!0,fetchMyTrades:!0,fetchOpenOrders:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPosition:!0,fetchPositions:!0,fetchTicker:!0,fetchTickers:!0,prediction:!0},urls:{logo:"https://github.com/user-attachments/assets/e9419b93-ccb0-46aa-9bff-c883f096274b",api:{sapi:"https://api.binance.com/sapi/v1/w3w/wallet/prediction"},www:"https://www.binance.com/en/markets/prediction",doc:["https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading"]},api:{sapi:{private:{get:{"category/list":{cost:200},"market/list":{cost:200},"market/search":{cost:200},"market/detail":{cost:200},"order-book":{cost:200},"order-book/last-trade-price":{cost:200},"wallet/list":{cost:200},"balance/payment-options":{cost:200},"quota/limit/status":{cost:200},"pnl/portfolio":{cost:200},"pnl/query":{cost:200},"position/list":{cost:200},"position/filter":{cost:200},"position/token":{cost:200},"position/settled-history":{cost:200},"order/list":{cost:200},"order/history":{cost:200}},post:{"trade/get-quote":{cost:200},"trade/place-order-bundle":{cost:200},"trade/batch-cancel":{cost:200}}}}},requiredCredentials:{apiKey:!0,secret:!0},fees:{trading:{tierBased:!1,percentage:!0,maker:0,taker:.02}},exceptions:{exact:{"-1003":o.RateLimitExceeded,"-1021":o.InvalidNonce,"-1022":o.AuthenticationError,"-1102":o.BadRequest,"-1121":o.BadSymbol,"-2008":o.AuthenticationError,"-2014":o.AuthenticationError,"-2015":o.PermissionDenied,"-2010":o.InsufficientFunds},broad:{"insufficient balance":o.InsufficientFunds,"Order does not exist":o.InvalidOrder}},options:{defaultVendor:"PREDICT_FUN",fetchOutcomeSearchLimit:10,maxFetchEventsResults:25,marketsPageLimit:100,maxFetchMarketsLimit:200,loadAllOutcomes:!1,allowUnscopedFetchEvents:!0,eventScopeParams:["l1Category","l2Category"]}})}nonce(){return this.milliseconds()}async fetchMarkets(e={}){if(this.parseSearchQueries(e).length>0){let t=this.omit(e,["limit"]),i=await this.fetchEvents(t),s=i.length,r=[];for(let e=0;e<s;e++){let t=this.safeList(i[e],"markets",[]),s=t.length;for(let e=0;e<s;e++)r.push(t[e])}return r}let t=this.safeInteger(e,"limit",this.safeInteger(this.options,"maxFetchMarketsLimit",200)),i=this.omit(e,["query","queries","limit"]),s=await this.fetchRawTopics(t,i),r=[],a=[],o=s.length;for(let e=0;e<o;e++){let t=this.parseEvent(s[e]);r.push(t);let i=this.safeList(t,"markets",[]),o=i.length;for(let e=0;e<o;e++)a.push(i[e])}return this.setEvents(r),a}async fetchRawTopics(e,t={}){let i=void 0===e?this.safeInteger(this.options,"maxFetchMarketsLimit",200):e,s=this.safeInteger(this.options,"marketsPageLimit",100);s>100&&(s=100);let r=[],a=0;for(;;){let e=s,o=i-r.length;if(o<e&&(e=o),e<=0)break;let n={offset:a,limit:e},d=await this.sapiPrivateGetMarketList(this.extend(n,t)),h=this.safeList(d,"marketTopics",[]),c=h.length;for(let e=0;e<c;e++)r.push(h[e]);if(!0!==this.safeBool(d,"hasMore",!1)||c<e)break;a=this.sum(a,c)}return r}async fetchRawTopicDetail(e,t={}){return await this.sapiPrivateGetMarketDetail(this.extend({marketTopicId:e},t))}async completeRawTopics(e){let t=[],i=e.length;for(let s=0;s<i;s++){let i=e[s],r=this.safeList(i,"markets",[]),a=r.length,o=!1;if(a>0){let e=this.safeDict(r,0,{});o=this.safeList(e,"outcomes",[]).length>0}if(o)t.push(i);else{let e=this.safeString(i,"marketTopicId");if(void 0!==e){let i=await this.fetchRawTopicDetail(e);t.push(i)}}}return t}async fetchEvents(e={}){!0!==this.safeBool(this.options,"allowUnscopedFetchEvents",!1)&&this.requireEventQuery(e);let t=this.parseSearchQueries(e),i=this.safeList(e,"tags",[]),s=i.length,r=[];for(let e=0;e<t.length;e++)r.push(t[e]);for(let e=0;e<s;e++)r.push(i[e]);let a=r.length,o=this.omit(e,["query","queries"]),n=["tags","l1Category","l2Category"],d=this.safeInteger(o,"limit"),h=this.safeInteger(this.options,"maxFetchEventsResults",100);void 0!==d&&(h=d);let c=this.omit(o,["status","limit","sort","searchIn","eventId","slug","tags","l1Category","l2Category"]),l=this.safeString(o,"eventId"),u=this.safeString(o,"l1Category"),f=this.safeString(o,"l2Category");void 0===this.markets&&(this.markets=this.createSafeDictionary());let p=[];if(a>0)p=await this.fetchEventsByQuery(r,h,c);else if(void 0!==l)p=[await this.fetchRawTopicDetail(l,c)];else{let e={};void 0!==u&&(e.l1Category=u),void 0!==f&&(e.l2Category=f);let t=this.safeStringUpper2(o,"sortBy","sort");void 0!==t&&("NEWEST"===t?t="CREATED_TIME":"LIQUIDITY"===t&&(t=void 0),void 0!==t&&(e.sortBy=t,n.push("sort"),n.push("sortBy")));let i=await this.fetchRawTopics(h,this.extend(e,c));p=await this.completeRawTopics(i)}let m=p.length,g=[];for(let e=0;e<m;e++){let t=this.parseEvent(p[e]);g.push(t);let i=this.safeList(t,"markets",[]),s=i.length;for(let e=0;e<s;e++){let t=i[e],s=this.safeString(t,"market");void 0!==s&&(this.markets[s]=t)}}this.populateOutcomes();let v=this.omit(o,n);return this.applyEventFetchParams(g,v,[])}async fetchEventsByQuery(e,t,i={}){let s={},r=[],a=e.length,o=t;void 0===t?o=20:t>50&&(o=50);for(let t=0;t<a;t++){let a={query:e[t]};a.topK=o;let n=await this.sapiPrivateGetMarketSearch(this.extend(a,i)),d=n.length;for(let e=0;e<d;e++){let t=this.safeDict(n,e),i=this.safeString(t,"marketTopicId");void 0!==i&&void 0===this.safeString(s,i)&&(s[i]=i,r.push(t))}}let n=r,d=r.length;return void 0!==o&&d>o&&(n=this.arraySlice(r,0,o)),await this.completeRawTopics(n)}async fetchEvent(e,t={}){let i=await this.fetchEvents(this.extend({eventId:e},t));return this.safeDict(i,0)}parseEvent(e){let t,i=this.safeList(e,"markets",[]),s=[],r=!1,a=i.length;for(let t=0;t<a;t++){let a=this.parseTopicMarket(i[t],e);s.push(a),this.safeBool(a,"active",!1)&&(r=!0)}let o=this.safeString(e,"marketTopicId"),n=this.safeString(e,"slug"),d=this.safeString(e,"title"),h=this.safeInteger(e,"endDate"),c=this.safeInteger2(e,"publishedAt","startDate"),l=this.safeString(e,"status"),u=r;return 0===a&&(u="REGISTERED"===l||"OPEN"===l),void 0!==l&&(t="RESOLVED"===l||"SETTLED"===l),{id:o,slug:n,event:void 0!==n?this.shortenSlug(n):void 0,title:d,description:this.safeString(e,"description"),markets:s,active:u,volume:this.safeNumber(e,"tradeVolume"),liquidity:this.safeNumber(e,"liquidity"),url:void 0,image:this.safeString(e,"imageUrl"),created:c,createdDatetime:this.iso8601(c),end:h,endDatetime:this.iso8601(h),category:this.safeString(e,"chartType"),resolved:t,info:e}}parseTopicMarket(e,t){let i,s=this.safeString(e,"marketId"),a=this.safeString(t,"marketTopicId"),o=this.safeString(t,"slug"),n=this.safeString(t,"vendor"),d=this.safeString(t,"collateral","USDT"),h=this.safeString(e,"title",s),c=this.slugToMarketSymbol(o,h),l=this.safeString(e,"tradingStatus"),u=this.safeString(e,"status"),f="OPEN"===l;void 0===l&&(f="REGISTERED"===u||"OPEN"===u);let p="RESOLVED"===u||"SETTLED"===u,m=this.safeInteger(t,"endDate"),g=this.safeString(t,"feeRateBps","200"),v=this.parseNumber(r.Y.stringDiv(g,"10000")),y=this.safeString(e,"decimalPrecision","2"),b={amount:.01,price:this.parseNumber(this.parsePrecision(y))},w=this.safeNumber(e,"tradeVolume"),k=this.safeNumber(e,"liquidity"),S=this.safeList(e,"outcomes",[]),O=[],T=S.length;for(let l=0;l<T;l++){let u,m,v=this.safeDict(S,l),y=this.safeStringUpper(v,"name"),w=this.safeString(v,"tokenId"),k=c+":"+y,T=this.safeString(v,"price");p&&void 0!==T&&(m=+!!(u=r.Y.stringEq(T,"1")),u&&(i=k));let P=u,I=m;O.push({id:w,outcomeId:w,outcome:k,market:c,label:y,price:this.parseNumber(T),active:f,winner:P,settleFraction:I,precision:b,info:{tokenId:w,marketId:s,marketTopicId:a,vendor:n,chainId:this.safeString(t,"chainId"),slug:o,marketTitle:h,outcomeLabel:y,index:this.safeString(v,"index"),price:T,chance:this.safeString(v,"chance"),collateral:d,feeRateBps:g,slippageBps:this.safeString(t,"slippageBps"),conditionId:this.safeString(e,"conditionId"),externalId:this.safeString(e,"externalId")}})}return{id:s,market:c,base:d,quote:d,settle:void 0,baseId:s,quoteId:d,settleId:void 0,type:"prediction",marketType:"binary",executionModel:"clob",collateral:d,spot:!1,margin:!1,swap:!1,future:!1,option:!1,prediction:!0,active:f,resolved:p,resolvedOutcome:i,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:m,expiryDatetime:this.iso8601(m),strike:void 0,optionType:void 0,taker:v,maker:0,percentage:!0,tierBased:!1,feeSide:"get",precision:b,limits:{leverage:{min:1,max:1},amount:{min:void 0,max:void 0},price:{min:.01,max:.99},cost:{min:1.5,max:void 0}},outcomes:O,info:this.extend(e,{marketTopicId:a,vendor:n,slug:o,volume:w,liquidity:k}),created:this.safeInteger(t,"publishedAt")}}async fetchTicker(e,t={}){await this.loadOutcome(e);let i=this.outcome(e),s=this.safeDict(i,"info",{}),r={marketId:this.safeString(s,"marketId")},a=await this.sapiPrivateGetOrderBookLastTradePrice(this.extend(r,t));return this.parsePredictionTicker(a,i)}parsePredictionTicker(e,t){let i,s=this.safeOutcome(this.safeString(t,"outcome"),t),a=this.safeDict(s,"info",{}),o=this.safeString(a,"index"),n=!1;if(void 0!==o)n="0"!==o;else{let e=this.safeStringUpper(s,"label","YES");n="NO"===e||"DOWN"===e}let d=this.safeString(e,"lastTradePrice");return void 0!==d&&(i=n?this.parseNumber(r.Y.stringSub("1",d)):this.parseNumber(d)),this.safePredictionTicker({outcome:this.safeString(s,"outcome"),outcomeId:this.safeString2(s,"outcomeId","id"),label:this.safeString(s,"label"),market:this.safeString(s,"market"),timestamp:void 0,datetime:void 0,high:void 0,low:void 0,bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:void 0,close:i,last:i,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:void 0,quoteVolume:void 0,info:e},t)}async fetchTickers(e,t={}){if(void 0===e)throw new o.ArgumentsRequired(this.id+" fetchTickers() requires an outcomes argument — the venue has no all-tickers endpoint; pass the outcome handles to fetch (discover them via fetchEvents ())");await this.loadOutcomes(e);let i={},s={},r=e.length;for(let a=0;a<r;a++){let r=this.outcome(e[a]),o=this.safeDict(r,"info",{}),n=this.safeString(o,"marketId");if(void 0===n)continue;let d=this.safeDict(i,n);if(void 0===d){let e={marketId:n};d=await this.sapiPrivateGetOrderBookLastTradePrice(this.extend(e,t)),i[n]=d}let h=this.parsePredictionTicker(d,r);s[this.safeString(h,"outcome",e[a])]=h}return s}async fetchOrderBook(e,t,i={}){await this.loadOutcome(e);let s=this.outcome(e),r=this.safeDict(s,"info",{}),a={vendor:this.safeString(r,"vendor",this.safeString(this.options,"defaultVendor")),marketId:this.safeString(r,"marketId"),tokenId:this.safeString2(s,"outcomeId","id")},o=await this.sapiPrivateGetOrderBook(this.extend(a,i)),n=this.safeInteger(o,"timestamp"),d=this.parseOrderBook(o,this.safeOutcomeSymbol(e,s),n,"bids","asks","price","size");return this.safePredictionOrderBook(d,s)}async fetchBalance(e={}){let[t,i]=this.handleOptionStringAndParams(e,"fetchBalance","type","SPOT"),s=await this.sapiPrivateGetBalancePaymentOptions(i),r={info:s},a=this.safeList(s,"items",[]);for(let e=0;e<a.length;e++){let i=this.safeDict(a,e);if(this.safeString(i,"accountType")===t){let e=this.safeString(i,"availableBalanceDisplay"),t=this.account();t.free=e,r.USDT=t}}return this.safeBalance(r)}parsePredictionOrder(e,t){let i=this.parseOrderStatus(this.safeString(e,"status")),s=t;if(void 0===s){let t=this.safeString(e,"marketId"),i=this.safeStringUpper(e,"outcome"),r=this.safeMarket(t),a=this.safeString(r,"market");void 0===a&&(a=t),a+=":"+i,s=this.safeOutcome(a)}let r=this.safeStringLower(e,"side"),a=this.safeInteger(e,"createTime");return this.safePredictionOrder({id:this.safeString(e,"orderId"),clientOrderId:void 0,info:e,timestamp:a,datetime:this.iso8601(a),lastTradeTimestamp:void 0,status:i,outcome:this.safeString(s,"outcome"),outcomeId:this.safeString(s,"id"),label:this.safeString(s,"label"),market:this.safeString(s,"market"),type:this.safeStringLower(e,"orderType"),timeInForce:void 0,postOnly:void 0,reduceOnly:void 0,side:r,price:this.safeNumber(e,"price"),triggerPrice:void 0,amount:void 0,cost:void 0,average:void 0,filled:void 0,remaining:void 0,fee:void 0,trades:[]},s)}parseOrderStatus(e){if(void 0!==e)return e.endsWith("Rejected")?"rejected":e.endsWith("Canceled")?"canceled":this.safeString({OPENING:"open",FILLED:"closed"},e,e)}async fetchOpenOrders(e,t,i,s={}){let r,a=!1,o={};[a,o]=this.handleOptionBoolAndParams(s,"fetchOpenOrders","paginate",!1);let[n,d]=this.handleOptionIntegerAndParams(o,"fetchOpenOrders","maxEntriesPerRequest",100),h="ccxtPageKey";if(a)return await this.fetchPaginatedCallIncremental("fetchOpenOrders",e,t,i,d,h,n);let c=this.safeInteger(d,h,1)-1,l={},u=this.safeInteger(d,"offset",c*n);u>0&&(l.offset=u),void 0!==e&&(await this.loadOutcome(e),r=this.outcome(e),l.marketId=this.market(r.market).id),void 0!==i&&(l.limit=i),l.walletAddress=(await this.fetchWallet("fetchOpenOrders",d)).walletAddress;let f=await this.sapiPrivateGetOrderList(this.extend(l,d)),p=this.safeList(f,"orders",[]),m=this.parsePredictionOrders(p,r,t);return this.filterByOutcomeSinceLimit(m,e,t,i)}async fetchOrders(e,t,i,s={}){let r,a=!1,o={};[a,o]=this.handleOptionBoolAndParams(s,"fetchOrders","paginate",!1);let[n,d]=this.handleOptionIntegerAndParams(o,"fetchOrders","maxEntriesPerRequest",100),h="ccxtPageKey";if(a)return await this.fetchPaginatedCallIncremental("fetchOrders",e,t,i,d,h,n);let c=this.safeInteger(d,h,1)-1,l={},u=this.safeInteger(d,"offset",c*n);u>0&&(l.offset=u),void 0!==e&&(await this.loadOutcome(e),r=this.outcome(e)),void 0!==i&&(l.limit=i),void 0!==t&&(l.startDate=this.yyyymmdd(t));let f=this.safeInteger(d,"until"),p=this.omit(d,"until");void 0!==f&&(l.endDate=this.yyyymmdd(f)),l.walletAddress=(await this.fetchWallet("fetchOrders",p)).walletAddress;let m=await this.sapiPrivateGetOrderHistory(this.extend(l,p)),g=this.safeList(m,"orders",[]),v=this.parsePredictionOrders(g,r,t);return this.filterByOutcomeSinceLimit(v,e,t,i)}async fetchPositions(e,t={}){await this.loadOutcomes();let i={};if(void 0!==e)for(let t=0;t<e.length;t++){let s=e[t],r=this.safeOutcome(s);i[this.safeString(r,"outcome",s)]=!0}let s={walletAddress:(await this.fetchWallet("fetchPositions",t)).walletAddress},r=await this.sapiPrivateGetPositionList(this.extend(s,t)),a=this.safeList(r,"positions",[]),o=this.parsePredictionPositions(a);if(void 0===e)return o;let n=[],d=o.length;for(let e=0;e<d;e++){let t=o[e],s=this.safeString(t,"outcome");void 0!==s&&s in i&&n.push(t)}return n}async fetchPosition(e,t={}){let i,s={};void 0!==e&&(await this.loadOutcome(e),i=this.outcome(e),s.marketTopicId=this.market(i.market).info.marketTopicId),s.walletAddress=(await this.fetchWallet("fetchOrders",t)).walletAddress;let r=await this.sapiPrivateGetPositionFilter(this.extend(s,t)),a=this.safeList(r,"positions",[]),o=this.parsePredictionPositions(a),n=this.filterByOutcomeSinceLimit(o,e,void 0,void 0);return this.safeDict(n,0)}parsePredictionPosition(e,t){let i=t;if(void 0===i){let t=this.safeString(e,"marketId"),s=this.safeStringUpper(e,"outcomeName"),r=this.safeMarket(t),a=this.safeString(r,"market");void 0===a&&(a=t),a+=":"+s,i=this.safeOutcome(a)}let s=this.safeInteger(e,"createdTime"),r=this.parseNumber(this.safeString(e,"totalCost"));return this.safePredictionPosition({id:this.safeInteger(e,"positionId"),outcome:this.safeString(i,"outcome"),outcomeId:this.safeString2(i,"outcomeId","id"),market:this.safeString(i,"market"),timestamp:s,datetime:this.iso8601(s),isolated:!1,hedged:void 0,side:"long",contracts:void 0,contractSize:this.parseNumber(this.safeString(e,"shares")),entryPrice:this.parseNumber(this.safeString(e,"avgPrice")),markPrice:void 0,notional:this.parseNumber(this.safeString(e,"value")),leverage:void 0,collateral:r,initialMargin:r,maintenanceMargin:void 0,initialMarginPercentage:void 0,maintenanceMarginPercentage:void 0,unrealizedPnl:this.parseNumber(this.safeString(e,"unrealizedPnl")),realizedPnl:this.parseNumber(this.safeString(e,"realizedPnl")),liquidationPrice:void 0,marginRatio:void 0,marginMode:"cross",percentage:this.parseNumber(this.safeString(e,"unrealizedPnlPercent")),info:e})}async fetchMyTrades(e,t,i,s={}){let r,a=!1,o={};[a,o]=this.handleOptionBoolAndParams(s,"fetchMyTrades","paginate",!1);let[n,d]=this.handleOptionIntegerAndParams(o,"fetchMyTrades","maxEntriesPerRequest",100),h="ccxtPageKey";if(a)return await this.fetchPaginatedCallIncremental("fetchMyTrades",e,t,i,d,h,n);let c=this.safeInteger(d,h,1)-1,l={status:"FILLED"},u=this.safeInteger(d,"offset",c*n);u>0&&(l.offset=u),void 0!==e&&(await this.loadOutcome(e),r=this.outcome(e)),void 0!==i&&(l.limit=i),void 0!==t&&(l.startDate=this.yyyymmdd(t));let f=this.safeInteger(d,"until"),p=this.omit(d,"until");void 0!==f&&(l.endDate=this.yyyymmdd(f)),l.walletAddress=(await this.fetchWallet("fetchMyTrades",p)).walletAddress;let m=await this.sapiPrivateGetOrderHistory(this.extend(l,p)),g=this.safeList(m,"orders",[]),v=this.parsePredictionTrades(g,r);return this.filterByOutcomeSinceLimit(v,e,t,i)}parsePredictionTrade(e,t){let i,s=t;if(void 0===s){let t=this.safeString(e,"marketId"),i=this.safeStringUpper(e,"outcome"),r=this.safeMarket(t),a=this.safeString(r,"market");void 0===a&&(a=t),a+=":"+i,s=this.safeOutcome(a)}let a=this.safeInteger(e,"createTime"),o=this.safeString(e,"filledShareQty"),n=this.safeString(e,"filledUsdtAmount"),d=this.safeString(e,"price"),h=this.safeStringLower(e,"orderType");if("market"===h&&void 0!==n&&void 0!==d&&void 0!==o){let e=r.Y.stringAbs(r.Y.stringSub(n,r.Y.stringMul(d,o)));i={currency:"USDT",cost:this.parseNumber(e)}}return this.safePredictionTrade({id:void 0,info:e,timestamp:a,datetime:this.iso8601(a),outcome:this.safeString(s,"outcome"),outcomeId:this.safeString(s,"id"),label:this.safeString(s,"label"),market:this.safeString(s,"market"),order:this.safeString(e,"orderId"),type:h,side:this.safeStringLower(e,"side"),takerOrMaker:void 0,price:d,amount:this.safeString(e,"makerShareQty"),cost:n,fee:i},s)}async fetchWallet(e,t={}){let i=this.safeDict(this.options,"wallet");if(void 0!==i)return i;let s=this.handleOptionStringAndParams(t,e,"walletAddress",this.walletAddress)[0],r=await this.sapiPrivateGetWalletList(),a=this.safeList(r,"wallets",[]);if(void 0===s)return i=this.safeDict(a,0),this.options.wallet=i,i;let n=a.length;for(let e=0;e<n;e++)if(this.safeString(a[e],"walletAddress","")===s){i=a[e];break}if(void 0===i)throw new o.NotSupported(this.id+"fetchWallet could'n find wallet "+s);return this.options.wallet=i,i}async fetchQuote(e,t={}){return await this.sapiPrivatePostTradeGetQuote(this.extend(e,t))}priceToPrecision(e,t){let i=this.market(e),s=this.safeNumber(this.safeDict(i,"precision",{}),"price",1e-4),r=4;return void 0!==s&&s>0&&(r=this.precisionFromString(this.numberToString(s))),this.decimalToPrecision(t,1,r,2,this.paddingMode)}amountToPrecision(e,t){let i=this.market(e),s=this.safeNumber(this.safeDict(i,"precision",{}),"amount",.01),r=2;return void 0!==s&&s>0&&(r=this.precisionFromString(this.numberToString(s))),this.decimalToPrecision(t,0,r,2,this.paddingMode)}async createOrder(e,t,i,s,a,n={}){await this.loadOutcome(e);let d=this.outcome(e),h=this.safeString(d,"market"),c=this.market(h),l=t.toUpperCase(),u=i.toUpperCase(),f=await this.fetchWallet("createOrder",n),p=this.safeString(this.options,"defaultSlippage","0.05"),m=this.safeString(n,"slippage",p),g=this.safeString(n,"cost"),v=this.parseToInt(r.Y.stringMul(m,"10000")),y={walletAddress:f.walletAddress,orderType:l,slippageBps:v},b=this.numberToString(s),w=this.numberToString(a),k="FOK";if("LIMIT"===l){if(void 0===a)throw new o.ArgumentsRequired(this.id+"createOrder requires price for limit order");y.priceLimit=this.priceToPrecision(h,a),k="GTC"}if("BUY"===u)if(void 0!==g)b=g;else{let e=this.safeString(n,"feeRateBps","200");if("LIMIT"===l)e="0";else if(void 0===a)throw new o.ArgumentsRequired(this.id+" createOrder requires price for "+i+" order");let t=r.Y.stringDiv(e,"10000"),s=r.Y.stringMin(w,r.Y.stringSub("1",w)),d=r.Y.stringMul(r.Y.stringMul(t,s),b);b=r.Y.stringAdd(r.Y.stringMul(b,w),d)}let S=this.safeStringUpper(n,"timeInForce",k),O=this.safeString(n,"accountType");if(void 0===O)throw new o.ArgumentsRequired(this.id+" createOrder requires accountType (SPOT, FUNDING)");let T=this.omit(n,["timeInForce","accountType","cost"]),P=this.extend(y,{tokenId:d.id,side:u,amountIn:r.Y.stringMul(this.amountToPrecision(h,b),"1000000000000000000")}),I=await this.fetchQuote(P,T),A=this.safeString(I,"quoteId"),x=this.extend(y,{walletId:f.walletId,quoteId:A,timeInForce:S,accountType:O}),M=await this.sapiPrivatePostTradePlaceOrderBundle(this.extend(x,T));return this.safePredictionOrder({id:this.safeString(M,"orderId"),clientOrderId:void 0,info:M,timestamp:void 0,datetime:void 0,status:void 0,outcome:this.safeString(d,"outcome",e),outcomeId:this.safeString(d,"id"),label:this.safeString(d,"label"),market:this.safeString(d,"market"),type:t,side:i,price:a,amount:s,filled:void 0,remaining:void 0,cost:void 0,fee:void 0,trades:[]},c)}async createMarketOrderWithCost(e,t,i,s={}){return await this.createOrder(e,"market",t,i,void 0,this.extend({cost:i},s))}async cancelOrder(e,t,i={}){let s=await this.cancelOrders([e],t,i);return this.safeDict(s,0,{})}async cancelOrders(e,t,i={}){let s;void 0!==t&&(await this.loadOutcome(t),s=this.outcome(t));let r=await this.fetchWallet("cancelOrders",i),a={walletAddress:r.walletAddress,walletId:r.walletId};for(let t=0;t<e.length;t++)a["cancelInfoList["+this.numberToString(t)+"].orderId"]=e[t];let n=await this.sapiPrivatePostTradeBatchCancel(this.extend(a,i)),d=this.safeList(n,"canceled",[]),h=this.safeString(s,"outcome",t),c=this.safeList(n,"failed",[]),l=c.length;if(l>0){let e="";for(let t=0;t<l;t++){let i=this.safeDict(c,t);t>0&&(e+=", "),e=e+this.safeString(i,"orderId")+": "+this.safeString(i,"reason")}throw new o.OrderNotFound(this.id+" cancelOrders() failed for "+e)}let u=[],f=d.length;for(let e=0;e<f;e++){let t=d[e],i={id:t,clientOrderId:void 0,info:t,status:"canceled",outcome:h,outcomeId:this.safeString(s,"id"),label:this.safeString(s,"label"),market:this.safeString(s,"market"),timestamp:void 0,datetime:void 0};u.push(this.safePredictionOrder(i))}return u}handleErrors(e,t,i,s,a,n,d,h,c){if(void 0===d)return;let l=this.safeString(d,"code");if(void 0!==l&&r.Y.stringLt(l,"0")){let e=this.safeString(d,"msg",""),t=this.id+" "+n;throw this.throwExactlyMatchedException(this.exceptions.exact,l,t),this.throwBroadlyMatchedException(this.exceptions.broad,e,t),new o.ExchangeError(t)}}sign(e,t="sapi",i="GET",s={},r,o){let n="string"==typeof t?t:t[0],d=this.urls.api,h=this.safeString(d,n,d.sapi)+"/"+this.implodeParams(e,s),c=this.omit(s,this.extractParams(e));this.checkRequiredCredentials();let l=this.extend({timestamp:this.nonce()},c),u=this.safeInteger(this.options,"recvWindow");void 0!==u&&(l.recvWindow=u);let f=this.urlencodeNested(l);f=(f=f.replaceAll("%5B","[")).replaceAll("%5D","]");let p=this.hmac(this.encode(f),this.encode(this.secret),a.sc);f=f+"&signature="+p;let m={"X-MBX-APIKEY":this.apiKey},g=o;return"GET"===i||"DELETE"===i?h=h+"?"+f:(g=f,m["Content-Type"]="application/x-www-form-urlencoded"),{url:h,method:i,body:g,headers:m}}}i.d(t,{A:()=>n})},6470(e,t,i){"use strict";var s=i(6834),r=i(6885),a=i(5087),o=i(7749),n=i(1093),d=i(1453);class h extends a.A{describe(){return this.deepExtend(super.describe(),{id:"hyperliquid",name:"Hyperliquid",countries:[],rateLimit:50,certified:!1,pro:!1,dex:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!1,future:!1,option:!1,cancelOrder:!0,cancelOrders:!0,createOrder:!0,fetchBalance:!0,fetchCurrencies:!1,fetchEvents:!0,fetchMarkets:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPositions:!0,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,prediction:!0},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","8h":"8h","12h":"12h","1d":"1d","3d":"3d","1w":"1w","1M":"1M"},urls:{logo:"https://github.com/user-attachments/assets/550769b3-d270-461e-9e02-8e8b8c0210b8",api:{public:"https://api.hyperliquid.xyz",private:"https://api.hyperliquid.xyz"},test:{public:"https://api.hyperliquid-testnet.xyz",private:"https://api.hyperliquid-testnet.xyz"},www:"https://hyperliquid.xyz",doc:"https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api",fees:"https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees",referral:"https://app.hyperliquid.xyz/"},api:{public:{post:{info:{cost:20,byType:{l2Book:2,allMids:2,spotClearinghouseState:2,candleSnapshot:4,orderStatus:2}}}},private:{post:{exchange:{cost:1}}}},requiredCredentials:{apiKey:!1,secret:!1,walletAddress:!0,privateKey:!0},fees:{trading:{tierBased:!1,percentage:!0,maker:2e-4,taker:5e-4}},options:{defaultType:"prediction",loadAllOutcomes:!0,sandboxMode:!1,outcomeQuoteCurrency:"USDH",defaultSlippage:.05,zeroAddress:"0x0000000000000000000000000000000000000000",builderFee:!0,builder:"0x6530512A6c89C7cfCEbC3BA7fcD9aDa5f30827a6",feeRate:"0%",feeInt:0},exceptions:{exact:{"Order was never placed, already canceled, or filled.":d.OrderNotFound,"Insufficient spot balance":d.InsufficientFunds,"Too many cumulative requests sent":d.RateLimitExceeded,"Order has zero size.":d.InvalidOrder,"Order has invalid size":d.InvalidOrder,"Order price cannot be more than 80% away from the reference price":d.InvalidOrder,"No liquidity available for market order.":d.InvalidOrder},broad:{Insufficient:d.InsufficientFunds}}})}setSandboxMode(e){super.setSandboxMode(e),this.options.sandboxMode=e}nonce(){return this.milliseconds()}outcomeEncoding(e,t){return this.sum(10*e,t)}outcomeAssetId(e){return this.sum(1e8,e)}outcomeCoin(e){return"#"+e.toString()}outcomeToken(e){return"+"+e.toString()}parseOutcomeDescription(e){if(void 0===e||""===e)return{};let t=e.split("|"),i={};for(let e=0;e<t.length;e++){let s=t[e],r=s.indexOf(":");if(r>-1){let e=s.slice(0,r),t=s.slice(r+1);i[e]=t}}return i}buildOutcomeSymbol(e,t,i){let s=this.safeString(e,"underlying","OUTCOME"+i.toString()),r=this.safeString(e,"targetPrice"),a=this.safeString(e,"expiry",""),o="";""!==a&&(o=a.split("-")[0]);let n="NO";0===t&&(n="YES");let d=s.toUpperCase();return void 0!==r&&""!==r&&(d=d+"_ABOVE_"+r),void 0!==o&&""!==o&&(d=d+"_"+o),d+":"+n}buildOutcomeParentSymbol(e,t,i="",s={}){let r=this.safeString(e,"underlying");if(void 0!==r&&""!==r){let t=this.safeString(e,"targetPrice"),i=this.safeString(e,"expiry",""),s="";""!==i&&(s=i.split("-")[0]);let a=r.toUpperCase();return void 0!==t&&""!==t&&(a=a+"_ABOVE_"+t),void 0!==s&&""!==s&&(a=a+"_"+s),a}let a=this.safeString(s,"description");if(void 0!==a&&""!==a){let t=this.parseOutcomeDescription(a);if("pricebucket"===this.safeStringLower(t,"class")){let s=this.safeString(t,"underlying"),r=this.safeString(t,"expiry",""),a="";""!==r&&(a=r.split("-")[0]);let o=this.safeString(t,"priceThresholds",""),n=this.safeString(e,"index"),d=this.safeStringLower(e,"description",""),h=i.toLowerCase();if(void 0!==s&&""!==s&&""!==o&&void 0!==n){let e=o.split(","),t=[];for(let i=0;i<e.length;i++){let s=e[i].trim();s.length>0&&t.push(s)}let i=t.length,r=this.parseToInt(n);if(i>0){let e;e=r<=0?"BELOW_"+t[0]:r>=i?"ABOVE_"+t[i-1]:"BETWEEN_"+t[r-1]+"_"+t[r];let o=s.toUpperCase()+"_"+e;return void 0!==a&&""!==a&&(o=o+"_"+a),o}}let c="other"===d||h.indexOf("fallback")>=0||h.indexOf("other")>=0;if(void 0!==s&&""!==s&&c){let e=s.toUpperCase()+"_OTHER";return void 0!==a&&""!==a&&(e=e+"_"+a),e}}}let o=this.safeString(s,"name");if(void 0!==o&&""!==o){let e=this.shortenSlug(o);if(void 0!==e&&""!==e){let s=this.shortenSlug(i);return(s in{RECURRING:!0,RECURRING_FALLBACK:!0,RECURRING_NAMED_OUTCOME:!0}&&(s=s.indexOf("FALLBACK")>=0?"OTHER":""),void 0!==s&&""!==s)?e+"_"+s+"_"+t.toString():e+"_"+t.toString()}}return void 0!==i&&""!==i?this.shortenSlug(i)+"_"+t.toString():"OUTCOME_"+t.toString()}async fetchMarkets(e={}){let t=await this.publicPostInfo(this.extend({type:"outcomeMeta"},e)),i=this.safeList(t,"outcomes",[]),s=this.safeList(t,"questions",[]),r={};for(let e=0;e<s.length;e++){let t=this.safeDict(s,e,{}),i=this.safeInteger(t,"fallbackOutcome");void 0!==i&&(r[i.toString()]=t);let a=this.safeList(t,"namedOutcomes",[]);for(let e=0;e<a.length;e++){let i=this.safeInteger(a,e);void 0!==i&&(r[i.toString()]=t)}}let a=[];void 0===this.outcomes&&(this.outcomes={}),void 0===this.outcomes_by_id&&(this.outcomes_by_id={});for(let e=0;e<i.length;e++){let t=this.safeDict(i,e,{}),s=this.safeInteger(t,"outcome",e),o=this.safeDict(r,s.toString(),{}),n=this.parseOutcomeMarket(t,s,o);a.push(n);let d=this.safeList(n,"outcomes",[]);for(let e=0;e<d.length;e++){let t=this.safeDict(d,e,{}),i=this.safeString2(t,"outcome","symbol"),s=this.safeString2(t,"outcomeId","id");void 0!==i&&(this.outcomes[i]=t),void 0!==s&&(this.outcomes_by_id[s]=t)}}return a}parseOutcomeMarket(e,t,i={}){let s,r,a=this.safeString(e,"description",""),o=this.safeString(e,"name",""),n=this.safeList(e,"sideSpecs",[]),d=this.parseOutcomeDescription(a),h=this.buildOutcomeParentSymbol(d,t,o,i),c=this.outcomeEncoding(t,0),l=this.outcomeEncoding(t,1),u=h+":YES",f=h+":NO",p=this.safeString(d,"expiry");if(void 0!==p&&""!==p){let e=p.split("-"),t=e.length;if(t>=1&&8===e[0].length){let i=e[0],a="0000";t>=2&&(a=e[1]);let o=i.slice(0,4)+"-"+i.slice(4,6)+"-"+i.slice(6,8)+"T"+a.slice(0,2)+":"+a.slice(2,4)+":00Z";s=this.parse8601(o),r=o}}let m=this.safeStringUpper(this.safeDict(n,0,{}),"name","YES"),g=this.safeStringUpper(this.safeDict(n,1,{}),"name","NO"),v=this.safeString(this.options,"outcomeQuoteCurrency","USDH"),y={amount:this.parseNumber(this.parsePrecision("4")),price:1e-4},b=[{id:this.outcomeCoin(c),outcomeId:this.outcomeCoin(c),outcome:u,market:h,label:m,active:!0,precision:y,info:{encoding:c,assetId:this.outcomeAssetId(c),coinName:this.outcomeCoin(c),tokenName:this.outcomeToken(c),side:0,outcomeId:t,name:o,description:a,parsedDescription:d}},{id:this.outcomeCoin(l),outcomeId:this.outcomeCoin(l),outcome:f,market:h,label:g,active:!0,precision:y,info:{encoding:l,assetId:this.outcomeAssetId(l),coinName:this.outcomeCoin(l),tokenName:this.outcomeToken(l),side:1,outcomeId:t,name:o,description:a,parsedDescription:d}}],w=this.safeMarketStructure({id:t.toString(),market:h,base:h.split("/")[0],quote:v,settle:void 0,baseId:t.toString(),quoteId:v,settleId:void 0,type:"prediction",marketType:"binary",executionModel:"clob",spot:!1,margin:void 0,swap:!1,future:!1,option:!1,prediction:!0,active:!0,contract:!1,linear:void 0,inverse:void 0,taker:5e-4,maker:2e-4,contractSize:void 0,expiry:s,expiryDatetime:r,strike:void 0,optionType:void 0,percentage:!0,tierBased:!1,feeSide:"get",precision:y,limits:{leverage:{min:void 0,max:void 0},amount:{min:void 0,max:void 0},price:{min:1e-4,max:.9999},cost:{min:this.parseNumber("1"),max:void 0}},outcomes:b,info:this.extend(e,{outcomeId:t,parentSymbol:h,description:a,parsedDescription:d}),created:void 0});return this.omit(w,"symbol")}calculatePricePrecision(e,t){if(e<=0)return 1e-4;let i=this.numberToString(e).split(".")[0],s=Math.max(1,Math.min(8-t,Math.max(5,i.length)-i.length)),r="",a=s-1;for(let e=0;e<a;e++)r+="0";return this.parseToNumeric("0."+r+"1")}async fetchTicker(e,t={}){await this.loadOutcome(e);let i=this.outcome(e),s=this.safeDict(i,"info",{}),r=this.safeString(s,"coinName"),a=await this.publicPostInfo(this.extend({type:"l2Book",coin:r},t)),o=this.safeDict({book:a},"book",{});return this.parsePredictionTicker(o,i)}async fetchTickers(e,t={}){let i={};if(void 0!==e){await this.loadOutcomes(e);for(let t=0;t<e.length;t++){let s=e[t],r=this.safeOutcome(s);i[this.safeString(r,"outcome",s)]=!0}}else await this.loadOutcomes();let s=await this.publicPostInfo(this.extend({type:"allMids"},t)),r={};"string"==typeof s||Array.isArray(s)||(r=s);let a=this.safeDict(r,"mids",r),o={},n=void 0!==this.outcomes?this.outcomes:{},d=Object.keys(n);for(let t=0;t<d.length;t++){let s=d[t];if(void 0!==e&&!(s in i))continue;let r=this.safeDict(n,s,{}),h=this.safeDict(r,"info",{}),c=this.safeString(h,"coinName"),l=this.safeNumber(a,c);if(void 0===l)continue;let u=this.parsePredictionTicker({levels:[[],[]],mid:l},r);o[s]=u}return o}parsePredictionTicker(e,t){let i,s=this.safeInteger(e,"time"),r=this.safeOutcome(void 0,t),a=this.safeString(r,"outcome"),o=this.safeList(e,"levels",[]),n=this.safeList(o,0,[]),d=this.safeList(o,1,[]),h=this.safeDict(n,0),c=this.safeDict(d,0),l=void 0!==h?this.safeNumber(h,"px"):void 0,u=void 0!==c?this.safeNumber(c,"px"):void 0,f=void 0!==h?this.safeNumber(h,"sz"):void 0,p=void 0!==c?this.safeNumber(c,"sz"):void 0,m=this.safeNumber(e,"mid");void 0===m&&void 0!==l&&void 0!==u&&(m=this.sum(l,u)/2);let g=this.safeString(r,"market");void 0!==g&&(i=this.safeMarket(g));let v=void 0!==i?this.safeDict(this.safeDict(i,"info",{}),"ctx",{}):{},y=this.safeNumber(v,"dayNtlVlm");return this.safePredictionTicker({outcome:a,outcomeId:this.safeString2(r,"outcomeId","id"),label:this.safeString(r,"label"),market:this.safeString(r,"market"),timestamp:s,datetime:this.iso8601(s),high:void 0,low:void 0,bid:l,bidVolume:f,ask:u,askVolume:p,vwap:void 0,open:void 0,close:m,last:m,previousClose:void 0,change:void 0,percentage:void 0,average:m,baseVolume:void 0,quoteVolume:y,info:e},t)}async fetchOrderBook(e,t,i={}){await this.loadOutcome(e);let s=this.outcome(e),r=this.safeDict(s,"info",{}),a={type:"l2Book",coin:this.safeString(r,"coinName")},o=await this.publicPostInfo(this.extend(a,i)),n=this.safeInteger(o,"time"),d=this.safeList(o,"levels",[]),h=this.safeList(d,0,[]),c=this.safeList(d,1,[]),l=[],u=[];for(let e=0;e<h.length;e++){let t=this.safeDict(h,e);l.push([this.safeNumber(t,"px"),this.safeNumber(t,"sz")])}for(let e=0;e<c.length;e++){let t=this.safeDict(c,e);u.push([this.safeNumber(t,"px"),this.safeNumber(t,"sz")])}let f=this.parseOrderBook({bids:l,asks:u},this.safeString(s,"outcome",e),n);return this.safePredictionOrderBook(f,s)}async fetchOHLCV(e,t="1m",i,s,r={}){await this.loadOutcome(e);let a=this.outcome(e),o=this.market(this.safeString(a,"market")),n=this.safeDict(a,"info",{}),h=this.safeInteger(r,"until",this.milliseconds()),c=i;if(void 0===i){let e=this.parseTimeframe(t),i=void 0!==s?s:100;if(void 0===(c=this.sum(h,-(e*i*1e3))))throw new d.ExchangeError(this.id+" fetchOHLCV() missing startTime");c<0&&(c=0)}let l={type:"candleSnapshot",req:{coin:this.safeString(n,"coinName"),interval:this.safeString(this.timeframes,t,t),startTime:c,endTime:h}},u=this.omit(r,"until"),f=await this.publicPostInfo(this.extend(l,u)),p=[];return Array.isArray(f)&&(p=f),this.parseOHLCVs(p,o,t,i,s)}parseOHLCV(e,t){return[this.safeInteger(e,"t"),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}async fetchBalance(e={}){let[t,i]=this.handlePublicAddress("fetchBalance",e),s=await this.publicPostInfo(this.extend({type:"spotClearinghouseState",user:t},i)),r={info:s},a=this.safeList(s,"balances",[]);for(let e=0;e<a.length;e++){let t=this.safeDict(a,e),i=this.safeString(t,"coin"),s=this.safeString(t,"total"),o=this.safeString(t,"hold"),n=this.account();n.total=s,n.used=o,void 0!==i&&(r[i]=n)}return this.safeBalance(r)}async fetchPositions(e,t={}){let i={};if(void 0!==e){await this.loadOutcomes(e);for(let t=0;t<e.length;t++){let s=e[t],r=this.safeOutcome(s);i[this.safeString(r,"outcome",s)]=!0}}else await this.loadOutcomes();let[s,r]=this.handlePublicAddress("fetchPositions",t),a=[this.publicPostInfo(this.extend({type:"spotClearinghouseState",user:s},r)),this.publicPostInfo({type:"allMids"})],n=await Promise.all(a),d=this.safeDict(n,0),h=n[1],c=this.safeList(d,"balances",[]),l={};"string"==typeof h||Array.isArray(h)||(l=h);let u=this.safeDict(l,"mids",l),f=[];for(let t=0;t<c.length;t++){let s=this.safeDict(c,t,{}),r=this.safeString(s,"coin","");if(0!==r.indexOf("+"))continue;let a=this.safeString(s,"total");if(void 0===a||o.Y.stringEq(a,"0"))continue;let n="#"+r.slice(1),d=this.safeOutcome(n);if(void 0!==e){let e=this.safeString(d,"outcome");if(void 0===e||!(e in i))continue}let h=this.extend(s,{markPx:this.safeString(u,n)});f.push(this.parsePredictionPosition(h,d))}return f}parsePredictionPosition(e,t){let i,s,r,a=this.safeOutcome(void 0,t),n=this.safeString(e,"total"),d=this.parseNumber(n),h=this.safeString(e,"entryNtl");void 0===h||void 0===n||o.Y.stringEq(n,"0")||(i=this.parseNumber(o.Y.stringDiv(h,n)));let c=this.safeString(e,"markPx");if(void 0!==c&&void 0!==n){let e=o.Y.stringMul(n,c);s=this.parseNumber(e),void 0!==h&&(r=this.parseNumber(o.Y.stringSub(e,h)))}return this.safePredictionPosition({id:void 0,outcome:this.safeString(a,"outcome"),outcomeId:this.safeString2(a,"outcomeId","id"),market:this.safeString(a,"market"),timestamp:void 0,datetime:void 0,isolated:!1,hedged:void 0,side:"long",contracts:d,contractSize:1,entryPrice:i,markPrice:this.parseNumber(c),notional:s,leverage:void 0,collateral:this.safeNumber(e,"hold"),initialMargin:void 0,maintenanceMargin:void 0,initialMarginPercentage:void 0,maintenanceMarginPercentage:void 0,unrealizedPnl:r,realizedPnl:void 0,liquidationPrice:void 0,marginRatio:void 0,marginMode:"cross",percentage:void 0,info:e})}findOutcomeInMarket(e,t){let i=this.safeList(e,"outcomes",[]),s=void 0!==t&&""!==t?t.toUpperCase():void 0;if(void 0!==s)for(let e=0;e<i.length;e++){let t=this.safeDict(i,e,{}),r=this.safeString2(t,"outcome","symbol","");if(this.safeStringUpper(t,"label")===s||r.endsWith(":"+s))return t}for(let e=0;e<i.length;e++){let t=this.safeDict(i,e,{}),s=this.safeDict(t,"info",{});if(0===this.safeInteger(s,"side"))return t}return this.safeDict(i,0,{})}parseOutcomeInputSideHint(e){if(void 0===e||""===e)return;let t=e.indexOf(":");if(t>-1&&t<e.length-1){let i=e.slice(t+1).toUpperCase();if("YES"===i||"NO"===i)return i}let i=e.toLowerCase();return i.endsWith("-yes")?"YES":i.endsWith("-no")?"NO":void 0}resolveOutcomeInput(e){if(void 0===e)throw new d.ArgumentsRequired(this.id+" resolveOutcomeInput() requires an outcome symbol or id");if(void 0===this.outcomes||void 0===this.outcomes_by_id)throw new d.ExchangeError(this.id+" outcomes not loaded");let t=this.parseOutcomeInputSideHint(e),i=[e];e.startsWith("+")&&i.push("#"+e.slice(1));let s=this.stringToCharsArray(e),r=s.length>0;for(let e=0;e<s.length;e++)if(0>"0123456789".indexOf(s[e])){r=!1;break}if(r){i.push("#"+e);let t=this.parseToInt(e);i.push(this.outcomeCoin(this.outcomeEncoding(t,0))),i.push(this.outcomeCoin(this.outcomeEncoding(t,1)))}for(let e=0;e<i.length;e++){let t=i[e];if(t in this.outcomes)return this.safeDict(this.outcomes,t,{});if(t in this.outcomes_by_id)return this.safeDict(this.outcomes_by_id,t,{})}if(void 0!==this.markets&&e in this.markets||void 0!==this.markets_by_id&&e in this.markets_by_id){let i=this.safeMarket(e),s="YES";void 0!==t&&(s=t);let r=this.findOutcomeInMarket(i,s);if(Object.keys(r).length>0)return r}throw new d.ArgumentsRequired(this.id+" cannot resolve outcome from input: "+e+". Provide an outcome symbol (e.g. MARKET:YES), outcome id (#<encoding>), or market id with side.")}async createOrder(e,t,i,s,r,a={}){let n;await this.initializeClient(),await this.loadOutcome(e);let h=this.outcome(e),c=this.safeString(h,"market"),l=this.market(c),u=this.safeDict(h,"info",{}),f=this.incrementingNonce(),p="BUY"===i.toUpperCase(),m="MARKET"===t.toUpperCase(),g=this.safeInteger(u,"assetId"),v=this.safeString2(a,"clientOrderId","client_id"),y=this.safeBool(a,"reduceOnly",!1),b=this.safeBool(a,"postOnly",!1),w=this.safeString(this.options,"defaultSlippage","0.05"),k=this.safeString(a,"slippage",w),S="Gtc";m&&(S="Ioc"),!0===b&&(S="Alo");let O=this.capitalize(this.safeStringLower(a,"timeInForce",S));if(void 0===r){if(m)throw new d.ArgumentsRequired(this.id+" createOrder() requires a reference price for market orders on outcome markets in between 0 and 1. The exchange uses this reference price together with the configured slippage to derive the execution price.");throw new d.ArgumentsRequired(this.id+" createOrder() requires a limit price for outcome markets in between 0 and 1.")}if(m){let e=this.numberToString(r);n=p?o.Y.stringMul(e,o.Y.stringAdd("1",k)):o.Y.stringMul(e,o.Y.stringSub("1",k)),n=this.priceToPrecision(c,n)}else n=this.priceToPrecision(c,r);if(void 0===n)throw new d.ArgumentsRequired(this.id+" createOrder() could not determine price");let T={a:g,b:p,p:n,s:this.amountToPrecision(c,s),r:y,t:{limit:{tif:O}}};void 0!==v&&(T.c=v);let P=this.handleOptionStringAndParams(a,"createOrder","vaultAddress")[0],I=this.formatVaultAddress(P),A={type:"order",orders:[T],grouping:"na"};if(this.safeBool(this.options,"approvedBuilderFee",!1)){let e=this.safeStringLower(this.options,"builder","0x6530512A6c89C7cfCEbC3BA7fcD9aDa5f30827a6"),t=this.safeInteger(this.options,"feeInt",0);this.safeBool(this.options,"builderFee",!0)||(t=0),A.builder={b:e,f:t}}let x=this.signL1Action(A,f,I),M={action:A,nonce:f,signature:x};void 0!==I&&(M.vaultAddress=I);let _=await this.privatePostExchange(M),C=this.safeDict(_,"response",{}),B=this.safeDict(C,"data",{}),E=this.safeList(B,"statuses",[]),R=this.safeDict(E,0,{}),L=this.safeDict(R,"resting",{}),N=this.safeDict(R,"filled",{}),D=this.safeString(L,"oid",this.safeString(N,"oid")),q=this.safeString(L,"oid"),F="closed";return void 0!==q&&(F="open"),this.safePredictionOrder({id:D,clientOrderId:v,info:_,timestamp:void 0,datetime:void 0,status:F,outcome:this.safeString(h,"outcome",e),outcomeId:this.safeString(h,"id"),label:this.safeString(h,"label"),market:this.safeString(h,"market"),type:t,side:i,price:r,amount:s,filled:this.safeNumber(N,"totalSz"),remaining:void 0,cost:void 0,fee:void 0,trades:[]},l)}async cancelOrder(e,t,i={}){let s=await this.cancelOrders([e],t,i);return this.safeDict(s,0)}async cancelOrders(e,t,i={}){if(this.checkRequiredCredentials(),void 0===t)throw new d.ArgumentsRequired(this.id+" cancelOrders() requires an outcome argument");await this.initializeClient(),await this.loadOutcome(t);let s=this.outcome(t),r=this.safeDict(s,"info",{}),a=this.safeInteger(r,"assetId"),o=this.incrementingNonce(),n=this.safeValue2(i,"clientOrderId","client_id"),h=this.omit(i,["clientOrderId","client_id"]),c=[],l={type:"cancel",cancels:[]};if(void 0!==n){let e=Array.isArray(n)?n:[n];l.type="cancelByCloid";for(let t=0;t<e.length;t++)c.push({asset:a,cloid:e[t]})}else{l.type="cancel";for(let t=0;t<e.length;t++)c.push({a:a,o:this.parseToNumeric(e[t])})}l.cancels=c;let u=this.handleOptionStringAndParams(h,"cancelOrders","vaultAddress")[0],f=this.formatVaultAddress(u),p=this.signL1Action(l,o,f),m={action:l,nonce:o,signature:p};void 0!==f&&(m.vaultAddress=f);let g=await this.privatePostExchange(m),v=this.safeDict(g,"response"),y=this.safeDict(v,"data"),b=this.safeList(y,"statuses",[]),w=this.safeString(s,"outcome",t),k=e;void 0!==n&&(k=Array.isArray(n)?n:[n]);let S=[];for(let e=0;e<b.length;e++){let t=b[e],i=this.safeString(t,"error");if(void 0!==i)throw new d.OrderNotFound(this.id+" cancelOrders() failed for "+this.safeString(k,e,this.safeString(k,0))+": "+i);if("success"!==t&&"success"!==this.safeString(t,"status"))throw new d.ExchangeError(this.id+" cancelOrders() received an unexpected status: "+this.json(t));let r=this.safeString(k,e,this.safeString(k,0)),a={id:r,clientOrderId:void 0!==n?r:void 0,info:t,status:"canceled",outcome:w,outcomeId:this.safeString(s,"id"),label:this.safeString(s,"label"),market:this.safeString(s,"market"),timestamp:void 0,datetime:void 0};S.push(this.safePredictionOrder(a))}return S}async fetchOpenOrders(e,t,i,s={}){let r,[a,o]=this.handlePublicAddress("fetchOpenOrders",s),[n,d]=this.handleOptionStringAndParams(o,"fetchOpenOrders","method","frontendOpenOrders"),h=await this.publicPostInfo(this.extend({type:n,user:a},d)),c=[],l=[];Array.isArray(h)&&(l=h);for(let e=0;e<l.length;e++){let t=l[e];c.push(this.extend(t,{ccxtStatus:"open"}))}let u=this.parsePredictionOrders(c,void 0,t);if(void 0!==e){await this.loadOutcome(e);let t=this.outcome(e);r=this.safeString(t,"outcome")}return this.filterByOutcomeSinceLimit(u,r,t,i)}async fetchOrders(e,t,i,s={}){let r,[a,o]=this.handlePublicAddress("fetchOrders",s),n=await this.publicPostInfo(this.extend({type:"historicalOrders",user:a},o)),d={},h=[];Array.isArray(n)&&(h=n);for(let e=0;e<h.length;e++){let t=h[e],i=this.safeDict(t,"order");void 0===i&&(i=t);let s=this.safeString(i,"oid");if(void 0!==s)if(s in d){let e=this.safeInteger(d[s],"statusTimestamp"),i=this.safeInteger(t,"statusTimestamp");void 0!==i&&(void 0===e||i>e)&&(d[s]=t)}else d[s]=t}let c=Object.values(d),l=this.parsePredictionOrders(c,void 0,t);if(void 0!==e){await this.loadOutcome(e);let t=this.outcome(e);r=this.safeString(t,"outcome")}return this.filterByOutcomeSinceLimit(l,r,t,i)}async fetchOrder(e,t,i={}){let[s,r]=this.handlePublicAddress("fetchOrder",i),a=this.safeString(r,"clientOrderId"),o={type:"orderStatus",user:s},n=r;void 0!==a?(n=this.omit(r,"clientOrderId"),o.oid=a):o.oid=e.length>=34?e:this.parseToNumeric(e);let h=await this.publicPostInfo(this.extend(o,n)),c={};"string"==typeof h||Array.isArray(h)||(c=h);let l=this.safeDict(c,"order",c),u=this.parsePredictionOrder(l,void 0);if(void 0!==t){await this.loadOutcome(t);let i=this.outcome(t),s=this.safeString(i,"outcome");if(this.safeString(u,"outcome")!==s)throw new d.OrderNotFound(this.id+" fetchOrder() order "+e+" is not in outcome "+s)}return u}parsePredictionOrder(e,t){let i,s=this.safeDict(e,"order",e),r=this.parseOrderStatus(this.safeString2(e,"ccxtStatus","status")),a=this.safeString(s,"coin"),n=this.safeOutcome(a,t),d=this.safeString(n,"outcome"),h=t;void 0!==d&&""!==d&&(h=this.safeMarket(d,t));let c=this.safeString(s,"side"),l="sell";"B"===c&&(l="buy");let u=this.safeString(s,"origSz"),f=this.safeString(s,"sz");void 0!==f&&void 0!==u&&(i=o.Y.stringSub(u,f));let p=this.safeInteger(s,"timestamp"),m=this.safeString(s,"tif"),g=this.parseTimeInForce(m),v=this.safeBool(s,"isTrigger",!1)?this.safeNumber(s,"triggerPx"):void 0;return this.safePredictionOrder({id:this.safeString(s,"oid"),clientOrderId:this.safeString(s,"cloid"),info:e,timestamp:p,datetime:this.iso8601(p),lastTradeTimestamp:void 0,status:r,outcome:this.safeString(n,"outcome"),outcomeId:this.safeString(n,"id"),label:this.safeString(n,"label"),market:this.safeString(n,"market"),type:this.parseOrderType(this.safeString(s,"orderType","limit")),timeInForce:g,postOnly:"PO"===g,reduceOnly:this.safeBool(s,"reduceOnly",!1),side:l,price:this.safeNumber(s,"limitPx"),triggerPrice:v,amount:this.parseNumber(u),cost:void 0,average:this.safeNumber(s,"avgPx"),filled:this.parseNumber(i),remaining:this.parseNumber(f),fee:void 0,trades:[]},h)}parseOrderStatus(e){if(void 0!==e)return e.endsWith("Rejected")?"rejected":e.endsWith("Canceled")?"canceled":this.safeString({triggered:"open",filled:"closed",open:"open",canceled:"canceled",rejected:"rejected",marginCanceled:"canceled"},e,e)}parseOrderType(e){let t=void 0!==e&&""!==e?e.toLowerCase():void 0;return this.safeString({"stop limit":"limit","stop market":"market"},t,t)}parseTimeInForce(e){let t=void 0!==e&&""!==e?e.toLowerCase():void 0;return this.safeString({gtc:"GTC",ioc:"IOC",fok:"FOK",alo:"PO"},t,e)}async fetchTrades(e,t,i,s={}){await this.loadOutcome(e);let r=this.outcome(e),a=this.safeDict(r,"info",{}),o={type:"recentTrades",coin:this.safeString(a,"coinName")},n=await this.publicPostInfo(this.extend(o,s)),d=[];return Array.isArray(n)?d=n:"string"!=typeof n&&(d=this.toArray(n)),this.parsePredictionTrades(d,r,t,i)}async fetchMyTrades(e,t,i,s={}){let r;if(void 0!==e){let t=await this.loadOutcome(e);r=this.safeString(t,"outcome")}else await this.loadOutcomes();let[a,o]=this.handlePublicAddress("fetchMyTrades",s),n={user:a};void 0!==t?(n.type="userFillsByTime",n.startTime=t):n.type="userFills";let d=this.safeInteger(o,"until"),h=this.omit(o,"until");void 0!==d&&(n.endTime=d);let c=await this.publicPostInfo(this.extend(n,h)),l=[];Array.isArray(c)?l=c:"string"!=typeof c&&(l=this.toArray(c));let u=this.parsePredictionTrades(l,void 0);return this.filterByOutcomeSinceLimit(u,r,t,i)}parsePredictionTrade(e,t){let i,s,r=this.safeInteger(e,"time"),a=this.safeString(e,"px"),n=this.safeString(e,"sz"),d=this.safeString(e,"coin"),h=this.safeOutcome(d,t),c=this.safeString(h,"outcome"),l=t;void 0!==c&&""!==c&&(l=this.safeMarket(c,t));let u=this.safeString(e,"side"),f="sell";"B"===u&&(f="buy");let p=this.safeNumber(e,"fee"),m=this.safeString(e,"feeToken","USDC"),g=this.safeString(h,"outcome");void 0!==p&&(i={cost:p,currency:m}),void 0!==a&&void 0!==n&&(s=this.parseNumber(o.Y.stringMul(a,n)));let v=this.safeBool(e,"crossed",!1),y="maker";return v&&(y="taker"),this.safePredictionTrade({id:this.safeString(e,"tid"),info:e,timestamp:r,datetime:this.iso8601(r),outcome:g,outcomeId:this.safeString(h,"id"),label:this.safeString(h,"label"),market:this.safeString(h,"market"),order:this.safeString(e,"oid"),type:"limit",side:f,takerOrMaker:y,price:this.parseNumber(a),amount:this.parseNumber(n),cost:s,fee:i},l)}async fetchEvents(e={}){this.requireEventQuery(e);let t=this.parseSearchQueries(e),i=await this.loadMarkets(),s=this.toArray(i),r={};if(void 0===t)throw new d.ExchangeError(this.id+" fetchEvents() missing queries");let a=[];for(let e=0;e<t.length;e++){let i=t[e];a.push(i.toLowerCase())}let o=a.length;for(let e=0;e<s.length;e++){let t=s[e];if(!this.safeBool(t,"prediction",!1))continue;let i=this.safeDict(t,"info",{}),n=this.safeString(i,"parentSymbol",this.safeString2(t,"market","symbol"));if(o>0){let e=this.safeString(i,"description","").toLowerCase()+" "+(void 0!==n?n:"").toLowerCase(),t=!1;for(let i=0;i<a.length;i++){let s=a[i].split(" "),r=s.length,o=!0;for(let t=0;t<r;t++){let i=s[t];if(""!==i&&0>e.indexOf(i)){o=!1;break}}if(o){t=!0;break}}if(!t)continue}if(void 0===n)throw new d.ExchangeError(this.id+" fetchEvents() missing parentSymbol");n in r||void 0===n||(r[n]=[]);let h=this.safeValue(r,n);h.push(t),void 0!==n&&(r[n]=h)}let n=[],h=Object.keys(r);for(let e=0;e<h.length;e++){let t=h[e],i=r[t],s=this.parseEvent({parentSymbol:t,markets:i});n.push(s)}return this.applyEventFetchParams(n,e,t)}parseEvent(e){let t,i,s=this.safeString(e,"parentSymbol"),r=this.safeList(e,"markets",[]),a=r.length>0?r[0]:{},o=this.safeDict(a,"info",{}),n=this.safeDict(o,"parsedDescription",{}),d=this.safeString(n,"underlying"),h=this.safeString(n,"targetPrice"),c=this.safeString(n,"expiry");if(void 0!==c&&""!==c){let e=c.split("-"),s=e.length;if(s>=1&&8===e[0].length){let r=e[0],a="0000";s>=2&&(a=e[1]);let o=r.slice(0,4)+"-"+r.slice(4,6)+"-"+r.slice(6,8)+"T"+a.slice(0,2)+":"+a.slice(2,4)+":00Z";t=this.parse8601(o),i=o}}let l=this.safeInteger(a,"expiry"),u=s;if(void 0!==d){let e="";void 0!==h&&""!==h&&(e=e+" ABOVE "+h),void 0!==c&&""!==c&&(e=e+" @ "+c),u=d+e}let f=void 0!==t?t:l;return this.extend({id:s,slug:s,event:s,title:u,markets:r,url:void 0,image:void 0,created:void 0,createdDatetime:void 0,end:f,endDatetime:i,category:"crypto",lastUpdatedAt:void 0,resolutionSource:"Hyperliquid mark price",resolved:void 0,info:e})}amountToPrecision(e,t){let i=this.market(e),s=this.safeNumber(this.safeDict(i,"precision",{}),"amount",1e-4),r=4;if(void 0===s)throw new d.ExchangeError(this.id+" amountToPrecision() missing prec");return s>0&&(r=this.precisionFromString(this.numberToString(s))),this.decimalToPrecision(t,1,r,2,this.paddingMode)}priceToPrecision(e,t){let i=this.market(e),s=this.safeNumber(this.safeDict(i,"precision",{}),"price",1e-4),r=4;if(void 0===s)throw new d.ExchangeError(this.id+" priceToPrecision() missing prec");return s>0&&(r=this.precisionFromString(this.numberToString(s))),this.decimalToPrecision(t,1,r,2,this.paddingMode)}hashMessage(e){return"0x"+this.hash(e,s.lY,"hex")}signHash(e,t){let i=(0,n.h1)(e.slice(-64),t.slice(-64),r.bI,void 0),s=i.r,a=i.s;return{r:"0x"+s.padStart(64,"0"),s:"0x"+a.padStart(64,"0"),v:this.sum(27,i.v)}}signMessage(e,t){return this.signHash(this.hashMessage(e),t.slice(-64))}constructPhantomAgent(e,t=!0){let i="a";return t&&(i="b"),{source:i,connectionId:e}}actionHash(e,t,i){let r=this.packb(e),a=this.binaryToBase16(r);return a+="00000"+this.intToBase16(i),void 0===t?a+="00":(a+="01",a+=t),this.hash(this.base16ToBinary(a),s.lY,"binary")}signL1Action(e,t,i){this.checkRequiredCredentials();let s=this.actionHash(e,i,t),r=this.safeBool(this.options,"sandboxMode",!1),a=this.constructPhantomAgent(s,r),o=this.safeString(this.options,"zeroAddress"),n=this.ethEncodeStructuredData({chainId:1337,name:"Exchange",verifyingContract:o,version:"1"},{Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]},a);return this.signMessage(n,this.privateKey)}signUserSignedAction(e,t){let i=this.safeString(this.options,"zeroAddress"),s=this.ethEncodeStructuredData({chainId:421614,name:"HyperliquidSignTransaction",verifyingContract:i,version:"1"},e,t);return this.signMessage(s,this.privateKey)}buildApproveBuilderFeeSig(e){return this.signUserSignedAction({"HyperliquidTransaction:ApproveBuilderFee":[{name:"hyperliquidChain",type:"string"},{name:"maxFeeRate",type:"string"},{name:"builder",type:"address"},{name:"nonce",type:"uint64"}]},e)}async approveBuilderFee(e,t){let i=this.incrementingNonce(),s={hyperliquidChain:!0===this.safeBool(this.options,"sandboxMode",!1)?"Testnet":"Mainnet",maxFeeRate:t,builder:e,nonce:i},r=this.buildApproveBuilderFeeSig(s),a={hyperliquidChain:s.hyperliquidChain,signatureChainId:"0x66eee",maxFeeRate:s.maxFeeRate,builder:s.builder,nonce:i,type:"approveBuilderFee"};return await this.privatePostExchange({action:a,nonce:i,signature:r,vaultAddress:void 0})}async initializeClient(){if((await this.loadMarkets(),!0===this.safeBool(this.options,"builderFee",!1))&&!this.safeBool(this.options,"approvedBuilderFee",!1))try{let e=this.safeString(this.options,"builder","0x6530512A6c89C7cfCEbC3BA7fcD9aDa5f30827a6"),t=this.safeString(this.options,"feeRate","0%");await this.approveBuilderFee(e,t),this.options.approvedBuilderFee=!0}catch(e){this.options.builderFee=!1}}handlePublicAddress(e,t){let[i,s]=this.handleOptionStringAndParams2(t,e,"user","subAccountAddress"),[r,a]=this.handleOptionStringAndParams(s,e,"address",i);if(void 0!==r&&""!==r)return[r,a];if(void 0!==this.walletAddress&&""!==this.walletAddress)return[this.walletAddress,a];throw new d.ArgumentsRequired(this.id+" "+e+"() requires a user parameter or walletAddress to be set")}formatVaultAddress(e){if(void 0===e)return;let t=e;return(t.startsWith("0x")||t.startsWith("0X"))&&(t=t.slice(2)),t.toLowerCase()}sign(e,t="public",i="POST",s={},r,a){let o,n=Array.isArray(t)?t[0]:t;if(!0===this.safeBool(this.options,"sandboxMode",!1)){let e=this.safeDict(this.urls,"test",{});o=this.safeString(e,n,this.safeString(e,"public",""))}else{let e=this.safeDict(this.urls,"api",{});o=this.safeString(e,n,this.safeString(e,"public",""))}let d=o+"/"+e,h=r,c=a;return"POST"===i&&(h={"Content-Type":"application/json"},c=this.json(s)),{url:d,method:i,body:c,headers:h}}handleErrors(e,t,i,s,r,a,o,n,h){if(void 0===o)return;if("err"===this.safeString(o,"status","")){let e=this.safeString(o,"response",a),t=this.id+" "+a;throw this.throwExactlyMatchedException(this.exceptions.exact,e,t),this.throwBroadlyMatchedException(this.exceptions.broad,e,t),new d.ExchangeError(t)}let c=this.safeDict(o,"response",{}),l=this.safeDict(c,"data",{}),u=this.safeList(l,"statuses",[]);for(let e=0;e<u.length;e++){let t=this.safeString(u[e],"error");if(void 0!==t){let e=this.id+" "+a;throw this.throwExactlyMatchedException(this.exceptions.exact,t,e),this.throwBroadlyMatchedException(this.exceptions.broad,t,e),new d.ExchangeError(e)}}}calculateRateLimiterCost(e,t,i,s,r={}){if("byType"in r&&"type"in s){let e=s.type,t=r.byType;if(e in t)return t[e]}return this.safeValue(r,"cost",1)}}i.d(t,{A:()=>h})},7788(e,t,i){"use strict";var s=i(4721),r=i(1695),a=i(7749),o=i(8748),n=i(1453);class d extends r.A{describe(){return this.deepExtend(super.describe(),{id:"kalshi",name:"Kalshi",countries:["US"],rateLimit:200,certified:!1,pro:!1,has:{CORS:void 0,spot:!1,margin:!1,swap:!1,future:!1,option:!1,cancelAllOrders:!0,cancelOrder:!0,createOrder:!0,editOrder:!0,fetchBalance:!0,fetchClosedOrders:!0,fetchCurrencies:!1,fetchEvent:!0,fetchEvents:!0,fetchMarkets:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPositions:!0,fetchSettlements:!0,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,prediction:!0},timeframes:{"1m":1,"1h":60,"1d":1440},urls:{logo:"https://github.com/user-attachments/assets/74fc2acb-58d0-4db0-b316-3124e7dc24db",api:{kalshi:"https://external-api.kalshi.com/trade-api/v2",elections:"https://api.elections.kalshi.com/v1"},test:{kalshi:"https://external-api.demo.kalshi.co/trade-api/v2",elections:"https://api.elections.kalshi.com/v1"},www:"https://kalshi.com",doc:["https://trading-api.readme.io/reference/getting-started"]},api:{kalshi:{public:{get:{events:{cost:1},"events/multivariate":{cost:1},"events/fee_changes":{cost:1},"events/{event_ticker}":{cost:1},"events/{event_ticker}/metadata":{cost:1},series:{cost:1},"series/fee_changes":{cost:1},"series/{series_ticker}":{cost:1},"series/{series_ticker}/markets/{ticker}/candlesticks":{cost:1},"series/{series_ticker}/events/{ticker}/candlesticks":{cost:1},"series/{series_ticker}/events/{ticker}/forecast_percentile_history":{cost:1},markets:{cost:1},"markets/trades":{cost:1},"markets/orderbooks":{cost:1},"markets/candlesticks":{cost:1},"markets/{ticker}":{cost:1},"markets/{ticker}/orderbook":{cost:1},"exchange/status":{cost:1},"exchange/schedule":{cost:1},"exchange/announcements":{cost:1},"exchange/user_data_timestamp":{cost:1},milestones:{cost:1},"milestones/{milestone_id}":{cost:1},structured_targets:{cost:1},"structured_targets/{structured_target_id}":{cost:1},"search/filters_by_sport":{cost:1},"search/tags_by_categories":{cost:1},"live_data/batch":{cost:1},"live_data/milestone/{milestone_id}":{cost:1},"historical/markets":{cost:1},"historical/markets/{ticker}/candlesticks":{cost:1},"historical/trades":{cost:1},"historical/cutoff_timestamps":{cost:1},multivariate_event_collections:{cost:1},"multivariate_event_collections/{collection_ticker}":{cost:1},"multivariate_event_collections/{collection_ticker}/lookup":{cost:1},incentive_programs:{cost:1}}},private:{get:{"portfolio/balance":{cost:1},"portfolio/orders":{cost:1},"portfolio/orders/{order_id}":{cost:1},"portfolio/orders/{order_id}/queue_position":{cost:1},"portfolio/orders/queue_positions":{cost:1},"portfolio/positions":{cost:1},"portfolio/fills":{cost:1},"portfolio/settlements":{cost:1},"portfolio/deposits":{cost:1},"portfolio/withdrawals":{cost:1},"portfolio/order_groups":{cost:1},"portfolio/order_groups/{order_group_id}":{cost:1},"portfolio/summary/total_resting_order_value":{cost:1},"portfolio/subaccounts/balances":{cost:1},"portfolio/subaccounts/netting":{cost:1},"portfolio/subaccounts/transfers":{cost:1},"historical/fills":{cost:1},"historical/orders":{cost:1}},post:{"portfolio/orders":{cost:1},"portfolio/events/orders":{cost:1},"portfolio/orders/batched":{cost:1},"portfolio/orders/{order_id}/amend":{cost:1},"portfolio/orders/{order_id}/decrease":{cost:1},"portfolio/order_groups/create":{cost:1},"portfolio/subaccounts":{cost:1},"portfolio/subaccounts/transfer":{cost:1},"multivariate_event_collections/{collection_ticker}":{cost:1}},put:{"portfolio/order_groups/{order_group_id}/reset":{cost:1},"portfolio/order_groups/{order_group_id}/trigger":{cost:1},"portfolio/order_groups/{order_group_id}/limit":{cost:1},"portfolio/subaccounts/netting":{cost:1},"multivariate_event_collections/{collection_ticker}/lookup":{cost:1}},delete:{"portfolio/orders/{order_id}":{cost:1},"portfolio/orders/batched":{cost:1},"portfolio/events/orders/{order_id}":{cost:1},"portfolio/order_groups/{order_group_id}":{cost:1}}}},elections:{public:{get:{"search/series":{cost:1}}}}},requiredCredentials:{apiKey:!0,secret:!1,privateKey:!0},fees:{trading:{tierBased:!1,percentage:!0,maker:0,taker:.07}},exceptions:{exact:{not_found:n.BadSymbol,invalid_order:n.InvalidOrder,fill_or_kill_insufficient_resting_volume:n.OrderNotFillable},broad:{}},options:{defaultFetchEventsLimit:200,maxFetchMarketsLimit:1e3,searchSeriesLimit:25,maxFetchEventsResults:100,maxEventPagesPerSeries:20,defaultEventStatus:"open",eventScopeParams:["category","series_ticker"]}})}async fetchMarkets(e={}){let t;if(this.parseSearchQueries(e).length>0){let t=this.omit(e,["limit"]),i=await this.fetchEvents(t),s=i.length,r=[];for(let e=0;e<s;e++){let t=this.safeList(i[e],"markets",[]),s=t.length;for(let e=0;e<s;e++)r.push(t[e])}return r}let i=this.omit(e,["query","queries","limit"]),s=this.safeInteger(e,"limit",this.safeInteger(this.options,"maxFetchMarketsLimit",1e3)),r=[],a={},o=Math.min(s,this.safeInteger(this.options,"marketsPageLimit",1e3)),n=this.safeString(i,"status","open");for(;;){let e={limit:o,status:n};void 0!==t&&(e.cursor=t);let d=await this.kalshiPublicGetMarkets(this.extend(e,i)),h=this.safeList(d,"markets",[]),c=h.length;for(let e=0;e<h.length;e++){let t,i=h[e],s=this.parseBinaryMarketToOutcomes(i),o=this.safeString(i,"event_ticker"),n=this.safeString(i,"title",o);void 0!==n&&""!==n&&(t=this.shortenSlug(n));for(let e=0;e<s.length;e++){let i=s[e];if(r.push(i),void 0!==t&&""!==t){t in a||(a[t]={id:o,slug:o,event:t,title:n,markets:[]});let e=a[t],s=e.markets;s.push(i),e.markets=s}}}t=this.safeString(d,"cursor");let l=r.length;if(void 0===t||""===t||c<o||l>=s)break}return(this.events=a,r.length>s)?this.arraySlice(r,0,s):r}parseBinaryMarketToOutcomes(e){return[this.parseMarket(e)]}async fetchOutcome(e){if(0>e.indexOf(":")){let t,i=this.parseToInt(e.length),s=e.slice(i-3),r=e;"-NO"===s&&(r=e.slice(0,i-3));try{t=await this.kalshiPublicGetMarketsTicker({ticker:r})}catch(e){if(!(e instanceof n.BadSymbol))throw e;t=void 0}if(void 0!==t){let i=this.safeDict(t,"market",t),s=this.parseMarket(i);if(void 0===this.markets&&(this.markets=this.createSafeDictionary()),void 0===s)throw new n.ExchangeError(this.id+" fetchOutcome() could not resolve parsed");return this.markets[s.market]=s,this.indexMarketOutcomes(s),this.outcome(e)}}else{let t=e.split(":"),i=this.safeString(t,0,"").split("_"),s=this.safeString(i,0);if(void 0!==s&&""!==s){try{await this.fetchEvents({series_ticker:s})}catch(e){if(!(e instanceof n.BadSymbol))throw e}if(this.hasOutcome(e))return this.safeOutcome(e)}}return await super.fetchOutcome(e)}async fetchOutcomes(e){let t=[],i={};for(let s=0;s<e.length;s++){let r=e[s];if(r.indexOf(":")>=0)continue;let a=this.parseToInt(r.length),o=r.slice(a-3),n=r;"-NO"===o&&(n=r.slice(0,a-3)),n in i||(i[n]=!0,t.push(n))}void 0===this.markets&&(this.markets=this.createSafeDictionary());let s=this.safeInteger(this.options,"fetchOutcomesBatchSize",100),r=t.length,a=0;for(;a<r;){let e=this.sum(a,s);e>r&&(e=r);let i=[];for(let s=a;s<e;s++)i.push(t[s]);let o={tickers:i.join(","),limit:s},d=await this.kalshiPublicGetMarkets(o),h=this.safeList(d,"markets",[]);for(let e=0;e<h.length;e++){let t=this.parseMarket(h[e]);if(void 0===t)throw new n.ExchangeError(this.id+" fetchOutcomes() could not resolve parsed");this.markets[t.market]=t,this.indexMarketOutcomes(t)}a=this.sum(a,s)}for(let t=0;t<e.length;t++)this.hasOutcome(e[t])||await this.fetchOutcome(e[t]);return this.outcomes}handleErrors(e,t,i,s,r,a,o,d,h){if(null==o)return;let c=this.safeDict(o,"error");if(void 0!==c){let e=this.safeString(c,"code"),t=this.id+" "+a;this.throwExactlyMatchedException(this.exceptions.exact,e,t),this.throwBroadlyMatchedException(this.exceptions.broad,e,t)}if(400===e){let e=this.id+" "+a;throw new n.BadRequest(e)}}calculateFee(e,t,i,s,r,o="taker",n={}){let d=this.numberToString(r),h=this.numberToString(s),c=a.Y.stringSub("1",d),l=a.Y.stringMul("0.07",h);return l=a.Y.stringMul(l,d),l=a.Y.stringMul(l,c),{type:o,currency:"USD",rate:.07,cost:this.parseNumber(l)}}parseMarket(e){let t,i=this.safeString(e,"ticker"),s=this.safeString(e,"event_ticker"),r=this.safeString(e,"subtitle",this.safeString(e,"title")),o=this.safeString(e,"status"),n="active"===o||"open"===o,d=this.safeStringLower(e,"result"),h="settled"===o||void 0!==d&&""!==d,c=this.safeString(e,"expiration_time"),l=this.safeNumber2(e,"volume_fp","volume"),u=this.safeNumber2(e,"liquidity_dollars","liquidity"),f=this.safeNumber2(e,"open_interest_fp","open_interest"),p=[];void 0!==s&&""!==s&&(p=s.split("-"));let m=s,g=p.length;g>1&&(m=this.arraySlice(p,0,g-1).join("-"));let v=i;void 0!==r&&(v=r);let y=this.slugToMarketSymbol(s,v),b=this.safeList(e,"price_ranges",[]),w=this.safeDict(b,0,{}),k=this.safeString(w,"step"),S=this.parseNumber(a.Y.stringDiv(this.safeString(e,"tick_size","1"),"100"));void 0!==k&&(S=this.parseNumber(k));let O={amount:1,price:S},T=["YES","NO"],P=[i,i+"-NO"],I=[];for(let e=0;e<T.length;e++){let a,o,c=T[e],p=this.slugToOutcomeSymbol(s,v,c);h&&void 0!==d&&""!==d&&(o=+!!(a=c.toLowerCase()===d),a&&(t=p));let g=a,b=o;I.push({id:P[e],outcomeId:P[e],outcome:p,market:y,label:c,active:n,winner:g,settleFraction:b,precision:O,info:{ticker:i,eventTicker:s,seriesTicker:m,subtitle:r,outcomeLabel:c,volume:l,liquidity:u,openInterest:f}})}return{id:i,market:y,base:"USD",quote:"USD",settle:void 0,baseId:i,quoteId:"USD",settleId:void 0,type:"prediction",marketType:"binary",executionModel:"clob",spot:!1,margin:!1,swap:!1,future:!1,option:!1,prediction:!0,active:n,resolved:h,resolvedOutcome:t,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0!==c&&""!==c?this.parse8601(c):void 0,expiryDatetime:c,strike:void 0,optionType:void 0,taker:.07,maker:0,percentage:!0,tierBased:!1,feeSide:"get",precision:O,limits:{leverage:{min:1,max:1},amount:{min:1,max:void 0},price:{min:.01,max:.99},cost:{min:void 0,max:void 0}},outcomes:I,info:this.extend(e,{ticker:i,eventTicker:s,seriesTicker:m,subtitle:r,volume:l,liquidity:u,openInterest:f}),created:void 0}}async fetchTicker(e,t={}){await this.loadOutcome(e);let i=this.outcome(e),s=this.safeString(i.info,"ticker"),r=await this.kalshiPublicGetMarketsTicker(this.extend({ticker:s},t)),a=this.safeValue(r,"market",r);return this.parsePredictionTicker(a,i)}async fetchStatus(e={}){let t=await this.kalshiPublicGetExchangeStatus(e);return{status:!0===this.safeBool(t,"trading_active",!1)?"ok":"maintenance",updated:void 0,eta:void 0,url:void 0,info:t}}async fetchOpenInterest(e,t={}){await this.loadOutcome(e);let i=this.outcome(e),s=this.safeString(i.info,"ticker"),r=await this.kalshiPublicGetMarketsTicker(this.extend({ticker:s},t)),a=this.safeDict(r,"market",r);return this.parsePredictionOpenInterest(a,i)}parsePredictionOpenInterest(e,t){let i=this.parse8601(this.safeString(e,"updated_time")),s=this.safeOpenInterest({symbol:this.safeSymbol(void 0,t),openInterestAmount:this.safeNumber2(e,"open_interest_fp","open_interest"),openInterestValue:void 0,baseVolume:void 0,quoteVolume:void 0,timestamp:i,datetime:this.iso8601(i),info:e},t);return s.outcome=this.safeOutcomeSymbol(void 0,t),s.outcomeId=this.safeString(t,"outcomeId"),delete s.symbol,s}parsePredictionTicker(e,t){let i,s,r,o,n,d,h,c,l=this.safeOutcome(this.safeString(t,"outcome"),t),u="NO"===(null!=t?this.safeString(t,"label",this.safeString(t.info,"outcomeLabel","YES")):"YES").toUpperCase(),f=this.parse8601(this.safeString(e,"updated_time")),p=this.safeString(l,"outcome"),m=this.safeNumber(e,"yes_ask_dollars"),g=this.safeNumber(e,"yes_bid_dollars"),v=this.safeNumber(e,"no_ask_dollars"),y=this.safeNumber(e,"no_bid_dollars"),b=this.safeNumber(e,"last_price_dollars");return u?(i=y,s=v,r=void 0!==b?this.parseNumber(a.Y.stringSub("1",this.numberToString(b))):void 0):(i=g,s=m,r=b),o=u?this.safeString(e,"yes_ask_size_fp"):this.safeString(e,"yes_bid_size_fp"),n=u?this.safeString(e,"yes_bid_size_fp"):this.safeString(e,"yes_ask_size_fp"),void 0!==o&&a.Y.stringGe(o,"0")&&(d=this.parseNumber(o)),void 0!==n&&a.Y.stringGe(n,"0")&&(h=this.parseNumber(n)),void 0!==i&&void 0!==s&&(c=this.parseNumber(a.Y.stringDiv(a.Y.stringAdd(this.numberToString(i),this.numberToString(s)),"2"))),this.safePredictionTicker({outcome:p,outcomeId:this.safeString2(l,"outcomeId","id"),label:this.safeString(l,"label"),market:this.safeString2(l,"market","outcome"),timestamp:f,datetime:this.iso8601(f),high:void 0,low:void 0,bid:i,bidVolume:d,ask:s,askVolume:h,vwap:void 0,open:void 0,close:r,last:r,previousClose:void 0,change:void 0,percentage:void 0,average:c,baseVolume:this.safeNumberN(e,["volume_24h_fp","volume_24h","volume"]),quoteVolume:void 0,info:e},t)}async fetchTickers(e,t={}){if(void 0===e)throw new n.ArgumentsRequired(this.id+" fetchTickers() requires an outcomes argument — the venue has no all-tickers endpoint; pass the outcome handles to fetch (discover them via fetchEvents ())");await this.loadOutcomes(e);let i=[];for(let t=0;t<e.length;t++)i.push(e[t]);let s={},r=[];for(let e=0;e<i.length;e++){let t=this.outcome(i[e]),a=this.safeString(t.info,"ticker");if(void 0===a)continue;a in s||(s[a]=[],r.push(a));let o=s[a];o.push(t),s[a]=o}let a=this.safeInteger(this.options,"fetchTickersBatchSize",100),o={},d=r.length,h=0;for(;h<d;){let e=this.sum(h,a);e>d&&(e=d);let i=[];for(let t=h;t<e;t++)i.push(r[t]);let n={tickers:i.join(","),limit:a},c=await this.kalshiPublicGetMarkets(this.extend(n,t)),l=this.safeList(c,"markets",[]);for(let e=0;e<l.length;e++){let t=l[e],i=this.safeString(t,"ticker");if(void 0===i||!(i in s))continue;let r=s[i];for(let e=0;e<r.length;e++){let i=this.parsePredictionTicker(t,r[e]),s=this.safeString(i,"outcome");void 0!==s&&(o[s]=i)}}h=this.sum(h,a)}return o}async fetchOrderBook(e,t,i={}){await this.loadOutcome(e);let s=this.outcome(e),r=this.safeString(s.info,"ticker"),o="NO"===s.label,n=await this.kalshiPublicGetMarketsTickerOrderbook(this.extend({ticker:r},i)),d=this.safeValue(n,"orderbook_fp",n),h=this.safeList(d,"yes_dollars",[]),c=this.safeList(d,"no_dollars",[]),l=[],u=[];if(o){for(let e=0;e<c.length;e++){let t=this.safeNumber(c[e],0);l.push([t,this.safeNumber(c[e],1)])}for(let e=0;e<h.length;e++){let t=this.safeNumber(h[e],0),i=void 0!==t?this.parseNumber(a.Y.stringSub("1",this.numberToString(t))):void 0;u.push([i,this.safeNumber(h[e],1)])}}else{for(let e=0;e<h.length;e++){let t=this.safeNumber(h[e],0);l.push([t,this.safeNumber(h[e],1)])}for(let e=0;e<c.length;e++){let t=this.safeNumber(c[e],0),i=void 0!==t?this.parseNumber(a.Y.stringSub("1",this.numberToString(t))):void 0;u.push([i,this.safeNumber(c[e],1)])}}return this.safePredictionOrderBook(this.sortedOrders(this.safeString(s,"outcome",e),void 0,l,u),s)}sortedOrders(e,t,i,s){return{outcome:e,bids:this.sortBy(i,0,!0),asks:this.sortBy(s,0),timestamp:t,datetime:this.iso8601(t),nonce:void 0}}async fetchOHLCV(e,t="1m",i,s,r={}){await this.loadOutcome(e);let a=this.outcome(e),o=this.safeString(a.info,"ticker"),d=this.safeString(a.info,"seriesTicker",o),h=this.safeInteger(this.timeframes,t);if(void 0===h){let e=Object.keys(this.timeframes).join(", ");throw new n.BadRequest(this.id+" fetchOHLCV() does not support the "+t+" timeframe (supported: "+e+")")}let c={series_ticker:d,ticker:o,period_interval:h},l=this.seconds(),u=this.parseTimeframe(t);if(void 0!==i){let e=this.parseToInt(i/1e3);if(c.start_ts=e,void 0!==s){let t=this.sum(e,s*u);c.end_ts=t<l?t:l}else c.end_ts=l}else{let e=this.safeInteger(this.options,"defaultFetchOHLCVLimit",200),t=void 0!==s?s:e;c.end_ts=l,c.start_ts=l-t*u}let f=await this.kalshiPublicGetSeriesSeriesTickerMarketsTickerCandlesticks(this.extend(c,r)),p=this.safeList(f,"candlesticks",[]),m=[];for(let e=0;e<p.length;e++){let t=p[e],i=this.safeDict(t,"price",{}),s=this.safeNumber(i,"open_dollars"),r=this.safeNumber(i,"previous_dollars");(void 0!==s||void 0!==r)&&m.push(t)}return this.options.ohlcvCandleDurationSeconds=u,this.parseOHLCVs(m,a,t,i,s)}parseOHLCV(e,t){let i=this.safeDict(e,"price",{}),s=this.safeNumber(i,"previous_dollars"),r=this.safeTimestamp(e,"end_period_ts"),a=this.safeInteger(this.options,"ohlcvCandleDurationSeconds",0),o=r;return void 0!==r&&(o=r-1e3*a),[o,this.safeNumber(i,"open_dollars",s),this.safeNumber(i,"high_dollars",s),this.safeNumber(i,"low_dollars",s),this.safeNumber(i,"close_dollars",s),this.safeNumber(e,"volume_fp",0)]}async fetchTrades(e,t,i,s={}){await this.loadOutcome(e);let r=this.outcome(e),a=this.safeString(r.info,"ticker"),o={ticker:a};void 0!==i&&(o.limit=Math.min(i,1e3));let n=await this.kalshiPublicGetMarketsTrades(this.extend(o,s)),d=this.safeList(n,"trades",[]),h=[];for(let e=0;e<d.length;e++){let t=d[e],i=this.safeString2(t,"ticker","market_ticker");(void 0===i||i===a)&&h.push(t)}return this.parsePredictionTrades(h,r,t,i)}parsePredictionTrade(e,t){let i,s,r,a=this.safeString(e,"trade_id"),o=this.parse8601(this.safeString(e,"created_time")),n=this.safeNumber2(e,"yes_price_dollars","price_dollars"),d=this.safeNumber2(e,"yes_price","price");void 0!==n?i=n:void 0!==d&&(i=d/100);let h=this.safeNumber2(e,"count_fp","size_fp"),c=this.safeNumber(e,"count",h),l=this.safeStringLower(e,"taker_side"),u=this.safeOutcome(this.safeString(t,"outcome"),t),f=this.safeDict(u,"info",{}),p=this.safeStringLower(u,"label",this.safeStringLower(f,"outcomeLabel")),m=this.safeString(u,"outcome"),g=this.safeString2(u,"outcomeId","id");return("yes"===l||"no"===l)&&(s="yes"===p||"no"===p?l===p?"buy":"sell":"yes"===l?"buy":"sell"),void 0!==i&&void 0!==c&&(r=i*c),this.safePredictionTrade({id:a,info:e,timestamp:o,datetime:this.iso8601(o),outcome:m,outcomeId:g,label:this.safeString(u,"label"),market:this.safeString2(u,"market","outcome"),order:void 0,type:void 0,side:s,takerOrMaker:"taker",price:i,amount:c,cost:r,fee:void 0},t)}async fetchMyTrades(e,t,i,s={}){let r,a;void 0!==e&&await this.loadOutcome(e);let o={};if(void 0!==e){if(void 0===(r=this.outcome(e)))throw new n.ArgumentsRequired(this.id+" requires a valid outcome");o.ticker=this.safeString(r.info,"ticker")}void 0!==i&&(o.limit=i);let d=await this.kalshiPrivateGetPortfolioFills(this.extend(o,s)),h=this.safeList(d,"fills",[]),c=h.length,l=[];for(let e=0;e<c;e++)l.push(this.parseMyTrade(h[e],r));void 0!==e&&(a=this.safeString(this.outcome(e),"outcome"));let u=[];for(let e=0;e<l.length;e++){let t=l[e];(void 0===a||this.safeString(t,"outcome")===a)&&u.push(t)}return this.filterBySinceLimit(u,t,i,"timestamp")}parseMyTrade(e,t){let i,s,r,a=this.safeString2(e,"fill_id","trade_id"),o=this.safeString(e,"order_id"),n=this.safeString2(e,"ticker","market_ticker"),d=this.safeStringLower(e,"side"),h=n;"no"===d&&void 0!==n&&(h=n+"-NO");let c=this.safeOutcome(h,t),l=this.parse8601(this.safeString(e,"created_time")),u=this.safeStringLower(e,"action"),f="buy";if("sell"===u&&(f="sell"),"no"===d){if(void 0===(i=this.safeNumber(e,"no_price_dollars"))){let t=this.safeNumber(e,"no_price");void 0!==t&&(i=t/100)}}else if(void 0===(i=this.safeNumber(e,"yes_price_dollars"))){let t=this.safeNumber(e,"yes_price");void 0!==t&&(i=t/100)}let p=this.safeNumber2(e,"count_fp","count");void 0!==i&&void 0!==p&&(s=i*p);let m=this.safeBool(e,"is_taker",!0),g="maker";!0===m&&(g="taker");let v=this.safeNumber(e,"fee_cost");return void 0!==v&&(r={cost:v,currency:"USD"}),this.safePredictionTrade({id:a,info:e,timestamp:l,datetime:this.iso8601(l),outcome:this.safeString(c,"outcome",h),outcomeId:this.safeString2(c,"outcomeId","id"),label:this.safeString(c,"label"),market:this.safeString2(c,"market","outcome"),order:o,type:void 0,side:f,takerOrMaker:g,price:i,amount:p,cost:s,fee:r},t)}async fetchBalance(e={}){let t=await this.kalshiPrivateGetPortfolioBalance(e);return this.parseBalance(t)}parseBalance(e){let t,i={info:e},s=this.safeNumber(e,"balance");return void 0!==s&&(t=s/100),i.USD={free:t,used:0,total:t},this.safeBalance(i)}async fetchPositions(e,t={}){let i=0;void 0!==e&&(i=e.length),i>0&&await this.loadOutcomes(e);let s=await this.kalshiPrivateGetPortfolioPositions(t),r=this.safeList(s,"market_positions",[]),a=this.parsePredictionPositions(r);if(0===i)return a;let o={};if(void 0===e)throw new n.ExchangeError(this.id+" fetchPositions() missing outcomes");for(let t=0;t<e.length;t++){let i=this.outcome(e[t]),s=this.safeDict(i,"info",{}),r=this.safeString(s,"ticker");void 0!==r&&(o[r]=!0)}let d=[];for(let e=0;e<a.length;e++){let t=a[e],i=this.safeDict(t,"info",{}),s=this.safeString(i,"ticker");void 0!==s&&s in o&&d.push(t)}return d}async fetchSettlements(e,t,i,s={}){let r;void 0!==e&&await this.loadOutcome(e);let a={};void 0!==i&&(a.limit=i);let o=await this.kalshiPrivateGetPortfolioSettlements(this.extend(a,s)),n=this.safeList(o,"settlements",[]),d=n.length,h=[];for(let e=0;e<d;e++)h.push(this.parseSettlement(n[e]));void 0!==e&&(r=this.safeString(this.outcome(e),"outcome"));let c=[];for(let e=0;e<h.length;e++){let t=h[e];(void 0===r||this.safeString(t,"outcome")===r)&&c.push(t)}return this.filterBySinceLimit(c,t,i,"timestamp")}parseSettlement(e,t){let i,s,r=this.safeString(e,"ticker"),a=this.safeNumber2(e,"yes_count_fp","yes_count",0),o=this.safeNumber2(e,"no_count_fp","no_count",0),n=a>=o,d="NO";n&&(d="YES");i=n||void 0===r?r:r+"-NO";let h=this.safeOutcome(i,t),c=this.safeStringUpper(e,"market_result"),l=c===d,u=this.safeNumber(e,"revenue_dollars");if(void 0===u){let t=this.safeNumber(e,"revenue");void 0!==t&&(u=t/100)}let f="no_total_cost";n&&(f="yes_total_cost");let p="no_total_cost_dollars";n&&(p="yes_total_cost_dollars");let m=this.safeNumber(e,p);if(void 0===m){let t=this.safeNumber(e,f);void 0!==t&&(m=t/100)}void 0!==u&&void 0!==m&&(s=u-m);let g=this.parse8601(this.safeString(e,"settled_time"));return{info:e,id:r,timestamp:g,datetime:this.iso8601(g),outcome:this.safeString(h,"outcome",i),outcomeId:this.safeString2(h,"outcomeId","id",i),market:this.safeString2(h,"market","outcome"),event:void 0,result:c,won:l,amount:n?a:o,price:+!!l,cost:m,payout:u,pnl:s}}parsePredictionPosition(e,t){let i,s,r=this.safeString(e,"ticker"),o=this.safeOutcome(r,t),n=this.safeNumber(e,"position");return void 0!==n&&(i=n>=0?"long":"short",s=this.parseNumber(a.Y.stringAbs(this.numberToString(n)))),this.safePredictionPosition({id:void 0,outcome:this.safeString(o,"outcome",r),outcomeId:this.safeString2(o,"outcomeId","id"),label:this.safeString(o,"label"),market:this.safeString2(o,"market","outcome"),timestamp:void 0,datetime:void 0,contracts:s,contractSize:1,side:i,notional:void 0,leverage:1,unrealizedPnl:void 0,realizedPnl:void 0,collateral:void 0,entryPrice:void 0,markPrice:void 0,liquidationPrice:void 0,hedged:!1,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,initialMargin:void 0,initialMarginPercentage:void 0,marginRatio:void 0,marginMode:"cross",marginType:"cross",percentage:void 0,info:e})}async fetchOpenOrders(e,t,i,s={}){let r;void 0!==e&&await this.loadOutcome(e);let a={status:"resting"};if(void 0!==e){if(void 0===(r=this.outcome(e)))throw new n.ArgumentsRequired(this.id+" requires a valid outcome");a.ticker=this.safeString(r.info,"ticker")}let o=await this.kalshiPrivateGetPortfolioOrders(this.extend(a,s)),d=this.safeList(o,"orders",[]);return this.parsePredictionOrders(d,r,t,i)}async fetchOrders(e,t,i,s={}){let r;void 0!==e&&await this.loadOutcome(e);let a={};if(void 0!==e){if(void 0===(r=this.outcome(e)))throw new n.ArgumentsRequired(this.id+" requires a valid outcome");a.ticker=this.safeString(r.info,"ticker")}let o=await this.kalshiPrivateGetPortfolioOrders(this.extend(a,s)),d=this.safeList(o,"orders",[]);return this.parsePredictionOrders(d,r,t,i)}async fetchClosedOrders(e,t,i,s={}){let r=await this.fetchOrders(e,void 0,void 0,s),a=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.safeString(t,"status");("closed"===i||"canceled"===i)&&a.push(t)}return this.filterBySinceLimit(a,t,i,"timestamp")}async fetchOrder(e,t,i={}){void 0!==t&&await this.loadOutcome(t);let s=await this.kalshiPrivateGetPortfolioOrdersOrderId(this.extend({order_id:e},i));return this.parsePredictionOrder(this.safeValue(s,"order",s))}parsePredictionOrder(e,t){let i,s=this.safeString(e,"order_id"),r=this.safeString(e,"ticker"),a=this.safeStringLower(e,"side"),o=r;"no"===a&&void 0!==r&&(o=r+"-NO");let n=this.safeOutcome(o,t),d=this.parseOrderStatus(this.safeString(e,"status")),h=this.safeStringLower(e,"action");"buy"===h?i="buy":"sell"===h&&(i="sell");let c="NO"===this.safeStringUpper(n,"label"),l="yes_price_dollars";c&&(l="no_price_dollars");let u="yes_price";c&&(u="no_price");let f=this.safeNumber(e,l);if(void 0===f){let t=this.safeNumber(e,u);void 0!==t&&(f=t/100)}let p=this.safeNumber2(e,"initial_count_fp","count"),m=this.safeNumber2(e,"fill_count_fp","filled_count",0),g=this.safeNumber(e,"remaining_count_fp");void 0===g&&void 0!==p&&void 0!==m&&(g=p-m);let v=this.parse8601(this.safeString(e,"created_time"));return this.safePredictionOrder({id:s,clientOrderId:this.safeString(e,"client_order_id"),info:e,timestamp:v,datetime:this.iso8601(v),lastTradeTimestamp:void 0,status:d,outcome:this.safeString(n,"outcome"),outcomeId:this.safeString2(n,"outcomeId","id"),label:this.safeString(n,"label"),market:this.safeString2(n,"market","outcome"),type:this.safeStringLower(e,"type","limit"),timeInForce:"GTC",postOnly:void 0,side:i,price:f,stopPrice:void 0,triggerPrice:void 0,average:void 0,amount:p,cost:void 0,filled:m,remaining:g,fee:void 0,trades:[]},n)}parseOrderStatus(e){return this.safeString({resting:"open",executed:"closed",canceled:"canceled",pending:"open"},e,e)}async createOrder(e,t,i,s,r,o={}){if(void 0===r)throw new n.ArgumentsRequired(this.id+" createOrder() requires a price - kalshi has only limit orders (no market orders). For immediate execution pass an aggressive price with params { 'time_in_force': 'immediate_or_cancel' }");await this.loadOutcome(e);let d=this.outcome(e),h=this.safeString(d.info,"ticker"),c="NO"===d.label,l="buy"===i,u="ask";l&&(u="bid");let f=r;c&&(u=l?"ask":"bid",void 0!==r&&(f=this.parseNumber(a.Y.stringSub("1",this.numberToString(r)))));let p=this.safeStringUpper(o,"timeInForce"),m=this.omit(o,"timeInForce"),g="good_till_canceled";"market"===t&&(g="immediate_or_cancel"),"IOC"===p?g="immediate_or_cancel":"FOK"===p?g="fill_or_kill":"GTC"===p&&(g="good_till_canceled");let[v,y]=this.handleOptionStringAndParams(m,"createOrder","time_in_force",g),[b,w]=this.handleOptionStringAndParams(y,"createOrder","self_trade_prevention_type","taker_at_cross"),k={ticker:h,side:u,count:this.numberToString(s),time_in_force:v,self_trade_prevention_type:b};void 0!==f&&(k.price=this.numberToString(f));let S=await this.kalshiPrivatePostPortfolioEventsOrders(this.extend(k,w)),O=this.parsePredictionOrder(S,d);O.side=i,O.amount=s,O.price=r;let T=this.safeNumber(S,"remaining_count"),P=this.safeNumber(S,"fill_count");if(void 0!==P?O.filled=P:void 0!==T&&void 0!==s&&(O.filled=s-T),void 0!==T&&(O.remaining=T),void 0===O.status){let e="open";void 0!==T&&0===T&&(e="closed"),O.status=e}return O}async editOrder(e,t,i,s,r,a,o={}){if(void 0===a)throw new n.ArgumentsRequired(this.id+" editOrder() requires a price - kalshi has only limit orders");if(void 0===r)throw new n.ArgumentsRequired(this.id+" editOrder() requires an amount");return await this.loadOutcome(t),await this.cancelOrder(e,t),await this.createOrder(t,i,s,r,a,o)}async cancelOrder(e,t,i={}){let s;void 0!==t&&(s=await this.loadOutcome(t));let r=await this.kalshiPrivateDeletePortfolioEventsOrdersOrderId(this.extend({order_id:e},i)),a=this.parsePredictionOrder(this.safeDict(r,"order",r),s);return void 0===a.id&&(a.id=e),void 0===a.status&&(a.status="canceled"),a}async cancelAllOrders(e,t={}){void 0!==e&&await this.loadOutcome(e);let i={status:"resting"};if(void 0!==e){let t=this.outcome(e);i.ticker=this.safeString(t.info,"ticker")}let s=await this.kalshiPrivateGetPortfolioOrders(i),r=this.safeList(s,"orders",[]),a=r.length,o=[];for(let e=0;e<a;e++){let i=r[e],s=this.safeString(i,"order_id");if(void 0!==s){await this.kalshiPrivateDeletePortfolioEventsOrdersOrderId(this.extend({order_id:s},t));let e=this.parsePredictionOrder(i);e.status="canceled",o.push(e)}}return o}async fetchEvents(e={}){let t,i=this.parseSearchQueries(e);if(void 0===i)throw new n.ExchangeError(this.id+" fetchEvents() missing queries");let s=i.length,r=this.omit(e,["query","queries"]),a=this.safeInteger(r,"limit"),o=this.safeInteger(this.options,"maxFetchEventsResults",100);void 0!==a&&(o=a);let d=this.safeString(r,"status",this.safeString(this.options,"defaultEventStatus","open"));"active"===d||"open"===d?t="open":"closed"===d||"inactive"===d?t="closed":("settled"===d||"resolved"===d)&&(t="settled");let h=this.omit(r,["status","limit","maxPages","sort","searchIn","eventId","slug","tags","category","series_ticker"]);void 0===this.markets&&(this.markets=this.createSafeDictionary());let c=this.safeString2(r,"eventId","slug"),l=[];if(s>0)l=await this.fetchEventsByQuery(i,o,h);else if(void 0!==c)l=[await this.fetchRawEventByTicker(c,h)];else{let e=await this.resolveEventSeriesTickers(r);0===e.length&&this.requireEventQuery(r),l=await this.fetchSeriesEvents(e,t,o,h)}let u=l.length,f=[];for(let e=0;e<u;e++){let t=this.parseEvent(l[e]);f.push(t);let i=t.markets,s=void 0!==i?i:[],r=s.length;for(let e=0;e<r;e++){let t=s[e];this.markets[t.market]=t}}this.populateOutcomes();let p=this.omit(r,["tags","category","series_ticker"]);return this.applyEventFetchParams(f,p,[])}async fetchEventsByQuery(e,t,i={}){let s=void 0!==t?t:this.safeInteger(this.options,"searchSeriesLimit",25),r={},a=[],o=e.length;for(let t=0;t<o;t++){let i=await this.electionsPublicGetSearchSeries({query:e[t],order_by:"querymatch",page_size:s}),o=this.safeList(i,"current_page",[]),n=o.length;for(let e=0;e<n;e++){let t=this.safeString(o[e],"event_ticker");void 0!==t&&void 0===this.safeString(r,t)&&(r[t]=t,a.push(t))}}let d=[],h=a.length;for(let e=0;e<h;e++){let s=d.length;if(void 0!==t&&s>=t)break;try{let t=await this.fetchRawEventByTicker(a[e],i);d.push(t)}catch(e){if(!(e instanceof n.BadSymbol))throw e}}return d}async fetchRawEventByTicker(e,t={}){let i=await this.kalshiPublicGetEventsEventTicker(this.extend({event_ticker:e,with_nested_markets:!0},t)),s=this.safeDict(i,"event",i);return void 0===this.safeList(s,"markets")&&(s.markets=this.safeList(i,"markets",[])),s}async resolveEventSeriesTickers(e={}){let t=[],i=this.safeList(e,"tags",[]),s=i.length;for(let e=0;e<s;e++){let s=await this.kalshiPublicGetSeries({tags:i[e]}),r=this.safeList(s,"series",[]),a=r.length;for(let e=0;e<a;e++){let i=this.safeString(r[e],"ticker");void 0!==i&&t.push(i)}}let r=this.safeString(e,"category");if(void 0!==r){let e=await this.kalshiPublicGetSeries({category:r}),i=this.safeList(e,"series",[]),s=i.length;for(let e=0;e<s;e++){let s=this.safeString(i[e],"ticker");void 0!==s&&t.push(s)}}let a=this.safeString(e,"series_ticker");if(void 0!==a){let e=a.split(","),i=e.length;for(let s=0;s<i;s++)t.push(e[s])}let o={},n=[],d=t.length;for(let e=0;e<d;e++){let i=t[e],s=this.safeString(o,i);void 0!==i&&""!==i&&void 0===s&&(o[i]=i,n.push(i))}return n}async fetchSeriesEvents(e,t,i,s={}){let r=[],a=e.length,o=this.safeInteger(this.options,"defaultFetchEventsLimit",200),n=this.safeInteger(this.options,"maxEventPagesPerSeries",20);for(let d=0;d<a;d++){let a,h=r.length;if(void 0!==i&&h>=i)break;for(let h=0;h<n;h++){let n=o;if(void 0!==i){let e=i-r.length;if(e<n&&(n=e),n<=0)break}let h={series_ticker:e[d],status:t,with_nested_markets:!0,limit:n};void 0!==a&&(h.cursor=a);let c=await this.kalshiPublicGetEvents(this.extend(h,s)),l=this.safeList(c,"events",[]),u=l.length;for(let e=0;e<u;e++)r.push(l[e]);a=this.safeString(c,"cursor");let f=r.length;if(void 0!==i&&f>=i||void 0===a||""===a||u<n)break}}return r}async fetchEvent(e,t={}){let i=await this.fetchRawEventByTicker(e,t),s=this.parseEvent(i);return this.indexEventOutcomes(s),s}parseEvent(e){let t,i,s,r,a=this.safeList(e,"markets",[]),o=[],n=0,d=0,h=!1,c=!0;for(let e=0;e<a.length;e++){let s=a[e],r=this.parseMarket(s);o.push(r),n=this.sum(n,this.safeNumber2(s,"volume_fp","volume",0)),d=this.sum(d,this.safeNumber2(s,"liquidity_dollars","liquidity",0));let l=this.parse8601(this.safeString(s,"open_time"));void 0!==l&&(void 0===t||l<t)&&(t=l);let u=this.safeString(s,"status");"active"===u&&(h=!0);let f=this.safeString(s,"result");"settled"!==u&&(void 0===f||""===f)&&(c=!1);let p=this.parse8601(this.safeString(s,"close_time"));void 0!==p&&(void 0===i||p>i)&&(i=p)}let l=o.length;l>0&&(s=h);let u=this.safeBool(e,"resolved");void 0===u&&l>0&&(u=c);let f=this.parse8601(this.safeString(e,"end_date_iso"));void 0===f&&(f=i);let p=this.safeString(e,"event_ticker"),m=this.safeString(e,"title");void 0!==m&&""!==m&&(r=this.shortenSlug(m));let g=this.parse8601(this.safeString(e,"created_date_iso"));return void 0===g&&(g=t),this.extend({id:p,slug:p,event:r,title:m,markets:o,volume:n,liquidity:d,url:this.safeString(e,"url"),image:this.safeString(e,"image_url"),created:g,createdDatetime:this.safeString(e,"created_date_iso"),end:f,endDatetime:this.iso8601(f),category:this.safeString(e,"category"),lastUpdatedAt:this.parse8601(this.safeString(e,"last_updated_date_iso")),lastUpdatedAtDatetime:this.safeString(e,"last_updated_date_iso"),resolutionSource:this.safeString(e,"resolution_source"),active:s,resolved:u,info:e})}sign(e,t="kalshi",i="GET",r={},a,n){let d="string"==typeof t?t:t[0],h="string"==typeof t?"public":t[1],c=this.urls.api,l=this.safeString(c,d,c.kalshi),u=this.implodeParams(e,r),f=l+"/"+u,p=this.omit(r,this.extractParams(e)),m=this.urlencode(p);"GET"===i&&""!==m&&(f+="?"+m);let g=this.extend({Accept:"application/json","Content-Type":"application/json"},void 0!==a?a:{}),v=n;if("private"===h){this.checkRequiredCredentials();let e=this.milliseconds().toString(),t=l.indexOf("/trade-api"),r=l.slice(t),a=this.privateKey.split("\\n").join("\n"),n=(0,o.n)(e+i+(r+"/")+u,a,s.sc,"pss");g=this.extend(g,{"KALSHI-ACCESS-KEY":this.apiKey,"KALSHI-ACCESS-SIGNATURE":n,"KALSHI-ACCESS-TIMESTAMP":e}),"GET"!==i&&""!==m&&(v=this.json(p))}return{url:f,method:i,body:v,headers:g}}}i.d(t,{A:()=>d})},3454(e,t,i){"use strict";var s=i(4721),r=i(6885),a=i(6834),o=i(4531),n=i(1453),d=i(7749),h=i(1093);class c extends o.A{describe(){return this.deepExtend(super.describe(),{id:"limitless",name:"Limitless",countries:[],rateLimit:200,certified:!1,pro:!1,has:{CORS:void 0,spot:!1,margin:!1,swap:!1,future:!1,option:!1,approve:!0,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,createOrder:!0,fetchAccounts:!0,fetchBalance:!1,fetchClosedOrders:!0,fetchCurrencies:!1,fetchEvent:!0,fetchEvents:!0,fetchMarkets:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchOrdersByIds:!0,fetchPositions:!0,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,prediction:!0,redeem:!0},timeframes:{"1h":"1h","6h":"6h","1d":"1d","1w":"1w","1M":"1m"},urls:{logo:"https://github.com/user-attachments/assets/bb10c8b4-7b97-49f5-927c-057709dbaf7e",api:{limitless:"https://api.limitless.exchange"},www:"https://limitless.exchange",doc:["https://docs.limitless.exchange"]},api:{limitless:{public:{get:{"markets/active":{cost:1},"markets/active/{categoryId}":{cost:1},categories:{cost:1},"markets/{addressOrSlug}":{cost:1},"markets/categories/count":{cost:1},"markets/active/slugs":{cost:1},"markets/search":{cost:1},"markets/{slug}/orderbook":{cost:1},"markets/{slug}/historical-price":{cost:1},"auth/signing-message":{cost:1},"markets/{addressOrSlug}/oracle-candles":{cost:1},"markets/{slug}/get-feed-events":{cost:1},"markets/{slug}/events":{cost:1},"markets/timeline":{cost:1},"markets/{slug}/timeline":{cost:1},navigation:{cost:1},"market-pages/by-path":{cost:1},"market-pages/{id}/markets":{cost:1},"property-keys":{cost:1},"property-keys/{id}":{cost:1},"property-keys/{id}/options":{cost:1},"portfolio/{account}/traded-volume":{cost:1},"portfolio/{account}/positions":{cost:1},"portfolio/{account}/pnl-chart":{cost:1}}},private:{get:{"auth/api-keys":{cost:1},"profiles/partner-accounts":{cost:1},"markets/{slug}/user-orders":{cost:1},"portfolio/positions":{cost:1},"portfolio/trades":{cost:1},"markets/{slug}/locked-balance":{cost:1},"profiles/me":{cost:1},"profiles/{account}":{cost:1},"portfolio/pnl-chart":{cost:1},"portfolio/history":{cost:1},"portfolio/points":{cost:1},"portfolio/trading/allowance":{cost:1},"auth/api-tokens/capabilities":{cost:1},"auth/api-tokens":{cost:1},"profiles/partner-accounts/{profileId}/allowances":{cost:1}},post:{"auth/logout":{cost:1},"auth/api-keys":{cost:1},"auth/login":{cost:1},orders:{cost:1},"orders/cancel":{cost:1},"orders/cancel-batch":{cost:1},"orders/batch-cancel":{cost:1},"orders/status/batch":{cost:1},"portfolio/redeem":{cost:1},"portfolio/withdraw":{cost:1},"portfolio/withdrawal-addresses":{cost:1},"auth/api-tokens/derive":{cost:1},"profiles/partner-accounts":{cost:1},"profiles/partner-accounts/{profileId}/allowances/retry":{cost:1}},delete:{"auth/api-keys":{cost:1},"orders/{order_id}":{cost:1},"orders/all/{slug}":{cost:1},"auth/api-tokens/{tokenId}":{cost:1},"portfolio/withdrawal-addresses/{address}":{cost:1}}}}},requiredCredentials:{apiKey:!0,secret:!0,privateKey:!0},fees:{trading:{tierBased:!1,percentage:!0,maker:.02,taker:.02}},options:{defaultFetchMarketsPages:5,marketsPageSize:25,usdcDecimals:6,warnOnCancelAllOrdersWithOutcome:!0,zeroAddress:"0x0000000000000000000000000000000000000000",chainId:8453,rpcUrl:"https://mainnet.base.org",collateralAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",exchangeAddress:"0x05c748E2f4DcDe0ec9Fa8DDc40DE6b867f923fa5",createMarketBuyOrderRequiresPrice:!0},exceptions:{exact:{},broad:{"Order not found":n.OrderNotFound,"Orders not found":n.OrderNotFound,"already canceled":n.OrderNotFound,"must be a UUIDv4":n.BadRequest,"Invalid signature":n.InvalidOrder}}})}async fetchMarkets(e={}){let t=this.parseSearchQueries(e),i=this.omit(e,["query","queries","limit"]),s=this.safeInteger(e,"limit",this.safeInteger(this.options,"fetchMarketsLimit",1e3)),r=[];if(t.length>0){let s=Math.min(this.safeInteger(e,"limit",50),50),a=this.omit(i,["limit"]),o={};for(let e=0;e<t.length;e++){let i=t[e],n=await this.limitlessPublicGetMarketsSearch(this.extend({query:i,limit:s},a)),d=this.safeList(n,"markets",[]);for(let e=0;e<d.length;e++){let t=d[e],i=this.safeString(t,"slug");void 0===i||""===i||i in o||(o[i]=!0,r.push(t))}}}else{let e=1,t=this.safeInteger(this.options,"marketsPageSize",25),a={page:e,limit:t},o=await this.limitlessPublicGetMarketsActive(this.extend(a,i)),n=this.safeInteger(o,"totalMarketsCount"),d=this.safeList(o,"data",[]);r=this.arrayConcat(r,d);let h=[],c=Math.ceil(s/t),l=Math.min(Math.ceil((void 0!==n?n:0)/t),c);for(let t=2;t<=l;t++)a.page=e=t,h.push(this.limitlessPublicGetMarketsActive(this.extend(a,i)));let u=await Promise.all(h),f=u.length;for(let e=0;e<f;e++){let t=this.safeDict(u,e),i=this.safeList(t,"data",[]);r=this.arrayConcat(r,i)}let p=this.safeDict(u,f-1),m=this.safeList(p,"data",[]).length,g=r.length;if(m>=t&&g<s)for(;;){a.page=e=this.sum(e,1);let o=await this.limitlessPublicGetMarketsActive(this.extend(a,i)),n=[];Array.isArray(o)&&(n=o);let d=this.safeList(o,"data",n),h=void 0!==d?d:[],c=h.length;if(0===c)break;for(let e=0;e<h.length;e++){let t=h[e];r.push(t)}let l=r.length;if(c<t||l>=s)break}}let a=[],o={},n=this.expandGroupRows(r);for(let e=0;e<n.length;e++){let t,i=n[e],s=this.safeStringN(i,["groupSlug","groupId"],this.safeString(i,"slug"));void 0!==s&&""!==s&&(t=this.shortenSlug(s));let r=this.parseMarket(i);if(a.push(r),void 0!==t&&""!==t){t in o||(o[t]={groupId:s,title:this.safeString2(i,"groupTitle","title",s),raw:i,markets:[]});let e=o[t],a=e.markets;a.push(r),e.markets=a}}let d={},h=Object.keys(o);for(let e=0;e<h.length;e++){let t=h[e],i=o[t];d[t]=this.parseEvent(i)}return(this.events=d,a.length>s)?this.arraySlice(a,0,s):a}parseMarket(e){let t,i=this.safeString(e,"slug"),s=this.safeString(e,"address",i),r=this.safeStringN(e,["groupSlug","groupId"],i),a=this.safeString(e,"conditionId"),o=this.safeDict(e,"tokens",{}),n=this.safeBool(e,"expired",!1),d=this.safeString(e,"status"),h=!0!==n&&"FUNDED"===d,c=this.safeInteger(e,"expirationTimestamp"),l=this.safeNumber(e,"volumeFormatted"),u=this.safeInteger(e,"winningOutcomeIndex"),f=void 0!==u,p=this.slugToMarketSymbol(r,i),m=this.safeDict(e,"collateralToken",{}),g=this.safeInteger(m,"decimals",this.safeInteger(this.options,"usdcDecimals",6)),v={amount:this.parseNumber(this.parsePrecision(this.numberToString(g))),price:.001},y=[],b=Object.keys(o);for(let e=0;e<b.length;e++){let n,d,c=b[e],m=o[c],g=this.slugToOutcomeSymbol(r,i,c),w=c.toLowerCase(),k=e;"yes"===w?k=0:"no"===w&&(k=1),f&&(d=+!!(n=k===u),n&&(t=g));let S=n,O=d;y.push({outcome:g,outcomeId:m,market:p,label:c,active:h,winner:S,settleFraction:O,precision:v,info:{slug:i,address:s,conditionId:a,outcomeLabel:c,tokenId:m,volume24h:l}})}return{id:i,market:p,marketType:y.length>2?"categorical":"binary",executionModel:"clob",collateral:"USDC",base:i,quote:"USDC",settle:void 0,baseId:i,quoteId:"USDC",settleId:void 0,type:"prediction",spot:!1,margin:!1,swap:!1,future:!1,option:!1,prediction:!0,active:h,resolved:f,resolvedOutcome:t,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:c,expiryDatetime:this.iso8601(c),strike:void 0,optionType:void 0,taker:.02,maker:.02,percentage:!0,tierBased:!1,feeSide:"get",precision:v,limits:{leverage:{min:1,max:1},amount:{min:0,max:void 0},price:{min:.001,max:.999},cost:{min:void 0,max:void 0}},outcomes:y,info:this.extend(e,{slug:i,address:s,volume24h:l}),created:void 0}}async fetchEvent(e,t={}){let i=await this.limitlessPublicGetMarketsAddressOrSlug(this.extend({addressOrSlug:e},t)),s=this.expandGroupRows([i]),r=this.extend(i,{markets:s}),a=this.parseEvent(r);return this.indexEventOutcomes(a),a}expandGroupRows(e){let t=[];for(let i=0;i<e.length;i++){let s=e[i],r=this.safeString(s,"marketType"),a=this.safeList(s,"markets");if("group"===r&&void 0!==a){let e=this.safeString(s,"slug"),i=this.safeString(s,"title",e),r=a.length;for(let s=0;s<r;s++){let r=this.extend(a[s],{groupSlug:e,groupTitle:i});t.push(r)}}else t.push(s)}return t}parseEvent(e){let t,i=this.safeString(e,"address",this.safeString(e,"groupId",this.safeString(e,"slug"))),s=this.safeString(e,"deadline",this.safeString(e,"expiresAt")),r=this.safeString(e,"title",i);void 0!==i&&""!==i&&(t=this.shortenSlug(i));let a=void 0!==s&&""!==s?this.parse8601(s):void 0,o=[],n=this.safeList(e,"markets",[]),d=0;for(let e=0;e<n.length;e++){let t=n[e],i=this.safeString2(t,"market","symbol"),s=this.safeList(t,"outcomes");void 0!==i&&void 0!==s?o.push(t):o.push(this.parseMarket(t));let r=this.safeDict(t,"info",t);d=this.sum(d,this.safeNumber(r,"volumeFormatted",0))}return this.extend({id:i,slug:i,event:t,title:r,description:this.safeString(e,"description"),markets:o,volume:d,liquidity:this.safeNumber(e,"liquidity"),url:this.safeString(e,"url"),image:this.safeString(e,"imageUrl",this.safeString(e,"image")),active:this.safeBool(e,"active",!0),resolved:this.safeBool(e,"resolved",!1),category:this.safeString(e,"category"),tags:this.safeList(e,"tags"),created:this.parse8601(this.safeString(e,"createdAt")),createdDatetime:this.safeString(e,"createdAt"),end:a,endDatetime:s,lastUpdatedAt:this.parse8601(this.safeString(e,"updatedAt")),resolutionSource:this.safeString(e,"resolutionSource"),info:e})}async fetchTicker(e,t={}){await this.loadOutcome(e);let i=this.outcome(e),s=this.safeString(i.info,"slug"),r=[this.limitlessPublicGetMarketsAddressOrSlug(this.extend({addressOrSlug:s},t)),this.limitlessPublicGetMarketsSlugOrderbook({slug:s})],a=await Promise.all(r),o={market:a[0],book:a[1]};return this.parsePredictionTicker(o,i)}parsePredictionTicker(e,t){let i,s,r,a,o,n,h,c,l=e;"market"in e&&(l=this.safeDict(e,"market",{}),i=this.safeDict(e,"book"));let u="no"!==(void 0!==t?this.safeString(t,"label",this.safeString(t.info,"outcomeLabel","yes")):"yes").toLowerCase();if(void 0!==i){let e=this.safeList(i,"bids",[]),t=this.safeList(i,"asks",[]),c=e.length,l=t.length,f=c>0?e[0]:void 0,p=l>0?t[0]:void 0,m=this.safeString(f,"price"),g=this.safeString(f,"size"),v=this.safeString(p,"price"),y=this.safeString(p,"size"),b=this.safeString(i,"lastTradePrice"),w=this.safeString(i,"midpoint");u?(s=m,a=g,r=v,o=y,n=b,h=w):(void 0!==v&&(s=d.Y.stringSub("1",v)),a=y,void 0!==m&&(r=d.Y.stringSub("1",m)),o=g,void 0!==b&&(n=d.Y.stringSub("1",b)),void 0!==w&&(h=d.Y.stringSub("1",w)))}let f=this.safeList(l,"prices",[]),p=f.length;void 0===n&&p>0&&(n=u?this.safeString(f,0):this.safeString(f,1));let m=this.safeString(l,"volume");void 0!==m&&(c=d.Y.stringDiv(m,"1000000")),void 0!==a&&(a=d.Y.stringDiv(a,"1000000")),void 0!==o&&(o=d.Y.stringDiv(o,"1000000"));let g=this.safeOutcomeSymbol(void 0,t);return this.safePredictionTicker({outcome:g,outcomeId:this.safeString(t,"outcomeId"),label:this.safeString(t,"label"),market:this.safeString(t,"market"),timestamp:void 0,datetime:void 0,high:void 0,low:void 0,bid:this.parseNumber(s),bidVolume:this.parseNumber(a),ask:this.parseNumber(r),askVolume:this.parseNumber(o),vwap:void 0,open:void 0,close:this.parseNumber(n),last:this.parseNumber(n),previousClose:void 0,change:void 0,percentage:void 0,average:this.parseNumber(h),baseVolume:void 0,quoteVolume:this.parseNumber(c),info:e})}async fetchTickers(e,t={}){if(void 0===e)throw new n.ArgumentsRequired(this.id+" fetchTickers() requires an outcomes argument — the venue has no all-tickers endpoint; pass the outcome handles to fetch (discover them via fetchEvents ())");let i={};await this.loadOutcomes(e);let s={},r=[];for(let t=0;t<e.length;t++){let i=this.outcome(e[t]),a=this.safeString(i.info,"slug");if(void 0===a)throw new n.ExchangeError(this.id+" fetchTickers() missing slug");a in s||(void 0!==a&&(s[a]=[]),r.push(a));let o=this.safeValue(s,a);o.push(i),void 0!==a&&(s[a]=o)}let a=[];for(let e=0;e<r.length;e++){let i=r[e];a.push(this.limitlessPublicGetMarketsAddressOrSlug(this.extend({addressOrSlug:i},t))),a.push(this.limitlessPublicGetMarketsSlugOrderbook({slug:i}))}let o=await Promise.all(a);for(let e=0;e<r.length;e++){let t=r[e],a=2*e,n={market:o[a],book:o[this.sum(a,1)]},d=s[t];for(let e=0;e<d.length;e++){let t=this.parsePredictionTicker(n,d[e]),s=this.safeString(t,"outcome");void 0!==s&&(i[s]=t)}}return i}async fetchTrades(e,t,i,s={}){await this.loadOutcome(e);let r=this.outcome(e),a=this.safeString(r.info,"slug"),o=this.safeString(r,"outcomeId"),n={slug:a};void 0!==i&&(n.limit=Math.min(i,100));let d=await this.limitlessPublicGetMarketsSlugEvents(this.extend(n,s)),h=this.safeList(d,"events",[]),c=[];for(let e=0;e<h.length;e++){let t=h[e],i=this.safeString(t,"tokenId");(void 0===o||void 0===i||i===o)&&c.push(t)}return this.parsePredictionTrades(c,r,t,i)}async fetchOrderBook(e,t,i={}){await this.loadOutcome(e);let s=this.outcome(e),r=this.safeString(s.info,"slug"),a=await this.limitlessPublicGetMarketsSlugOrderbook(this.extend({slug:r},i)),o=this.safeInteger(this.options,"usdcDecimals",6),n=this.parsePrecision(this.numberToString(-o)),h="no"!==this.safeStringLower(s.info,"outcomeLabel","yes"),c=this.safeList(a,"bids",[]),l=this.safeList(a,"asks",[]),u=l;h&&(u=c);let f=c;h&&(f=l);let p=[],m=[];for(let e=0;e<u.length;e++){let t=this.safeString(u[e],"price");h||void 0===t||(t=d.Y.stringSub("1",t));let i=this.safeString(u[e],"size");void 0!==i&&(i=d.Y.stringDiv(i,n)),p.push([this.parseNumber(t),this.parseNumber(i)])}for(let e=0;e<f.length;e++){let t=this.safeString(f[e],"price");h||void 0===t||(t=d.Y.stringSub("1",t));let i=this.safeString(f[e],"size");void 0!==i&&(i=d.Y.stringDiv(i,n)),m.push([this.parseNumber(t),this.parseNumber(i)])}let g={outcome:this.safeOutcomeSymbol(e,s),bids:this.sortBy(p,0,!0),asks:this.sortBy(m,0),timestamp:void 0,datetime:void 0,nonce:void 0};return this.safePredictionOrderBook(g,s)}async fetchOHLCV(e,t="1d",i,s,r={}){await this.loadOutcome(e);let a=this.outcome(e),o=this.safeString(a.info,"slug"),d=this.safeStringUpper(a.info,"outcomeLabel"),h=this.safeString(this.timeframes,t,"1d"),c=await this.limitlessPublicGetMarketsSlugHistoricalPrice(this.extend({slug:o,interval:h},r)),l=[];Array.isArray(c)&&(l=c);let u=this.safeList(c,"data",this.safeList(c,"prices",l)),f=void 0!==u?u:[],p=f;if(f.length>0){let e=this.safeDict(f,0,{});if(void 0!==this.safeList(e,"prices")){let t=e;for(let e=0;e<f.length;e++){let i=this.safeDict(f,e,{}),s=this.safeStringUpper(i,"title","");if(void 0===s)throw new n.ExchangeError(this.id+" fetchOHLCV() missing title");if(void 0!==d&&s.indexOf(d)>=0){t=i;break}}p=this.safeList(t,"prices",[])}}let m=[];for(let e=0;e<p.length;e++){let t=this.safeDict(p,e),i=this.safeNumber(t,"price"),s=this.safeInteger(t,"timestamp");if(void 0===s){let e=this.safeString(t,"timestamp");s=void 0!==e&&""!==e?this.parse8601(e):void 0}else s<1e12&&(s*=1e3);void 0!==i&&void 0!==s&&m.push({timestamp:s,price:i,amount:0})}let g=this.sortBy(m,"timestamp"),v=1e3*this.parseTimeframe(t),y={},b=[];for(let e=0;e<g.length;e++){let t=this.safeDict(g,e),i=this.safeInteger(t,"timestamp"),s=this.safeNumber(t,"price");if(void 0===i)throw new n.ExchangeError(this.id+" method() missing pTs");let r=this.parseToInt(i/v)*v,a=r.toString();if(a in y){let e=y[a],t=void 0===s?0:s;e[2]=Math.max(e[2],t);let i=void 0===e[3]?s:e[3],r=void 0===s?e[3]:s;e[3]=Math.min(i,r),e[4]=s,y[a]=e}else y[a]=[r,s,s,s,s,0],b.push(a)}let w=[];for(let e=0;e<b.length;e++)w.push(y[b[e]]);return this.filterBySinceLimit(w,i,s,0)}async fetchOrders(e,t,i,s={}){if(void 0===e)throw new n.ArgumentsRequired(this.id+" fetchOrders requires an outcome argument");await this.loadOutcome(e);let r=this.outcome(e),a=this.safeDict(r,"info"),o={slug:this.safeString(a,"slug"),statuses:["LIVE","MATCHED"]};void 0!==i&&(o.limit=i);let d=await this.limitlessPrivateGetMarketsSlugUserOrders(this.extend(o,s));return this.parsePredictionOrders(this.toArray(d),void 0,t,i)}async fetchOpenOrders(e,t,i,s={}){if(void 0===e)throw new n.ArgumentsRequired(this.id+" fetchOpenOrders requires an outcome argument");await this.loadOutcome(e);let r=this.extend(s,{statuses:["LIVE"]});return await this.fetchOrders(e,t,i,r)}async fetchClosedOrders(e,t,i,s={}){if(void 0===e)throw new n.ArgumentsRequired(this.id+" fetchClosedOrders requires an outcome argument");await this.loadOutcome(e);let r=this.extend(s,{statuses:["MATCHED"]});return await this.fetchOrders(e,t,i,r)}async fetchOrdersByIds(e,t,i={}){void 0!==t&&await this.loadOutcome(t);let s=e.length;if(s>50)throw new n.BadRequest(this.id+" fetchOrdersByIds can only fetch up to 50 orders at a time");let r=[];for(let t=0;t<s;t++){let i={orderId:this.safeString(e,t)};r.push(i)}let a=await this.limitlessPrivatePostOrdersStatusBatch(this.extend({items:r},i)),o=this.safeList(a,"results",[]),d=[];for(let e=0;e<o.length;e++){let t=this.safeDict(o,e,{});"found"===this.safeString(t,"status")&&d.push(t)}return this.parsePredictionOrders(d)}async fetchOrder(e,t,i={}){void 0!==t&&await this.loadOutcome(t);let s=await this.fetchOrdersByIds([e],t,i),r=this.safeDict(s,0);if(void 0===r)throw new n.OrderNotFound(this.id+" fetchOrder() could not find order "+e);return r}parsePredictionOrder(e,t){let i,s,r,a,o=this.safeDict(e,"data"),n=this.safeDict(o,"order",e),d=this.safeDict(n,"order");void 0!==d&&(n=d);let h=this.safeString(n,"id"),c=this.safeString2(n,"token","tokenId"),l=this.safeOutcome(c,t),u=this.safeString(l,"outcome"),f=this.safeString(n,"side"),p=this.parseOrderSide(f),m=this.safeString(n,"price"),g="makerAmount";"buy"===p&&(g="takerAmount");let v=this.safeString(n,g),y=this.safeString(n,"remainingSize"),b=this.safeString(n,"createdAt"),w=this.parse8601(b),k=this.safeString2(n,"type","orderType");"GTC"===k?i="limit":"FAK"===k&&(i="market");let S=this.safeString(n,"status"),O=this.safeDict(o,"execution");if(void 0!==O){S=this.safeString(O,"settlementStatus");let e=this.safeDict(O,"totalsRaw");a=this.safeString(e,"usdGross"),r=this.safeString(e,"contractsGross");let t="USDC",i=this.safeString(e,"usdFee");"buy"===p&&(t=u,i=this.safeString(e,"contractsFee")),s={cost:this.parseNumber(this.applyScale(i)),currency:t}}return this.safePredictionOrder({id:h,clientOrderId:void 0,info:e,timestamp:w,datetime:b,lastTradeTimestamp:void 0,status:this.parseOrderStatus(S),outcome:u,outcomeId:this.safeString(l,"outcomeId"),label:this.safeString(l,"label"),market:this.safeString(l,"market"),type:i,timeInForce:this.parseOrderTimeInForce(k),postOnly:void 0,side:p,price:m,stopPrice:void 0,triggerPrice:void 0,average:void 0,amount:this.applyScale(v),cost:this.applyScale(a),filled:this.applyScale(r),remaining:this.applyScale(y),fee:s,trades:[]})}parseOrderStatus(e){return this.safeString({LIVE:"open",MATCHED:"closed",PENDING:"pending",MINED:"closed",CONFIRMED:"closed",FAILED:"rejected"},e,e)}parseOrderTimeInForce(e){return this.safeString({FAK:"FOK"},e,e)}parseOrderSide(e){return this.safeString({BUY:"buy",SELL:"sell",0:"buy",1:"sell"},e,e)}applyScale(e,t=!1){let i=this.safeInteger(this.options,"usdcDecimals",6),s=this.numberToString(Math.pow(10,i));return t?d.Y.stringMul(e,s):d.Y.stringDiv(e,s)}parseAccount(e){return{id:this.safeString(e,"id"),type:void 0,code:void 0,info:e}}async fetchAccounts(e={}){let t=await this.limitlessPrivateGetProfilesMe(e);return this.parseAccounts([t])}async createOrder(e,t,i,s,r,a={}){let o,h,c=await this.loadAccounts();await this.loadOutcome(e);let l=this.outcome(e),u=this.safeDict(c,0),f=this.safeDict(u,"info"),p="smartWallet"===this.safeString(f,"tradeWalletOption"),m=p?this.safeString(f,"smartWallet"):this.safeString(f,"account");""!==this.walletAddress&&(m=this.walletAddress);let g=a;[m,g]=this.handleOptionAndParams(g,"createOrder","maker",m);try{this.checkAddress(m)}catch(e){throw new n.InvalidAddress(this.id+' createOrder requires a valid maker address. Set the "maker" parameter to a valid address or set the "walletAddress" property in the constructor options.')}let v=this.safeString(f,"embeddedAccount"),y=void 0!==v,b=p&&y,w=m;b&&(w=v),[w,g]=this.handleOptionAndParams(g,"createOrder","signer",w);try{this.checkAddress(w)}catch(e){throw new n.InvalidAddress(this.id+' createOrder requires a valid signer address. Set the "signer" parameter to a valid address or set the "walletAddress" property in the constructor options.')}let k=this.safeString(this.options,"nullAddress","0x0000000000000000000000000000000000000000");[k,g]=this.handleOptionAndParams(g,"createOrder","taker",k);try{this.checkAddress(k)}catch(e){throw new n.InvalidAddress(this.id+' createOrder requires a valid taker address. Set the "taker" parameter to a valid address or set the "nullAddress" property in the constructor options.')}let S=this.incrementingNonce();this.checkRequiredArgument("createOrder",i,"side");let O=this.safeInteger({buy:0,sell:1},i.toLowerCase()),T=this.safeDict(f,"rank"),P=2*!!b;[P,g]=this.handleOptionAndParams(g,"createOrder","signatureType",P);let I={salt:S,maker:m,signer:w,taker:k,tokenId:l.outcomeId,nonce:0,feeRateBps:this.safeInteger(T,"feeRateBps",0),side:O,signatureType:P},A=this.safeInteger(g,"expiration");void 0!==A?(g=this.omit(g,"expiration"),I.expiration=this.numberToString(A)):I.expiration="0";let x=this.numberToString(s),M=this.numberToString(r),_="market"===t,C=!1;[C,g]=this.handlePostOnly(_,!1,g);let B=this.safeString(g,"timeInForce");g=this.omit(g,"timeInForce"),void 0===B&&(B=_?"FOK":"GTC");let E=this.safeString(l,"market");if(_&&"buy"===i){let t=!0;[t,g]=this.handleOptionBoolAndParams(g,"createOrder","createMarketBuyOrderRequiresPrice",!0);let i=this.safeNumber(g,"cost");if(g=this.omit(g,"cost"),t)if(void 0===r&&void 0===i)throw new n.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument");else{let t=this.parseToNumeric(d.Y.stringMul(x,M));o=this.costToPredictionPrecision(e,void 0!==i?i:t)}else o=this.costToPredictionPrecision(e,s)}else if(_)o=this.amountToPredictionPrecision(e,s);else{let t=d.Y.stringMul(x,M);"buy"===i?(o=this.costToPredictionPrecision(e,t),h=this.amountToPredictionPrecision(e,s)):(o=this.amountToPredictionPrecision(e,s),h=this.costToPredictionPrecision(e,t))}I.makerAmount=this.parseToInt(this.applyScale(o,!0)),I.takerAmount=_?1:this.parseToInt(this.applyScale(h,!0));let R=this.signOrderRequest(I,E);I.signature=R,_||void 0===r||(I.price=this.parseNumber(M));let L=this.safeString(l.info,"slug"),N={ownerId:this.safeInteger(u,"id"),order:I,marketSlug:L,orderType:B};C&&(N.postOnly=C);let D=await this.limitlessPrivatePostOrders(this.extend(N,g)),q=this.parsePredictionOrder(D,l);return void 0===q.status&&(q.status="open"),q}signOrderRequest(e,t){if(this.checkRequiredCredentials(),void 0===this.privateKey)throw new n.ArgumentsRequired(this.id+" createOrder() requires a privateKey (the embedded/trading wallet key) to sign orders");let i=this.market(t),s=this.safeDict(i,"info"),r=this.safeDict(s,"venue"),a=this.safeString(r,"exchange"),o=this.ethEncodeStructuredData({chainId:8453,name:"Limitless CTF Exchange",verifyingContract:a,version:"1"},{Order:[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"signer",type:"address"},{name:"taker",type:"address"},{name:"tokenId",type:"uint256"},{name:"makerAmount",type:"uint256"},{name:"takerAmount",type:"uint256"},{name:"expiration",type:"uint256"},{name:"nonce",type:"uint256"},{name:"feeRateBps",type:"uint256"},{name:"side",type:"uint8"},{name:"signatureType",type:"uint8"}]},e);return this.signMessage(o,this.privateKey)}hashMessage(e){return"0x"+this.hash(e,a.lY,"hex")}signHash(e,t){let i=(0,h.h1)(e.slice(-64),t.slice(-64),r.bI,void 0),s=i.r,a=i.s,o=this.intToBase16(this.sum(27,i.v));return("0x"+s.padStart(64,"0")+a.padStart(64,"0")+o).toLowerCase()}signMessage(e,t){return this.signHash(this.hashMessage(e),t.slice(-64))}signEvmTransaction(e,t){let i=this.rlpEncodeList([]),s=[this.rlpEncodeBytes(this.intToRlpHex(this.safeInteger(e,"chainId"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"nonce"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"maxPriorityFeePerGas"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"maxFeePerGas"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"gasLimit"))),this.rlpEncodeBytes(this.remove0xPrefix(this.safeString(e,"to"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"value","0x0"))),this.rlpEncodeBytes(this.remove0xPrefix(this.safeString(e,"data","0x"))),i],o="02"+this.rlpEncodeList(s),n=this.hash(this.base16ToBinary(o),a.lY,"hex"),d=(0,h.h1)(n,this.remove0xPrefix(t),r.bI,void 0),c=this.safeString(d,"r"),l=this.safeString(d,"s");c=this.padHexToEven(c),l=this.padHexToEven(l);let u=this.safeInteger(d,"v"),f=[];for(let e=0;e<s.length;e++)f.push(s[e]);return f.push(this.rlpEncodeBytes(this.intToRlpHex(u))),f.push(this.rlpEncodeBytes(c)),f.push(this.rlpEncodeBytes(l)),"0x02"+this.rlpEncodeList(f)}async approve(e={}){if(this.checkRequiredCredentials(),void 0===this.privateKey)throw new n.ArgumentsRequired(this.id+" approve() requires a privateKey to sign the on-chain transaction");let t=this.safeString(e,"rpcUrl",this.safeString(this.options,"rpcUrl")),i=this.safeInteger(this.options,"chainId",8453),s=this.safeString(e,"token",this.safeString(this.options,"collateralAddress")),r=this.safeString(e,"spender",this.safeString(this.options,"exchangeAddress")),a=this.safeString(e,"owner",this.walletAddress);void 0===a&&(a=this.ethGetAddressFromPrivateKey(this.privateKey));let o=this.safeString(e,"gasLimit","0x186a0"),h="ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",c=this.safeString(e,"amount");if(void 0!==c){let e=this.safeInteger(this.options,"usdcDecimals",6),t=d.Y.stringDiv(c,this.parsePrecision(this.numberToString(e))),i=this.parseToInt(t);h=this.intToBase16(i).padStart(64,"0")}let l="0x095ea7b3"+this.padHexAddress(r)+h,u=await this.sendEvmTransaction(t,i,a,s,"0x0",l,o);return await this.waitForTransactionReceipt(t,u)}async cancelOrder(e,t,i={}){void 0!==t&&await this.loadOutcome(t);let s=await this.limitlessPrivateDeleteOrdersOrderId(this.extend({order_id:e},i)),r=this.parsePredictionOrder(s);return void 0===r.id&&(r.id=e),void 0===r.status&&(r.status="canceled"),r}async redeem(e,t={}){let i=this.safeString2(t,"conditionId","condition_id");if(void 0===i){if(void 0===e)throw new n.ArgumentsRequired(this.id+" redeem() requires an outcome or a params.conditionId");await this.loadOutcome(e);let t=this.outcome(e);i=this.safeString(this.safeDict(t,"info",{}),"conditionId")}if(void 0===i)throw new n.ArgumentsRequired(this.id+" redeem() could not resolve the market conditionId - pass params.conditionId (a bytes32 hex string)");let s={conditionId:i},r=this.omit(t,["conditionId","condition_id"]);return{info:await this.limitlessPrivatePostPortfolioRedeem(this.extend(s,r)),id:i,conditionId:i}}async cancelOrders(e,t,i={}){void 0!==t&&await this.loadOutcome(t);let s=await this.limitlessPrivatePostOrdersCancelBatch(this.extend({orderIds:e},i)),r=this.safeList(s,"canceled",[]);if(this.safeList(s,"failed",[]).length>0){let e=this.json(s),t=this.id+" cancelOrders failed: "+e;throw new n.OrderNotFound(t)}return this.parsePredictionOrders(r)}async cancelAllOrders(e,t={}){let i=t;if(void 0!==e){let e=!0;if([e,i]=this.handleOptionAndParams(i,"cancelAllOrders","warnOnCancelAllOrdersWithOutcome",e),e)throw new n.BadRequest(this.id+" cancelAllOrders cancels all orders for entire slug (both YES and NO outcomes). Please provide params.slug to specify the slug, or set the warnOnCancelAllOrdersWithOutcome option to false to suppress this warning message.")}let s={},r=this.safeString(i,"slug");if(void 0!==e){let t=await this.loadOutcome(e);s.slug=this.safeString(t.info,"slug")}else if(void 0===r)throw new n.ArgumentsRequired(this.id+" cancelAllOrders requires either an outcome argument or a slug parameter");let a=await this.limitlessPrivateDeleteOrdersAllSlug(this.extend(s,i));return[this.safePredictionOrder({info:a})]}async fetchMyTrades(e,t,i,s={}){let r=e;if(void 0!==e){let t=await this.loadOutcome(e);r=this.safeString(t,"outcome")}let a=!1,o=s;if([a,o]=this.handleOptionAndParams(o,"fetchMyTrades","paginate",a),a)return o=this.omit(o,"paginate"),await this.fetchPaginatedCallCursor("fetchMyTrades",e,t,i,o,"nextCursor","cursor",void 0,100);let n={};void 0!==i&&(n.limit=Math.min(i,100));let d=await this.limitlessPrivateGetPortfolioHistory(this.extend(n,o)),h=this.safeList(d,"data",[]),c=[];for(let e=0;e<h.length;e++){let t=this.safeDict(h,e),i=this.safeStringLower(t,"strategy");if(void 0!==i){let e=i.indexOf("buy"),s=i.indexOf("sell");(e>=0||s>=0)&&c.push(t)}}let l=this.parsePredictionTrades(c,void 0);return this.filterByOutcomeSinceLimit(l,r,t,i)}parsePredictionTrade(e,t){let i,s,r=this.safeString(e,"matchedSize");if(void 0!==r){let i,s,a=this.parse8601(this.safeString(e,"createdAt")),o=this.safeString(e,"side");"0"===o?i="buy":"1"===o&&(i="sell");let n=d.Y.stringDiv(r,"1000000"),h=this.safeString(e,"price");void 0!==h&&(s=d.Y.stringMul(h,n));let c=this.safeOutcomeSymbol(void 0,t);return this.safePredictionTrade({id:this.safeString(e,"txHash"),info:e,timestamp:a,datetime:this.iso8601(a),outcome:c,outcomeId:this.safeString(t,"outcomeId"),label:this.safeString(t,"label"),market:this.safeString(t,"market"),order:void 0,type:void 0,side:i,takerOrMaker:"taker",price:this.parseNumber(h),amount:this.parseNumber(n),cost:this.parseNumber(s),fee:void 0})}let a=this.safeString(e,"transactionHash"),o=this.safeIntegerProduct(e,"blockTimestamp",1e3),h=this.safeString(e,"outcomeTokenPrice"),c=this.safeString(e,"outcomeTokenAmount"),l=this.safeString(e,"collateralAmount"),u=this.safeStringLower(e,"strategy");if(void 0===u)throw new n.ExchangeError(this.id+" parsePredictionTrade() missing rawSide");let f=u.indexOf("sell"),p="buy";if(f>=0&&(p="sell"),void 0===u)throw new n.ExchangeError(this.id+" parsePredictionTrade() missing rawSide");if(u.indexOf("limit")>=0){if(i="limit",s="maker",void 0===u)throw new n.ExchangeError(this.id+" method() missing rawSide")}else u.indexOf("market")>=0&&(i="market",s="taker");let m=this.safeDict(e,"market",{}),g=this.safeString(m,"slug"),v=this.safeInteger(e,"outcomeIndex"),y="no";0===v&&(y="yes");let b=this.getOutcomeBySlugAndLabel(g,y,t),w=this.safeString(b,"outcome");return this.safePredictionTrade({id:a,info:e,timestamp:o,datetime:this.iso8601(o),outcome:w,outcomeId:this.safeString(e,"asset"),label:this.safeString(b,"label"),market:this.safeString(b,"market"),order:void 0,type:i,side:p,takerOrMaker:s,price:h,amount:c,cost:l,fee:void 0})}getOutcomeBySlugAndLabel(e,t,i){let s=this.safeMarket(e,i),r=this.safeList(s,"outcomes",[]);for(let e=0;e<r.length;e++){let i=this.safeDict(r,e);if(this.safeString(i,"label")===t)return i}}async fetchPositions(e,t={}){let i=0;void 0!==e&&(i=e.length),i>0&&await this.loadOutcomes(e);let s=await this.limitlessPrivateGetPortfolioPositions(t),r=this.safeList(s,"clob",[]),a=[],o=["yes","no"];for(let e=0;e<r.length;e++){let t=this.safeDict(r,e);for(let e=0;e<o.length;e++){let i=this.safeString(o,e),s=this.getPositionFromClobEntry(i,t);void 0!==s&&a.push(s)}}return a}getPositionFromClobEntry(e,t){if(void 0===t)return;let i=this.safeDict(t,"tokensBalance"),s=this.omitZero(this.safeString(i,e));if(void 0===s)return;let r=this.safeDict(t,"positions"),a=this.safeDict(r,e,{}),o=this.safeDict(t,"market"),n=this.safeString(o,"slug"),d=this.getOutcomeBySlugAndLabel(n,e),h=this.parsePredictionPosition(a,d);h.contracts=this.parseNumber(this.applyScale(s));let c=this.safeDict(t,"latestTrade"),l="latestYesPrice";return"no"===e&&(l="latestNoPrice"),h.markPrice=this.safeNumber(c,l),h.info=t,this.safePredictionPosition(h)}parsePredictionPosition(e,t){let i=this.safeString(t,"outcome"),s=this.applyScale(this.safeString(e,"marketValue")),r=this.applyScale(this.safeString(e,"unrealizedPnl")),a=this.applyScale(this.safeString(e,"realisedPnl")),o=this.applyScale(this.safeString(e,"cost")),n=this.applyScale(this.safeString(e,"fillPrice"));return{id:void 0,outcome:i,outcomeId:this.safeString(t,"outcomeId"),label:this.safeString(t,"label"),market:this.safeString(t,"market"),timestamp:void 0,datetime:void 0,contracts:void 0,contractSize:1,side:"long",notional:this.parseNumber(s),leverage:1,unrealizedPnl:this.parseNumber(r),realizedPnl:this.parseNumber(a),collateral:this.parseNumber(o),entryPrice:this.parseNumber(n),markPrice:void 0,liquidationPrice:void 0,hedged:!1,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,initialMargin:void 0,initialMarginPercentage:void 0,marginRatio:void 0,marginMode:"cross",marginType:"cross",percentage:void 0,info:e}}async fetchEvents(e={}){this.requireEventQuery(e);let t=this.parseSearchQueries(e);if(void 0===t)throw new n.ExchangeError(this.id+" fetchEvents() missing queries");let i=t.length,s=this.omit(e,["query","queries","limit","sort","searchIn","eventId","slug","status"]),r=this.safeString2(e,"eventId","slug"),a=[];if(i>0){let i=Math.min(this.safeInteger(e,"limit",50),50),r={};for(let e=0;e<t.length;e++){if(void 0===t)throw new n.ExchangeError(this.id+" fetchEvents() missing queries");let o=t[e],d=await this.limitlessPublicGetMarketsSearch(this.extend({query:o,limit:i},s)),h=this.safeList(d,"markets",[]);for(let e=0;e<h.length;e++){let t=h[e],i=this.safeString(t,"slug");void 0===i||""===i||i in r||(r[i]=!0,a.push(t))}}}else if(void 0!==r){let e=await this.limitlessPublicGetMarketsAddressOrSlug(this.extend({addressOrSlug:r},s));a.push(e)}else{let t=this.safeList(e,"tags",[]),i=await this.fetchRawMarketsByTags(t,e),s=i.length;for(let e=0;e<s;e++)a.push(i[e])}void 0===this.events&&(this.events={}),void 0===this.markets&&(this.markets=this.createSafeDictionary());let o={},d=this.expandGroupRows(a),h=d.length;for(let e=0;e<h;e++){let t,i=d[e],s=this.safeStringN(i,["groupSlug","groupId"],this.safeString(i,"slug"));void 0!==s&&""!==s&&(t=this.shortenSlug(s));let r=this.parseMarket(i);if(void 0===r)throw new n.ExchangeError(this.id+" fetchEvents() missing m");if(this.markets[r.market]=r,void 0!==t&&""!==t){t in o||(o[t]={groupId:s,title:this.safeString2(i,"groupTitle","title",s),raw:i,markets:[]});let e=o[t],a=e.markets;a.push(r),e.markets=a}}let c=[],l=Object.keys(o),u=l.length;for(let e=0;e<u;e++){let t=o[l[e]],i=this.parseEvent(t);c.push(i)}this.setEvents(c),this.populateOutcomes();let f=this.extend({searchIn:"both"},e),p=this.omit(f,["tags"]);return this.applyEventFetchParams(c,p,t)}async fetchRawActiveMarkets(e={},t){let i=this.safeInteger(e,"limit",this.safeInteger(this.options,"fetchMarketsLimit",1e3)),s=this.safeInteger(this.options,"marketsPageSize",25),r=this.omit(e,["query","queries","limit","sort","searchIn","eventId","slug","status","tags"]),a=[],o=1,n=0;for(;;){let e,d={page:o,limit:s};void 0!==t?(d.categoryId=t,e=await this.limitlessPublicGetMarketsActiveCategoryId(this.extend(d,r))):e=await this.limitlessPublicGetMarketsActive(this.extend(d,r));let h=this.safeList(e,"data",[]),c=h.length;if(0===c)break;for(let e=0;e<c;e++)n<i&&(a.push(h[e]),n=this.sum(n,1));if(o=this.sum(o,1),c<s||n>=i)break}return a}async fetchRawMarketsByTags(e,t={}){let i=await this.limitlessPublicGetCategories(),s=[];Array.isArray(i)&&(s=i);let r=[];for(let t=0;t<e.length;t++)r.push(e[t].toLowerCase());let a=[],o=s.length;for(let e=0;e<o;e++){let t=this.safeDict(s,e),i=this.safeStringLower(t,"name",""),o=this.safeString(t,"id"),d=!1;for(let e=0;e<r.length;e++){if(void 0===i)throw new n.ExchangeError(this.id+" fetchRawMarketsByTags() missing name");if(i.indexOf(r[e])>=0){d=!0;break}}d&&void 0!==o&&a.push(o)}let d=a.length;if(0===d)throw new n.BadRequest(this.id+" fetchEvents() could not match the requested tags to any limitless category — GET /categories lists the valid names");let h={},c=[];for(let e=0;e<d;e++){let i=await this.fetchRawActiveMarkets(t,a[e]),s=i.length;for(let e=0;e<s;e++){let t=i[e],s=this.safeString(t,"slug");void 0===s||s in h||(h[s]=!0,c.push(t))}}return c}nonce(){return this.milliseconds()}sign(e,t="limitless",i="GET",r={},a,o){let n="string"==typeof t?t:t[0],d="string"==typeof t?"public":t[1],h=this.urls.api,c=this.safeString(h,n,h.limitless),l="/"+this.implodeParams(e,r),u=this.omit(r,this.extractParams(e)),f=this.urlencodeWithArrayRepeat(u);"GET"===i&&""!==f&&(l+="?"+f);let p=a,m=o;if("private"===d){let e="";if(void 0===p&&(p={}),"POST"===i&&""!==f){m=e=this.json(u);let t=void 0!==p?p:{};p=this.extend({Accept:"application/json","Content-Type":"application/json"},t)}this.checkRequiredCredentials();let t=this.iso8601(this.milliseconds()),r=t+"\n"+i+"\n"+l+"\n"+e,a=this.hmac(this.encode(r),this.base64ToBinary(this.secret),s.sc,"base64");p=this.extend(p,{"lmts-timestamp":t,"lmts-signature":a});let o={};o["lmts-api-key"]=this.apiKey,p=this.extend(p,o)}return{url:l=c+l,method:i,body:m,headers:p}}handleErrors(e,t,i,s,r,a,o,d,h){if(void 0===o||e>=200&&e<300)return;let c=this.id+" "+a,l=this.safeString(o,"message");if(void 0!==l&&this.throwExactlyMatchedException(this.exceptions.exact,l,c),this.throwBroadlyMatchedException(this.exceptions.broad,a,c),400===e)throw new n.BadRequest(c)}}i.d(t,{A:()=>c})},2244(e,t,i){"use strict";var s=i(6834),r=i(6885),a=i(5843),o=i(1093),n=i(1697),d=i(7749),h=i(1453);class c extends a.A{describe(){return this.deepExtend(super.describe(),{id:"myriad",name:"Myriad",countries:[],rateLimit:200,certified:!1,pro:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!1,future:!1,option:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,createMarketBuyOrderWithCost:!0,createOrder:!0,createOrders:!0,editOrder:!0,fetchBalance:!0,fetchCanceledOrders:!0,fetchClosedOrders:!0,fetchCurrencies:!1,fetchEvent:!0,fetchEvents:!0,fetchMarkets:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPositions:!0,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,fetchTradingFee:!0,prediction:!0,watchMyTrades:!0,watchOHLCV:!0,watchOrderBook:!0,watchOrders:!0,watchPositions:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0},timeframes:{"1m":"24h","5m":"24h","15m":"7d","1h":"7d","6h":"30d","1d":"30d"},urls:{logo:"https://github.com/user-attachments/assets/a393c885-99e8-4943-897d-ebc0555c3773",api:{myriad:"https://api-v2.myriadprotocol.com",ws:"wss://ws.myriadprotocol.com/ws"},test:{myriad:"https://api-v2.staging.myriadprotocol.com",ws:"wss://ws.staging.myriadprotocol.com/ws"},www:"https://myriad.markets",doc:["https://docs.myriad.markets"]},api:{myriad:{public:{get:{questions:{cost:1},"questions/{id}":{cost:1},markets:{cost:1},"markets/{id}":{cost:1},"markets/{networkId}/{id}":{cost:1},"markets/{id}/events":{cost:1},"markets/{id}/orderbook":{cost:1},"markets/{id}/trades":{cost:1},"markets/{id}/holders":{cost:1},"markets/{id}/referrals":{cost:1},events:{cost:1},orders:{cost:1},"orders/{hash}":{cost:1},"users/{address}/events":{cost:1},"users/{address}/referrals":{cost:1},"users/{address}/portfolio":{cost:1},"users/{address}/markets":{cost:1},tags:{cost:1},topics:{cost:1}},post:{"markets/quote":{cost:1},"markets/claim":{cost:1},orders:{cost:1},"orders/cancel-batch":{cost:1},"orders/cancel-all":{cost:1},"positions/split":{cost:1},"positions/merge":{cost:1},"positions/redeem":{cost:1},"positions/redeem-voided":{cost:1},"positions/neg-risk/split":{cost:1},"positions/neg-risk/merge":{cost:1}},delete:{"orders/{hash}":{cost:1}}},private:{post:{"markets/quote_with_fee":{cost:1}}}}},requiredCredentials:{apiKey:!1,secret:!1,walletAddress:!1,privateKey:!0},fees:{trading:{tierBased:!1,percentage:!0,maker:.01,taker:.01}},exceptions:{exact:{"Order not found":h.OrderNotFound,"Market not found":h.BadSymbol,"Invalid order payload":h.InvalidOrder},broad:{Insufficient:h.InsufficientFunds,allowance:h.InsufficientFunds,"not found":h.OrderNotFound,Unauthorized:h.AuthenticationError,Forbidden:h.AuthenticationError,"rate limit":h.RateLimitExceeded,"Too many requests":h.RateLimitExceeded,expired:h.InvalidOrder,closed:h.InvalidOrder,resolved:h.InvalidOrder,Invalid:h.InvalidOrder}},options:{defaultFetchMarketsLimit:50,defaultFetchEventsLimit:50,allowUnscopedFetchEvents:!0,defaultMarketStatus:"open",defaultTradingModel:"all",defaultNetworkId:"56",obDomainName:"MyriadCTFExchange",obDomainVersion:"1",networks:{2741:"Abstract",59144:"Linea",56:"BNB Chain"},chains:{56:{rpcUrl:"https://bsc-dataseed.binance.org/",predictionMarket:"0x39E66eE6b2ddaf4DEfDEd3038E0162180dbeF340",obExchangeAddress:"0xa0b6f8ef8EdB64f395018D1933f2273Ce9f0f16A",obConditionalTokens:"0x6413734f92248D4B29ae35883290BD93212654Dc",collateralToken:"0x8d0D000Ee44948FC98c9B98A4FA4921476f08B0d",collateralCurrency:"USD1",collateralDecimals:18},2741:{rpcUrl:"https://api.mainnet.abs.xyz",predictionMarket:"0x3e0F5F8F5Fb043aBFA475C0308417Bf72c463289"},59144:{rpcUrl:"https://rpc.linea.build",predictionMarket:"0x39e66ee6b2ddaf4defded3038e0162180dbef340"}}}})}async fetchMarkets(e={}){let t=this.parseSearchQueries(e),i=this.omit(e,["query","queries"]),s=t.length,r=[];r=s>0?await this.fetchRawMarketsBySearch(t,i):await this.fetchRawMarketsList(i);let a=[],o={};for(let e=0;e<r.length;e++){let t=r[e],i=this.parseMyriadMarket(t);a.push(i);let s=this.parseMarketToEvent(t,i),n=this.safeString(s,"event");void 0!==n&&(o[n]=s)}return this.events=o,a}async fetchRawMarketsBySearch(e,t={}){let i=this.safeInteger(t,"limit",this.safeInteger(this.options,"defaultFetchEventsLimit",50)),s=this.safeString(t,"state",this.safeString(this.options,"defaultMarketStatus","open")),r=this.omit(t,["limit","state"]),a={},o=[];for(let t=0;t<e.length;t++){let n=e[t],d=await this.myriadPublicGetMarkets(this.extend({keyword:n,state:s,limit:i},r)),h=Array.isArray(d)?d:this.safeList(d,"data",[]),c=void 0!==h?h:[];for(let e=0;e<c.length;e++){let t=c[e],i=this.safeString(t,"networkId")+":"+this.safeString(t,"id");i in a||(a[i]=!0,o.push(t))}}return o}async fetchRawMarketsList(e={}){let t=this.safeInteger(this.options,"defaultFetchMarketsLimit",50),i=this.safeInteger(e,"limit",this.safeInteger(this.options,"fetchMarketsLimit",1e3)),s=this.safeString2(e,"state","status",this.safeString(this.options,"defaultMarketStatus","open")),r=this.safeString2(e,"tradingModel","trading_model",this.safeString(this.options,"defaultTradingModel","all")),a=this.omit(e,["state","status","limit","tradingModel","trading_model"]),o=[],n=0,d=1;for(;;){let e=await this.myriadPublicGetMarkets(this.extend({state:s,limit:t,page:d,trading_model:r},a)),h=Array.isArray(e)?e:this.safeList(e,"data",[]),c=void 0!==h?h:[],l=c.length;if(0===l)break;for(let e=0;e<l;e++)n<i&&(o.push(c[e]),n=this.sum(n,1));if(d=this.sum(d,1),l<t||n>=i)break}return o}async fetchEvent(e,t={}){if(0>e.indexOf(":")){let i=await this.fetchRawQuestionById(e,t),s=this.parseEvent(i);return this.indexEventOutcomes(s),s}let i=await this.fetchRawMarketById(e,t),s=this.parseMyriadMarket(i),r=this.parseMarketToEvent(i,s);return this.indexEventOutcomes(r),r}async fetchRawMarketById(e,t={}){let i=e.split(":"),s=i.length,r={};return s>1?(r.network_id=this.safeString(i,0),r.id=this.safeString(i,1)):r.id=e,await this.myriadPublicGetMarketsId(this.extend(r,t))}async fetchRawQuestionById(e,t={}){let i;try{i=await this.myriadPublicGetQuestionsId(this.extend({id:e},t))}catch(o){if(o instanceof h.RateLimitExceeded||o instanceof h.AuthenticationError)throw o;let i=await this.myriadPublicGetQuestions(this.extend({keyword:e,limit:50},t)),s=this.safeList(i,"data",[]),r=s.length,a=e.toLowerCase();for(let e=0;e<r;e++){let t=this.safeDict(s,e,{}),i=this.safeString(t,"id",""),r=this.safeString(t,"slug",""),o=this.safeString(t,"title",""),n=this.shortenSlug(r);if(i.toLowerCase()===a||r.toLowerCase()===a||o.toLowerCase()===a||void 0!==n&&n.toLowerCase()===a)return t}throw o}return i}async fetchRawQuestionsBySearch(e,t={}){let i=this.safeInteger(t,"limit",this.safeInteger(this.options,"defaultFetchEventsLimit",50)),s=this.omit(t,["limit"]),r={},a=[];for(let t=0;t<e.length;t++){let o=e[t],n=await this.myriadPublicGetQuestions(this.extend({keyword:o,limit:i},s)),d=Array.isArray(n)?n:this.safeList(n,"data",[]),h=void 0!==d?d:[];for(let e=0;e<h.length;e++){let t=h[e],i=this.safeString(t,"id");void 0===i||i in r||(r[i]=!0,a.push(t))}}return a}async fetchRawQuestionsList(e={}){let t=this.safeInteger(this.options,"defaultFetchEventsLimit",50),i=this.safeInteger(e,"limit",this.safeInteger(this.options,"fetchEventsLimit",1e3)),s=this.safeString2(e,"state","status",this.safeString(this.options,"defaultMarketStatus","open")),r=this.omit(e,["state","status","limit","tradingModel","trading_model"]),a=[],o={},n=0,d=1;for(;;){let e={limit:t,page:d};void 0!==s&&(e.state=s);let h=await this.myriadPublicGetQuestions(this.extend(e,r)),c=Array.isArray(h)?h:this.safeList(h,"data",[]),l=void 0!==c?c:[],u=l.length;if(0===u)break;for(let e=0;e<u;e++){let t=l[e],s=this.safeString(t,"id");void 0!==s&&s in o||(void 0!==s&&(o[s]=!0),n<i&&(a.push(t),n=this.sum(n,1)))}if(d=this.sum(d,1),u<t||n>=i)break}return a}async fetchPositions(e,t={}){let i=this.safeString2(t,"address","user",this.walletAddressOrUndefined());if(void 0===i)throw new h.ArgumentsRequired(this.id+" fetchPositions() requires a walletAddress or an address parameter");let s=this.omit(t,["address","user"]),r=await this.myriadPublicGetUsersAddressPortfolio(this.extend({address:i},s)),a=this.safeList(r,"data",[]),o=[];for(let e=0;e<a.length;e++)o.push(this.parsePredictionPosition(a[e]));return this.filterByArray(o,"outcome",e,!1)}parsePredictionPosition(e,t){let i,s=this.safeString(e,"marketSlug",""),r=this.safeString(e,"outcomeTitle",""),a=this.slugToOutcomeSymbol(s,s,r),o=this.slugToMarketSymbol(s,s),n=this.safeString(e,"networkId"),h=this.safeString(e,"marketId"),c=this.safeString(e,"outcomeId"),l=this.safeNumber(e,"shares"),u=this.safeNumber(e,"value"),f=this.safeNumber(e,"profit"),p=this.safeString(e,"roi");return void 0!==p&&(i=d.Y.stringMul(p,"100")),this.safePredictionPosition({info:e,id:n+":"+h+"/"+c,outcome:a,outcomeId:c,label:r,market:o,contracts:l,side:"long",notional:u,markPrice:this.safeNumber(e,"price"),unrealizedPnl:f,percentage:this.parseNumber(i),marginMode:"cash",hedged:!1})}async fetchTradeQuote(e,t,i,s={}){await this.loadOutcome(e);let r=this.outcome(e),a=this.safeDict(r,"info",{}),o=this.safeString(a,"networkId"),n=this.safeString(a,"marketId"),d=this.safeInteger(a,"outcomeId"),h=t.toLowerCase(),c={market_id:this.parseToInt(n),network_id:this.parseToInt(o),outcome_id:d,action:h,slippage:this.safeNumber(s,"slippage",.005)};"buy"===h?c.value=i:c.shares=i;let l=this.omit(s,["slippage"]),u=await this.myriadPublicPostMarketsQuote(this.extend(c,l));return this.parseTradeQuote(this.extend(u,{action:h}),r)}parseTradeQuote(e,t){return{outcome:this.safeString(t,"outcome"),side:this.safeStringLower(e,"action"),value:this.safeNumber(e,"value"),shares:this.safeNumber(e,"shares"),sharesThreshold:this.safeNumber(e,"shares_threshold"),priceAverage:this.safeNumber(e,"price_average"),priceBefore:this.safeNumber(e,"price_before"),priceAfter:this.safeNumber(e,"price_after"),netAmount:this.safeNumber(e,"net_amount"),fees:this.safeDict(e,"fees"),calldata:this.safeString(e,"calldata"),info:e}}signEvmTransaction(e,t){let i=this.rlpEncodeList([]),a=[this.rlpEncodeBytes(this.intToRlpHex(this.safeInteger(e,"chainId"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"nonce"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"maxPriorityFeePerGas"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"maxFeePerGas"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"gasLimit"))),this.rlpEncodeBytes(this.remove0xPrefix(this.safeString(e,"to"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"value","0x0"))),this.rlpEncodeBytes(this.remove0xPrefix(this.safeString(e,"data","0x"))),i],n="02"+this.rlpEncodeList(a),d=this.hash(this.base16ToBinary(n),s.lY,"hex"),c=(0,o.h1)(d,this.remove0xPrefix(t),r.bI,void 0),l=this.safeString(c,"r"),u=this.safeString(c,"s");if(void 0===l)throw new h.ExchangeError(this.id+" signEvmTransaction() missing rHex");if(l.length%2!=0&&(l="0"+l),void 0===u)throw new h.ExchangeError(this.id+" signEvmTransaction() missing sHex");u.length%2!=0&&(u="0"+u);let f=this.safeInteger(c,"v"),p=[];for(let e=0;e<a.length;e++)p.push(a[e]);return p.push(this.rlpEncodeBytes(this.intToRlpHex(f))),p.push(this.rlpEncodeBytes(l)),p.push(this.rlpEncodeBytes(u)),"0x02"+this.rlpEncodeList(p)}async ethRpc(e,t,i){let s=await this.fetch(e,"POST",{"Content-Type":"application/json"},this.json({jsonrpc:"2.0",id:1,method:t,params:i})),r=this.safeValue(s,"error");if(void 0!==r)throw new h.ExchangeError(this.id+" rpc "+t+" error: "+this.json(r));return this.safeValue(s,"result")}async ensureErc20Allowance(e,t,i,s,r){let a="0xdd62ed3e"+this.padHexAddress(s)+this.padHexAddress(r),o=await this.ethRpc(e,"eth_call",[{to:i,data:a},"latest"]);if(this.hexToRlpBytes(o).length>=50)return;let n="0x095ea7b3"+this.padHexAddress(r)+"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",d=await this.sendEvmTransaction(e,this.parseToInt(t),s,i,"0x0",n,"0x186a0");await this.waitForTransactionReceipt(e,d)}async createOrder(e,t,i,s,r,a={}){let o=await this.loadOutcome(e),n=this.safeDict(o,"info",{}),d=this.safeString(n,"tradingModel","amm"),c=this.safeStringLower(a,"tradingModel",d),l=this.omit(a,["tradingModel"]);if("ob"===c)return await this.createOrderbookOrder(e,t,i,s,r,l);if(!0!==this.safeBool2(a,"enableAmm","enableAmmOrders",this.safeBool(this.options,"enableAmmOrders",!1)))throw new h.NotSupported(this.id+" createOrder() only supports the gasless order book; this market uses the on-chain AMM (needs native gas and is unverified) — pass params.enableAmm=true to opt in");return await this.createAmmOrder(e,t,i,s,r,this.omit(l,["enableAmm","enableAmmOrders"]))}async createOrderbookOrder(e,t,i,s,r,a={}){let o=this.buildOrderbookOrder(e,t,i,s,r,a),n=this.safeDict(o,"order"),d=this.safeString(o,"networkId"),h=this.safeString(o,"timeInForce"),c={order:n,signature:this.safeString(o,"signature"),network_id:this.parseToInt(d),time_in_force:h},l=await this.myriadPublicPostOrders(c),u={trader:this.safeString(n,"trader"),marketId:this.safeString(n,"marketId"),outcomeId:this.safeNumber(n,"outcomeId"),side:this.safeNumber(n,"side"),amount:this.safeString(n,"amount"),price:this.safeString(n,"price"),minFillAmount:this.safeString(n,"minFillAmount"),nonce:this.safeString(n,"nonce"),expiration:this.safeString(n,"expiration")},f=this.extend(l,{order:u,networkId:d,timeInForce:h}),p=this.outcome(e),m=this.parsePredictionOrder(f,p),g=void 0===i?void 0:i.toLowerCase(),v=void 0===t?"limit":t.toLowerCase();return void 0===this.safeString(m,"side")&&(m.side=g),void 0===this.safeString(m,"type")&&(m.type=v),void 0===this.safeString(m,"timeInForce")&&(m.timeInForce=h),void 0===this.safeNumber(m,"price")&&void 0!==r&&(m.price=r),void 0===this.safeNumber(m,"amount")&&void 0!==s&&(m.amount=s),void 0===this.safeString(m,"status")&&(m.status="open"),m}buildOrderbookOrder(e,t,i,s,r,a={}){if(void 0===this.privateKey)throw new h.ArgumentsRequired(this.id+" createOrder() requires a privateKey to sign the order");let o=this.outcome(e),n=this.safeDict(o,"info",{}),c=this.safeString(n,"networkId",this.safeString(this.options,"defaultNetworkId","56")),l=this.safeString(n,"marketId"),u=this.safeInteger(n,"outcomeId",0),f=this.ethGetAddressFromPrivateKey(this.privateKey),p=void 0===t?"limit":t.toLowerCase(),m=+("buy"!==i.toLowerCase()),g="market"===p,v="GTC";g&&(v="FOK");let y=this.safeStringUpper(a,"timeInForce",v),b=r;if(void 0===b)if(g)b=+(0===m);else throw new h.ArgumentsRequired(this.id+" createOrder() requires a price for limit orders");let w=this.toOrderbookWei(b);if(d.Y.stringLt(w,"1")&&(w="1"),d.Y.stringGt(w,"1000000000000000000"))throw new h.InvalidOrder(this.id+" createOrder() price must be a fraction between 0 and 1");let k=this.toOrderbookWei(s);if(d.Y.stringLt(k,"1"))throw new h.InvalidOrder(this.id+" createOrder() amount is too small (rounds to zero shares)");let S=this.safeString(a,"nonce",this.numberToString(this.milliseconds())),O=this.safeString(a,"expiration","0"),T=this.safeString(a,"minFillAmount","0"),P={trader:f,marketId:l,outcomeId:this.parseToNumeric(u),side:this.parseToNumeric(m),amount:k,price:w,minFillAmount:T,nonce:S,expiration:O},I=this.signClobOrder(P,c);return{order:P,signature:I,timeInForce:y,networkId:c}}async createOrders(e,t={}){let i=e.length,s=[];for(let t=0;t<i;t++){let i=this.safeString(e[t],"outcome");void 0!==i&&s.push(i)}await this.loadOutcomes(s);let r=[];for(let s=0;s<i;s++){let i=this.safeDict(e,s),a=this.safeString(i,"outcome"),o=this.safeString(i,"type"),n=this.safeString(i,"side"),d=this.safeNumber(i,"amount"),h=this.safeNumber(i,"price"),c=this.safeDict(i,"params",{}),l=await this.createOrderbookOrder(a,o,n,d,h,this.extend(c,t));r.push(l)}return r}async editOrder(e,t,i,s,r,a,o={}){return await this.loadOutcome(t),await this.cancelOrder(e,t,o),await this.createOrderbookOrder(t,i,s,r,a,o)}async createAmmOrder(e,t,i,s,r,a={}){let o=void 0!==i?i.toLowerCase():void 0,n=this.safeBool(a,"costDenominated",!1);if("buy"===o&&!0!==n)throw new h.NotSupported(this.id+" createOrder() market buy on the AMM sizes by collateral, not shares — use createMarketBuyOrderWithCost(outcome, collateral) for a dollar buy, or the default order book (omit enableAmm) for a share-denominated order");if(void 0===this.privateKey)throw new h.ArgumentsRequired(this.id+" createOrder() requires a privateKey to sign the on-chain transaction");await this.loadOutcome(e);let d=this.outcome(e),c=this.safeDict(d,"info",{}),l=this.safeString(c,"networkId"),u=this.safeDict(this.options,"chains",{}),f=this.safeDict(u,l);if(void 0===f)throw new h.NotSupported(this.id+" createOrder() has no on-chain config for network "+l);let p=this.safeString2(a,"rpcUrl","rpc",this.safeString(f,"rpcUrl")),m=this.safeString(f,"predictionMarket"),g=this.safeString2(a,"token","tokenAddress",this.safeString(c,"tokenAddress")),v=this.safeString(a,"gasLimit","0xaae60"),y=this.omit(a,["rpcUrl","rpc","token","tokenAddress","gasLimit","costDenominated","quote","transactionHash","txHash","skipAllowance","skipWaitForReceipt"]),b=this.safeDict(a,"quote");void 0===b&&(b=await this.fetchTradeQuote(e,o,s,y));let w=this.safeString(this.safeDict(b,"info",{}),"calldata");if(void 0===w)throw new h.BadRequest(this.id+" createAmmOrder is missing calldata from fetchTradeQuote");let k=this.ethGetAddressFromPrivateKey(this.privateKey),S=this.safeString2(a,"transactionHash","txHash"),O=void 0!==S,T=this.safeBool(a,"skipAllowance",O);"buy"===o&&void 0!==g&&!0!==T&&await this.ensureErc20Allowance(p,l,g,k,m);let P=this.safeBool(a,"skipWaitForReceipt",O),I=S;return void 0===I&&(I=await this.sendEvmTransaction(p,this.parseToInt(l),k,m,"0x0",w,v)),!0!==P&&await this.waitForTransactionReceipt(p,I),this.parseTradeTx(I,b,d,o)}async createMarketBuyOrderWithCost(e,t,i={}){let s=this.extend(i,{enableAmm:!0,costDenominated:!0});return await this.createOrder(e,"market","buy",t,void 0,s)}signOrderbookTypedData(e,t,i){let a=this.safeDict(this.options,"chains",{}),n=this.safeDict(a,i,{}),d=this.safeString(n,"obExchangeAddress");if(void 0===d)throw new h.NotSupported(this.id+" order book trading is not configured for network "+i);let c={name:this.safeString(this.options,"obDomainName","MyriadCTFExchange"),version:this.safeString(this.options,"obDomainVersion","1"),chainId:this.parseToInt(i),verifyingContract:d},l=this.ethEncodeStructuredData(c,e,t),u=this.hash(l,s.lY,"hex"),f=(0,o.h1)(u,this.remove0xPrefix(this.privateKey),r.bI,void 0),p=f.r,m=f.s,g=p.padStart(64,"0"),v=m.padStart(64,"0"),y=this.sum(27,f.v);return("0x"+g+v+this.intToBase16(y)).toLowerCase()}signClobOrder(e,t){return this.signOrderbookTypedData({Order:[{name:"trader",type:"address"},{name:"marketId",type:"uint256"},{name:"outcomeId",type:"uint8"},{name:"side",type:"uint8"},{name:"amount",type:"uint256"},{name:"price",type:"uint256"},{name:"minFillAmount",type:"uint256"},{name:"nonce",type:"uint256"},{name:"expiration",type:"uint256"}]},e,t)}signCancelAll(e,t){return this.signOrderbookTypedData({CancelAll:[{name:"trader",type:"address"},{name:"marketId",type:"uint256"},{name:"timestamp",type:"uint256"}]},e,t)}clobOrderMessage(e){this.safeString2(e,"trader","user");return{trader:void 0!==this.privateKey?this.ethGetAddressFromPrivateKey(this.privateKey):this.walletAddressOrUndefined(),marketId:this.safeString(e,"marketId"),outcomeId:this.safeInteger(e,"outcomeId",0),side:this.safeInteger(e,"side",0),amount:this.safeString(e,"amount"),price:this.safeString(e,"price"),minFillAmount:this.safeString(e,"minFillAmount","0"),nonce:this.safeString(e,"nonce"),expiration:this.safeString(e,"expiration","0")}}getOrderResponseFromParams(e,t={}){let i=this.safeDict(t,"orderResponse");if(void 0!==i)return i;let s=this.safeDict(t,"rawOrder");if(void 0!==s)return{orderHash:e,order:s,networkId:this.safeString2(t,"networkId","network_id")};let r=this.safeDict(t,"orderResponses");if(void 0!==r){let t=this.safeDict(r,e);if(void 0!==t)return t}let a=this.safeList(t,"orderResponses");if(void 0!==a){let t=a.length;for(let i=0;i<t;i++){let t=this.safeDict(a,i,{}),s=this.safeStringN(t,["orderHash","hash","id"]);if(void 0!==s&&s===e)return t}}}toOrderbookWei(e){let t=this.numberToString(e),i=d.Y.stringMul(t,"1000000000000000000");if(void 0===i)throw new h.ExchangeError(this.id+" toOrderbookWei() missing scaled");let s=i.indexOf(".");if(void 0===i)throw new h.ExchangeError(this.id+" toOrderbookWei() missing scaled");return s>-1?i.slice(0,s):i}parseOrderStatus(e){return this.safeString({open:"open",pending:"open",partially_filled:"open",filled:"closed",cancelled:"canceled",canceled:"canceled",expired:"expired"},e,e)}parsePredictionOrder(e,t){let i,s=this.safeDict(e,"order",{}),r=this.safeString2(e,"orderHash","hash"),a=this.safeInteger(s,"side"),o="buy";1===a&&(o="sell");let n=this.safeString(s,"amount"),h=this.safeString(s,"price"),c=this.safeString(e,"filledAmount"),l=void 0===n?void 0:this.parseNumber(d.Y.stringDiv(n,"1000000000000000000")),u=void 0===h?void 0:this.parseNumber(d.Y.stringDiv(h,"1000000000000000000")),f=void 0===c?void 0:this.parseNumber(d.Y.stringDiv(c,"1000000000000000000")),p=this.safeStringLower(e,"status"),m=this.parseOrderStatus(p),g=this.parse8601(this.safeString(e,"createdAt")),v=this.safeStringUpper(e,"timeInForce"),y="FOK"===v||"FAK"===v;i=void 0===t?void 0:this.safeString(t,"outcome");let b=t;if(void 0===i){let r,a=this.safeString2(e,"networkId","network_id",this.safeString(this.options,"defaultNetworkId","56")),o=this.safeString(s,"marketId"),n=this.safeString(s,"outcomeId");void 0!==a&&void 0!==o&&void 0!==n&&(r=a+":"+o+"/"+n),b=this.safeOutcome(r,t),i=this.safeString(b,"outcome")}return this.safePredictionOrder({id:r,clientOrderId:void 0,info:e,timestamp:g,datetime:this.iso8601(g),lastTradeTimestamp:void 0,outcome:i,outcomeId:this.safeString2(b,"outcomeId","id"),label:this.safeString(b,"label"),market:this.safeString(b,"market"),type:y?"market":"limit",timeInForce:v,postOnly:"PO"===v,side:o,price:u,triggerPrice:void 0,amount:l,filled:f,remaining:void 0,cost:void 0,average:void 0,status:m,fee:void 0,trades:void 0},t)}parseAmmEventToOrder(e,t){let i,s,r=this.safeString(e,"networkId"),a=this.safeString(e,"marketId"),o=this.safeString(e,"outcomeId");void 0!==r&&void 0!==a&&void 0!==o&&(i=r+":"+a+"/"+o);let n=this.safeOutcome(i,t),h=this.safeString(e,"marketSlug",a),c=this.safeString(e,"outcomeTitle",o),l=this.safeString(n,"outcome");void 0===l&&(l=this.slugToOutcomeSymbol(h,h,c));let u=this.safeString(n,"market");void 0===u&&(u=this.slugToMarketSymbol(h,h));let f=this.safeString(n,"label");void 0===f&&(f=c);let p=this.safeTimestamp(e,"timestamp"),m=this.safeString(e,"shares"),g=this.safeString(e,"value");return void 0===m||void 0===g||d.Y.stringEq(m,"0")||(s=d.Y.stringDiv(g,m)),this.safePredictionOrder({id:this.safeString2(e,"txId","id"),clientOrderId:void 0,info:e,timestamp:p,datetime:this.iso8601(p),lastTradeTimestamp:p,lastUpdateTimestamp:void 0,status:"closed",outcome:l,outcomeId:i,label:f,market:u,type:"market",timeInForce:"IOC",postOnly:!1,side:this.safeStringLower(e,"action"),price:this.parseNumber(s),triggerPrice:void 0,amount:this.parseNumber(m),filled:this.parseNumber(m),remaining:0,cost:this.parseNumber(g),average:this.parseNumber(s),fee:void 0,reduceOnly:void 0,trades:[],event:void 0},t)}async fetchAmmOrders(e,t,i,s={}){let r,a,o,n=this.safeStringLower(s,"status");if("open"===n||"cancelled"===n||"canceled"===n||"expired"===n)return[];let d=this.safeString2(s,"trader","address");if(void 0===d&&(d=this.walletAddressOrUndefined()),void 0===d)throw new h.ArgumentsRequired(this.id+" fetchOrders() for AMM history requires a trader address or wallet/privateKey");let c={address:d};if(void 0!==e){r=await this.loadOutcome(e),a=this.safeString(r,"outcome",e);let t=this.safeDict(r,"info",{});c.market_id=this.safeString(t,"marketId"),c.network_id=this.safeString(t,"networkId"),o=this.safeString(t,"outcomeId")}void 0!==t&&(c.since=this.parseToInt(t/1e3)),void 0!==i&&(c.limit=i);let l=this.omit(s,["trader","address","status"]),u=await this.myriadPublicGetUsersAddressEvents(this.extend(c,l)),f=this.safeList(u,"data",[]),p=[],m=f.length;for(let e=0;e<m;e++){let t=f[e],i=this.safeStringLower(t,"action");if("buy"!==i&&"sell"!==i)continue;let s=this.safeString(t,"outcomeId");(void 0===o||s===o)&&p.push(this.parseAmmEventToOrder(t,r))}let g=this.sortBy(p,"timestamp",!0);return this.filterByOutcomeSinceLimit(g,a,t,i)}async cancelOrder(e,t,i={}){let s;if(void 0===this.privateKey)throw new h.ArgumentsRequired(this.id+" cancelOrder() requires a privateKey to sign the cancellation");let r=this.getOrderResponseFromParams(e,i),a=this.safeString2(i,"networkId","network_id"),o=this.omit(i,["orderResponse","orderResponses","rawOrder","networkId","network_id"]);void 0===r&&(r=await this.myriadPublicGetOrdersHash(this.extend({hash:e},o)));let n=this.safeDict(r,"info",{}),d=this.safeDict(r,"order",{});0===Object.keys(d).length&&(d=this.safeDict(n,"order",{}));let c=this.safeStringN(r,["networkId","network_id"]);void 0===c&&(c=this.safeStringN(n,["networkId","network_id"])),void 0===c&&(c=a),void 0===c&&(c=this.safeString(this.options,"defaultNetworkId","56"));let l=this.clobOrderMessage(d),u=this.signClobOrder(l,c),f={hash:e,order:l,signature:u,network_id:this.parseToInt(c)},p=await this.myriadPublicDeleteOrdersHash(this.extend(f,o)),m=this.safeString(p,"status","canceled"),g=this.extend(r,{status:m,networkId:c});return void 0!==t&&(s=await this.loadOutcome(t)),this.parsePredictionOrder(g,s)}async cancelAllOrders(e,t={}){if(void 0===this.privateKey)throw new h.ArgumentsRequired(this.id+" cancelAllOrders() requires a privateKey to sign the cancellation");let i=this.ethGetAddressFromPrivateKey(this.privateKey),s=this.safeString(t,"market_id","0"),r=this.safeString(t,"network_id",this.safeString(this.options,"defaultNetworkId","56"));if(void 0!==e){let t=await this.loadOutcome(e),i=this.safeDict(t,"info",{});s=this.safeString(i,"marketId",s),r=this.safeString(i,"networkId",r)}let a=this.safeString(t,"timestamp",this.numberToString(this.seconds())),o={trader:i,marketId:s,timestamp:a},n=this.signCancelAll(o,r),d={trader:i,market_id:this.parseToInt(s),timestamp:a,signature:n,network_id:this.parseToInt(r)},c=await this.myriadPublicPostOrdersCancelAll(d);return[this.safePredictionOrder({info:c,status:"canceled"})]}async cancelOrders(e,t,i={}){if(void 0===this.privateKey)throw new h.ArgumentsRequired(this.id+" cancelOrders() requires a privateKey to sign the cancellations");let s=this.safeString2(i,"networkId","network_id"),r=this.omit(i,["orderResponse","orderResponses","rawOrder","networkId","network_id"]),a=e.length,o=[],n=[],d=this.safeString(this.options,"defaultNetworkId","56");for(let t=0;t<a;t++){let r=e[t],a=this.getOrderResponseFromParams(r,i);void 0===a&&(a=await this.myriadPublicGetOrdersHash({hash:r}));let h=this.safeDict(a,"info",{}),c=this.safeDict(a,"order",{});0===Object.keys(c).length&&(c=this.safeDict(h,"order",{}));let l=this.safeStringN(a,["networkId","network_id"]);void 0===l&&(l=this.safeStringN(h,["networkId","network_id"])),void 0===l&&(l=s),void 0!==l&&(d=l);let u=this.clobOrderMessage(c),f=this.signClobOrder(u,d);o.push({order:u,signature:f}),n.push(this.extend(a,{status:"canceled",networkId:d}))}let c={orders:o,network_id:this.parseToInt(d)};return await this.myriadPublicPostOrdersCancelBatch(this.extend(c,r)),this.parsePredictionOrders(n)}async fetchOrder(e,t,i={}){let s,r=await this.myriadPublicGetOrdersHash(this.extend({hash:e},i));return void 0!==t&&(s=await this.loadOutcome(t)),this.parsePredictionOrder(r,s)}async fetchOrders(e,t,i,s={}){let r,a,o={};void 0===this.safeString(s,"trader")&&(void 0!==this.privateKey?o.trader=this.ethGetAddressFromPrivateKey(this.privateKey):void 0!==this.walletAddress&&(o.trader=this.walletAddress));let n=this.safeStringLower2(s,"tradingModel","trading_model"),d=this.omit(s,["tradingModel","trading_model"]);if(void 0!==e&&(r=await this.loadOutcome(e),a=this.safeString(r,"outcome",e),void 0===n)){let e=this.safeDict(r,"info",{});n=this.safeStringLower(e,"tradingModel")}if("amm"===n)return await this.fetchAmmOrders(e,t,i,d);let h=await this.myriadPublicGetOrders(this.extend(o,d)),c=this.safeList(h,"data",[]),l=this.parsePredictionOrders(c);return this.filterByOutcomeSinceLimit(l,a,t,i)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({status:"open"},s))}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({status:"filled"},s))}async fetchCanceledOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({status:"cancelled"},s))}async fetchMyTrades(e,t,i,s={}){let r=await this.fetchOrders(e,t,i,this.extend({status:"filled"},s)),a=[],o=r.length;for(let e=0;e<o;e++){let t=r[e];a.push(this.orderToTrade(t))}return this.filterByValueSinceLimit(a,"outcome",e,t,i,"timestamp",!0)}orderToTrade(e){let t,i=this.safeInteger(e,"timestamp"),s=this.safeString(e,"type");return"market"!==s&&(t=this.safeNumber(e,"price")),this.safePredictionTrade({id:this.safeString(e,"id"),order:this.safeString(e,"id"),info:this.safeDict(e,"info",{}),timestamp:i,datetime:this.iso8601(i),outcome:this.safeString(e,"outcome"),outcomeId:this.safeString(e,"outcomeId"),label:this.safeString(e,"label"),market:this.safeString(e,"market"),type:s,side:this.safeString(e,"side"),takerOrMaker:void 0,price:t,amount:this.safeNumber(e,"filled"),cost:void 0,fee:void 0})}async fetchBalance(e={}){let t=this.safeString2(e,"network_id","network",this.safeString(this.options,"defaultNetworkId","56")),i=this.safeDict(this.options,"chains",{}),s=this.safeDict(i,t,{}),r=this.safeString2(e,"rpcUrl","rpc",this.safeString(s,"rpcUrl")),a=this.safeString2(e,"token","tokenAddress",this.safeString(s,"collateralToken"));if(void 0===a)throw new h.NotSupported(this.id+" fetchBalance() has no collateral token configured for network "+t);let o=this.safeString(e,"currency",this.safeString(s,"collateralCurrency","USD1")),n=this.safeInteger(e,"decimals",this.safeInteger(s,"collateralDecimals",18)),d=this.walletAddressFromKeys(),c=[{to:a,data:"0x70a08231"+this.padHexAddress(d)},"latest"],l=await this.ethRpc(r,"eth_call",c),u=this.fromWeiWithDecimals(l,n),f={info:{balanceHex:l,token:a,networkId:t}},p=this.account();return p.free=u,p.total=u,f[o]=p,this.safeBalance(f)}hexToDecimalString(e){let t=this.remove0xPrefix(e);if(""===t)return;let i=this.stringToCharsArray(t.toLowerCase()),s=i.length,r="0";for(let e=0;e<s;e++){let t="0123456789abcdef".indexOf(i[e]);if(t>-1){let e=d.Y.stringMul(r,"16"),i=this.numberToString(t);r=d.Y.stringAdd(e,i)}}return r}fromWeiWithDecimals(e,t){let i=this.hexToDecimalString(e);if(void 0===i)return;let s="1";if(void 0===t)throw new h.ExchangeError(this.id+" fromWeiWithDecimals() missing decimals");for(let e=0;e<t;e++)s+="0";return d.Y.stringDiv(i,s)}parseTradeTx(e,t,i,s){return this.safePredictionOrder({id:e,clientOrderId:void 0,info:this.extend({transactionHash:e},this.safeDict(t,"info",{})),outcome:this.safeString(i,"outcome"),outcomeId:this.safeString(i,"id"),label:this.safeString(i,"label"),market:this.safeString(i,"market"),type:"market",side:s,price:this.safeNumber(t,"priceAverage"),amount:this.safeNumber(t,"shares"),cost:this.safeNumber(t,"value"),status:"closed",fee:void 0},i)}parseMarketToEvent(e,t){let i=this.safeString(e,"slug",this.safeString(e,"id")),s=this.safeString(e,"state","open"),r=this.safeString(e,"expiresAt");return{id:t.id,slug:i,event:t.market,title:this.safeString2(e,"title","shortName"),description:this.safeString(e,"description"),markets:[t],volume:this.safeNumber2(e,"volumeNotional24h","volume24h"),liquidity:this.safeNumber(e,"liquidity"),url:void 0,image:this.safeString(e,"imageUrl"),active:"open"===s,resolved:"resolved"===s,category:void 0,tags:this.safeList(e,"topics"),created:this.parse8601(this.safeString(e,"publishedAt")),createdDatetime:this.safeString(e,"publishedAt"),end:void 0!==r?this.parse8601(r):void 0,endDatetime:r,lastUpdatedAt:void 0,resolutionSource:this.safeString(e,"resolutionSource"),info:e}}parseMyriadMarket(e,t){let i,s=this.safeString(e,"networkId"),r=this.safeString(e,"id"),a=this.safeString(e,"slug",r),o=this.safeList(e,"outcomes",[]),n=this.safeString(e,"expiresAt"),d=this.safeString(e,"state","open"),h="open"===d,c=this.safeString(e,"resolvedOutcomeId","-1"),l=this.safeBool(e,"voided",!1),u="-1"!==c&&void 0!==c&&""!==c,f=this.safeNumber(e,"volume24h"),p=this.slugToMarketSymbol(t,a),m=this.safeDict(e,"token",{}),g=this.safeString(m,"address"),v=this.safeInteger(m,"decimals",18),y=this.safeString(m,"symbol","USDC"),b=this.safeDict(e,"fees",{}),w=this.safeDict(b,"buy",{}),k=this.safeDict(b,"sell",{}),S=this.safeNumber(w,"fee",.01),O=this.safeNumber(k,"fee",0),T=[];for(let n=0;n<o.length;n++){let m,y,b=this.safeDict(o,n,{}),w=this.safeString(b,"outcomeId",this.safeString(b,"id",n.toString())),k=this.safeString(b,"label",this.safeString(b,"title",w)),S=this.safeNumber(b,"price"),O=this.slugToOutcomeSymbol(t,a,k),P=s+":"+r+"/"+w;u?(y=+!!(m=w===c),m&&(i=O)):!0===l&&(m=!1);let I=m,A=y;T.push({id:P,outcomeId:P,outcome:O,market:p,label:k,active:h,winner:I,settleFraction:A,precision:{amount:.01,price:.001},info:{networkId:s,marketId:r,slug:a,outcomeId:w,outcomeLabel:k,outcomePrice:S,volume24h:f,state:d,tradingModel:this.safeString(e,"tradingModel","amm"),tokenAddress:g,tokenDecimals:v}})}let P=this.safeString(e,"tradingModel","amm"),I="clob";return"amm"===P&&(I="amm"),{id:s+":"+r,market:p,marketType:T.length>2?"categorical":"binary",executionModel:I,base:a,quote:y,settle:void 0,baseId:s+":"+r,quoteId:y,settleId:void 0,type:"prediction",spot:!1,margin:!1,swap:!1,future:!1,option:!1,prediction:!0,active:h,resolved:u||l,resolvedOutcome:i,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0!==n&&""!==n?this.parse8601(n):void 0,expiryDatetime:n,strike:void 0,optionType:void 0,taker:S,maker:O,percentage:!0,tierBased:!1,feeSide:"get",precision:{amount:.01,price:.001},limits:{leverage:{min:1,max:1},amount:{min:0,max:void 0},price:{min:.001,max:.999},cost:{min:void 0,max:void 0}},outcomes:T,info:this.extend(e,{networkId:s,marketId:r,slug:a,volume24h:f,state:d}),created:void 0}}async fetchTicker(e,t={}){let i=await this.loadOutcome(e),s=this.safeString(i.info,"networkId"),r=this.safeString(i.info,"marketId"),a=await this.myriadPublicGetMarketsId(this.extend({id:r,network_id:s},t));return this.parsePredictionTicker(a,i)}async fetchTradingFee(e,t={}){let i=await this.loadOutcome(e),s=this.safeDict(i,"info",{}),r={id:this.safeString(s,"marketId"),network_id:this.safeString(s,"networkId")},a=await this.myriadPublicGetMarketsId(this.extend(r,t)),o=this.safeDict(a,"fees",{}),n=this.safeDict(o,"buy",{}),d=this.safeDict(o,"sell",{});return{info:a,outcome:this.safeOutcomeSymbol(void 0,i),outcomeId:this.safeString(i,"outcomeId"),maker:this.safeNumber(d,"fee"),taker:this.safeNumber(n,"fee"),percentage:!0,tierBased:!1}}parsePredictionTicker(e,t){let i,s,r,a,o=null!=t?this.safeString(t.info,"outcomeId"):void 0,n=this.safeList(e,"outcomes",[]);for(let e=0;e<n.length;e++){let t=this.safeDict(n,e);if(this.safeString(t,"outcomeId",this.safeString(t,"id"))===o){i=this.safeNumber(t,"price"),s=this.safeNumber(t,"priceChange24h");break}}return void 0!==i&&void 0!==s&&0!=(r=i-s)&&(a=s/r*100),this.safePredictionTicker({outcome:this.safeString(t,"outcome"),outcomeId:this.safeString(t,"id"),label:this.safeString(t,"label"),market:this.safeString(t,"market"),timestamp:void 0,datetime:void 0,high:void 0,low:void 0,bid:i,bidVolume:void 0,ask:i,askVolume:void 0,vwap:void 0,open:r,close:i,last:i,previousClose:r,change:s,percentage:a,average:i,baseVolume:this.safeNumber(e,"volumeNotional24h"),quoteVolume:this.safeNumber(e,"volume24h"),info:e},t)}async fetchOrderBook(e,t,i={}){let s,r,a,o=await this.loadOutcome(e),n=this.safeString(o.info,"networkId"),h=this.safeString(o.info,"marketId"),c=this.safeString(o.info,"outcomeId");if("ob"===this.safeString(o.info,"tradingModel","amm")){let t=await this.myriadPublicGetMarketsIdOrderbook(this.extend({id:h,network_id:n,outcome:c},i));return this.safePredictionOrderBook(this.parseWeiOrderBook(t,this.safeOutcomeSymbol(e,o)),o)}let l=await this.myriadPublicGetMarketsId(this.extend({id:h,network_id:n},i)),u=this.safeList(l,"outcomes",[]);for(let e=0;e<u.length;e++){let t=this.safeDict(u,e);if(this.safeString(t,"outcomeId",this.safeString(t,"id"))===c){s=this.safeNumber(t,"price");break}}void 0!==s&&(s>.001&&(r=this.parseNumber(d.Y.stringSub(this.numberToString(s),"0.001"))),s<.999&&(a=this.parseNumber(d.Y.stringAdd(this.numberToString(s),"0.001"))));let f=this.parseNumber("9999"),p=[];void 0!==r&&p.push([r,f]);let m=[];void 0!==a&&m.push([a,f]);let g={outcome:this.safeOutcomeSymbol(e,o),bids:p,asks:m,timestamp:void 0,datetime:void 0,nonce:void 0};return this.safePredictionOrderBook(g,o)}parseWeiOrderBook(e,t){let i=this.safeList(e,"bids",[]),s=this.safeList(e,"asks",[]),r=[];for(let e=0;e<i.length;e++){let t=this.safeList(i,e),s=d.Y.stringDiv(this.safeString(t,0),"1000000000000000000"),a=d.Y.stringDiv(this.safeString(t,1),"1000000000000000000");r.push([this.parseNumber(s),this.parseNumber(a)])}let a=[];for(let e=0;e<s.length;e++){let t=this.safeList(s,e),i=d.Y.stringDiv(this.safeString(t,0),"1000000000000000000"),r=d.Y.stringDiv(this.safeString(t,1),"1000000000000000000");a.push([this.parseNumber(i),this.parseNumber(r)])}return{outcome:t,bids:this.sortBy(r,0,!0),asks:this.sortBy(a,0),timestamp:void 0,datetime:void 0,nonce:void 0}}async fetchOHLCV(e,t="1d",i,s,r={}){let a,o,n=await this.loadOutcome(e),d=this.safeDict(n,"info",{}),h=this.safeString(n.info,"networkId"),c=this.safeString(n.info,"marketId"),l=this.safeString(d,"outcomeId",this.safeString(d,"id")),u=this.safeString(d,"outcomeLabel",this.safeString(d,"label",this.safeString(d,"title"))),f=this.safeString(this.timeframes,t,"30d"),p=await this.myriadPublicGetMarketsId(this.extend({id:c,network_id:h},r)),m=this.safeList(p,"outcomes",[]);for(let e=0;e<m.length;e++){let t=m[e],i=this.safeString(t,"id",this.safeString(t,"outcomeId")),s=this.safeString(t,"title",this.safeString(t,"label"));if(void 0!==l&&i===l){a=t;break}void 0===a&&void 0!==u&&s===u&&(a=t)}let g=this.safeList(a,"price_charts");if(void 0!==g)for(let e=0;e<g.length;e++){let t=g[e];if(this.safeString(t,"timeframe")===f){o=t;break}}else{let e=this.safeDict(a,"price_charts",{});o=this.safeValue(e,f)}let v=this.safeList(o,"prices",this.safeList(o,"data",o)),y=void 0!==v?v:[];if(0===y.length){let e=this.safeDict(p,"price_charts",{}),t=this.safeValue(e,f,{});y=this.safeList(t,l,this.safeList(t,"data",[]))}let b=[];for(let e=0;e<y.length;e++){let t=y[e],i=this.safeNumber(t,"open"),s=this.safeNumber(t,"price",this.safeNumber(t,"value")),r=this.safeInteger(t,"timestamp");(void 0!==i||void 0!==s)&&void 0!==r&&b.push(t)}return this.parseOHLCVs(b,n,t,i,s)}parseOHLCV(e,t){let i=this.safeNumber(e,"open"),s=this.safeNumber(e,"high"),r=this.safeNumber(e,"low"),a=this.safeNumber(e,"close"),o=this.safeNumber(e,"price",this.safeNumber(e,"value"));return[this.safeTimestamp(e,"timestamp"),void 0!==i?i:o,void 0!==s?s:o,void 0!==r?r:o,void 0!==a?a:o,0]}async fetchTickers(e,t={}){if(void 0===e)throw new h.ArgumentsRequired(this.id+" fetchTickers() requires an outcomes argument — the venue has no all-tickers endpoint; pass the outcome handles to fetch (discover them via fetchEvents ())");let i={};await this.loadOutcomes(e);let s={},r=[];for(let t=0;t<e.length;t++){let i=this.outcome(e[t]),a=this.safeDict(i,"info",{}),o=this.safeString(a,"networkId")+":"+this.safeString(a,"marketId");o in s||(s[o]=[],r.push(o));let n=s[o];n.push(i),s[o]=n}let a=[];for(let e=0;e<r.length;e++){let i=s[r[e]],o=this.safeDict(i,0),n=this.safeDict(o,"info",{});a.push(this.myriadPublicGetMarketsId(this.extend({id:this.safeString(n,"marketId"),network_id:this.safeString(n,"networkId")},t)))}let o=await Promise.all(a);for(let e=0;e<r.length;e++){let t=r[e],a=o[e],n=s[t];for(let e=0;e<n.length;e++){let t=n[e],s=this.parsePredictionTicker(a,t),r=this.safeString(s,"outcome");void 0!==r&&(i[r]=s)}}return i}async fetchTrades(e,t,i,s={}){let r=await this.loadOutcome(e),a=this.safeDict(r,"info",{}),o=this.safeString(a,"networkId"),n=this.safeString(a,"marketId"),d=this.safeString(a,"outcomeId"),h={id:n,network_id:o};void 0!==i&&(h.limit=i);let c=await this.myriadPublicGetMarketsIdEvents(this.extend(h,s)),l=Array.isArray(c)?c:this.safeList(c,"data",[]),u=void 0!==l?l:[],f=[];for(let e=0;e<u.length;e++){let t=this.safeDict(u,e),i=this.safeString(t,"action");if("buy"!==i&&"sell"!==i)continue;let s=this.safeString(t,"outcomeId");(void 0===d||s===d)&&f.push(t)}return this.parsePredictionTrades(f,r,t,i)}parsePredictionTrade(e,t){let i,s=this.safeTimestamp(e,"timestamp"),r=this.safeString(e,"shares"),a=this.safeString(e,"value");return void 0===r||void 0===a||d.Y.stringEq(r,"0")||(i=d.Y.stringDiv(a,r)),this.safePredictionTrade({id:this.safeString(e,"txId"),info:e,timestamp:s,datetime:this.iso8601(s),outcome:this.safeString(t,"outcome"),outcomeId:this.safeString(t,"id"),label:this.safeString(t,"label"),market:this.safeString(t,"market"),order:void 0,type:void 0,side:this.safeString(e,"action"),takerOrMaker:"taker",price:this.parseNumber(i),amount:this.parseNumber(r),cost:this.parseNumber(a),fee:void 0},t)}async fetchEvents(e={}){!0!==this.safeBool(this.options,"allowUnscopedFetchEvents",!1)&&this.requireEventQuery(e);let t=this.parseSearchQueries(e),i=this.omit(e,["query","queries","sort","searchIn","eventId","slug","status","tags"]);if(void 0===t)throw new h.ExchangeError(this.id+" fetchEvents() missing queries");let s=t.length,r=this.safeString(e,"eventId"),a=[],o=[];if(s>0){let e=await Promise.all([this.fetchRawMarketsBySearch(t,i),this.fetchRawQuestionsBySearch(t,i)]);a=this.safeList(e,0,[]),o=this.safeList(e,1,[])}else if(void 0!==r)r.indexOf(":")>-1?a=[await this.fetchRawMarketById(r,i)]:o=[await this.fetchRawQuestionById(r,i)];else{let t=this.safeList(e,"tags",[]),s=t.length;if(0===s){let e=await Promise.all([this.fetchRawMarketsList(i),this.fetchRawQuestionsList(i)]);a=this.safeList(e,0,[]),o=this.safeList(e,1,[])}else{let e=[];for(let i=0;i<s;i++){let s=t[i];e.push(s.replaceAll("-"," "))}let r=await Promise.all([this.fetchRawMarketsBySearch(e,i),this.fetchRawQuestionsBySearch(e,i)]);a=this.safeList(r,0,[]),o=this.safeList(r,1,[])}}void 0===this.markets&&(this.markets=this.createSafeDictionary());let n={},d=[],c=o.length;for(let e=0;e<c;e++){let t=o[e],i=this.parseEvent(t),s=this.safeList(i,"markets",[]),r=s.length,a=[];for(let e=0;e<r;e++){let t=this.safeDict(s,e,{}),i=this.safeString(t,"market");if(void 0!==i){if(i in n)continue;n[i]=!0,this.markets[i]=t}a.push(t)}let h=a.length;r>0&&0===h||(i.markets=a,d.push(i))}let l=a.length;for(let e=0;e<l;e++){let t=a[e],i=this.parseMyriadMarket(t),s=this.safeString(i,"market");if(void 0!==s&&s in n){this.markets[s]=i;continue}void 0!==s&&(n[s]=!0,this.markets[s]=i);let r=this.parseMarketToEvent(t,i);d.push(r)}this.setEvents(d),this.populateOutcomes();let u=this.omit(e,["tags"]);return this.applyEventFetchParams(d,u,t)}parseEvent(e){let t=this.safeString(e,"slug",this.safeString(e,"id")),i=this.safeList(e,"markets",[]),s=[];for(let e=0;e<i.length;e++){let r=i[e];s.push(this.parseMyriadMarket(r,t))}let r=this.safeString(e,"expiresAt",this.safeString(e,"endDate"));return this.extend(e,{id:this.safeString(e,"id"),slug:t,event:void 0!==t&&""!==t?this.shortenSlug(t):void 0,title:this.safeString(e,"title"),description:this.safeString(e,"description"),markets:s,volume:this.safeNumber2(e,"volumeNotional24h","volume24h"),liquidity:this.safeNumber(e,"liquidity"),url:this.safeString(e,"url"),image:this.safeString(e,"imageUrl",this.safeString(e,"image")),active:this.safeBool(e,"active"),resolved:this.safeBool(e,"resolved",!1),category:this.safeString(e,"category"),tags:this.safeList(e,"tags"),created:this.parse8601(this.safeString(e,"createdAt")),createdDatetime:this.safeString(e,"createdAt"),end:void 0!==r&&""!==r?this.parse8601(r):void 0,endDatetime:r,lastUpdatedAt:this.parse8601(this.safeString(e,"updatedAt")),resolutionSource:this.safeString(e,"resolutionSource"),info:e})}requestId(e){void 0===this.safeValue(this.options,"requestId")&&(this.options.requestId=this.createSafeDictionary());let t=this.options.requestId,i=this.safeInteger(t,e,0),s=this.sum(i,1);return void 0!==e&&(this.options.requestId[e]=s),s}fromWei(e){if(void 0!==e)return this.parseNumber(d.Y.stringDiv(e,"1000000000000000000"))}marketOutcomeToSymbol(e,t,i){if(void 0===e||void 0===t||void 0===i)return;let s=this.safeDict(this.outcomes_by_id,e+":"+t+"/"+i);return this.safeString(s,"outcome")}async connectCentrifugo(e){let t=this.client(e);if(void 0===this.safeValue(t.subscriptions,"connect")){this.options.wsConnected=!1;let t=this.requestId(e);return await this.watch(e,"centrifugoConnected",{connect:{name:"ccxt"},id:t},"connect")}if(!this.safeBool(this.options,"wsConnected",!1))return await t.future("centrifugoConnected")}async pong(e,t){await e.send("{}")}async subscribeMyriadChannel(e,t,i={}){let s=this.safeString(this.urls.api,"ws");await this.connectCentrifugo(s);let r=this.requestId(s);return await this.watch(s,e,{subscribe:{channel:t},id:r},t)}handleMessage(e,t){if("string"==typeof t){let i=t.split("\n"),s=i.length;for(let t=0;t<s;t++){let s=i[t];if(s.length>0){let t=JSON.parse(s);this.handleCentrifugoFrame(e,t)}}return}this.handleCentrifugoFrame(e,t)}handleCentrifugoFrame(e,t){if(0===Object.keys(t).length)return void this.spawn(this.pong,e,t);if(void 0!==this.safeDict(t,"connect")){this.options.wsConnected=!0,e.resolve(!0,"centrifugoConnected");return}let i=this.safeDict(t,"push");if(void 0===i)return;let s=this.safeString(i,"channel");if(void 0===s)return;let r=this.safeDict(i,"pub",{}),a=this.safeDict(r,"data",{}),o=s.split(":"),n=this.safeString(o,0);"orderbook"===n?this.handleOrderBook(e,a):"trades"===n?this.handleTrades(e,a):"prices"===n?this.handleTicker(e,a):"orders"===n?this.handleOrder(e,a):"positions"===n&&this.handlePosition(e,a)}async watchOrderBook(e,t,i={}){let s=await this.loadOutcome(e),r=this.safeDict(s,"info",{}),a=this.safeString(r,"networkId"),o=this.safeString(r,"marketId"),n=this.safeOutcomeSymbol(e,s),d="orderbook:"+a+":"+o,h="orderbook::"+n,c=this.safeString(this.urls.api,"ws");await this.connectCentrifugo(c);let l=this.client(c),u=void 0===this.safeValue(l.subscriptions,d);u&&await this.seedOrderBook(e,n,t);let f=this.requestId(c),p=this.watch(c,h,{subscribe:{channel:d},id:f},d);return u&&l.resolve(this.safeValue(this.orderbooks,n),h),(await p).limit()}async seedOrderBook(e,t,i){let s=await this.fetchOrderBook(e,i),r=this.orderBook({});r.reset(s),this.orderbooks[t]=r}handleOrderBook(e,t){let i=this.safeString(t,"networkId"),s=this.safeString(t,"marketId"),r=this.safeInteger(t,"ts"),a=this.safeList(t,"changes",[]),o=a.length,n={};for(let e=0;e<o;e++){let t=this.safeDict(a,e),o=this.safeString(t,"outcome"),d=this.marketOutcomeToSymbol(i,s,o);if(void 0===d||void 0===this.safeValue(this.orderbooks,d))continue;let h=this.orderbooks[d],c=this.fromWei(this.safeString(t,"price")),l=this.fromWei(this.safeString(t,"amount"));("bid"===this.safeString(t,"side")?h.bids:h.asks).storeArray([c,l]),h.timestamp=r,h.datetime=this.iso8601(r),n[d]=!0}let d=Object.keys(n),h=d.length;for(let t=0;t<h;t++){let i=d[t];e.resolve(this.orderbooks[i],"orderbook::"+i)}}async watchTrades(e,t,i,s={}){let r=await this.loadOutcome(e),a=this.safeDict(r,"info",{}),o=this.safeString(a,"networkId"),n=this.safeString(a,"marketId"),d=this.safeOutcomeSymbol(e,r),h=await this.subscribeMyriadChannel("trades::"+d,"trades:"+o+":"+n,s);return this.filterBySinceLimit(h,t,i,"timestamp",!0)}async watchMyTrades(e,t,i,s={}){if(void 0===e)throw new h.ArgumentsRequired(this.id+" watchMyTrades() requires a outcome (the trades channel is per-market)");let r=await this.loadOutcome(e),a=this.safeDict(r,"info",{}),o=this.safeString(a,"networkId"),n=this.safeString(a,"marketId"),d=this.safeOutcomeSymbol(e,r),c=await this.subscribeMyriadChannel("myTrades","trades:"+o+":"+n,s);return this.filterByValueSinceLimit(c,"outcome",d,t,i,"timestamp",!0)}walletAddressOrUndefined(){return void 0!==this.walletAddress&&this.walletAddress.length>0?this.walletAddress.toLowerCase():void 0!==this.privateKey?this.ethGetAddressFromPrivateKey(this.privateKey).toLowerCase():void 0}handleTrades(e,t){let i=this.safeString(t,"networkId"),s=this.safeString(t,"marketId"),r=this.safeInteger(t,"ts"),a=this.safeString(t,"txHash"),o=this.safeDict(t,"taker",{}),d=this.safeString(o,"outcome"),h=this.marketOutcomeToSymbol(i,s,d);if(void 0===h)return;let c=this.safeMarket(h),l=this.safeOutcome(h),u=this.safeDict(o,"totalFees",{}),f=this.safePredictionTrade({id:a,info:t,timestamp:r,datetime:this.iso8601(r),outcome:h,outcomeId:this.safeString2(l,"outcomeId","id"),label:this.safeString(l,"label"),market:this.safeString(l,"market"),order:this.safeString(o,"orderHash"),type:void 0,side:this.safeStringLower(o,"side"),takerOrMaker:"taker",price:this.safeNumber(o,"averagePrice"),amount:this.safeNumber(o,"totalAmount"),cost:void 0,fee:{cost:this.safeNumber(u,"total"),currency:this.safeString(c,"quote")}},c);if(void 0===this.trades&&(this.trades=this.createSafeDictionary()),void 0===this.safeValue(this.trades,h)){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.trades[h]=new n.I3(e)}let p=this.trades[h];p.append(f),e.resolve(p,"trades::"+h);let m=this.walletAddressOrUndefined();if(void 0!==m){let d=[];this.safeStringLower(o,"trader")===m&&d.push(f);let h=this.safeList(t,"makers",[]),c=h.length;for(let e=0;e<c;e++){let t=h[e];if(this.safeStringLower(t,"trader")===m){let e=this.marketOutcomeToSymbol(i,s,this.safeString(t,"outcome")),o=this.safeMarket(e),n=this.safeOutcome(e),h=this.safeDict(t,"fees",{}),c=this.safePredictionTrade({id:a,info:t,timestamp:r,datetime:this.iso8601(r),outcome:e,outcomeId:this.safeString(n,"id"),label:this.safeString(n,"label"),market:this.safeString(n,"market"),order:this.safeString(t,"orderHash"),type:void 0,side:this.safeStringLower(t,"side"),takerOrMaker:"maker",price:this.safeNumber(t,"price"),amount:this.safeNumber(t,"amount"),cost:void 0,fee:{cost:this.safeNumber(h,"total"),currency:this.safeString(o,"quote")}},o);d.push(c)}}let l=d.length;if(l>0){if(void 0===this.myTrades){let e=this.safeInteger(this.options,"myTradesLimit",1e3);this.myTrades=new n.$0(e)}let t=this.myTrades;for(let e=0;e<l;e++)t.append(d[e]);e.resolve(t,"myTrades")}}}async watchTicker(e,t={}){let i=await this.loadOutcome(e),s=this.safeDict(i,"info",{}),r=this.safeString(s,"networkId"),a=this.safeString(s,"marketId"),o=this.safeOutcomeSymbol(e,i);return await this.subscribeMyriadChannel("ticker::"+o,"prices:"+r+":"+a,t)}async watchTickers(e,t={}){if(void 0===e)throw new h.ArgumentsRequired(this.id+" watchTickers() requires a list of outcomes (the prices channel is per-market)");let i=e.length,s=this.safeString(this.urls.api,"ws");await this.connectCentrifugo(s),await this.loadOutcomes(e);let r=this.client(s),a={},o=[];for(let t=0;t<i;t++){let i=this.outcome(e[t]),r=this.safeDict(i,"info",{}),n="prices:"+this.safeString(r,"networkId")+":"+this.safeString(r,"marketId");if(o.push(this.safeOutcomeSymbol(e[t],i)),void 0===this.safeValue(a,n)){a[n]=!0;let e={subscribe:{channel:n},id:this.requestId(s)};this.watch(s,"tickers",e,n)}}let n=await r.future("tickers");return this.filterByArray(n,"outcome",o,!0)}async watchOHLCV(e,t="1m",i,s,r={}){let a=await this.watchTrades(e,i,s,r),o=this.buildOHLCVC(a,t,0,0x7fffffff),n=[],d=o.length;for(let e=0;e<d;e++){let t=o[e];n.push([t[0],t[1],t[2],t[3],t[4],t[5]])}return this.filterBySinceLimit(n,i,s,0,!0)}handleTicker(e,t){let i=this.safeString(t,"networkId"),s=this.safeString(t,"marketId"),r=this.safeInteger(t,"ts"),a=this.safeList(t,"outcomes",[]),o=a.length;void 0===this.tickers&&(this.tickers=this.createSafeDictionary());for(let t=0;t<o;t++){let o=a[t],n=this.safeString(o,"outcome"),d=this.marketOutcomeToSymbol(i,s,n);if(void 0===d)continue;let h=this.safeMarket(d),c=this.safeOutcome(d),l=this.fromWei(this.safeString(o,"last")),u=this.safePredictionTicker({outcome:d,outcomeId:this.safeString2(c,"outcomeId","id"),label:this.safeString(c,"label"),market:this.safeString(c,"market"),timestamp:r,datetime:this.iso8601(r),high:void 0,low:void 0,bid:this.fromWei(this.safeString(o,"bestBid")),bidVolume:void 0,ask:this.fromWei(this.safeString(o,"bestAsk")),askVolume:void 0,vwap:void 0,open:void 0,close:l,last:l,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:void 0,quoteVolume:void 0,info:o},h);this.tickers[d]=u,e.resolve(u,"ticker::"+d)}e.resolve(this.tickers,"tickers")}async watchOrders(e,t,i,s={}){let r=this.walletAddressFromKeys(),a=this.safeString(this.options,"defaultNetworkId","56"),o=e;if(void 0!==o){let e=await this.loadOutcome(o),t=this.safeDict(e,"info",{});a=this.safeString(t,"networkId",a),o=this.safeOutcomeSymbol(o,e)}let n="orders:"+a+":"+r,d=await this.subscribeMyriadChannel("orders",n,s);return this.filterByValueSinceLimit(d,"outcome",o,t,i,"timestamp",!0)}handleOrder(e,t){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new n.$0(e)}let i=this.safeString(t,"networkId"),s=this.safeString(t,"marketId"),r=this.safeString(t,"outcome"),a=this.marketOutcomeToSymbol(i,s,r),o=this.safeOutcome(a),d=this.fromWei(this.safeString(t,"price")),h=this.fromWei(this.safeString(t,"amount")),c=this.fromWei(this.safeString(t,"filledAmount")),l=this.parseOrderStatus(this.safeStringLower(t,"status")),u=this.safeStringUpper(t,"timeInForce"),f="FOK"===u||"FAK"===u,p=this.parse8601(this.safeString2(t,"updatedAt","createdAt")),m=this.safePredictionOrder({id:this.safeString(t,"orderHash"),clientOrderId:void 0,info:t,timestamp:p,datetime:this.iso8601(p),outcome:a,outcomeId:this.safeString2(o,"outcomeId","id"),label:this.safeString(o,"label"),market:this.safeString(o,"market"),type:f?"market":"limit",timeInForce:u,side:this.safeStringLower(t,"side"),price:d,amount:h,filled:c,remaining:void 0,average:void 0,cost:void 0,status:l,fee:void 0,trades:void 0}),g=this.orders;g.append(m),e.resolve(g,"orders"),void 0!==a&&e.resolve(g,"orders::"+a)}async watchPositions(e,t,i,s={}){void 0!==e&&await this.loadOutcomes(e);let r=this.walletAddressFromKeys(),a="positions:"+this.safeString(this.options,"defaultNetworkId","56")+":"+r,o=this.safeString(this.urls.api,"ws");await this.connectCentrifugo(o);let n=this.client(o);void 0===this.safeValue(n.subscriptions,a)&&await this.seedPositionBalances(r);let d=this.requestId(o),h=await this.watch(o,"positions",{subscribe:{channel:a},id:d},a);return this.newUpdates?h:this.filterByOutcomesSinceLimit(h,e,t,i,!0)}async seedPositionBalances(e){let t=await this.fetchPositions(void 0,{address:e}),i={},s=t.length;for(let e=0;e<s;e++){let s=this.safeDict(t,e),r=this.safeString(s,"id");void 0!==r&&(i[r]=this.numberToString(this.safeNumber(s,"contracts",0)))}this.options.positionBalances=i}handlePosition(e,t){let i,s;if(void 0===this.positions){let e=this.safeInteger(this.options,"positionsLimit",1e3);this.positions=new n.$0(e)}let r=this.safeString(t,"networkId"),a=this.safeString(t,"marketId"),o=this.safeString(t,"outcome"),h=this.marketOutcomeToSymbol(r,a,o),c=this.safeOutcome(h),l=this.safeInteger(t,"ts"),u=this.safeString(t,"delta","0");"+"===u.slice(0,1)&&(u=u.slice(1));let f=d.Y.stringDiv(u,"1000000000000000000");if(void 0!==r&&void 0!==a&&void 0!==o){s=r+":"+a+"/"+o;let e=this.safeDict(this.options,"positionBalances",{}),t=this.safeString(e,s,"0"),n=d.Y.stringAdd(t,f);void 0!==s&&(e[s]=n),this.options.positionBalances=e,i=this.parseNumber(n)}let p=this.safePredictionPosition({info:t,id:s,outcome:h,outcomeId:s,label:this.safeString(c,"label"),market:this.safeString(c,"market"),timestamp:l,datetime:this.iso8601(l),side:"long",contracts:i,entryPrice:void 0,markPrice:void 0,notional:void 0,collateral:void 0,unrealizedPnl:void 0}),m=this.positions;m.append(p),e.resolve(m,"positions")}walletAddressFromKeys(){let e=this.walletAddress;if(!(void 0!==e&&this.walletAddress.length>0)){if(void 0===this.privateKey)throw new h.ArgumentsRequired(this.id+" requires a walletAddress or privateKey to watch private channels");e=this.ethGetAddressFromPrivateKey(this.privateKey)}return e.toLowerCase()}handleErrors(e,t,i,s,r,a,o,n,d){if(void 0===o)return;let c=this.safeString(o,"error");if(void 0===c||""===c)return;let l=this.id+" "+a;throw this.throwExactlyMatchedException(this.exceptions.exact,c,l),this.throwBroadlyMatchedException(this.exceptions.broad,c,l),new h.ExchangeError(l)}sign(e,t="myriad",i="GET",s={},r,a){let o="string"==typeof t?t:t[0],n=this.urls.api,d=this.safeString(n,o,n.myriad)+"/"+this.implodeParams(e,s),h=this.omit(s,this.extractParams(e));if("GET"===i){let e=this.urlencode(h);""!==e&&(d+="?"+e)}let c=this.extend({Accept:"application/json","Content-Type":"application/json"},void 0!==r?r:{}),l=a;if("GET"!==i&&Object.keys(h).length>0&&(l=this.json(h)),void 0!==this.apiKey&&""!==this.apiKey){let e={};e["x-api-key"]=this.apiKey,c=this.extend(c,e)}return{url:d,method:i,body:l,headers:c}}}i.d(t,{A:()=>c})},2478(e,t,i){"use strict";var s=i(6834),r=i(6885),a=i(3647),o=i(1093),n=i(7749),d=i(1697),h=i(1453);class c extends a.A{describe(){return this.deepExtend(super.describe(),{id:"opinion",name:"Opinion",countries:["HK"],rateLimit:67,certified:!1,pro:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!1,future:!1,option:!1,cancelOrder:!0,createOrder:!0,fetchBalance:!0,fetchClosedOrders:!0,fetchEvent:!0,fetchEvents:!0,fetchMarkets:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPositions:!0,fetchTicker:!0,fetchTickers:!0,prediction:!0,watchMyTrades:!0,watchOrderBook:!0,watchOrders:!0,watchTicker:!0,watchTrades:!0},timeframes:{"1h":"1h","1d":"1d"},urls:{logo:"https://github.com/user-attachments/assets/9905d9d4-3eb3-48d2-bdb3-551a9ddc7559",api:{opinion:"https://openapi.opinion.trade/openapi",ws:"wss://ws.opinion.trade"},www:"https://opinion.trade",doc:["https://docs.opinion.trade"]},api:{opinion:{public:{get:{market:{cost:1},"market/{marketId}":{cost:1},"market/categorical/{marketId}":{cost:1},"market/slug/{slug}":{cost:1},label:1,"token/latest-price":{cost:1},"token/orderbook":{cost:1},"token/price-history":{cost:1},quoteToken:{cost:1}}},private:{get:{order:{cost:1},"order/{orderId}":{cost:1},"positions/user/{walletAddress}":{cost:1},"trade/user/{walletAddress}":{cost:1},"auth/api-key":{cost:1},"user/auth":{cost:1},"user/balance":{cost:1}},post:{"auth/api-key":{cost:1},order:{cost:1},"order/cancel":{cost:1}},delete:{"auth/api-key":{cost:1}}}}},requiredCredentials:{apiKey:!0,secret:!1,walletAddress:!0,privateKey:!0},fees:{trading:{tierBased:!1,percentage:!0,maker:-.02,taker:.04}},exceptions:{exact:{10014:h.AccountNotEnabled,10403:h.PermissionDenied,11001:h.AuthenticationError,11002:h.AuthenticationError,10605:h.InvalidOrder,10610:h.InvalidOrder,11004:h.AuthenticationError,11005:h.AuthenticationError,11009:h.AuthenticationError,11010:h.AuthenticationError,11011:h.AuthenticationError,11012:h.AuthenticationError,11013:h.AuthenticationError},broad:{"Insufficient token balance":h.InsufficientFunds,"below the minimum required value":h.InvalidOrder,"must be the current multi-signature wallet":h.InvalidOrder}},streaming:{keepAlive:25e3},options:{tradesLimit:1e3,ordersLimit:1e3,myTradesLimit:1e3,eventScopeParams:["labelId"],defaultFetchEventsLimit:20,maxFetchEventsResults:100,maxEventsPages:50,marketsPageLimit:20,maxMarketsPages:50}})}async fetchMarkets(e={}){let t=this.omit(e,["limit"]),i=this.safeInteger(e,"limit"),s=this.safeInteger(this.options,"marketsPageLimit",20),r=this.safeInteger(this.options,"maxMarketsPages",50),a=[],o={},n=[],d=1,h=0;for(;;){let e={marketType:2,limit:s,page:d},c=await this.opinionPublicGetMarket(this.extend(e,t)),l=this.safeDict(c,"result",{}),u=this.safeList(l,"list",[]),f=u.length;h=this.sum(h,f);let p=this.safeInteger(l,"total");for(let e=0;e<f;e++){let t=u[e];if(1===this.safeInteger(t,"marketType")){let e=this.parseEvent(t),i=e.markets,s=i.length;for(let e=0;e<s;e++)a.push(i[e]);let r=this.safeString(e,"event");void 0===r||""===r||r in o||(o[r]=!0,n.push(e))}else a.push(this.parseOpinionMarket(t))}let m=a.length;if(f<s||d>=r||void 0!==p&&h>=p||void 0!==i&&m>=i)break;d=this.sum(d,1)}this.setEvents(n);let c=a.length;return void 0!==i&&c>i?this.arraySlice(a,0,i):a}async fetchOutcome(e){return void 0===this.outcomeSearchQuery(e)&&(await this.loadOutcomes(),this.hasOutcome(e))?this.safeOutcome(e):await super.fetchOutcome(e)}parseOpinionMarket(e,t){let i,s,r=this.safeString(e,"marketId"),a=this.safeString(e,"slug"),o=t;void 0!==t&&void 0!==a&&0===a.indexOf(t)&&(o=void 0);let n=this.slugToMarketSymbol(o,a),d=this.safeString(e,"statusEnum"),h="Activated"===d,c="Resolved"===d,l=this.safeString(e,"resultTokenId"),u=c&&void 0!==l&&""!==l,f=[this.safeString(e,"yesLabel","YES"),this.safeString(e,"noLabel","NO")],p=[this.safeString(e,"yesTokenId"),this.safeString(e,"noTokenId")],m=[];for(let t=0;t<f.length;t++){let s,r,d=f[t],c=p[t],g=this.slugToOutcomeSymbol(o,a,d);u&&(r=+!!(s=c===l),s&&(i=g)),m.push({id:c,outcomeId:c,outcome:g,market:n,label:d,active:h,winner:s,settleFraction:r,info:e})}let g=i;0!==this.safeInteger(e,"cutoffAt",0)&&(s=this.safeTimestamp(e,"cutoffAt"));let v=this.safeTimestamp(e,"createdAt");return{id:r,market:n,base:"USDT",quote:"USDT",settle:void 0,baseId:r,quoteId:"USDT",settleId:void 0,type:"prediction",marketType:"binary",executionModel:"clob",spot:!1,margin:!1,swap:!1,future:!1,option:!1,prediction:!0,active:h,resolved:c,resolvedOutcome:g,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:s,expiryDatetime:this.iso8601(s),strike:void 0,optionType:void 0,taker:this.fees.trading.taker,maker:this.fees.trading.maker,percentage:!0,tierBased:!1,feeSide:"get",precision:{amount:void 0,price:void 0},limits:{leverage:{min:1,max:1},amount:{min:void 0,max:void 0},price:{min:0,max:1},cost:{min:void 0,max:void 0}},outcomes:m,info:e,created:v}}async fetchEvents(e={}){this.requireEventQuery(e);let t=this.parseSearchQueries(e),i=this.safeString(e,"eventId"),s=this.safeString(e,"slug");if(void 0!==i||void 0!==s){let r,a=this.omit(e,["eventId","slug","query","queries","tags","status","sort","searchIn","limit"]);r=void 0!==s?await this.opinionPublicGetMarketSlugSlug(this.extend({slug:s},a)):await this.opinionPublicGetMarketCategoricalMarketId(this.extend({marketId:i},a));let o=this.safeDict(r,"result",{}),n=this.safeDict(o,"data",{}),d=this.parseEvent(n);return this.indexEventOutcomes(d),this.applyEventFetchParams([d],e,t)}let r=this.omit(e,["query","queries","tags","status","sort","searchIn","limit"]),a=this.safeInteger(this.options,"defaultFetchEventsLimit",20),o=this.safeInteger(e,"limit"),n=this.safeInteger(this.options,"maxFetchEventsResults",100);void 0!==o&&(n=o);let d=this.safeInteger(this.options,"maxEventsPages",50),h=[],c=1,l=0;for(;;){let e=a,t=n-l;if(t<e&&(e=t),e<=0)break;let i={marketType:1,limit:e,page:c},s=await this.opinionPublicGetMarket(this.extend(i,r)),o=this.safeDict(s,"result",{}),u=this.safeList(o,"list",[]),f=u.length;l=this.sum(l,f);for(let e=0;e<f;e++)h.push(u[e]);let p=this.safeInteger(o,"total");if(f<e||c>=d||void 0!==p&&l>=p||l>=n)break;c=this.sum(c,1)}let u=h.length,f=[];void 0===this.markets&&(this.markets=this.createSafeDictionary());for(let e=0;e<u;e++){let t=this.parseEvent(h[e]);f.push(t);let i=this.safeList(t,"markets",[]),s=i.length;for(let e=0;e<s;e++){let t=i[e];this.markets[t.market]=t}}return this.populateOutcomes(),this.applyEventFetchParams(f,e,t)}async fetchEvent(e,t={}){let i;i=e.indexOf("-")>=0?await this.opinionPublicGetMarketSlugSlug(this.extend({slug:e},t)):await this.opinionPublicGetMarketCategoricalMarketId(this.extend({marketId:e},t));let s=this.safeDict(i,"result",{}),r=this.safeDict(s,"data",{}),a=this.parseEvent(r);return this.indexEventOutcomes(a),a}parseEvent(e){let t,i,s=this.safeString(e,"marketId"),r=this.safeString(e,"slug"),a=this.safeString(e,"marketTitle");t=void 0!==a?this.shortenSlug(a):this.shortenSlug(r);let o=this.safeList(e,"childMarkets",[]),n=o.length,d=[];for(let e=0;e<n;e++)d.push(this.parseOpinionMarket(o[e],r));let h=this.safeString(e,"statusEnum");0!==this.safeInteger(e,"cutoffAt",0)&&(i=this.safeTimestamp(e,"cutoffAt"));let c=this.safeTimestamp(e,"createdAt"),l=this.safeList(e,"labels",[]);return this.extend({id:s,event:t,title:a,description:this.safeString(e,"rules"),slug:r,category:this.safeString(l,0),tags:l,markets:d,active:"Activated"===h,resolved:"Resolved"===h,volume:this.safeNumber(e,"volume"),created:c,createdDatetime:this.iso8601(c),end:i,endDatetime:this.iso8601(i),image:this.safeString2(e,"coverUrl","thumbnailUrl"),info:e})}async fetchTicker(e,t={}){let i=await this.loadOutcome(e),s=i.outcomeId,r=[this.opinionPublicGetTokenLatestPrice(this.extend({token_id:s},t)),this.opinionPublicGetTokenOrderbook(this.extend({token_id:s},t))],[a,o]=await Promise.all(r);return this.parsePredictionTicker({price:a,book:o},i)}parsePredictionTicker(e,t){let i=this.safeDict(e,"price",{}),s=this.safeDict(i,"result",{}),r=this.safeDict(e,"book",{}),a=this.safeDict(r,"result",{}),o=this.safeList(a,"bids",[]),n=this.safeList(a,"asks",[]),d=this.safeDict(o,0,{}),h=this.safeDict(n,0,{}),c=this.safeNumber(s,"price"),l=this.safeInteger(s,"timestamp");return 0===l&&(l=void 0),this.safePredictionTicker({outcome:this.safeString(t,"outcome"),outcomeId:this.safeString2(t,"outcomeId","id"),label:this.safeString(t,"label"),market:this.safeString2(t,"market","outcome"),timestamp:l,datetime:this.iso8601(l),high:void 0,low:void 0,bid:this.safeNumber(d,"price"),bidVolume:this.safeNumber(d,"size"),ask:this.safeNumber(h,"price"),askVolume:this.safeNumber(h,"size"),open:void 0,close:c,last:c,change:void 0,percentage:void 0,average:void 0,baseVolume:void 0,quoteVolume:void 0,info:e},t)}async fetchTickers(e,t={}){if(void 0===e)throw new h.ArgumentsRequired(this.id+" fetchTickers() requires an outcomes argument — the venue has no all-tickers endpoint; pass the outcome handles or token ids to fetch (discover them via fetchEvents ())");await this.loadOutcomes(e);let i=e.length,s=[];for(let r=0;r<i;r++){let i=this.outcome(e[r]).outcomeId;s.push(this.opinionPublicGetTokenLatestPrice(this.extend({token_id:i},t))),s.push(this.opinionPublicGetTokenOrderbook(this.extend({token_id:i},t)))}let r=await Promise.all(s),a={};for(let t=0;t<i;t++){let i=this.outcome(e[t]),s=2*t,o={price:r[s],book:r[this.sum(s,1)]},n=this.parsePredictionTicker(o,i),d=this.safeString(n,"outcome");void 0!==d&&(a[d]=n)}return a}async fetchOrderBook(e,t,i={}){let s=await this.loadOutcome(e),r=s.outcomeId,a=await this.opinionPublicGetTokenOrderbook(this.extend({token_id:r},i)),o=this.safeDict(a,"result",{}),n=this.safeInteger(o,"timestamp"),d=this.parseOrderBook(o,this.safeOutcomeSymbol(e,s),n,"bids","asks","price","size");return this.safePredictionOrderBook(d,s)}async fetchOHLCV(e,t="1d",i,s,r={}){if(!(t in this.timeframes)){let e=Object.keys(this.timeframes);throw new h.BadRequest(this.id+" fetchOHLCV() unsupported timeframe "+t+", supported timeframes are "+e.join(", "))}let a=(await this.loadOutcome(e)).outcomeId,o=this.safeString(this.timeframes,t),n=await this.opinionPublicGetTokenPriceHistory(this.extend({token_id:a,interval:o},r)),d=this.safeDict(n,"result",{}),c=this.safeList(d,"history",[]),l=[],u=c.length;for(let e=0;e<u;e++){let t=this.safeDict(c,e),i=this.safeNumber(t,"p"),s=this.safeTimestamp(t,"t");void 0!==i&&void 0!==s&&l.push([s,i,i,i,i,void 0])}let f=this.sortBy(l,0);return this.filterBySinceLimit(f,i,s,0)}parseOHLCV(e,t){let i=this.safeNumber(e,"p");return[this.safeTimestamp(e,"t"),i,i,i,i,void 0]}async loadQuoteToken(e){if(void 0===e)throw new h.ArgumentsRequired(this.id+" loadQuoteToken() requires a quoteTokenAddress");let t=e.toLowerCase(),i=this.safeDict(this.options,"quoteTokens",{}),s=this.safeDict(i,t);if(void 0!==s)return s;let r=await this.opinionPublicGetQuoteToken({}),a=this.safeDict(r,"result",{}),o=this.safeList(a,"list",[]),n=o.length,d={};for(let e=0;e<n;e++){let t=o[e],i=this.safeStringLower(t,"quoteTokenAddress");void 0!==i&&(d[i]=t)}this.options.quoteTokens=d;let c=this.safeDict(d,t);if(void 0===c)throw new h.ExchangeError(this.id+" loadQuoteToken() could not find quote token "+e);return c}async loadMultiSignAddress(){let e=this.safeString(this.options,"multiSignAddress");if(void 0!==e)return e;let t=await this.opinionPrivateGetUserAuth({}),i=this.safeDict(t,"result",{}),s=this.safeDict(i,"walletUsers",{}),r=this.safeString(s,"56",this.walletAddress);return this.options.multiSignAddress=r,r}signOpinionOrder(e,t){let i=this.ethEncodeStructuredData({name:"OPINION CTF Exchange",version:"1",chainId:56,verifyingContract:t},{Order:[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"signer",type:"address"},{name:"taker",type:"address"},{name:"tokenId",type:"uint256"},{name:"makerAmount",type:"uint256"},{name:"takerAmount",type:"uint256"},{name:"expiration",type:"uint256"},{name:"nonce",type:"uint256"},{name:"feeRateBps",type:"uint256"},{name:"side",type:"uint8"},{name:"signatureType",type:"uint8"}]},e),s=this.signMessage(i,this.privateKey);return"0x"+this.remove0xPrefix(s.r)+this.remove0xPrefix(s.s)+this.intToBase16(s.v)}opinionOrderRawAmounts(e,t,i,s,r){let a,o,d="1";for(let e=0;e<r;e++)d+="0";let c=this.numberToString(i);if(e&&"BUY"===t)return{makerAmount:this.decimalToPrecision(n.Y.stringMul(c,d),0,0,2),takerAmount:"0"};let l=this.decimalToPrecision(this.numberToString(s),1,6,2),u=l.split("."),f=this.safeString(u,0,"0"),p=this.safeString(u,1,""),m="1000000",g=n.Y.stringAdd(n.Y.stringMul(f,m),p.padEnd(6,"0"));if("0"===g)throw new h.InvalidOrder(this.id+" createOrder() invalid price "+l);let v=c;"BUY"===t&&(v=n.Y.stringMul(c,l));let y=this.decimalToPrecision(n.Y.stringMul(v,d),0,0,2);if("BUY"===t){let e=n.Y.stringDiv(y,g,0);a=n.Y.stringMul(e,g),o=n.Y.stringMul(e,m)}else{let e=n.Y.stringDiv(y,m,0);a=n.Y.stringMul(e,m),o=n.Y.stringMul(e,g)}return{makerAmount:a,takerAmount:o}}async createOrder(e,t,i,s,r,a={}){await this.loadApiKey(),this.checkRequiredCredentials();let o=await this.loadOutcome(e),n=o.outcomeId,d="market"===t,c=i.toUpperCase();if(void 0===r){if(!d)throw new h.ArgumentsRequired(this.id+" createOrder() requires a price for limit orders");if("SELL"===c)throw new h.ArgumentsRequired(this.id+" createOrder() requires a price for market sell orders")}let l="0";d&&"SELL"===c&&(l=this.numberToString(r));let u=this.safeDict(o,"info",{}),f=this.safeInteger(u,"marketId"),p=this.safeString(u,"quoteToken"),m=await this.loadQuoteToken(p),g=this.safeString(m,"ctfExchangeAddress",""),v=this.safeInteger(m,"decimal",18),y=this.opinionOrderRawAmounts(d,c,s,r,v),b=this.safeString(y,"makerAmount"),w=this.safeString(y,"takerAmount"),k=+("BUY"!==c),S=this.numberToString(this.milliseconds()),O=this.safeBool(a,"postOnly",!1),T=this.omit(a,["postOnly"]),P=await this.loadMultiSignAddress(),I=2*(P.toLowerCase()!==this.walletAddress.toLowerCase()),A={salt:S,maker:P,signer:this.walletAddress,taker:"0x0000000000000000000000000000000000000000",tokenId:n,makerAmount:b,takerAmount:w,expiration:"0",nonce:"0",feeRateBps:"0",side:k,signatureType:I},x=this.signOpinionOrder(A,g),M=this.remove0xPrefix(x),_=this.extend({salt:S,maker:P,signer:this.walletAddress,taker:"0x0000000000000000000000000000000000000000",tokenId:n,makerAmount:b,takerAmount:w,expiration:"0",nonce:"0",feeRateBps:"0",side:k.toString(),signatureType:I.toString(),signature:x,sign:M.slice(0,64),contractAddress:"",currencyAddress:p,topicId:f,price:d?l:this.numberToString(r),tradingMethod:d?1:2,timestamp:this.seconds(),safeRate:"0",orderExpTime:"0",postOnly:O},T),C=await this.opinionPrivatePostOrder(_),B=this.safeDict(C,"result",{}),E=this.safeDict(B,"orderData",{});return this.parsePredictionOrder(E,o)}async cancelOrder(e,t,i={}){await this.loadApiKey();let s=await this.opinionPrivatePostOrderCancel(this.extend({orderId:e},i)),r=this.safeDict(s,"result",{}),a=this.safeBool(r,"result",!1);return this.safePredictionOrder({id:e,status:!0===a?"canceled":void 0,info:s})}parseOrderStatus(e){return this.safeString({Pending:"open",Finished:"closed",Canceled:"canceled",Expired:"canceled",Failed:"canceled"},e,e)}parsePredictionOrder(e,t){let i=this.safeString(e,"orderId"),s=this.safeString(e,"statusEnum"),r=this.parseOrderStatus(s),a=this.safeStringLower(e,"sideEnum"),o=this.safeStringLower(e,"tradingMethodEnum"),n=this.safeTimestamp(e,"createdAt");return this.safePredictionOrder({id:i,clientOrderId:void 0,info:e,timestamp:n,datetime:this.iso8601(n),lastTradeTimestamp:void 0,status:r,outcome:this.safeString(t,"outcome"),outcomeId:this.safeString2(t,"outcomeId","id"),label:this.safeString(t,"label"),market:this.safeString2(t,"market","outcome"),type:o,side:a,price:this.safeNumber(e,"price"),amount:this.safeNumber(e,"orderShares"),cost:this.safeNumber(e,"filledAmount"),filled:this.safeNumber(e,"filledShares"),fee:void 0,trades:[]},t)}async fetchOrders(e,t,i,s={}){let r;await this.loadApiKey();let a={};if(void 0!==e){r=await this.loadOutcome(e);let t=this.safeDict(r,"info",{});a.marketId=this.safeInteger(t,"marketId")}let o=await this.opinionPrivateGetOrder(this.extend(a,s)),n=this.safeDict(o,"result",{}),d=this.safeList(n,"list",[]);return this.parsePredictionOrders(d,r,t,i)}async fetchOrder(e,t,i={}){let s;await this.loadApiKey(),void 0!==t&&(s=await this.loadOutcome(t));let r=await this.opinionPrivateGetOrderOrderId(this.extend({orderId:e},i)),a=this.safeDict(r,"result",{}),o=this.safeDict(a,"orderData",{});return this.parsePredictionOrder(o,s)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({status:"1"},s))}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrders(e,t,i,this.extend({status:"2,3,4,5"},s))}async fetchMyTrades(e,t,i,s={}){let r;if(void 0===this.walletAddress)throw new h.ArgumentsRequired(this.id+" fetchMyTrades() requires a walletAddress");await this.loadApiKey();let a={walletAddress:this.walletAddress};if(void 0!==e){r=await this.loadOutcome(e);let t=this.safeDict(r,"info",{});a.marketId=this.safeInteger(t,"marketId")}let o=await this.opinionPrivateGetTradeUserWalletAddress(this.extend(a,s)),n=this.safeDict(o,"result",{}),d=this.safeList(n,"list",[]),c=d.length;for(let e=0;e<c;e++){let t=d[e],i=this.safeString(t,"tokenId"),s=this.safeInteger(t,"marketId");if(void 0===i&&void 0!==s){let e=await this.loadTradeMarket(s),i=this.safeDict(e,"info",{}),r="yes"===this.safeStringLower(t,"outcomeSideEnum");t.tokenId=r?this.safeString(i,"yesTokenId"):this.safeString(i,"noTokenId")}}return this.parsePredictionTrades(d,r,t,i)}async loadTradeMarket(e){if(void 0===e)throw new h.ArgumentsRequired(this.id+" loadTradeMarket() requires a marketId");let t="tradeMarketsById",i=this.safeDict(this.options,t,{}),s=e.toString(),r=this.safeDict(i,s);if(void 0!==r)return r;let a=await this.opinionPublicGetMarketMarketId({marketId:e}),o=this.safeDict(a,"result",{}),n=this.safeDict(o,"data",{}),d=this.parseOpinionMarket(n);if(void 0===d)throw new h.ExchangeError(this.id+" loadTradeMarket() could not parse market "+s);void 0===this.markets&&(this.markets=this.createSafeDictionary());let c=this.safeString(d,"market","");return this.markets[c]=d,this.indexMarketOutcomes(d),i[s]=d,this.options[t]=i,d}parsePredictionTrade(e,t){let i=this.safeString(e,"tokenId"),s=this.safeOutcome(i,t),r=this.safeTimestamp(e,"createdAt"),a=this.safeStringLower(e,"side");return this.safePredictionTrade({id:this.safeString(e,"txHash"),timestamp:r,side:a,price:this.safeNumber(e,"price"),amount:this.safeNumber(e,"shares"),cost:this.safeNumber(e,"amount"),fee:{cost:this.safeNumber(e,"fee"),currency:"USDT"},outcome:this.safeString(s,"outcome"),outcomeId:this.safeString2(s,"outcomeId","id"),label:this.safeString(s,"label"),market:this.safeString2(s,"market","outcome")})}async fetchBalance(e={}){await this.loadApiKey();let t=await this.opinionPrivateGetUserBalance(this.extend({chain_id:"56"},e)),i=this.safeDict(t,"result",{}),s=this.safeList(i,"balances",[]),r=s.length;for(let e=0;e<r;e++){let t=s[e],i=this.safeString(t,"quoteToken"),r=await this.loadQuoteToken(i);t.symbol=this.safeString(r,"symbol","USDT")}return this.parseBalance(t)}parseBalance(e){let t={info:e},i=this.safeDict(e,"result",{}),s=this.safeList(i,"balances",[]),r=s.length;for(let e=0;e<r;e++){let i=this.safeDict(s,e);t[this.safeString(i,"symbol","USDT")]={free:this.safeNumber(i,"availableBalance"),used:this.safeNumber(i,"frozenBalance"),total:this.safeNumber(i,"totalBalance")}}return this.safeBalance(t)}async fetchPositions(e,t={}){if(void 0===this.walletAddress)throw new h.ArgumentsRequired(this.id+" fetchPositions() requires a walletAddress");await this.loadApiKey();let i=0;void 0!==e&&(i=e.length,await this.loadOutcomes(e));let s={walletAddress:this.walletAddress},r=await this.opinionPrivateGetPositionsUserWalletAddress(this.extend(s,t)),a=this.safeDict(r,"result",{}),o=this.safeList(a,"list",[]),n=this.parsePredictionPositions(o);if(0===i)return n;let d={},c=void 0===e?[]:e;for(let e=0;e<c.length;e++){let t=this.outcome(c[e]),i=this.safeString(t,"outcomeId");void 0!==i&&(d[i]=!0)}let l=[];for(let e=0;e<n.length;e++){let t=n[e],i=this.safeDict(t,"info",{}),s=this.safeString(i,"tokenId");void 0!==s&&s in d&&l.push(t)}return l}parsePredictionPosition(e,t){let i=this.safeString(e,"tokenId"),s=this.safeOutcome(i,t),r=this.safeStringLower(e,"outcomeSideEnum");return this.safePredictionPosition({contracts:this.safeNumber(e,"sharesOwned"),side:r,unrealizedPnl:this.safeNumber(e,"unrealizedPnl"),entryPrice:this.safeNumber(e,"avgEntryPrice"),outcome:this.safeString(s,"outcome"),outcomeId:this.safeString2(s,"outcomeId","id"),label:this.safeString(s,"label"),market:this.safeString2(s,"market","outcome"),info:e})}hashMessage(e){return"0x"+this.hash(e,s.lY,"hex")}signHash(e,t){let i=(0,o.h1)(e.slice(-64),t.slice(-64),r.bI,void 0),s=i.r,a=i.s;return{r:"0x"+s.padStart(64,"0"),s:"0x"+a.padStart(64,"0"),v:this.sum(27,i.v)}}signMessage(e,t){return this.signHash(this.hashMessage(e),t.slice(-64))}signApiKeyAuth(e,t,i){let s=this.ethEncodeStructuredData({name:"Opinion OpenAPI",version:"1",chainId:56},{OpinionApiKeyAuth:[{name:"walletAddress",type:"address"},{name:"action",type:"string"},{name:"timestamp",type:"string"}]},{walletAddress:e,action:t,timestamp:i}),r=this.signMessage(s,this.privateKey);return"0x"+this.remove0xPrefix(r.r)+this.remove0xPrefix(r.s)+this.intToBase16(r.v)}async createApiKey(e={}){let t=await this.opinionPrivatePostAuthApiKey(e),i=this.safeDict(t,"result",{});return this.setApiCredentials(i)}async fetchApiKey(e={}){let t=await this.opinionPrivateGetAuthApiKey(e),i=this.safeDict(t,"result",{});return this.setApiCredentials(i)}async deleteApiKey(e={}){let t=await this.opinionPrivateDeleteAuthApiKey(e);return this.options.apiKey=void 0,this.apiKey="",t}async loadApiKey(){let e;if(!this.isEmptyString(this.apiKey))return this.apiKey;let t=this.safeString(this.options,"apiKey");if(void 0!==t)return t;if(void 0===this.walletAddress||void 0===this.privateKey)throw new h.AuthenticationError(this.id+" private endpoints require an apiKey, or a walletAddress and privateKey to self-issue one");try{e=await this.fetchApiKey()}catch(t){e=await this.createApiKey()}return this.safeString(e,"apiKey")}setApiCredentials(e){let t={apiKey:this.safeString(e,"apiKey"),walletAddress:this.safeString(e,"walletAddress")};return this.options.apiKey=t.apiKey,this.apiKey=t.apiKey,t}opinionWsUrl(){let e=this.isEmptyString(this.apiKey)?this.safeString(this.options,"apiKey"):this.apiKey;if(void 0===e)throw new h.AuthenticationError(this.id+" websocket requires an apiKey - set it directly or call createApiKey()/fetchApiKey() first");return this.safeString(this.urls.api,"ws","")+"?apikey="+e}ping(e){return{action:"HEARTBEAT"}}async subscribeOpinionChannel(e,t,i){await this.loadApiKey();let s=this.opinionWsUrl(),r=t+":"+this.numberToString(i);return await this.watch(s,e,{action:"SUBSCRIBE",channel:t,marketId:i},r)}handleMessage(e,t){let i=this.safeString(t,"msgType");void 0!==i&&("market.depth.diff"===i?this.handleOrderBook(e,t):"market.last.price"===i?this.handleTicker(e,t):"market.last.trade"===i?this.handleTrades(e,t):"trade.order.update"===i?this.handleOrder(e,t):"trade.record.new"===i&&this.handleMyTrade(e,t))}opinionOutcomeByMarketIdSide(e,t){if(void 0===e||void 0===this.markets)return;let i=Object.keys(this.markets),s=i.length;for(let r=0;r<s;r++){let s=this.safeDict(this.markets,i[r]),a=this.safeDict(s,"info",{});if(this.safeInteger(a,"marketId")===e){let e=this.safeList(s,"outcomes",[]),i=+(2===t);return this.safeDict(e,i)}}}async watchOrderBook(e,t,i={}){let s=await this.loadOutcome(e),r=this.safeDict(s,"info",{}),a=this.safeInteger(r,"marketId"),o=this.safeOutcomeSymbol(e,s),n="market.depth.diff",d="orderbook::"+o;await this.loadApiKey();let h=this.opinionWsUrl(),c=this.client(h),l=n+":"+this.numberToString(a),u=void 0===this.safeValue(c.subscriptions,l);u&&await this.seedOrderBook(e,o,t);let f=this.watch(h,d,{action:"SUBSCRIBE",channel:n,marketId:a},l);return u&&c.resolve(this.safeValue(this.orderbooks,o),d),(await f).limit()}async seedOrderBook(e,t,i){let s=await this.fetchOrderBook(e,i),r=this.orderBook({});r.reset(s),this.orderbooks[t]=r}handleOrderBook(e,t){let i=this.safeString(t,"tokenId"),s=this.safeDict(this.outcomes_by_id,i),r=this.safeString(s,"outcome");if(void 0===r||void 0===this.safeValue(this.orderbooks,r))return;let a=this.orderbooks[r],o="bids"===this.safeString(t,"side")?a.bids:a.asks,n=this.safeNumber(t,"price"),d=this.safeNumber(t,"size");o.storeArray([n,d]),a.timestamp=void 0,a.datetime=void 0,e.resolve(a,"orderbook::"+r)}async watchTicker(e,t={}){let i=await this.loadOutcome(e),s=this.safeDict(i,"info",{}),r=this.safeInteger(s,"marketId"),a=this.safeOutcomeSymbol(e,i);return await this.subscribeOpinionChannel("ticker::"+a,"market.last.price",r)}handleTicker(e,t){let i=this.safeString(t,"tokenId"),s=this.safeDict(this.outcomes_by_id,i),r=this.safeString(s,"outcome");if(void 0===r)return;let a=this.safeNumber(t,"price"),o=this.safePredictionTicker({outcome:r,outcomeId:i,label:this.safeString(s,"label"),market:this.safeString(s,"market"),timestamp:void 0,datetime:void 0,close:a,last:a,info:t},s);this.tickers[r]=o,e.resolve(o,"ticker::"+r)}async watchTrades(e,t,i,s={}){let r=await this.loadOutcome(e),a=this.safeDict(r,"info",{}),o=this.safeInteger(a,"marketId"),n=this.safeOutcomeSymbol(e,r),d=await this.subscribeOpinionChannel("trades::"+n,"market.last.trade",o);return this.filterBySinceLimit(d,t,i,"timestamp",!0)}handleTrades(e,t){let i=this.safeString(t,"tokenId"),s=this.safeDict(this.outcomes_by_id,i),r=this.safeString(s,"outcome");if(void 0===r)return;let a=this.safePredictionTrade({id:void 0,info:t,timestamp:void 0,datetime:void 0,outcome:r,outcomeId:i,label:this.safeString(s,"label"),market:this.safeString(s,"market"),order:void 0,type:void 0,side:this.safeStringLower(t,"side"),takerOrMaker:"taker",price:this.safeNumber(t,"price"),amount:this.safeNumber(t,"shares"),cost:this.safeNumber(t,"amount"),fee:void 0},s);if(void 0===this.trades&&(this.trades=this.createSafeDictionary()),void 0===this.safeValue(this.trades,r)){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.trades[r]=new d.I3(e)}let o=this.trades[r];o.append(a),e.resolve(o,"trades::"+r)}async watchOrders(e,t,i,s={}){if(void 0===e)throw new h.ArgumentsRequired(this.id+" watchOrders() requires an outcome (the order update channel is per-market)");let r=await this.loadOutcome(e),a=this.safeDict(r,"info",{}),o=this.safeInteger(a,"marketId"),n=await this.subscribeOpinionChannel("orders","trade.order.update",o),d=this.safeOutcomeSymbol(e,r);return this.filterByValueSinceLimit(n,"outcome",d,t,i,"timestamp",!0)}parseWsOrderStatus(e){return 1===e?"open":2===e?"closed":3===e?"canceled":4===e?"expired":5===e?"rejected":void 0}handleOrder(e,t){let i=this.safeInteger(t,"marketId"),s=this.safeInteger(t,"outcomeSide"),r=this.opinionOutcomeByMarketIdSide(i,s),a=this.safeTimestamp(t,"createdAt"),o=this.safeInteger(t,"side"),n="sell";1===o&&(n="buy");let h=this.safeInteger(t,"tradingMethod"),c="limit";1===h&&(c="market");let l=this.safePredictionOrder({id:this.safeString(t,"orderId"),clientOrderId:void 0,info:t,timestamp:a,datetime:this.iso8601(a),lastTradeTimestamp:void 0,status:this.parseWsOrderStatus(this.safeInteger(t,"status")),outcome:this.safeString(r,"outcome"),outcomeId:this.safeString(r,"outcomeId"),label:this.safeString(r,"label"),market:this.safeString(r,"market"),type:c,side:n,price:this.safeNumber(t,"price"),amount:this.safeNumber(t,"shares"),cost:this.safeNumber(t,"filledAmount"),filled:this.safeNumber(t,"filledShares"),fee:void 0,trades:[]},r);if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new d.$0(e)}let u=this.orders;u.append(l),e.resolve(u,"orders")}async watchMyTrades(e,t,i,s={}){if(void 0===e)throw new h.ArgumentsRequired(this.id+" watchMyTrades() requires an outcome (the trade record channel is per-market)");let r=await this.loadOutcome(e),a=this.safeDict(r,"info",{}),o=this.safeInteger(a,"marketId"),n=await this.subscribeOpinionChannel("myTrades","trade.record.new",o),d=this.safeOutcomeSymbol(e,r);return this.filterByValueSinceLimit(n,"outcome",d,t,i,"timestamp",!0)}handleMyTrade(e,t){let i=this.safeInteger(t,"marketId"),s=this.safeInteger(t,"outcomeSide"),r=this.opinionOutcomeByMarketIdSide(i,s),a=this.safeString(r,"outcome"),o=this.safeTimestamp(t,"createdAt"),n=this.safePredictionTrade({id:this.safeString(t,"tradeNo"),info:t,timestamp:o,datetime:this.iso8601(o),outcome:a,outcomeId:this.safeString(r,"outcomeId"),label:this.safeString(r,"label"),market:this.safeString(r,"market"),order:this.safeString(t,"orderId"),type:void 0,side:this.safeStringLower(t,"side"),takerOrMaker:void 0,price:this.safeNumber(t,"price"),amount:this.safeNumber(t,"shares"),cost:this.safeNumber(t,"amount"),fee:{cost:this.safeNumber(t,"fee"),currency:"USDT"}},r);if(void 0===this.myTrades){let e=this.safeInteger(this.options,"myTradesLimit",1e3);this.myTrades=new d.$0(e)}let h=this.myTrades;h.append(n),e.resolve(h,"myTrades")}handleErrors(e,t,i,s,r,a,o,n,d){if(void 0===o)return;let c=this.safeInteger(o,"errno");if(void 0!==c&&0!==c){let e=this.safeString(o,"errmsg",""),t=this.id+" "+a;throw this.throwExactlyMatchedException(this.exceptions.exact,this.numberToString(c),t),this.throwBroadlyMatchedException(this.exceptions.broad,e,t),new h.ExchangeError(t)}}sign(e,t="opinion",i="GET",s={},r,a){let o="string"==typeof t?t:t[0],n="string"==typeof t?"public":t[1],d=this.urls.api,c=this.safeString(d,o,d.opinion)+"/"+this.implodeParams(e,s),l=this.omit(s,this.extractParams(e)),u=this.extend({Accept:"application/json","Content-Type":"application/json"},void 0!==r?r:{});if("private"===n)if("auth/api-key"===e){if(void 0===this.walletAddress||void 0===this.privateKey)throw new h.ArgumentsRequired(this.id+" "+e+" requires a walletAddress and privateKey");let t=this.safeString({POST:"create",GET:"get",DELETE:"delete"},i,"get"),s=this.numberToString(this.seconds());u.OPINION_ADDRESS=this.walletAddress,u.OPINION_SIGNATURE=this.signApiKeyAuth(this.walletAddress,t,s),u.OPINION_TIMESTAMP=s}else{let t=this.isEmptyString(this.apiKey)?this.safeString(this.options,"apiKey"):this.apiKey;if(void 0===t)throw new h.AuthenticationError(this.id+" "+e+" requires an apiKey - set it directly or call createApiKey()/fetchApiKey() first");u.apikey=t}let f=a;return"GET"===i?Object.keys(l).length>0&&(c+="?"+this.urlencode(l)):f=this.json(l),{url:c,method:i,body:f,headers:u}}}i.d(t,{A:()=>c})},7348(e,t,i){"use strict";var s=i(4721),r=i(6834),a=i(6885),o=i(9715),n=i(1093),d=i(7749),h=i(1697),c=i(1453);class l extends o.A{describe(){return this.deepExtend(super.describe(),{id:"polymarket",name:"Polymarket",countries:["US"],rateLimit:100,certified:!1,pro:!0,streaming:{ping:this.ping,keepAlive:1e4},has:{CORS:void 0,spot:!1,margin:!1,swap:!1,future:!1,option:!1,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,createMarketBuyOrderWithCost:!0,createOrder:!0,createOrders:!0,fetchBalance:!0,fetchCurrencies:!1,fetchDeposits:!1,fetchEvent:!0,fetchEvents:!0,fetchLedger:!1,fetchMarkets:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterest:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrderTrades:!0,fetchPosition:!0,fetchPositions:!0,fetchStatus:!0,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!0,fetchWithdrawals:!1,prediction:!0,watchMyTrades:!0,watchOrderBook:!0,watchOrders:!0,watchTicker:!0,watchTrades:!0},timeframes:{"1m":"1","5m":"5","1h":"60","6h":"360","1d":"1440"},urls:{logo:"https://github.com/user-attachments/assets/89e1a2c4-a682-44e7-ad50-9fb15b534437",api:{gamma:"https://gamma-api.polymarket.com",clob:"https://clob.polymarket.com",data:"https://data-api.polymarket.com",ws:"wss://ws-subscriptions-clob.polymarket.com/ws/market",wsUser:"wss://ws-subscriptions-clob.polymarket.com/ws/user"},www:"https://polymarket.com",doc:["https://docs.polymarket.com"],fees:"https://docs.polymarket.com/#fees"},api:{gamma:{public:{get:{status:{cost:1},comments:{cost:1},"comments/{id}":{cost:1},"comments/user_address/{user_address}":{cost:1},events:{cost:1},"events/creators":{cost:1},"events/creators/{id}":{cost:1},"events/keyset":{cost:1},"events/pagination":{cost:1},"events/results":{cost:1},"events/slug/{slug}":{cost:1},"events/{id}":{cost:1},"events/{id}/comments/count":{cost:1},"events/{id}/tags":{cost:1},"events/{id}/tweet-count":{cost:1},markets:{cost:1},"markets/keyset":{cost:1},"markets/slug/{slug}":{cost:1},"markets/{id}":{cost:1},"markets/{id}/description":{cost:1},"markets/{id}/tags":{cost:1},"profiles/user_address/{user_address}":{cost:1},"public-profile":{cost:1},"public-search":{cost:1},series:{cost:1},"series-summary/slug/{slug}":{cost:1},"series-summary/{id}":{cost:1},"series/{id}":{cost:1},"series/{id}/comments/count":{cost:1},sports:{cost:1},"sports/market-types":{cost:1},tags:{cost:1},"tags/slug/{slug}":{cost:1},"tags/slug/{slug}/related-tags":{cost:1},"tags/slug/{slug}/related-tags/tags":{cost:1},"tags/{id}":{cost:1},"tags/{id}/related-tags":{cost:1},"tags/{id}/related-tags/tags":{cost:1},teams:{cost:1},"teams/{id}":{cost:1}},post:{"markets/abridged":{cost:1},"markets/information":{cost:1}}}},clob:{public:{get:{book:{cost:1},books:{cost:1},"builder/trades":{cost:1},"clob-markets/{condition_id}":{cost:1},"fee-rate":{cost:1},"fee-rate/{token_id}":{cost:1},"last-trade-price":{cost:1},"last-trades-prices":{cost:1},"markets-by-token/{token_id}":{cost:1},"markets/live-activity/{condition_id}":{cost:1},midpoint:{cost:1},midpoints:{cost:1},"neg-risk":{cost:1},"neg-risk/{token_id}":{cost:1},price:{cost:1},prices:{cost:1},"prices-history":{cost:1},"rebates/current":{cost:1},"rewards/markets/current":{cost:1},"rewards/markets/multi":{cost:1},"rewards/markets/{condition_id}":{cost:1},"sampling-markets":{cost:1},"sampling-simplified-markets":{cost:1},"simplified-markets":{cost:1},spread:{cost:1},"tick-size":{cost:1},"tick-size/{token_id}":{cost:1},time:{cost:1}},post:{"batch-prices-history":{cost:1},books:{cost:1},"last-trades-prices":{cost:1},"markets/live-activity":{cost:1},midpoints:{cost:1},prices:{cost:1},spreads:{cost:1}}},private:{get:{"auth/api-keys":{cost:1},"auth/ban-status/closed-only":{cost:1},"auth/builder-api-key":{cost:1},"auth/derive-api-key":{cost:1},"balance-allowance":{cost:1},"balance-allowance/update":{cost:1},"data/order/{id}":{cost:1},"data/orders":{cost:1},"data/trades":{cost:1},notifications:{cost:1},"order-scoring":{cost:1},"orders-scoring":{cost:1},"rewards/user":{cost:1},"rewards/user/markets":{cost:1},"rewards/user/percentages":{cost:1},"rewards/user/total":{cost:1}},post:{"auth/api-key":{cost:1},"auth/builder-api-key":{cost:1},heartbeats:{cost:1},order:{cost:1},orders:{cost:1},"v1/heartbeats":{cost:1}},delete:{"auth/api-key":{cost:1},"auth/builder-api-key":{cost:1},"cancel-all":{cost:1},"cancel-market-orders":{cost:1},notifications:{cost:1},order:{cost:1},orders:{cost:1}}}},data:{public:{get:{activity:{cost:1},"closed-positions":{cost:1},holders:{cost:1},"live-volume":{cost:1},oi:{cost:1},other:{cost:1},positions:{cost:1},revisions:{cost:1},traded:{cost:1},trades:{cost:1},"v1/accounting/snapshot":{cost:1},"v1/activity/combos":{cost:1},"v1/builders/leaderboard":{cost:1},"v1/builders/volume":{cost:1},"v1/leaderboard":{cost:1},"v1/market-positions":{cost:1},"v1/positions/combos":{cost:1},value:{cost:1}}}},combos:{public:{get:{"v1/rfq/combo-markets":{cost:1}}},private:{post:{"v1/maker/confirmations":{cost:1},"v1/maker/quotes":{cost:1},"v1/maker/quotes/cancel":{cost:1}}}}},exceptions:{exact:{"not enough balance / allowance":c.InsufficientFunds,"invalid signature":c.AuthenticationError,"api key not found":c.AuthenticationError},broad:{"No orderbook exists":c.BadSymbol,"invalid clob token ids":c.BadSymbol,"not enough balance":c.InsufficientFunds,allowance:c.InsufficientFunds,"invalid amount":c.InvalidOrder,"invalid price":c.InvalidOrder,"minimum tick size":c.InvalidOrder,"no orders found to match":c.OrderNotFillable,"could not be fully filled":c.OrderNotFillable,geoblocked:c.PermissionDenied,"restricted jurisdiction":c.PermissionDenied,Unauthorized:c.AuthenticationError}},requiredCredentials:{apiKey:!1,secret:!1,password:!1,privateKey:!1,walletAddress:!1},fees:{trading:{tierBased:!1,percentage:!0,maker:0,taker:0}},options:{defaultFetchEventsLimit:100,eventsPageSize:100,fetchMarketsLimit:200,maxFetchEventsLimit:500,defaultEventStatus:"active",maxPricesHistoryWindow:1296e3,chainId:137,ctfExchangeName:"Polymarket CTF Exchange",ctfExchangeVersion:"2",exchangeAddress:"0xE111180000d2663C0091e4f400237545B87B996B",negRiskExchangeAddress:"0xe2222d279d744050d28e00520010520000310F59",builder:"0xea409de8b037bb6ac664b6d12d6831b03cb04a37",builderFee:!0,feeRate:0}})}async fetchMarkets(e={}){let t=this.parseSearchQueries(e),i=this.omit(e,["query","queries"]),s=t.length,r=[];r=s>0?await this.fetchRawEventsBySearch(t,i):await this.fetchRawEventsList(i);let a=[],o={};for(let e=0;e<r.length;e++){let t=r[e],i=this.parseEventToMarkets(t);for(let e=0;e<i.length;e++)a.push(i[e]);let s=this.parseEvent(t),n=this.safeString(t,"slug");void 0!==n&&""!==n&&(o[this.shortenSlug(n)]=s)}return this.events=o,a}async fetchRawEventsBySearch(e,t={}){let i=this.safeInteger(t,"limit"),s=this.safeInteger(this.options,"searchPageSize",100),r=this.safeInteger(t,"searchPageSize",s),a=this.safeString(t,"sort"),o="volume";"liquidity"===a?o="liquidity":"newest"===a&&(o="startDate");let n=this.safeString(t,"status","active"),d="active";"closed"===n||"inactive"===n?d="closed":"all"===n&&(d=void 0);let h=this.omit(t,["limit","sort","status","searchIn","eventId","slug","query","queries","searchPageSize","maxSearchPages"]),c={},l=[];for(let s=0;s<e.length;s++){let a={q:e[s],limit_per_type:r,sort:o,ascending:!1};void 0!==d&&(a.events_status=d);let n={page:1};n=this.extend(this.extend(n,a),h);let u=await this.gammaPublicGetPublicSearch(n),f=this.safeList(u,"events",[]),p=f.length,m=this.safeDict(u,"pagination",{}),g=Math.ceil(this.safeInteger(m,"totalResults",p)/r);if(void 0!==i){let e=Math.ceil(i/r);e<g&&(g=e)}else{let e=this.safeInteger(this.options,"maxSearchPages",5),i=this.safeInteger(t,"maxSearchPages",e);i<g&&(g=i)}let v=[];for(let e=2;e<=g;e++)v.push(e);let y=[];for(let e=0;e<v.length;e++){let t={page:v[e]};t=this.extend(this.extend(t,a),h),y.push(this.gammaPublicGetPublicSearch(t))}let b=await Promise.all(y),w=[];for(let e=0;e<f.length;e++)w.push(f[e]);for(let e=0;e<b.length;e++){let t=this.safeList(b[e],"events",[]);for(let e=0;e<t.length;e++)w.push(t[e])}for(let e=0;e<w.length;e++){let t=w[e],i=this.safeString(t,"id");void 0===i||""===i||i in c||(c[i]=!0,l.push(t))}}return l}tagToSlug(e){let t=e.toLowerCase(),i=this.stringToCharsArray(t),s="",r=!1;for(let e=0;e<i.length;e++){let t=i[e];"abcdefghijklmnopqrstuvwxyz0123456789".indexOf(t)>=0?(r&&""!==s&&(s+="-"),s+=t,r=!1):r=!0}return""===s?t:s}async fetchRawEventsList(e={}){let t=this.safeInteger(this.options,"eventsPageSize",100),i=this.safeInteger(e,"limit",this.safeInteger(this.options,"fetchMarketsLimit",200)),s=Math.ceil(i/t),r=this.safeString(e,"status",this.safeString(this.options,"defaultEventStatus","active")),a=this.safeString(e,"sort"),o="volume";"liquidity"===a?o="liquidity":"newest"===a&&(o="startDate");let n=this.omit(e,["status","limit","sort","searchIn","eventId","slug","query","queries","tags"]),d={limit:t,order:o,ascending:!1};d=this.extend(d,n);let h=this.safeList(e,"tags",[]),c=h.length;if(c>1){let t={},i=[];for(let s=0;s<c;s++){let r=this.extend({},e);r.tags=[h[s]];let a=await this.fetchRawEventsList(r);for(let e=0;e<a.length;e++){let s=a[e],r=this.safeString(s,"id");void 0===r||r in t||(t[r]=!0,i.push(s))}}return i}c>0&&(d.tag_slug=this.tagToSlug(this.safeString(h,0))),"active"===r?(d.active=!0,d.closed=!1):("closed"===r||"inactive"===r)&&(d.active=!1,d.closed=!0);let l={offset:0};l=this.extend(l,d);let u=await this.gammaPublicGetEvents(l),f=Array.isArray(u)?u:[],p=f.length,m=[];for(let e=0;e<p;e++)m.push(f[e]);if(p>=t){let e=[];for(let i=1;i<s;i++)e.push(i*t);let i=[];for(let t=0;t<e.length;t++){let s={offset:e[t]};s=this.extend(s,d),i.push(this.gammaPublicGetEvents(s))}let r=await Promise.all(i);for(let e=0;e<r.length;e++){let t=void 0!==r[e]?r[e]:[],i=t.length;for(let e=0;e<i;e++)m.push(t[e])}}return m.length>i?this.arraySlice(m,0,i):m}parseEventToMarkets(e){let t=this.safeString(e,"slug",this.safeString(e,"id")),i=this.safeList(e,"markets",[]),s=[];for(let e=0;e<i.length;e++){let r,a,o,n,h=i[e],c=this.safeString(h,"conditionId"),l=this.safeString(h,"id"),u=this.safeString(h,"slug",c),f=this.safeBool(h,"active",!1),p=this.safeBool(h,"closed",!1),m=!0===p||"resolved"===this.safeStringLower(h,"umaResolutionStatus"),g=this.safeNumber2(h,"orderPriceMinTickSize","minimumTickSize",.01),v=this.safeNumber(h,"orderMinSize",1),y=this.parseNumber(d.Y.stringSub("1",this.numberToString(g))),b=this.safeBool(h,"negRisk",!1),w=this.safeString(h,"endDate",this.safeString(h,"end_date_iso")),k=[],S=[],O=[],T=this.parseJson(this.safeString(h,"outcomes","[]")),P=this.parseJson(this.safeString(h,"clobTokenIds","[]")),I=this.parseJson(this.safeString(h,"outcomePrices","[]"));void 0!==T&&(a=T.length),void 0!==P&&(o=P.length),void 0!==I&&(n=I.length),void 0!==T&&void 0!==a&&(k=T),void 0!==P&&void 0!==o&&(S=P),void 0!==I&&void 0!==n&&(O=I);let A=k.length,x=S.length;if(0===A||0===x)continue;let M=this.slugToMarketSymbol(t,u),_=[];for(let e=0;e<k.length;e++){let i,s,a=k[e],o=S[e],n=this.safeNumber(O,e);if(void 0===o||""===o)continue;let d=this.slugToOutcomeSymbol(t,u,a);m&&void 0!==n&&(n>=.99?(i=!0,s=1,r=d):n<=.01&&(i=!1,s=0));let c=i,l=s;_.push({outcome:d,outcomeId:o,market:M,label:a,price:n,active:!0===f&&!0!==p,winner:c,settleFraction:l,precision:{amount:g,price:g},negRisk:b,info:h})}let C=void 0!==c?c:l,B=A>2?"categorical":"binary",E=r;s.push({id:c,market:M,marketType:B,executionModel:"clob",collateral:"USDC",base:"USDC",quote:"USDC",settle:void 0,baseId:C,quoteId:"USDC",settleId:void 0,type:"prediction",spot:!1,margin:!1,swap:!1,future:!1,option:!1,prediction:!0,active:!0===f&&!0!==p,resolved:m,resolvedOutcome:E,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:void 0!==w&&""!==w?this.parse8601(w):void 0,expiryDatetime:w,strike:void 0,optionType:void 0,taker:0,maker:0,percentage:!0,tierBased:!1,feeSide:"get",precision:{amount:g,price:g},limits:{leverage:{min:1,max:1},amount:{min:v,max:void 0},price:{min:g,max:y},cost:{min:void 0,max:void 0}},outcomes:_,info:h,created:void 0})}return s}async fetchOutcome(e){if(0>e.indexOf(":")&&void 0===this.outcomeSearchQuery(e)){let t=await this.gammaPublicGetMarkets({clob_token_ids:e}),i=void 0!==t?t:[];if(i.length>0){void 0===this.markets&&(this.markets=this.createSafeDictionary());let t=this.parseEventToMarkets({markets:i}),s=t.length;for(let e=0;e<s;e++){let i=t[e];if(void 0===i)throw new c.ExchangeError(this.id+" fetchOutcome() could not resolve mkt");this.markets[i.market]=i}this.populateOutcomes();let r=this.safeValue(this.outcomes_by_id,e);if(void 0!==r)return r}}return await super.fetchOutcome(e)}async fetchOutcomes(e){let t=[];for(let i=0;i<e.length;i++){let s=e[i];0>s.indexOf(":")&&void 0===this.outcomeSearchQuery(s)&&t.push(s)}let i=t.length;if(i>0){void 0===this.markets&&(this.markets=this.createSafeDictionary());let e=this.safeInteger(this.options,"fetchOutcomesBatchSize",50),s=0;for(;s<i;){let r=this.sum(s,e);r>i&&(r=i);let a=[];for(let e=s;e<r;e++)a.push(t[e]);let o=await this.gammaPublicGetMarkets({clob_token_ids:a,limit:e}),n=void 0!==o?o:[],d=this.parseEventToMarkets({markets:n});for(let e=0;e<d.length;e++){let t=d[e];if(void 0===t)throw new c.ExchangeError(this.id+" fetchOutcomes() could not resolve mkt");this.markets[t.market]=t}s=this.sum(s,e)}this.populateOutcomes()}for(let t=0;t<e.length;t++)this.hasOutcome(e[t])||await this.fetchOutcome(e[t]);return this.outcomes}async fetchTicker(e,t={}){let i=await this.loadOutcome(e),s=i.outcomeId,r=[this.clobPublicGetMidpoint({token_id:s}),this.clobPublicGetBook({token_id:s}),this.clobPublicGetLastTradePrice({token_id:s})],[a,o,n]=await Promise.all(r);return this.parsePredictionTicker({midpoint:a,book:o,lastTrade:n},i)}async fetchTickers(e,t={}){if(void 0===e)throw new c.ArgumentsRequired(this.id+" fetchTickers() requires an outcomes argument — the venue has no all-tickers endpoint; pass the outcome handles or token ids to fetch (discover them via fetchEvents ())");await this.loadOutcomes(e);let i=[];for(let t=0;t<e.length;t++)i.push(e[t]);let s={},r=[];for(let e=0;e<i.length;e++){let t=this.outcome(i[e]),a=this.safeString(t,"outcomeId");void 0===a||a in s||(s[a]=t,r.push(a))}let a=this.safeInteger(this.options,"fetchTickersBatchSize",200),o={},n=r.length,d=0;for(;d<n;){let e=this.sum(d,a);e>n&&(e=n);let t=[];for(let i=d;i<e;i++)t.push({token_id:r[i]});let i=[this.clobPublicPostBooks(t),this.clobPublicPostMidpoints(t),this.clobPublicPostLastTradesPrices(t)],h=await Promise.all(i),c=h[0],l=h[1],u=h[2],f=Array.isArray(c)?c:[],p=Array.isArray(u)?u:[],m={},g=p.length;for(let e=0;e<g;e++){let t=p[e],i=this.safeString(t,"token_id");void 0!==i&&(m[i]=t)}let v=f.length;for(let e=0;e<v;e++){let t=f[e],i=this.safeString(t,"asset_id");if(void 0===i||!(i in s))continue;let r=s[i],a={midpoint:{mid:this.safeString(l,i)},book:t,lastTrade:this.safeDict(m,i,{})},n=this.parsePredictionTicker(a,r);o[this.safeString(n,"outcome",i)]=n}d=this.sum(d,a)}return o}parsePredictionTicker(e,t){let i,s=this.safeDict(e,"midpoint",{}),r=this.safeDict(e,"book",{}),a=this.safeNumber(s,"mid"),o=this.safeList(r,"bids",[]),n=this.safeList(r,"asks",[]),d=o.length,h=n.length,c=d>0?o[d-1]:void 0,l=h>0?n[h-1]:void 0,u=this.safeDict(e,"lastTrade",{}),f=this.safeNumber(u,"price");(void 0===f||0===f)&&(f=a);let p=this.safeOutcomeSymbol(void 0,t),m=this.safeInteger(r,"timestamp");return void 0!==t&&(i=this.safeNumber2(t.info,"volume24hr","volume")),this.safePredictionTicker({outcome:p,outcomeId:this.safeString(t,"outcomeId"),label:this.safeString(t,"label"),market:this.safeString(t,"market"),timestamp:m,datetime:this.iso8601(m),high:void 0,low:void 0,bid:this.safeNumber(c,"price"),bidVolume:this.safeNumber(c,"size"),ask:this.safeNumber(l,"price"),askVolume:this.safeNumber(l,"size"),vwap:void 0,open:void 0,close:f,last:f,previousClose:void 0,change:void 0,percentage:void 0,average:a,baseVolume:void 0,quoteVolume:i,info:e},t)}async fetchOrderBook(e,t,i={}){let s=await this.loadOutcome(e),r=s.outcomeId,a=await this.clobPublicGetBook(this.extend({token_id:r},i)),o=this.safeInteger(a,"timestamp"),n=this.parseOrderBook(a,this.safeOutcomeSymbol(e,s),o,"bids","asks","price","size");return this.safePredictionOrderBook(n,s)}async fetchOHLCV(e,t="1m",i,s,r={}){let a;if(!(t in this.timeframes)){let e=Object.keys(this.timeframes);throw new c.BadRequest(this.id+" fetchOHLCV() unsupported timeframe "+t+", supported timeframes are "+e.join(", "))}let o=(await this.loadOutcome(e)).outcomeId,n=this.safeInteger(this.timeframes,t,1),d=this.seconds(),h=d;if(void 0!==i){if(a=this.parseToInt(i/1e3),void 0!==s){let e=this.sum(a,s*n*60);h=e<d?e:d}}else a=d-(void 0!==s?s:100)*n*60;let l=this.safeInteger(this.options,"maxPricesHistoryWindow",1296e3);h-a>l&&(void 0!==i?h=this.sum(a,l):a=h-l);let u={market:o,fidelity:n,startTs:a,endTs:h},f=await this.clobPublicGetPricesHistory(this.extend(u,r)),p=this.safeList(f,"history",[]),m=60*n*1e3,g={};for(let e=0;e<p.length;e++){let t=this.safeDict(p,e),i=this.safeInteger(t,"t"),s=this.safeNumber(t,"p");if(void 0===i||void 0===s)continue;let r=Math.floor(1e3*i/m)*m,a=this.safeNumber(t,"s");void 0===a&&(a=this.safeNumber(t,"v"));let o=r.toString();if(o in g){let e=g[o];if(e[2]=Math.max(e[2],s),e[3]=Math.min(e[3],s),e[4]=s,void 0!==a){let t=e[5];e[5]=void 0===t?a:this.sum(t,a)}g[o]=e}else g[o]=[r,s,s,s,s,a]}let v=Object.keys(g),y=[];for(let e=0;e<v.length;e++)y.push(g[v[e]]);let b=this.sortBy(y,0),w=b.length;return void 0!==s&&w>s?this.arraySlice(b,-s):b}parseOHLCV(e,t){let i=this.safeNumber(e,"p");return[this.safeTimestamp(e,"t"),i,i,i,i,void 0]}async fetchTime(e={}){let t=await this.clobPublicGetTime(e);return this.safeTimestamp({serverTime:t},"serverTime")}async fetchStatus(e={}){let t=await this.gammaPublicGetStatus(e);return{status:"OK"===t||"ok"===t?"ok":"maintenance",updated:void 0,eta:void 0,url:void 0,info:t}}async fetchOpenInterest(e,t={}){let i=await this.loadOutcome(e),s=this.safeDict(i,"info",{}),r=this.safeString(s,"conditionId");if(void 0===r)throw new c.BadRequest(this.id+" fetchOpenInterest() requires outcome.info.conditionId for "+e);let a=await this.dataPublicGetOi(this.extend({market:r},t)),o=this.safeDict(a,0,{});return this.parsePredictionOpenInterest(o,i)}parsePredictionOpenInterest(e,t){let i=this.safeOpenInterest({symbol:this.safeOutcomeSymbol(void 0,t),openInterestAmount:void 0,openInterestValue:this.safeNumber(e,"value"),baseVolume:void 0,quoteVolume:void 0,timestamp:void 0,datetime:void 0,info:e},t);return i.outcome=this.safeOutcomeSymbol(void 0,t),i.outcomeId=this.safeString(t,"outcomeId"),i.market=this.safeString(t,"market"),delete i.symbol,i}async fetchTradingFee(e,t={}){let i=await this.loadOutcome(e),s=this.safeString(i,"outcomeId"),r=await this.clobPublicGetFeeRate(this.extend({token_id:s},t)),a=this.safeString(r,"base_fee"),o=void 0!==a?this.parseNumber(d.Y.stringDiv(a,"10000")):void 0;return{info:r,outcome:this.safeOutcomeSymbol(void 0,i),outcomeId:this.safeString(i,"outcomeId"),market:this.safeString(i,"market"),maker:o,taker:o,percentage:!0,tierBased:!1}}async fetchTrades(e,t,i,s={}){let r=await this.loadOutcome(e),a=r.outcomeId,o=this.safeDict(r,"info",{}),n=this.safeString(o,"conditionId");if(void 0===n)throw new c.BadRequest(this.id+" fetchTrades() requires outcome.info.conditionId for an outcome "+a);let d={market:n};d.limit=this.safeInteger(this.options,"tradesPageSize",500);let h=await this.dataPublicGetTrades(this.extend(d,s)),l=Array.isArray(h)?h:this.safeList(h,"data",[]),u=[];for(let e=0;e<l.length;e++){let t=l[e];this.safeString(t,"asset")===a&&u.push(t)}return this.parsePredictionTrades(u,void 0,t,i)}async fetchMyTrades(e,t,i,s={}){let r;await this.loadApiCredentials();let a={};void 0!==e&&(a.asset_id=(r=await this.loadOutcome(e)).outcomeId);let o=await this.clobPrivateGetDataTrades(this.extend(a,s)),n=Array.isArray(o)?o:this.safeList(o,"data",[]);return this.parsePredictionTrades(n,r,t,i)}async fetchOrderTrades(e,t,i,s,r={}){let a=await this.fetchMyTrades(t,void 0,void 0,r),o=[];for(let t=0;t<a.length;t++){let i=a[t],s=this.safeDict(i,"info",{}),r=this.safeString(i,"order")===e||this.safeString(s,"taker_order_id")===e,n=this.safeList(s,"maker_orders",[]);for(let t=0;t<n.length;t++)this.safeString(n[t],"order_id")===e&&(r=!0);r&&o.push(i)}return this.filterBySinceLimit(o,i,s)}parsePredictionTrade(e,t){let i,s,r,a,o=this.safeStringN(e,["transactionHash","transaction_hash","id"]),n=this.safeIntegerProduct(e,"timestamp",1e3);void 0===n&&(n=this.safeIntegerProduct(e,"match_time",1e3));let h=this.safeNumber(e,"price"),c=this.safeNumber(e,"size"),l=this.safeStringLower(e,"side");("buy"===l||"sell"===l)&&(i=l);let u=this.safeString2(e,"asset","asset_id");s=void 0!==t?t:this.safeOutcome(u);let f=this.safeOutcomeSymbol(void 0,s),p=this.safeStringLower(e,"trader_side");("taker"===p||"maker"===p)&&(r=p);let m=this.safeString(e,"fee_rate_bps");return void 0!==m&&(a={currency:"USDC",rate:this.parseNumber(d.Y.stringDiv(m,"10000"))}),this.safePredictionTrade({id:o,info:e,timestamp:n,datetime:this.iso8601(n),outcome:f,outcomeId:u,label:this.safeString(s,"label"),market:this.safeString(s,"market"),order:this.safeString2(e,"orderId","taker_order_id"),type:void 0,side:i,takerOrMaker:r,price:h,amount:c,cost:void 0,fee:a},s)}async fetchBalance(e={}){await this.loadApiCredentials();let t=this.safeInteger2(e,"signatureType","signature_type",this.safeInteger(this.options,"signatureType",3)),i=this.omit(e,["signatureType","signature_type"]),s=await this.clobPrivateGetBalanceAllowance(this.extend({asset_type:"COLLATERAL",signature_type:t},i));return this.parseBalance(s)}parseBalance(e){let t,i={info:e},s=this.safeString(e,"balance");return void 0!==s&&(t=this.parseNumber(d.Y.stringDiv(s,"1000000"))),i.USDC={free:t,used:void 0,total:t},this.safeBalance(i)}async fetchPositions(e,t={}){let i=0;if(void 0!==e&&(i=e.length,await this.loadOutcomes(e)),void 0===this.walletAddress)throw new c.ArgumentsRequired(this.id+" walletAddress is required to fetchPositions");let s={user:this.walletAddress},r=await this.dataPublicGetPositions(this.extend(s,t)),a=this.safeList(r,"data",[]),o=this.parsePredictionPositions(a);if(0===i)return o;let n={};if(void 0===e)throw new c.ExchangeError(this.id+" fetchPositions() missing outcomes");for(let t=0;t<e.length;t++)n[this.outcome(e[t]).outcomeId]=!0;let d=[];for(let e=0;e<o.length;e++){let t=o[e],i=this.safeDict(t,"info",{}),s=this.safeString(i,"asset");void 0!==s&&s in n&&d.push(t)}return d}async fetchPosition(e,t={}){let i=await this.fetchPositions([e],t);return this.safeDict(i,0)}parsePredictionPosition(e,t){let i,s=this.safeString(e,"asset"),r=this.safeOutcome(s,t),a=this.safeNumber(e,"size"),o=this.safeNumber(e,"avgPrice"),n=this.safeNumber(e,"currentPrice");return void 0!==a&&void 0!==n&&(i=a*n),this.safePredictionPosition({id:this.safeString(e,"id"),outcome:this.safeString(r,"outcome"),outcomeId:this.safeString(r,"outcomeId"),market:this.safeString(r,"market"),label:this.safeString(r,"label"),event:this.safeString(r,"event"),timestamp:void 0,datetime:void 0,contracts:a,contractSize:1,side:"long",notional:i,leverage:1,unrealizedPnl:void 0,realizedPnl:this.safeNumber(e,"realizedPnl"),collateral:void 0,entryPrice:o,markPrice:n,liquidationPrice:void 0,hedged:!1,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,initialMargin:void 0,initialMarginPercentage:void 0,marginRatio:void 0,marginMode:"cross",marginType:"cross",percentage:void 0,info:e})}async fetchOpenOrders(e,t,i,s={}){let r;await this.loadApiCredentials();let a={};void 0!==e&&(a.asset_id=(r=await this.loadOutcome(e)).outcomeId);let o=await this.clobPrivateGetDataOrders(this.extend(a,s)),n=this.safeList(o,"data",[]);return this.parsePredictionOrders(n,r,t,i)}async fetchOrder(e,t,i={}){await this.loadApiCredentials();let s=await this.clobPrivateGetDataOrderId(this.extend({id:e},i));return this.parsePredictionOrder(s)}parsePredictionOrder(e,t){let i=this.safeString2(e,"id","orderID"),s=this.safeString(e,"asset_id"),r=this.safeOutcome(s,t),a=this.parseOrderStatus(this.safeString2(e,"status","type")),o=this.safeStringLower(e,"side"),n=this.safeNumber(e,"price"),d=this.safeNumber(e,"original_size"),h=this.safeNumber(e,"size_matched",0),c=this.safeIntegerProduct(e,"created_at",1e3);return this.safePredictionOrder({id:i,clientOrderId:void 0,info:e,timestamp:c,datetime:this.iso8601(c),lastTradeTimestamp:void 0,status:a,outcome:r.outcome,outcomeId:this.safeString(r,"outcomeId"),label:this.safeString(r,"label"),market:this.safeString(r,"market"),type:"limit",timeInForce:this.safeString(e,"time_in_force","GTC"),postOnly:this.safeBool(e,"postOnly"),side:o,price:n,stopPrice:void 0,triggerPrice:void 0,average:void 0,amount:d,cost:void 0,filled:h,remaining:void 0,fee:void 0,trades:[]},r)}parseOrderStatus(e){let t=this.safeStringLower({status:e},"status");return this.safeString({live:"open",matched:"closed",cancelled:"canceled",delayed:"open",placement:"open",update:"open",cancellation:"canceled"},t,t)}async createOrder(e,t,i,s,r,a={}){await this.loadApiCredentials(),await this.loadOutcome(e);let o=this.buildClobOrderBody(e,t,i,s,r,a),n=await this.clobPrivatePostOrder(this.safeDict(o,"body")),d=this.extend(this.safeDict(o,"request"),n),h=this.parsePredictionOrder(d,this.safeDict(o,"outcome"));return h.info=n,h}async createOrders(e,t={}){await this.loadApiCredentials();let i=[];for(let t=0;t<e.length;t++){let s=this.safeDict(e,t),r=this.safeString(s,"outcome");void 0!==r&&i.push(r)}await this.loadOutcomes(i);let s=[],r=[],a=[];for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),o=this.safeDict(i,"params",{});if(void 0===this.safeString(o,"salt")){let e=this.incrementingNonce();o=this.extend(o,{salt:this.numberToString(e)})}let n=this.buildClobOrderBody(this.safeString(i,"outcome"),this.safeString(i,"type"),this.safeString(i,"side"),this.safeNumber(i,"amount"),this.safeNumber(i,"price"),o);s.push(this.safeDict(n,"body",{})),r.push(this.safeDict(n,"outcome",{})),a.push(this.safeDict(n,"request",{}))}let o=await this.clobPrivatePostOrders(s),n=[];if(Array.isArray(o))for(let e=0;e<o.length;e++){let t=this.extend(a[e],o[e]),i=this.parsePredictionOrder(t,r[e]);i.info=o[e],n.push(i)}else n.push(this.parsePredictionOrder(o));return n}buildClobOrderBody(e,t,i,s,r,a={}){let o=this.outcome(e),n=o.outcomeId,d=i.toUpperCase(),h="market"===t,l=this.safeStringUpper(a,"orderType");if(void 0===l){let e=this.safeStringUpper(a,"timeInForce");"GTC"===e?l="GTC":"FOK"===e?l="FOK":"IOC"===e?l="FAK":"GTD"===e&&(l="GTD")}void 0===l&&(l=h?"FOK":"GTC");let u=r;if(void 0===u){if(!h)throw new c.ArgumentsRequired(this.id+" createOrder() requires a price for limit orders");if(void 0===(u=this.safeNumber(o,"price")))throw new c.ArgumentsRequired(this.id+" createOrder() could not determine a price from the outcome, pass an explicit price")}let f=this.safeDict(o,"precision",{}),p=this.safeString(a,"tickSize",this.numberToString(this.safeNumber(f,"price",.01))),m=this.safeBool(a,"negRisk",this.safeBool(o,"negRisk",!1)),g=this.safeBool(a,"postOnly",!1),v=this.safeInteger2(a,"signatureType","signature_type",this.safeInteger(this.options,"signatureType",3)),y=this.ethChecksumAddress(this.ethGetAddressFromPrivateKey(this.privateKey)),b=this.ethChecksumAddress(this.safeString2(a,"funder","maker",this.safeString(this.options,"funder",this.walletAddress))),w=this.incrementingNonce(),k=this.safeString(a,"salt",this.numberToString(w)),S=this.safeString(a,"timestamp",this.numberToString(this.milliseconds())),O=this.safeString(a,"expiration","0"),T=this.safeNumber(a,"cost"),P=this.omit(a,["signatureType","signature_type","funder","maker","orderType","timeInForce","postOnly","tickSize","negRisk","salt","timestamp","expiration","cost","builder","builderCode"]),I=this.polymarketOrderRawAmounts(d,s,u,p,T),A=this.safeString(I,"makerAmount"),x=this.safeString(I,"takerAmount"),M=+("BUY"!==d),_="0x0000000000000000000000000000000000000000000000000000000000000000",C=this.safeStringLower2(a,"builder","builderCode",this.safeStringLower(this.options,"builder")),B=_;if(void 0!==C){let e=this.remove0xPrefix(C);if(e.length<=40){let t=this.safeBool(this.options,"builderFee",!0),i=0;!0===t&&(i=this.safeInteger(this.options,"feeRate",0));let s=this.intToBase16(i);s=s.padStart(24,"0");let r=e;e=s+(r=r.padStart(40,"0"))}else e=e.padStart(64,"0");B="0x"+e}let E=y;3===v&&(E=b);let R={salt:k,maker:b,signer:E,tokenId:n,makerAmount:A,takerAmount:x,side:M,signatureType:v,timestamp:S,metadata:_,builder:B},L=this.safeString(this.options,"exchangeAddress","0xE111180000d2663C0091e4f400237545B87B996B"),N=this.safeString(this.options,"negRiskExchangeAddress","0xe2222d279d744050d28e00520010520000310F59"),D=L;!0===m&&(D=N);let q=this.safeString(this.options,"ctfExchangeVersion","2"),F=this.signClobOrder(R,D,q,v),V=this.safeString(this.options,"l2ApiKey",this.apiKey),G={deferExec:!1,postOnly:g,order:{salt:this.parseToInt(k),maker:b,signer:E,taker:"0x0000000000000000000000000000000000000000",tokenId:n,makerAmount:A,takerAmount:x,side:d,signatureType:v,timestamp:S,expiration:O,metadata:_,builder:B,signature:F},owner:V,orderType:l},H={side:d,price:u,asset_id:n,time_in_force:l,postOnly:g};return void 0===T&&(H.original_size=s),{body:this.extend(P,G),outcome:o,request:H}}async createMarketBuyOrderWithCost(e,t,i={}){let s=this.extend(i,{cost:t});return await this.createOrder(e,"market","buy",t,void 0,s)}polymarketOrderRawAmounts(e,t,i,s,r){let a,o,n={"0.1":{price:1,size:2,amount:3},"0.01":{price:2,size:2,amount:4},"0.001":{price:3,size:2,amount:5},"0.0001":{price:4,size:2,amount:6}},h=this.safeDict(n,s,this.safeDict(n,"0.01")),c=this.safeInteger(h,"price"),l=this.safeInteger(h,"size"),u=this.safeInteger(h,"amount"),f=this.numberToString(i),p=this.decimalToPrecision(f,1,c,2);if(void 0!==r&&"BUY"===e){let e=this.numberToString(r);a=this.decimalToPrecision(e,0,l,2),o=this.decimalToPrecision(d.Y.stringDiv(a,p),0,u,2)}else if("BUY"===e){let e=this.numberToString(t);o=this.decimalToPrecision(e,0,l,2),a=this.decimalToPrecision(d.Y.stringMul(o,p),1,u,2)}else{let e=this.numberToString(t);a=this.decimalToPrecision(e,0,l,2),o=this.decimalToPrecision(d.Y.stringMul(a,p),1,u,2)}return{makerAmount:this.decimalToPrecision(d.Y.stringMul(a,"1000000"),0,0,2),takerAmount:this.decimalToPrecision(d.Y.stringMul(o,"1000000"),0,0,2)}}signClobOrder(e,t,i,s){let a=this.safeInteger(this.options,"chainId",137),o=this.safeString(this.options,"ctfExchangeName","Polymarket CTF Exchange"),n="Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)",d=[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"signer",type:"address"},{name:"tokenId",type:"uint256"},{name:"makerAmount",type:"uint256"},{name:"takerAmount",type:"uint256"},{name:"side",type:"uint8"},{name:"signatureType",type:"uint8"},{name:"timestamp",type:"uint256"},{name:"metadata",type:"bytes32"},{name:"builder",type:"bytes32"}],h={name:o,version:i,chainId:a,verifyingContract:t};if(3!==this.parseToInt(s)){let t=this.ethEncodeStructuredData(h,{Order:d},e),i=this.signMessage(t,this.privateKey);return("0x"+this.remove0xPrefix(i.r)+this.remove0xPrefix(i.s)+this.intToBase16(i.v)).toLowerCase()}let c=this.hash(this.encode(n),r.lY,"binary"),l=this.ethAbiEncode(["bytes32","uint256","address","address","uint256","uint256","uint256","uint8","uint8","uint256","bytes32","bytes32"],[c,this.convertToBigInt(e.salt),e.maker,e.signer,this.convertToBigInt(e.tokenId),this.convertToBigInt(e.makerAmount),this.convertToBigInt(e.takerAmount),e.side,e.signatureType,this.convertToBigInt(e.timestamp),this.base16ToBinary(this.remove0xPrefix(e.metadata)),this.base16ToBinary(this.remove0xPrefix(e.builder))]),u="0x"+this.hash(l,r.lY,"hex"),f=this.hash(this.encode("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),r.lY,"binary"),p=this.hash(this.encode(o),r.lY,"binary"),m=this.hash(this.encode(i),r.lY,"binary"),g=this.ethAbiEncode(["bytes32","bytes32","bytes32","uint256","address"],[f,p,m,this.convertToBigInt(this.numberToString(a)),t]),v="0x"+this.hash(g,r.lY,"hex"),y={contents:e,name:"DepositWallet",version:"1",chainId:a,verifyingContract:e.signer,salt:"0x0000000000000000000000000000000000000000000000000000000000000000"},b=this.ethEncodeStructuredData(h,{TypedDataSign:[{name:"contents",type:"Order"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"}],Order:d},y),w=this.signMessage(b,this.privateKey),k=this.remove0xPrefix(w.r)+this.remove0xPrefix(w.s)+this.intToBase16(w.v),S=this.intToBase16(n.length).padStart(4,"0"),O=this.binaryToBase16(this.encode(n));return("0x"+k+this.remove0xPrefix(v)+this.remove0xPrefix(u)+O+S).toLowerCase()}async cancelOrder(e,t,i={}){await this.loadApiCredentials();let s=await this.clobPrivateDeleteOrder(this.extend({orderID:e},i)),r=this.safeDict(s,"not_canceled",{}),a=this.safeString(r,e),o="open";return void 0===a&&(o="canceled"),this.safePredictionOrder({id:e,status:o,info:s})}async cancelOrders(e,t,i={}){await this.loadApiCredentials();let s=await this.clobPrivateDeleteOrders(e),r=this.safeList(s,"canceled",[]),a=[];for(let e=0;e<r.length;e++)a.push(this.safePredictionOrder({id:this.safeString(r,e),status:"canceled",info:s}));return a}async cancelAllOrders(e,t={}){let i;if(await this.loadApiCredentials(),void 0!==e){let s={asset_id:(await this.loadOutcome(e)).outcomeId};i=await this.clobPrivateDeleteCancelMarketOrders(this.extend(s,t))}else i=await this.clobPrivateDeleteCancelAll(t);let s=this.safeList(i,"canceled",[]),r=[];for(let e=0;e<s.length;e++)r.push(this.safePredictionOrder({id:this.safeString(s,e),status:"canceled",info:i}));return r}async fetchEvents(e={}){this.requireEventQuery(e);let t=this.safeString(e,"eventId"),i=this.safeString(e,"slug"),s=this.parseSearchQueries(e),r=this.omit(e,["query","queries","eventId","slug"]);if(void 0===s)throw new c.ExchangeError(this.id+" fetchEvents() missing queries");let a=s.length,o=[];if(void 0!==t||void 0!==i){let e={};void 0!==t?e.id=t:e.slug=i;let s=await this.gammaPublicGetEvents(e);o=Array.isArray(s)?s:[]}else o=a>0?await this.fetchRawEventsBySearch(s,r):await this.fetchRawEventsList(r);void 0===this.events&&(this.events={}),void 0===this.markets&&(this.markets=this.createSafeDictionary());let n=[];for(let e=0;e<o.length;e++){let t=o[e],i=t,s=this.parseEventToMarkets(i);if(0===s.length){let e,r=this.safeString(t,"id"),a=this.safeString(t,"slug");void 0!==r?e=await this.gammaPublicGetEventsId({id:r}):void 0!==a&&(e=await this.gammaPublicGetEventsSlugSlug({slug:a})),void 0!==e&&(i=this.safeValue(e,"event",e),s=this.parseEventToMarkets(i))}for(let e=0;e<s.length;e++){let t=s[e];if(void 0===t)throw new c.ExchangeError(this.id+" fetchEvents() missing m");this.markets[t.market]=t}let r=this.parseEvent(i);n.push(r)}this.populateOutcomes();let d=e;return a>0&&((d=this.extend({},e)).status=this.safeString(e,"status","active"),d.searchIn=this.safeString(e,"searchIn","title")),this.applyEventFetchParams(n,d,s)}async fetchEvent(e,t={}){let i;i=e.indexOf("-")>=0?await this.gammaPublicGetEventsSlugSlug(this.extend({slug:e},t)):await this.gammaPublicGetEventsId(this.extend({id:e},t));let s=this.safeDict(i,"event",i);void 0===s&&(s={});let r=this.parseEvent(s);return this.indexEventOutcomes(r),r}parseEvent(e){let t,i=this.parseEventToMarkets(e),s=this.safeString(e,"slug"),r=this.safeString2(e,"createdAt","created_date_iso"),a=this.safeString2(e,"endDate","end_date_iso"),o=this.safeString2(e,"updatedAt","last_updated_date_iso"),n=this.safeBool(e,"active"),d=this.safeBool(e,"closed",!1);void 0!==n&&(t=!0===n&&!0!==d);let h=this.safeList(e,"tags",[]),c=h.length,l=[];for(let e=0;e<c;e++){let t=this.safeString2(h[e],"label","slug");void 0!==t&&l.push(t)}return this.extend({id:this.safeString(e,"id"),slug:s,event:void 0!==s&&""!==s?this.shortenSlug(s):void 0,title:this.safeString(e,"title"),tags:l,markets:i,active:t,url:this.safeString(e,"url"),image:this.safeString2(e,"image","image_url"),created:this.parse8601(r),createdDatetime:r,end:this.parse8601(a),endDatetime:a,category:this.safeString(e,"category"),lastUpdatedAt:this.parse8601(o),lastUpdatedAtDatetime:o,resolutionSource:this.safeString2(e,"resolutionSource","resolution_source"),resolved:this.safeBool2(e,"closed","resolved"),info:e})}parseEvents(e){let t=[];for(let i=0;i<e.length;i++){let s=e[i];t.push(this.parseEvent(s))}return t}handleErrors(e,t,i,s,r,a,o,n,d){if(void 0===o)return;let h=this.safeString2(o,"error","errorMsg");if(void 0!==h){let e=this.id+" "+a;this.throwExactlyMatchedException(this.exceptions.exact,h,e),this.throwBroadlyMatchedException(this.exceptions.broad,h,e)}}nonce(){return this.milliseconds()}sign(e,t="gamma",i="GET",r={},a,o){let n="string"==typeof t?t:t[0],d="string"==typeof t?"public":t[1],h=this.urls.api,l=this.safeString(h,n,h.gamma)+"/"+this.implodeParams(e,r),u=!1;Array.isArray(r)&&(u=r.length>0);let f={};u||(f=this.omit(r,this.extractParams(e)));let p=o;if("GET"===i){let e,t=!1,i=Object.keys(f);for(let e=0;e<i.length;e++)Array.isArray(f[i[e]])&&(t=!0);""!==(e=t?this.urlencodeWithArrayRepeat(f):this.urlencode(f))&&(l+="?"+e)}else u?p=this.json(r):Object.keys(f).length>0&&(p=this.json(f));let m=this.extend({Accept:"application/json","Content-Type":"application/json"},void 0!==a?a:{});if("private"===d)if("auth/api-key"===e||"auth/derive-api-key"===e||"auth/api-keys"===e){if(void 0===this.privateKey)throw new c.ArgumentsRequired(this.id+" "+e+" requires a privateKey");let t=this.ethChecksumAddress(this.ethGetAddressFromPrivateKey(this.privateKey)),i=this.seconds().toString(),s=this.safeInteger(r,"nonce",0),a=this.signClobAuth(t,i,s);m=this.extend(m,{POLY_ADDRESS:t,POLY_SIGNATURE:a,POLY_TIMESTAMP:i,POLY_NONCE:this.numberToString(s)})}else{let t,a=this.safeString(this.options,"l2ApiKey",this.apiKey),o=this.safeString(this.options,"l2Secret",this.secret),n=this.safeString(this.options,"l2Passphrase",this.password);t=void 0!==this.privateKey?this.ethChecksumAddress(this.ethGetAddressFromPrivateKey(this.privateKey)):this.walletAddress;let d=this.seconds().toString(),h=d+i+"/"+this.implodeParams(e,r);void 0!==p&&(h+=p);let c=o;c=(c=c.replaceAll("-","+")).replaceAll("_","/");let l=this.base64ToBinary(c),u=this.hmac(this.encode(h),l,s.sc,"base64");u=(u=u.replaceAll("+","-")).replaceAll("/","_"),m=this.extend(m,{POLY_ADDRESS:t,POLY_API_KEY:a,POLY_PASSPHRASE:n,POLY_SIGNATURE:u,POLY_TIMESTAMP:d})}return{url:l,method:i,body:p,headers:m}}hashMessage(e){return"0x"+this.hash(e,r.lY,"hex")}ethChecksumAddress(e){let t=this.remove0xPrefix(e).toLowerCase(),i=this.hash(this.encode(t),r.lY,"hex"),s=this.stringToCharsArray(t),a=this.stringToCharsArray(i),o="";for(let e=0;e<s.length;e++){let t=s[e];"89abcdef".indexOf(a[e])>=0?o+=t.toUpperCase():o+=t}return"0x"+o}signHash(e,t){let i=(0,n.h1)(e.slice(-64),t.slice(-64),a.bI,void 0),s=i.r,r=i.s;return{r:"0x"+s.padStart(64,"0"),s:"0x"+r.padStart(64,"0"),v:this.sum(27,i.v)}}signMessage(e,t){return this.signHash(this.hashMessage(e),t.slice(-64))}signClobAuth(e,t,i){let s=this.ethEncodeStructuredData({name:"ClobAuthDomain",version:"1",chainId:137},{ClobAuth:[{name:"address",type:"address"},{name:"timestamp",type:"string"},{name:"nonce",type:"uint256"},{name:"message",type:"string"}]},{address:e,timestamp:t,nonce:i,message:"This message attests that I control the given wallet"}),r=this.signMessage(s,this.privateKey);return"0x"+this.remove0xPrefix(r.r)+this.remove0xPrefix(r.s)+this.intToBase16(r.v)}async deriveApiKey(e={}){let t=await this.clobPrivateGetAuthDeriveApiKey(e);return this.setApiCredentials(t)}async createApiKey(e={}){let t=await this.clobPrivatePostAuthApiKey(e);return this.setApiCredentials(t)}async createOrDeriveApiKey(e={}){let t;try{t=await this.deriveApiKey(e)}catch(i){t=await this.createApiKey(e)}if(void 0===t)throw new c.ExchangeError(this.id+" createOrDeriveApiKey() returned no credentials");return t}setApiCredentials(e){let t={apiKey:this.safeString2(e,"apiKey","key"),secret:this.safeString(e,"secret"),passphrase:this.safeString(e,"passphrase")};return this.options.l2ApiKey=t.apiKey,this.options.l2Secret=t.secret,this.options.l2Passphrase=t.passphrase,t}async loadApiCredentials(){let e;if(void 0!==this.privateKey){void 0===this.safeString(this.options,"l2ApiKey")&&await this.createOrDeriveApiKey();return}let t=void 0!==this.apiKey?this.apiKey:this.safeString(this.options,"l2ApiKey");e=void 0!==this.secret?this.secret:this.safeString(this.options,"l2Secret");let i=void 0!==this.password?this.password:this.safeString(this.options,"l2Passphrase");if(void 0===t||void 0===e||void 0===i)throw new c.AuthenticationError(this.id+" requires L2 api credentials (apiKey, secret, password) or a privateKey to derive them")}ping(e){return"PING"}handleMessage(e,t){if("string"==typeof t){e.lastPong=this.milliseconds();return}let i=Array.isArray(t)?t:[t];for(let t=0;t<i.length;t++){let s=i[t];if(null==s||"object"!=typeof s)continue;let r=this.safeString(s,"event_type");"book"===r?this.handleOrderBookSnapshot(e,s):"price_change"===r?this.handleOrderBookDelta(e,s):"last_trade_price"===r?this.handleTrade(e,s):"order"===r?this.handleOrder(e,s):"trade"===r&&this.handleMyTrade(e,s)}}handleOrderBookSnapshot(e,t){let i=this.safeString(t,"asset_id"),s=this.tokenIdToSymbol(i);if(void 0===s)return;if(!(s in this.orderbooks)){let e=this.orderBook({});this.orderbooks[s]=e}let r=this.orderbooks[s],a=this.parsePolyTimestamp(this.safeString(t,"timestamp")),o=this.safeList(t,"bids",[]),n=this.safeList(t,"asks",[]),d=[];for(let e=0;e<o.length;e++){let t=this.safeDict(o,e);d.push([this.safeNumber(t,"price"),this.safeNumber(t,"size")])}let h=[];for(let e=0;e<n.length;e++){let t=this.safeDict(n,e);h.push([this.safeNumber(t,"price"),this.safeNumber(t,"size")])}let c=this.safeOutcome(s);r.reset({bids:d,asks:h,timestamp:a,datetime:this.iso8601(a),outcome:s,outcomeId:i,market:this.safeString(c,"market")}),e.resolve(r,"orderbook::"+s),e.resolve(r,"ticker::"+s)}handleOrderBookDelta(e,t){let i=this.parsePolyTimestamp(this.safeString(t,"timestamp")),s=this.safeList(t,"price_changes",[]),r={};for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),a=this.safeString(t,"asset_id"),o=this.tokenIdToSymbol(a);if(void 0===o||!(o in this.orderbooks))continue;let n=this.orderbooks[o],d=this.safeNumber(t,"price"),h=this.safeNumber(t,"size");("BUY"===this.safeStringUpper(t,"side","")?n.bids:n.asks).storeArray([d,h]),n.timestamp=i,n.datetime=this.iso8601(i),r[o]=!0}let a=Object.keys(r);for(let t=0;t<a.length;t++){let i=a[t],s=this.orderbooks[i];e.resolve(s,"orderbook::"+i),e.resolve(s,"ticker::"+i)}}handleTrade(e,t){let i=this.safeString(t,"asset_id"),s=this.tokenIdToSymbol(i);if(void 0===s)return;let r=this.parsePolyTimestamp(this.safeString(t,"timestamp")),a=this.safeNumber(t,"price"),o=this.safeNumber(t,"size"),n=this.safeOutcome(i),d=this.safePredictionTrade({id:this.safeString(t,"transaction_hash"),info:t,timestamp:r,datetime:this.iso8601(r),outcome:s,outcomeId:this.safeString(n,"outcomeId"),label:this.safeString(n,"label"),market:this.safeString(n,"market"),order:void 0,type:void 0,side:this.safeStringLower(t,"side"),takerOrMaker:"taker",price:a,amount:o,cost:void 0,fee:void 0},n);void 0===this.trades&&(this.trades={});let c=this.safeValue(this.trades,s);if(void 0===c){let e=this.safeInteger(this.options,"tradesLimit",1e3);c=new h.I3(e),this.trades[s]=c}c.append(d),e.resolve(c,"trades::"+s)}async watchOrderBook(e,t,i={}){let s=await this.loadOutcome(e),r=this.safeString(s,"outcomeId"),a=this.safeString(s,"outcome"),o=this.urls.api.ws;return(await this.watch(o,"orderbook::"+a,{assets_ids:[r],type:"market"},"subscribe::"+r)).limit()}async watchTrades(e,t,i,s={}){let r=await this.loadOutcome(e),a=this.safeString(r,"outcomeId"),o=this.safeString(r,"outcome"),n=this.urls.api.ws,d=await this.watch(n,"trades::"+o,{assets_ids:[a],type:"market"},"subscribe::"+a);return this.filterBySinceLimit(d,t,i,"timestamp",!0)}async watchTicker(e,t={}){let i,s,r,a,o,n=await this.loadOutcome(e),h=this.safeString(n,"outcomeId"),l=this.safeString(n,"outcome"),u="ticker::"+l;if(void 0===l)throw new c.ExchangeError(this.id+" watchTicker() missing outcome");if(!(l in this.orderbooks)){let e=this.orderBook({});void 0!==l&&(this.orderbooks[l]=e)}let f=this.urls.api.ws,p=await this.watch(f,u,{assets_ids:[h],type:"market"},"subscribe::"+h),m=p.bids,g=p.asks,v=0;void 0!==m&&(v=m.length),void 0!==m&&v>0&&(i=m[0][0],s=m[0][1]);let y=0;if(void 0!==g&&(y=g.length),void 0!==g&&y>0&&(r=g[0][0],a=g[0][1]),void 0!==i&&void 0!==r){let e=d.Y.stringAdd(this.numberToString(i),this.numberToString(r));o=this.parseNumber(d.Y.stringDiv(e,"2"))}else o=void 0!==i?i:r;let b=this.safeOutcome(l);return this.safePredictionTicker({outcome:l,outcomeId:this.safeString(b,"outcomeId"),label:this.safeString(b,"label"),market:this.safeString(b,"market"),timestamp:p.timestamp,datetime:p.datetime,high:void 0,low:void 0,bid:i,bidVolume:s,ask:r,askVolume:a,vwap:void 0,open:void 0,close:o,last:o,previousClose:void 0,change:void 0,percentage:void 0,average:o,baseVolume:void 0,quoteVolume:void 0,info:p},b)}async watchOrders(e,t,i,s={}){await this.loadApiCredentials();let r="orders",a=e;if(void 0!==a){let e=await this.loadOutcome(a);r="orders::"+(a=this.safeString(e,"outcome"))}let o=await this.subscribeUserChannel(r,s),n=i;return this.newUpdates&&(n=o.getLimit(a,n)),this.filterByOutcomeSinceLimit(o,a,t,n,!0)}async watchMyTrades(e,t,i,s={}){await this.loadApiCredentials();let r="myTrades",a=e;if(void 0!==a){let e=await this.loadOutcome(a);r="myTrades::"+(a=this.safeString(e,"outcome"))}let o=await this.subscribeUserChannel(r,s),n=i;return this.newUpdates&&(n=o.getLimit(a,n)),this.filterByOutcomeSinceLimit(o,a,t,n,!0)}async subscribeUserChannel(e,t={}){let i=void 0!==this.apiKey?this.apiKey:this.safeString(this.options,"l2ApiKey"),s={apiKey:i,secret:void 0!==this.secret?this.secret:this.safeString(this.options,"l2Secret"),passphrase:void 0!==this.password?this.password:this.safeString(this.options,"l2Passphrase")},r=this.urls.api.wsUser;return await this.watch(r,e,this.extend({auth:s,markets:[],type:"user"},t),"user")}handleOrder(e,t){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new h.$0(e)}let i=this.orders,s=this.parsePredictionOrder(t);i.append(s),e.resolve(i,"orders");let r=this.safeString(s,"outcome");void 0!==r&&e.resolve(i,"orders::"+r)}handleMyTrade(e,t){if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new h.$0(e)}let i=this.myTrades,s=this.parsePredictionTrade(t);i.append(s),e.resolve(i,"myTrades");let r=this.safeString(s,"outcome");void 0!==r&&e.resolve(i,"myTrades::"+r)}tokenIdToSymbol(e){if(void 0===e||""===e)return;let t=this.safeDict(this.outcomes_by_id,e);if(void 0!==t)return this.safeString(t,"outcome");let i=this.safeDict(this.markets_by_id,e);return this.safeString2(i,"market","symbol")}parsePolyTimestamp(e){if(void 0!==e)return this.parseToInt(e)}}i.d(t,{A:()=>l})},4884(e,t,i){"use strict";var s=i(6834),r=i(6885),a=i(883),o=i(1093),n=i(7749),d=i(1697),h=i(1453);class c extends a.A{describe(){return this.deepExtend(super.describe(),{id:"predictfun",name:"predict.fun",countries:[],rateLimit:250,version:"v1",certified:!1,pro:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!1,future:!1,option:!1,approve:!0,cancelAllOrders:!1,cancelOrder:!0,cancelOrders:!0,createMarketBuyOrderWithCost:!1,createOrder:!0,createOrders:!1,fetchBalance:!1,fetchClosedOrders:!0,fetchCurrencies:!1,fetchDeposits:!1,fetchEvent:!0,fetchEvents:!0,fetchLedger:!1,fetchMarkets:!0,fetchMyTrades:!0,fetchOHLCV:!1,fetchOpenInterest:!1,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!1,fetchOrderTrades:!1,fetchPosition:!0,fetchPositions:!0,fetchStatus:!1,fetchTicker:!0,fetchTickers:!1,fetchTime:!1,fetchTrades:!0,fetchTradingFee:!1,fetchWithdrawals:!1,prediction:!0,unWatchMyTrades:!0,unWatchOrderBook:!0,unWatchOrders:!0,watchMyTrades:!0,watchOrderBook:!0,watchOrders:!0,watchTicker:!1,watchTrades:!1},urls:{logo:"https://github.com/user-attachments/assets/9fb5dccf-faa3-4b5a-b144-81d6994bc598",api:{predictfun:"https://api.predict.fun",ws:"wss://ws.predict.fun/ws"},test:{predictfun:"https://api-testnet.predict.fun"},www:"https://predict.fun",doc:["https://docs.predict.fun"]},api:{predictfun:{get:{"v1/auth/message":{cost:1},"v1/categories":{cost:1},"v1/categories/{slug}":{cost:1},"v1/tags":{cost:1},"v1/markets":{cost:1},"v1/markets/{id}":{cost:1},"v1/markets/{id}/stats":{cost:1},"v1/markets/{id}/last-sale":{cost:1},"v1/markets/{id}/orderbook":{cost:1},"v1/markets/{id}/timeseries":{cost:1},"v1/markets/{id}/timeseries/latest":{cost:1},"v1/orders/{hash}":{cost:1},"v1/orders":{cost:1},"v1/orders/matches":{cost:1},"v1/account":{cost:1},"v1/account/activity":{cost:1},"v1/positions":{cost:1},"v1/positions/{address}":{cost:1},"v1/search":{cost:1}},post:{"v1/auth":{cost:1},"v1/orders/remove":{cost:1},"v1/orders":{cost:1},"v1/orders/remove-by-hash":{cost:1},"v1/account/referral":{cost:1},"v1/oauth/finalize":{cost:1},"v1/oauth/orders":{cost:1},"v1/oauth/orders/create":{cost:1},"v1/oauth/orders/cancel":{cost:1},"v1/oauth/positions":{cost:1}}}},requiredCredentials:{apiKey:!0,secret:!1,walletAddress:!1,privateKey:!1},fees:{trading:{tierBased:!1,percentage:!0,maker:0,taker:.02}},exceptions:{exact:{unauthorized:h.AuthenticationError,bad_request:h.BadRequest,not_found:h.BadRequest,create_order_hash_mismatch:h.InvalidOrder,create_order_insufficient_collateral_allowance:h.InsufficientFunds,create_order_insufficient_shares_allowance:h.InsufficientFunds,create_order_min_order_value_not_met:h.InvalidOrder,create_order_price_out_of_range:h.InvalidOrder,create_order_market_not_trading:h.MarketClosed},broad:{"do not belong to":h.OrderNotFound,"order hash must be a":h.BadRequest,"Orderbook not found":h.BadSymbol,"market not found":h.BadSymbol,"not currently trading":h.MarketClosed,"allowance is less than":h.InsufficientFunds,"price per share must be":h.InvalidOrder,"must have a value of at least":h.InvalidOrder}},options:{allowUnscopedFetchEvents:!0,maxFetchEventsResults:100,tokenExpiresIn:864e5,marketBuyPrice:.99,marketSellPrice:.01,warnOnMarketOrderWithoutPrice:!0,chainId:56,rpcUrls:{56:"https://bsc-dataseed.bnbchain.org/",97:"https://bsc-testnet-dataseed.bnbchain.org/"},collateral:{56:"0x55d398326f99059fF775485246999027B3197955",97:"0xB32171ecD878607FFc4F8FC0bCcE6852BB3149E0"},defaultExpiration:3600,marketOrderExpiration:300,exchanges:{56:{CTF_EXCHANGE:"0x8BC070BEdAB741406F4B1Eb65A72bee27894B689",NEG_RISK_CTF_EXCHANGE:"0x365fb81bd4A24D6303cd2F19c349dE6894D8d58A",YIELD_BEARING_CTF_EXCHANGE:"0x6bEb5a40C032AFc305961162d8204CDA16DECFa5",YIELD_BEARING_NEG_RISK_CTF_EXCHANGE:"0x8A289d458f5a134bA40015085A8F50Ffb681B41d"},97:{CTF_EXCHANGE:"0x2A6413639BD3d73a20ed8C95F634Ce198ABbd2d7",NEG_RISK_CTF_EXCHANGE:"0xd690b2bd441bE36431F6F6639D7Ad351e7B29680",YIELD_BEARING_CTF_EXCHANGE:"0x8a6B4Fa700A1e310b106E7a48bAFa29111f66e89",YIELD_BEARING_NEG_RISK_CTF_EXCHANGE:"0x95D5113bc50eD201e319101bbca3e0E250662fCC"}},conditionalTokens:{56:{CONDITIONAL_TOKENS:"0x22DA1810B194ca018378464a58f6Ac2B10C9d244",NEG_RISK_CONDITIONAL_TOKENS:"0x22DA1810B194ca018378464a58f6Ac2B10C9d244",YIELD_BEARING_CONDITIONAL_TOKENS:"0x9400F8Ad57e9e0F352345935d6D3175975eb1d9F",YIELD_BEARING_NEG_RISK_CONDITIONAL_TOKENS:"0xF64b0b318AAf83BD9071110af24D24445719A07F"},97:{CONDITIONAL_TOKENS:"0x2827AAef52D71910E8FBad2FfeBC1B6C2DA37743",NEG_RISK_CONDITIONAL_TOKENS:"0x2827AAef52D71910E8FBad2FfeBC1B6C2DA37743",YIELD_BEARING_CONDITIONAL_TOKENS:"0x38BF1cbD66d174bb5F3037d7068E708861D68D7f",YIELD_BEARING_NEG_RISK_CONDITIONAL_TOKENS:"0x26e865CbaAe99b62fbF9D18B55c25B5E079A93D5"}},adapters:{56:{NEG_RISK_ADAPTER:"0xc3Cf7c252f65E0d8D88537dF96569AE94a7F1A6E",YIELD_BEARING_NEG_RISK_ADAPTER:"0x41dCe1A4B8FB5e6327701750aF6231B7CD0B2A40"},97:{NEG_RISK_ADAPTER:"0x285c1B939380B130D7EBd09467b93faD4BA623Ed",YIELD_BEARING_NEG_RISK_ADAPTER:"0xb74aea04bdeBE912Aa425bC9173F9668e6f11F99"}},createOrder:{taker:"0x0000000000000000000000000000000000000000"}}})}async fetchMarkets(e={}){let t=await this.fetchEvents(e),i=t.length,s=[];for(let e=0;e<i;e++){let i=this.safeList(t[e],"markets",[]),r=i.length;for(let e=0;e<r;e++)s.push(i[e])}return s}async fetchEvent(e,t={}){let i=this.safeString(t,"slug"),s=e;if(void 0!==i&&(s=i),void 0===s)throw new h.ArgumentsRequired(this.id+' fetchEvent() requires the "id" argument or the "slug" parameter');let r=await this.fetchEvents(this.extend({slug:s},t));return this.safeDict(r,0)}async fetchEvents(e={}){this.safeBool(this.options,"allowUnscopedFetchEvents",!1)||this.requireEventQuery(e);let t=this.parseSearchQueries(e),i=t.length,s=this.omit(e,["query","queries"]),r=["tags"],a=this.safeInteger(s,"limit"),o=this.safeInteger(this.options,"maxFetchEventsResults",100);void 0!==a&&(o=a);let n=this.safeString2(s,"slug","eventId"),d=this.omit(s,["status","limit","sort","eventId","slug","tags","marketVariant"]);void 0===this.markets&&(this.markets=this.createSafeDictionary());let h=[];if(void 0!==n){let e=await this.predictfunGetV1CategoriesSlug(this.extend({slug:n},d));h=[this.safeDict(e,"data")]}else if(i>0)h=await this.fetchRawTopicsByQueries(t,s);else{let e={},t=this.safeList(s,"tags",[]);t.length>0&&(e.tagIds=t.join(",")),r.push("limit");let i=this.omit(s,["limit","tags"]),a=this.extend(e,i),n=await this.predictfunGetV1Categories(a),d=this.safeList(n,"data",[]),c=(h=this.arrayConcat(h,d)).length;for(;c<o;){let e=this.safeString(n,"cursor");if(void 0===e)break;a.after=e,n=await this.predictfunGetV1Categories(a),d=this.safeList(n,"data",[]),c=(h=this.arrayConcat(h,d)).length}c>o&&(h=this.arraySlice(h,0,o))}let c=h.length,l=[];for(let e=0;e<c;e++){let t=this.parseEvent(h[e]);l.push(t);let i=this.safeList(t,"markets",[]),s=i.length;for(let e=0;e<s;e++){let t=i[e],s=this.safeString(t,"market");void 0!==s&&(this.markets[s]=t)}}this.populateOutcomes();let u=this.omit(s,r),f=this.safeString(s,"status");return"OPEN"===f?u=this.extend(u,{status:"active"}):"RESOLVED"===f&&(u=this.extend(u,{status:"closed"})),this.applyEventFetchParams(l,u,t)}async fetchRawTopicsByQueries(e,t={}){let i=this.safeString(t,"status"),s="false";void 0!==i&&"active"!==i&&"OPEN"!==i&&(s="true");let r=this.omit(t,["query","queries","limit","sort","searchIn","status","eventId","slug","tags","marketVariant"]),a=e.length,o=[],n={},d={},h=[];for(let t=0;t<a;t++){let i={query:e[t],limit:25,includeResolved:s},a=await this.predictfunGetV1Search(this.extend(i,r)),c=this.safeDict(a,"data",{}),l=this.safeList(c,"categories",[]),u=l.length;for(let e=0;e<u;e++){let t=this.safeDict(l,e),i=this.safeString(t,"slug");void 0===i?o.push(t):i in n||(n[i]=!0,o.push(t))}let f=this.safeList(c,"markets",[]),p=f.length;for(let e=0;e<p;e++){let t=f[e],i=this.safeString(t,"categorySlug");if(void 0!==i)if(i in d){let e=d[i];e.push(t),d[i]=e}else d[i]=[t],h.push(i)}}let c=h.length;for(let e=0;e<c;e++){let t=h[e];if(!(t in n)){let e;n[t]=!0;let i=d[t],s=this.safeDict(i,0,{}),r=this.safeString(s,"status"),a=this.safeString(s,"tradingStatus");"RESOLVED"===r||"SETTLED"===r?e="RESOLVED":"OPEN"===a&&(e="OPEN"),o.push({id:t,slug:t,title:this.safeString(s,"title"),description:this.safeString(s,"description"),imageUrl:this.safeString(s,"imageUrl"),marketVariant:this.safeString(s,"marketVariant"),isNegRisk:this.safeBool(s,"isNegRisk"),isYieldBearing:this.safeBool(s,"isYieldBearing"),isVisible:this.safeBool(s,"isVisible"),status:e,createdAt:this.safeString(s,"createdAt"),markets:i})}}return o}parseEvent(e){let t,i=this.safeList(e,"markets",[]),s=[],r=!1,a=i.length;for(let t=0;t<a;t++){let a=this.parseTopicMarket(i[t],e);s.push(a),this.safeBool(a,"active",!1)&&(r=!0)}let o=this.safeString(e,"slug"),n=this.safeString(e,"title"),d=this.safeString(e,"endsAt"),h=this.safeString(e,"createdAt"),c=this.safeString(e,"status"),l=r;return 0===a&&(l="REGISTERED"===c||"OPEN"===c),void 0!==c&&(t="RESOLVED"===c||"SETTLED"===c),{id:o,slug:o,event:void 0!==o?this.shortenSlug(o):void 0,title:n,description:this.safeString(e,"description"),markets:s,active:l,url:void 0,image:this.safeString(e,"imageUrl"),created:this.parse8601(h),createdDatetime:h,end:this.parse8601(d),endDatetime:d,category:this.safeString(e,"marketVariant"),resolved:t,info:e}}stripPriceFormatting(e){if(void 0===e)return;let t="0123456789",i=this.stringToCharsArray(e),s=i.length,r="";for(let e=0;e<s;e++){let a=i[e],o=!0;if("$"===a)o=!1;else if(","===a){let r=e>0&&t.indexOf(i[e-1])>=0,a=e+1<s&&t.indexOf(i[e+1])>=0;o=!(r&&a)}o&&(r+=a)}return r}titleForMarketSymbol(e,t,i){return 1===i&&void 0!==e?e:this.stripPriceFormatting(t)}parseTopicMarket(e,t){let i,s,r=this.safeString(e,"id"),a=this.safeString(e,"categorySlug");void 0!==a&&(i=this.shortenSlug(a));let o=this.safeString(e,"title",r),d=this.safeList(t,"markets",[]).length,h=this.titleForMarketSymbol(a,o,d),c=this.slugToMarketSymbol(a,h),l=this.safeString(e,"tradingStatus"),u=this.safeString(e,"status"),f="OPEN"===l;void 0===l&&(f="REGISTERED"===u||"OPEN"===u);let p=this.safeString(t,"endsAt"),m=this.safeString(e,"feeRateBps","200"),g=this.parseNumber(n.Y.stringDiv(m,"10000")),v=this.safeString(e,"decimalPrecision","2"),y={amount:.01,price:this.parseNumber(this.parsePrecision(v))},b=this.safeList(e,"outcomes",[]),w=[],k=b.length;for(let e=0;e<k;e++){let t,a,o=b[e],n=this.safeStringUpper(o,"name"),d=this.stripPriceFormatting(n),h=this.safeString(o,"onChainId"),l=c+":"+d,u=this.safeString(o,"status");void 0!==u&&((t="WON"===u)?(a=1,s=l):a=0);let p=a;w.push({id:h,outcomeId:h,outcome:l,market:c,event:i,label:d,price:void 0,active:f,winner:t,settleFraction:p,precision:y,info:this.extend({marketId:r},o)})}let S=s,O="USDT",T="binary";k>2&&(T="categorical");let P=this.safeString(e,"createdAt");return{id:r,market:c,base:O,quote:O,settle:void 0,baseId:r,quoteId:O,settleId:void 0,type:"prediction",marketType:T,executionModel:"clob",collateral:O,spot:!1,margin:!1,swap:!1,future:!1,option:!1,prediction:!0,active:f,resolved:"RESOLVED"===u||"SETTLED"===u,resolvedOutcome:S,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:this.parse8601(p),expiryDatetime:p,strike:void 0,optionType:void 0,taker:g,maker:0,percentage:!0,tierBased:!1,feeSide:"get",precision:y,limits:{leverage:{min:1,max:1},amount:{min:void 0,max:void 0},price:{min:.01,max:.99},cost:{min:1,max:void 0}},outcomes:w,info:e,created:this.parse8601(P)}}async fetchOrderBook(e,t,i={}){await this.loadOutcome(e);let s=this.outcome(e),r=this.safeDict(s,"info",{}),a={id:this.safeString(r,"marketId")},o=await this.predictfunGetV1MarketsIdOrderbook(this.extend(a,i)),d=this.safeDict(o,"data",{}),h=this.safeInteger(d,"updateTimestampMs"),c=this.safeInteger(r,"indexSet"),l=this.safeOutcomeSymbol(e,s);if(1===c){let e=this.parseOrderBook(d,l,h,"bids","asks",0,1);return this.safePredictionOrderBook(e,s)}{let e=this.safeList(d,"bids",[]),t=this.safeList(d,"asks",[]),i=[],r=[];for(let t=0;t<e.length;t++){let i=this.safeList(e,t),s=this.safeString(i,0),a=this.parseNumber(this.safeString(i,1)),o=this.parseNumber(n.Y.stringSub("1",s));r.push([o,a])}for(let e=0;e<t.length;e++){let s=this.safeList(t,e),r=this.safeString(s,0),a=this.parseNumber(this.safeString(s,1)),o=this.parseNumber(n.Y.stringSub("1",r));i.push([o,a])}let a={bids:this.sortBy(i,0,!0),asks:this.sortBy(r,0),timestamp:h,datetime:this.iso8601(h),nonce:void 0};return this.safePredictionOrderBook(a,s)}}async fetchTicker(e,t={}){await this.loadOutcome(e);let i=this.outcome(e),s=this.safeDict(i,"info",{}),r={id:this.safeString(s,"marketId")},a=await this.predictfunGetV1MarketsId(this.extend(r,t)),o=this.safeDict(a,"data",{});return this.parsePredictionTicker(o,i)}parsePredictionTicker(e,t){let i=this.safeDict(t,"info",{}),s=this.safeInteger(i,"indexSet"),r=this.safeList(e,"outcomes",[]),a=r.length,o={},n=!1;for(let e=0;e<a;e++){let t=r[e];if(this.safeInteger(t,"indexSet")===s){o=t,n=!0;break}}if(!n){let e=this.safeOutcomeSymbol(void 0,t);throw new h.BadSymbol(this.id+" fetchTicker() did not find "+e+" among the outcomes of its market")}let d=this.safeDict(o,"bestBid",{}),c=this.safeDict(o,"bestAsk",{});return this.safePredictionTicker({outcome:this.safeOutcomeSymbol(void 0,t),outcomeId:this.safeString(t,"outcomeId"),label:this.safeString(t,"label"),market:this.safeString(t,"market"),event:this.safeString(t,"event"),timestamp:void 0,datetime:void 0,high:void 0,low:void 0,bid:this.safeNumber(d,"price"),bidVolume:this.safeNumber(d,"size"),ask:this.safeNumber(c,"price"),askVolume:this.safeNumber(c,"size"),open:void 0,close:void 0,last:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:void 0,quoteVolume:void 0,info:e})}async fetchMyTrades(e,t,i,s={}){let r,a=this.safeString(s,"signerAddress",this.walletAddress);if(void 0===a)throw new h.ArgumentsRequired(this.id+' fetchMyTrades() requires a walletAddress, or a "signerAddress" parameter for any other address');let o={signerAddress:a};if(void 0!==e){await this.loadOutcome(e),r=this.outcome(e);let t=this.safeDict(r,"info",{});o.marketId=this.safeString(t,"marketId")}let n=this.omit(s,"signerAddress"),d=await this.predictfunGetV1OrdersMatches(this.extend(o,n)),c=this.safeList(d,"data",[]),l=a.toLowerCase(),u=[],f=c.length;for(let e=0;e<f;e++){let t=c[e],i=this.safeDict(t,"taker",{});if(this.safeStringLower(i,"signer")===l){let e=this.extend(i,{role:"taker",takerOrMaker:"taker",type:"market"});u.push(this.extend(t,{partyToParse:e}))}let s=this.safeList(t,"makers",[]),r=s.length;for(let e=0;e<r;e++){let i=s[e];if(this.safeStringLower(i,"signer")===l){let e=this.extend(i,{role:"maker",takerOrMaker:"maker",type:"limit"});u.push(this.extend(t,{partyToParse:e}))}}}return this.parsePredictionTrades(u,r,t,i)}async fetchTrades(e,t,i,s={}){await this.loadOutcome(e);let r=this.outcome(e),a=this.safeDict(r,"info",{}),o={marketId:this.safeString(a,"marketId")},n=await this.predictfunGetV1OrdersMatches(this.extend(o,s)),d=this.safeList(n,"data",[]),h=[],c=d.length;for(let e=0;e<c;e++){let t=this.safeDict(d,e),i=this.safeDict(t,"taker",{}),s=this.safeDict(i,"outcome",{}),r=this.safeInteger(s,"indexSet"),o=this.safeInteger(a,"indexSet"),n=this.safeDict(t,"taker",{});if(r===o){let e={role:"taker",type:"market"};n=this.extend(n,e),h.push(this.extend(t,{partyToParse:n}))}else{let e=this.safeList(t,"makers",[]),i=e.length,s={role:"maker",type:"limit"};for(let r=0;r<i;r++){let i=e[r],a=this.safeDict(i,"outcome",{});this.safeInteger(a,"indexSet")===o&&(n=i,n=this.extend(n,s),h.push(this.extend(t,{partyToParse:n})))}}}return this.parsePredictionTrades(h,r,t,i)}parsePredictionTrade(e,t){let i,s,r,a=this.safeDict(e,"partyToParse",{}),o=this.safeDict(a,"outcome",{}),d=this.safeString(o,"onChainId"),h=this.outcomeForToken(d,t),c=this.safeString(a,"role"),l=this.safeString(a,"price");"taker"===c&&(l=this.safeString(e,"priceExecuted",l)),l=n.Y.stringDiv(l,"1000000000000000000");let u=this.safeString(a,"amount");u=n.Y.stringDiv(u,"1000000000000000000");let f=this.safeStringLower(a,"quoteType");"bid"===f?i="buy":"ask"===f&&(i="sell"),s=this.safeString(a,"hash");let p=this.safeDict(a,"fee");if(void 0!==p){let e=this.safeString(p,"type"),t=this.safeString(p,"amount");r={currency:"COLLATERAL"===e?"USDT":void 0,cost:this.parseNumber(n.Y.stringDiv(t,"1000000000000000000"))}}let m=this.parse8601(this.safeString(e,"executedAt"));return this.safePredictionTrade({id:this.safeString(e,"settlementId"),order:s,timestamp:m,datetime:this.iso8601(m),outcome:this.safeOutcomeSymbol(void 0,h),outcomeId:this.safeString(h,"outcomeId"),label:this.safeString(h,"label"),market:this.safeString(h,"market"),type:this.safeString(a,"type"),side:i,takerOrMaker:this.safeString(a,"takerOrMaker"),price:this.parseNumber(l),amount:this.parseNumber(u),cost:void 0,fee:r,info:this.omit(e,"partyToParse")})}setSandboxMode(e){let t=this.safeBool(this.options,"sandboxMode",!1);super.setSandboxMode(e),this.options.sandboxMode=e,this.options.chainId=e?97:56,this.requiredCredentials.apiKey=!e,t!==e&&(e?(this.options.backupJwtToken=this.safeString(this.options,"jwtToken"),this.options.backupJwtTokenExpiresAt=this.safeInteger(this.options,"jwtTokenExpiresAt",0),this.options.jwtToken=void 0,this.options.jwtTokenExpiresAt=0):(this.options.jwtToken=this.safeString(this.options,"backupJwtToken"),this.options.jwtTokenExpiresAt=this.safeInteger(this.options,"backupJwtTokenExpiresAt",0),this.options.backupJwtToken=void 0,this.options.backupJwtTokenExpiresAt=0))}hashMessage(e){let t=this.encode(e),i=this.binaryLength(t),r=this.base16ToBinary("19"),a=this.base16ToBinary("0a"),o=this.binaryConcat(r,this.encode("Ethereum Signed Message:"),a,this.encode(this.numberToString(i)));return"0x"+this.hash(this.binaryConcat(o,t),s.lY,"hex")}signHash(e,t){let i=(0,o.h1)(e.slice(-64),t.slice(-64),r.bI,void 0),s=i.r,a=i.s;return("0x"+s.padStart(64,"0")+a.padStart(64,"0")+this.intToBase16(this.sum(27,i.v))).toLowerCase()}async authenticate(e={}){if(void 0===this.walletAddress||void 0===this.privateKey)throw new h.ArgumentsRequired(this.id+" authenticate() requires a walletAddress and a privateKey");let t=this.milliseconds(),i=this.safeString(this.options,"jwtToken"),s=this.safeInteger(this.options,"jwtTokenExpiresAt",0);if(void 0!==i&&t<s)return i;let r=await this.predictfunGetV1AuthMessage(e),a=this.safeDict(r,"data",{}),o=this.safeString(a,"message");if(void 0===o)throw new h.AuthenticationError(this.id+' authenticate() got an auth reply without the "message" field to sign');let n=this.signHash(this.hashMessage(o),this.privateKey),d={signer:this.walletAddress,message:o,signature:n},c=await this.predictfunPostV1Auth(d),l=this.safeDict(c,"data",{}),u=this.safeString(l,"token");if(void 0===u)throw new h.AuthenticationError(this.id+" authenticate() did not return a token");this.options.jwtToken=u;let f=this.safeInteger(this.options,"tokenExpiresIn",864e5);return this.options.jwtTokenExpiresAt=this.sum(t,f),u}signPredictfunOrder(e,t,i){let r=this.safeInteger(this.options,"chainId",56),a=this.exchangeAddress(t,i),o=this.ethEncodeStructuredData({name:"predict.fun CTF Exchange",version:"1",chainId:r,verifyingContract:a},{Order:[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"signer",type:"address"},{name:"taker",type:"address"},{name:"tokenId",type:"uint256"},{name:"makerAmount",type:"uint256"},{name:"takerAmount",type:"uint256"},{name:"expiration",type:"uint256"},{name:"nonce",type:"uint256"},{name:"feeRateBps",type:"uint256"},{name:"side",type:"uint8"},{name:"signatureType",type:"uint8"}]},e),n="0x"+this.hash(o,s.lY,"hex");return{hash:n,signature:this.signHash(n,this.privateKey)}}async createOrder(e,t,i,s,r,a={}){await this.authenticate(),await this.loadOutcome(e);let o=this.outcome(e),d=this.safeString(o,"outcomeId");if(void 0===d)throw new h.ArgumentsRequired(this.id+" createOrder() could not resolve the on chain token id of "+e);let c="LIMIT";"market"===t&&(c="MARKET");let l="MARKET"===c;if(!l&&void 0===r)throw new h.ArgumentsRequired(this.id+' createOrder() requires a "price" argument for a limit order');let u="buy"===i,f=this.numberToString(s),p=this.numberToString(r),m=p,[g,v]=this.handleOptionBoolAndParams(a,"createOrder","warnOnMarketOrderWithoutPrice",!0);if(void 0===r){if(g)throw new h.ArgumentsRequired(this.id+' createOrder() market orders require a "price" argument. To use default values turn "warnOnMarketOrderWithoutPrice" off in options');m=u?this.numberToString(this.safeNumber(this.options,"marketBuyPrice",.99)):this.numberToString(this.safeNumber(this.options,"marketSellPrice",.01))}let y=n.Y.stringMul(f,"1000000000000000000"),b=n.Y.stringMul(m,"1000000000000000000"),w=n.Y.stringMul(m,y),k=y,S=w;u&&(k=w,S=y);let O=this.safeString(v,"slippageBps","0");n.Y.stringGt(O,"0")&&(u?k=n.Y.stringMin(n.Y.stringDiv(n.Y.stringMul(k,n.Y.stringAdd("10000",O)),"10000"),y):S=n.Y.stringMax(n.Y.stringDiv(n.Y.stringMul(S,n.Y.stringSub("10000",O)),"10000"),"0"));let T=this.safeString(o,"market"),P=this.safeDict(this.markets,T,{}),I=this.safeDict(P,"info",{}),A=this.safeString(I,"feeRateBps","200"),x=this.safeString(v,"feeRateBps",A),M=this.safeBool(I,"isNegRisk",!1),_=this.safeBool(v,"isNegRisk",M),C=this.safeBool(I,"isYieldBearing",!1),B=this.safeBool(v,"isYieldBearing",C),E=this.safeInteger(this.options,"defaultExpiration",3600),R=E,L=this.safeInteger(v,"expiration");if(void 0===L){l&&(R=this.safeInteger(this.options,"marketOrderExpiration",E));let e=this.seconds();L=this.sum(e,R)}let N=this.incrementingNonce(),D=this.safeString(v,"salt",this.numberToString(N)),[q,F]=this.handleOptionAndParams(v,"createOrder","taker","0x0000000000000000000000000000000000000000"),V={salt:D,maker:this.walletAddress,signer:this.walletAddress,taker:q,tokenId:d,makerAmount:this.decimalToPrecision(k,0,0,2),takerAmount:this.decimalToPrecision(S,0,0,2),expiration:L,nonce:this.safeString(F,"nonce","0"),feeRateBps:x,side:+!u,signatureType:0},G=this.signPredictfunOrder(V,_,B),H={order:this.extend(V,{hash:this.safeString(G,"hash"),signature:this.safeString(G,"signature")}),pricePerShare:this.decimalToPrecision(b,0,0,2),strategy:c},U=this.safeBool(F,"isPostOnly",!1),[W,j]=this.handlePostOnly(l,U,F);W&&(H.isPostOnly=W),"FOK"===this.safeStringUpper(j,"timeInForce")&&(H.isFillOrKill=!0);let K=this.safeStringUpper(j,"selfTradePrevention");void 0!==K&&(H.selfTradePrevention=K);let z=this.omit(j,["isPostOnly","timeInForce","isFillOrKill","feeRateBps","isNegRisk","isYieldBearing","slippageBps","salt","nonce","expiration","selfTradePrevention","taker"]),Y=await this.predictfunPostV1Orders(this.extend({data:H},z)),X=this.safeDict(Y,"data",{});return this.safePredictionOrder({id:this.safeString2(X,"orderHash","hash"),clientOrderId:void 0,info:Y,timestamp:void 0,datetime:void 0,status:void 0,outcome:this.safeString(o,"outcome",e),outcomeId:this.safeString(o,"outcomeId"),label:this.safeString(o,"label"),market:this.safeString(o,"market"),event:this.safeString(o,"event"),type:t,side:i,price:this.parseNumber(p),amount:this.parseNumber(f),filled:void 0,remaining:void 0,cost:void 0,fee:void 0,trades:[]})}async fetchPositions(e,t={}){let i,s=0;void 0!==e&&(s=e.length,await this.loadOutcomes(e));let r=this.safeString(t,"address");if(void 0!==r){let e=this.omit(t,"address");i=await this.predictfunGetV1PositionsAddress(this.extend({address:r},e))}else await this.authenticate(),i=await this.predictfunGetV1Positions(t);let a=this.safeList(i,"data",[]),o=this.parsePredictionPositions(a);if(0===s)return o;let n={},d=this.toArray(e);for(let e=0;e<s;e++){let t=this.outcome(d[e]);n[this.safeString(t,"outcomeId","")]=!0}let h=[],c=o.length;for(let e=0;e<c;e++){let t=o[e],i=this.safeString(t,"outcomeId");void 0!==i&&i in n&&h.push(t)}return h}async fetchPosition(e,t={}){await this.loadOutcome(e);let i=this.outcome(e),s=this.safeDict(i,"info",{}),r={marketId:this.safeString(s,"marketId")},a=await this.fetchPositions([e],this.extend(r,t));return this.safeDict(a,0)}parsePredictionPosition(e,t){let i,s,r,a,o,d,h=this.safeDict(e,"outcome",{}),c=this.safeDict(e,"market",{}),l=this.safeString(h,"onChainId"),u=this.outcomeForToken(l,t),f=n.Y.stringDiv(this.safeString(e,"amount"),"1000000000000000000"),p=this.safeString(e,"averageBuyPriceUsd"),m=this.safeString(e,"valueUsd"),g=this.safeString(e,"pnlUsd"),v=n.Y.stringMul(p,f);void 0!==m&&void 0!==f&&n.Y.stringGt(f,"0")&&(i=n.Y.stringDiv(m,f)),void 0!==g&&void 0!==v&&n.Y.stringGt(v,"0")&&(s=n.Y.stringMul(n.Y.stringDiv(g,v),"100"));let y=this.safeString(h,"status"),b=this.safeString(c,"status"),w="WON"===y||"LOST"===y,k=w||"RESOLVED"===b||"SETTLED"===b;w&&(a=(r="WON"===y)?"1":"0",o=r?f:"0");let S=g;return k&&(d=g,S=void 0),this.safePredictionPosition({id:this.safeString(e,"id"),timestamp:void 0,datetime:void 0,contracts:this.parseNumber(f),contractSize:1,side:"long",notional:this.parseNumber(m),unrealizedPnl:this.parseNumber(S),realizedPnl:this.parseNumber(d),collateral:this.parseNumber(v),entryPrice:this.parseNumber(p),markPrice:this.parseNumber(i),lastPrice:void 0,percentage:this.parseNumber(s),resolved:k,won:r,settleFraction:this.parseNumber(a),payout:this.parseNumber(o),outcome:this.safeOutcomeSymbol(void 0,u),outcomeId:this.safeString(u,"outcomeId",l),label:this.safeString(u,"label",this.safeStringUpper(h,"name")),market:this.safeString(u,"market"),event:this.safeString(u,"event"),info:e})}async cancelOrder(e,t,i={}){let s=await this.cancelOrders([e],t,i),r=this.safeDict(s,0);if(void 0===r)throw new h.OrderNotFound(this.id+" cancelOrder() could not remove "+e);return r}async cancelOrders(e,t,i={}){let s;void 0!==t&&(await this.loadOutcome(t),s=this.outcome(t));let r=e.length;if(0===r)throw new h.ArgumentsRequired(this.id+" cancelOrders() requires at least one order hash");if(r>100)throw new h.BadRequest(this.id+" cancelOrders() takes at most 100 order hashes per call");await this.authenticate();let a=await this.predictfunPostV1OrdersRemoveByHash(this.extend({data:{hashes:e}},i)),o=this.safeList(a,"rejected",[]);if(o.length>0)throw new h.OrderNotFound(this.id+" cancelOrders() was refused for "+this.json(o));let n=this.safeList(a,"removed",[]),d=this.safeList(a,"noop",[]),c=[],l=n.length;for(let e=0;e<l;e++)c.push(this.extend(a,{orderHash:n[e],status:"CANCELLED"}));let u=d.length;for(let e=0;e<u;e++)c.push(this.extend(a,{orderHash:d[e]}));return this.parsePredictionOrders(c,s)}async fetchOrder(e,t,i={}){let s;await this.authenticate(),void 0!==t&&(await this.loadOutcome(t),s=this.outcome(t));let r=await this.predictfunGetV1OrdersHash(this.extend({hash:e},i)),a=this.safeDict(r,"data",{});return this.parsePredictionOrder(a,s)}async fetchOpenOrders(e,t,i,s={}){return await this.fetchOrdersHelper(e,t,i,this.extend({status:"OPEN"},s))}async fetchClosedOrders(e,t,i,s={}){return await this.fetchOrdersHelper(e,t,i,this.extend({status:"FILLED"},s))}async fetchOrdersHelper(e,t,i,s={}){let r;void 0!==e&&(await this.loadOutcome(e),r=this.outcome(e)),await this.authenticate();let a=await this.predictfunGetV1Orders(this.extend({},s)),o=this.safeList(a,"data",[]);return this.parsePredictionOrders(o,r,t,i)}parsePredictionOrder(e,t){let i,s,r=this.safeDict2(e,"order","data"),a=this.safeString2(e,"hash","orderHash"),o=this.safeString(r,"hash",a),d=this.safeString(r,"tokenId"),h=this.outcomeForToken(d,t),c=this.safeString(r,"side");"0"===c||"Bid"===c?i="buy":("1"===c||"Ask"===c)&&(i="sell");let l=this.safeString(r,"makerAmount"),u=this.safeString(r,"takerAmount"),f=l,p=u;"buy"===i&&(f=u,p=l);let m=n.Y.stringDiv(f,"1000000000000000000"),g=n.Y.stringDiv(p,"1000000000000000000");"limit"===this.safeStringLower(e,"strategy")&&(s=n.Y.stringDiv(g,m));let v=this.safeString(e,"amountFilled"),y=n.Y.stringDiv(v,"1000000000000000000"),b=n.Y.stringMul(y,s);return this.safePredictionOrder({id:o,clientOrderId:void 0,timestamp:void 0,datetime:void 0,status:this.parseOrderStatus(this.safeString(e,"status")),type:this.safeStringLower(e,"strategy"),timeInForce:void 0,side:i,price:s,amount:m,filled:y,remaining:void 0,cost:b,fee:void 0,postOnly:this.safeBool(e,"isPostOnly"),trades:void 0,outcome:this.safeOutcomeSymbol(d,h),outcomeId:this.safeString(h,"outcomeId",d),label:this.safeString(h,"label"),market:this.safeString(h,"market"),event:this.safeString(h,"event"),info:e})}parseOrderStatus(e){return this.safeString({OPEN:"open",PENDING:"open",MATCHED:"closed",FILLED:"closed",CANCELLED:"canceled",CANCELED:"canceled",EXPIRED:"expired",REJECTED:"rejected"},e,e)}handleErrors(e,t,i,s,r,a,o,n,d){if(void 0===o||this.safeBool(o,"success",!0))return;let c=this.id+" "+a,l=this.safeString(o,"message");this.throwBroadlyMatchedException(this.exceptions.broad,l,c),401===e&&(this.options.jwtToken=void 0,this.options.jwtTokenExpiresAt=0);let u=this.safeString(o,"error");if(this.throwExactlyMatchedException(this.exceptions.exact,u,c),400===e)throw new h.BadRequest(c);throw new h.ExchangeError(c)}exchangeAddress(e,t){let i=this.safeInteger(this.options,"chainId",56),s=this.safeDict(this.options,"exchanges",{}),r=this.safeDict(s,this.numberToString(i),{}),a="CTF_EXCHANGE";return e&&t?a="YIELD_BEARING_NEG_RISK_CTF_EXCHANGE":e?a="NEG_RISK_CTF_EXCHANGE":t&&(a="YIELD_BEARING_CTF_EXCHANGE"),this.safeString(r,a)}conditionalTokensAddress(e,t){let i=this.safeInteger(this.options,"chainId",56),s=this.safeDict(this.options,"conditionalTokens",{}),r=this.safeDict(s,this.numberToString(i),{}),a="CONDITIONAL_TOKENS";return e&&t?a="YIELD_BEARING_NEG_RISK_CONDITIONAL_TOKENS":e?a="NEG_RISK_CONDITIONAL_TOKENS":t&&(a="YIELD_BEARING_CONDITIONAL_TOKENS"),this.safeString(r,a)}adapterAddress(e){let t=this.safeInteger(this.options,"chainId",56),i=this.safeDict(this.options,"adapters",{}),s=this.safeDict(i,this.numberToString(t),{}),r="NEG_RISK_ADAPTER";return e&&(r="YIELD_BEARING_NEG_RISK_ADAPTER"),this.safeString(s,r)}signEvmTransaction(e,t){let i=this.rlpEncodeList([]),a=[this.rlpEncodeBytes(this.intToRlpHex(this.safeInteger(e,"chainId"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"nonce"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"maxPriorityFeePerGas"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"maxFeePerGas"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"gasLimit"))),this.rlpEncodeBytes(this.remove0xPrefix(this.safeString(e,"to"))),this.rlpEncodeBytes(this.hexToRlpBytes(this.safeString(e,"value","0x0"))),this.rlpEncodeBytes(this.remove0xPrefix(this.safeString(e,"data","0x"))),i],n="02"+this.rlpEncodeList(a),d=this.hash(this.base16ToBinary(n),s.lY,"hex"),h=(0,o.h1)(d,this.remove0xPrefix(t),r.bI,void 0),c=this.safeString(h,"r"),l=this.safeString(h,"s");c=this.padHexToEven(c),l=this.padHexToEven(l);let u=this.safeInteger(h,"v"),f=[];for(let e=0;e<a.length;e++)f.push(a[e]);return f.push(this.rlpEncodeBytes(this.intToRlpHex(u))),f.push(this.rlpEncodeBytes(c)),f.push(this.rlpEncodeBytes(l)),"0x02"+this.rlpEncodeList(f)}async approve(e,t={}){if(void 0===this.privateKey)throw new h.ArgumentsRequired(this.id+" approve() requires a privateKey to sign the on-chain transaction");let i=this.safeStringLower(t,"side","buy"),s=this.safeInteger(this.options,"chainId",56),r=this.numberToString(s),a=this.safeDict(this.options,"rpcUrls",{}),o=this.safeString(t,"rpcUrl",this.safeString(a,r)),d=this.safeString(t,"owner",this.walletAddress);void 0===d&&(d=this.ethGetAddressFromPrivateKey(this.privateKey));let c=this.safeString(t,"gasLimit","0x186a0"),l=!1,u=!1;if(void 0!==e){await this.loadOutcome(e);let t=this.outcome(e),i=this.safeString(t,"market"),s=this.safeDict(this.markets,i,{}),r=this.safeDict(s,"info",{});l=this.safeBool(r,"isNegRisk",!1),u=this.safeBool(r,"isYieldBearing",!1)}if("sell"===i){let i=this.safeString(t,"token",this.conditionalTokensAddress(l,u)),a=[],n=this.safeString(t,"spender");if(void 0!==n)a.push(n);else if(void 0===e)throw new h.ArgumentsRequired(this.id+' approve() requires an "outcome" to resolve the contracts to approve for selling, or an explicit "spender" parameter');else a.push(this.exchangeAddress(l,u)),l&&a.push(this.adapterAddress(u));if(void 0===o||void 0===i)throw new h.ArgumentsRequired(this.id+' approve() could not resolve the "rpcUrl" or the conditional tokens for chain '+r);let f=this.safeBool(t,"approved",!0),p="0000000000000000000000000000000000000000000000000000000000000000";f&&(p="0000000000000000000000000000000000000000000000000000000000000001");let m=[],g=a.length;for(let e=0;e<g;e++){let t=a[e];if(void 0===t)throw new h.ArgumentsRequired(this.id+" approve() could not resolve the operator to approve for chain "+r);let n="0xa22cb465"+this.padHexAddress(t)+p,l=await this.sendEvmTransaction(o,s,d,i,"0x0",n,c),u=await this.waitForTransactionReceipt(o,l);m.push(u)}return m}let f=this.safeDict(this.options,"collateral",{}),p=this.safeString(t,"token",this.safeString(f,r)),m=this.safeString(t,"spender");if(void 0===m){if(void 0===e)throw new h.ArgumentsRequired(this.id+' approve() requires an "outcome" to resolve the exchange to approve, or an explicit "spender" parameter');m=this.exchangeAddress(l,u)}if(void 0===o||void 0===p||void 0===m)throw new h.ArgumentsRequired(this.id+' approve() could not resolve the "rpcUrl", the "token" or the "spender" for chain '+r);let g="ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",v=this.safeString(t,"amount");if(void 0!==v){let e=n.Y.stringMul(v,"1000000000000000000"),t=this.decimalToPrecision(e,0,0,2);g=this.intToBase16(this.convertToBigInt(t)).padStart(64,"0")}let y="0x095ea7b3"+this.padHexAddress(m)+g,b=await this.sendEvmTransaction(o,s,d,p,"0x0",y,c);return await this.waitForTransactionReceipt(o,b)}async watchOrderBook(e,t,i={}){await this.loadOutcome(e);let s=this.outcome(e),r=this.safeDict(s,"info",{}),a=this.safeString(r,"marketId");if(void 0===a)throw new h.ArgumentsRequired(this.id+" watchOrderBook() could not resolve the market id of "+e);let o=this.safeOutcomeSymbol(void 0,s),n="predictOrderbook/"+a,d=this.requestId(),c={id:this.numberToString(d),topic:n,subscribeHash:n,messageHashes:this.orderBookMessageHashes(a)},l=this.socketUrl();return(await this.watch(l,"orderbook::"+o,this.extend({method:"subscribe",requestId:d,params:[n]},i),n,c)).limit()}async unWatchOrderBook(e,t={}){await this.loadOutcome(e);let i=this.outcome(e),s=this.safeDict(i,"info",{}),r=this.safeString(s,"marketId");if(void 0===r)throw new h.ArgumentsRequired(this.id+" unWatchOrderBook() could not resolve the market id of "+e);let a="predictOrderbook/"+r,o=this.outcomesByMarketId(r),n=o.length,d=[],c=[],l=[];for(let e=0;e<n;e++){let t=this.safeString(o[e],"outcome");void 0!==t&&(d.push(t),c.push("orderbook::"+t),l.push("unsubscribe::orderbook::"+t))}let u=this.requestId(),f={unsubscribe:!0,id:this.numberToString(u),topic:"orderbook",symbols:d,subMessageHashes:c,messageHashes:l,subscribeHash:a},p="unsubscribe::orderbook::"+this.safeOutcomeSymbol(void 0,i),m=this.socketUrl();return await this.watch(m,p,this.extend({method:"unsubscribe",requestId:u,params:[a]},t),p,f)}orderBookMessageHashes(e){let t=this.outcomesByMarketId(e),i=t.length,s=[];for(let e=0;e<i;e++){let i=this.safeString(t[e],"outcome");void 0!==i&&s.push("orderbook::"+i)}return s}handleSubscriptionError(e,t,i){let s=this.safeDict(t,"error",{}),r=new h.ExchangeError(this.id+" subscribe request rejected "+this.json(s)),a=this.safeString(i,"subscribeHash");void 0!==a&&a in e.subscriptions&&delete e.subscriptions[a];let o=this.safeList(i,"messageHashes",[]);"walletEvents"===this.safeString(i,"topic")&&(o=this.walletEventMessageHashes(e));let n=o.length;if(0===n)throw r;for(let t=0;t<n;t++)e.reject(r,o[t])}handleUnSubscription(e,t){let i=this.safeList(t,"messageHashes",[]),s=this.safeList(t,"subMessageHashes",[]),r=i.length,a="walletEvents"===this.safeString(t,"topic");for(let t=0;t<r;t++)this.cleanUnsubscription(e,s[t],i[t],a);this.cleanCache(t);let o=this.safeString(t,"subscribeHash");void 0!==o&&o in e.subscriptions&&delete e.subscriptions[o];let n=s.length;for(let e=0;e<n;e++){let t=s[e];("orders"===t||"myTrades"===t)&&this.cleanCache({topic:t})}}async watchOrders(e,t,i,s={}){let r="orders",a=e;if(void 0!==a){await this.loadOutcome(a);let e=this.outcome(a);r="orders::"+(a=this.safeOutcomeSymbol(void 0,e))}else await this.loadOutcomes();let o=await this.watchWalletEvents(r,s),n=i;return this.newUpdates&&(n=o.getLimit(a,n)),this.filterByOutcomeSinceLimit(o,a,t,n,!0)}async watchMyTrades(e,t,i,s={}){let r="myTrades",a=e;if(void 0!==a){await this.loadOutcome(a);let e=this.outcome(a);r="myTrades::"+(a=this.safeOutcomeSymbol(void 0,e))}else await this.loadOutcomes();let o=await this.watchWalletEvents(r,s),n=i;return this.newUpdates&&(n=o.getLimit(a,n)),this.filterByOutcomeSinceLimit(o,a,t,n,!0)}async unWatchOrders(e,t={}){return await this.unWatchWalletEvents("orders",t)}async unWatchMyTrades(e,t={}){return await this.unWatchWalletEvents("myTrades",t)}async walletEventsTopic(){return"predictWalletEvents/"+await this.authenticate()}async watchWalletEvents(e,t={}){let i=await this.walletEventsTopic(),s=this.requestId(),r=this.socketUrl(),a=this.client(r),o={id:this.numberToString(s),topic:"walletEvents",subscribeHash:"walletEvents",messageHashes:this.walletEventMessageHashes(a,e)};return await this.watch(r,e,this.extend({method:"subscribe",requestId:s,params:[i]},t),"walletEvents",o)}walletEventMessageHashes(e,t){let i=["orders","myTrades"],s=Object.keys(e.futures),r=s.length;for(let e=0;e<r;e++){let t=s[e];(0===t.indexOf("orders::")||0===t.indexOf("myTrades::"))&&i.push(t)}return void 0===t||this.inArray(t,i)||i.push(t),i}async unWatchWalletEvents(e,t={}){let i=await this.walletEventsTopic(),s=this.requestId(),r={unsubscribe:!0,id:this.numberToString(s),topic:"walletEvents",symbols:[],subMessageHashes:["orders","myTrades"],messageHashes:["unsubscribe::orders","unsubscribe::myTrades"],subscribeHash:"walletEvents"},a="unsubscribe::"+e,o=this.socketUrl();return await this.watch(o,a,this.extend({method:"unsubscribe",requestId:s,params:[i]},t),a,r)}socketUrl(){let e=this.urls.api,t=this.safeString(e,"ws");if(void 0===t)throw new h.NotSupported(this.id+" does not have a sandbox websocket endpoint");if(void 0===this.apiKey)throw new h.AuthenticationError(this.id+" requires an apiKey for all methods - the venue answers the socket handshake with a 401 without one");return t+"?apiKey="+this.apiKey}requestId(){this.lockId();let e=this.safeInteger(this.options,"requestId",0),t=this.sum(e,1);return this.options.requestId=t,this.unlockId(),t}outcomeForToken(e,t){let i=this.safeString(t,"outcomeId");return void 0===e||i===e?this.safeOutcome(e,t):this.safeOutcome(e)}outcomesByMarketId(e){let t=[],i=this.outcomes;if(void 0===e||void 0===i)return t;let s=Object.keys(i),r=s.length;for(let a=0;a<r;a++){let r=i[s[a]],o=this.safeDict(r,"info",{});this.safeString(o,"marketId")===e&&t.push(r)}return t}handleOrderBook(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"marketId"),r=this.safeInteger(i,"updateTimestampMs"),a=this.safeList(i,"asks",[]),o=this.safeList(i,"bids",[]),d=[],h=[],c=[],l=[],u=o.length;for(let e=0;e<u;e++){let t=this.safeList(o,e),i=this.safeString(t,0),s=this.parseNumber(this.safeString(t,1));d.push([this.parseNumber(i),s]),l.push([this.parseNumber(n.Y.stringSub("1",i)),s])}let f=a.length;for(let e=0;e<f;e++){let t=this.safeList(a,e),i=this.safeString(t,0),s=this.parseNumber(this.safeString(t,1));h.push([this.parseNumber(i),s]),c.push([this.parseNumber(n.Y.stringSub("1",i)),s])}let p=this.outcomesByMarketId(s),m=p.length;for(let t=0;t<m;t++){let s=this.safeDict(p,t),a=this.safeDict(s,"info",{}),o=1===this.safeInteger(a,"indexSet"),n=this.safeString(s,"outcome");if(void 0!==n){n in this.orderbooks||(this.orderbooks[n]=this.orderBook({}));let t=this.orderbooks[n],a=d,u=h;o||(a=this.sortBy(c,0,!0),u=this.sortBy(l,0)),t.reset({bids:a,asks:u,timestamp:r,datetime:this.iso8601(r),outcome:n,outcomeId:this.safeString(s,"outcomeId"),market:this.safeString(s,"market"),nonce:this.safeInteger(i,"version")}),e.resolve(t,"orderbook::"+n)}}}handleWalletEvent(e,t){let i=this.safeDict(t,"data",{}),s=this.parseWalletEventOrder(i);this.handleWalletEventOrder(e,s),"orderTransactionSuccess"===this.safeString(i,"type")&&this.handleWalletEventTrade(e,i,s)}handleWalletEventOrder(e,t){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new d.$0(e)}let i=this.orders;i.append(t),e.resolve(i,"orders");let s=this.safeString(t,"outcome");void 0!==s&&e.resolve(i,"orders::"+s)}handleWalletEventTrade(e,t,i){let s=this.parseWalletEventTrade(t,i);if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new d.$0(e)}let r=this.myTrades;r.append(s),e.resolve(r,"myTrades");let a=this.safeString(s,"outcome");void 0!==a&&e.resolve(r,"myTrades::"+a)}walletEventOutcome(e){let t,i=this.safeString(e,"marketId"),s=this.safeInteger(e,"outcomeIndex"),r=this.outcomesByMarketId(i),a=r.length;for(let e=0;e<a;e++){let t=r[e],i=this.safeDict(t,"info",{});if(this.safeInteger(i,"indexSet")===s)return t}let o=this.safeString(e,"categorySlug");return void 0!==o&&(t=this.shortenSlug(o)),{outcome:void 0,outcomeId:void 0,market:void 0,label:this.stripPriceFormatting(this.safeStringUpper(e,"outcomeName")),event:t,info:e}}parseWalletEventOrder(e){let t,i,s,r=this.safeDict(e,"details",{}),a=this.walletEventOutcome(r),o=this.safeString(e,"type"),d=this.safeString(r,"quantity"),h=this.safeString(r,"quantityFilled");"orderAccepted"===o||"orderMarketMatchPlan"===o||"orderTransactionSubmitted"===o||"orderTransactionFailed"===o?t="open":"orderNotAccepted"===o?t="rejected":"orderExpired"===o?t="expired":"orderCancelled"===o?t="canceled":"orderTransactionSuccess"===o&&(t="open",void 0===d||void 0===h||n.Y.stringLt(h,d)||(t="closed"));let c=this.safeStringLower(r,"quoteType");"bid"===c?i="buy":"ask"===c&&(i="sell"),void 0!==d&&void 0!==h&&(s=n.Y.stringSub(d,h));let l=this.safeInteger(e,"timestamp");return this.safePredictionOrder({id:this.safeString2(e,"orderHash","orderId"),clientOrderId:void 0,timestamp:l,datetime:this.iso8601(l),lastTradeTimestamp:void 0,lastUpdateTimestamp:l,status:t,type:this.safeStringLower(r,"strategyType"),timeInForce:void 0,side:i,price:this.safeNumber(r,"price"),average:void 0,amount:this.parseNumber(d),filled:this.parseNumber(h),remaining:this.parseNumber(s),cost:this.safeNumber(r,"valueFilled"),fee:void 0,reduceOnly:void 0,postOnly:void 0,trades:[],outcome:this.safeOutcomeSymbol(void 0,a),outcomeId:this.safeString(a,"outcomeId"),label:this.safeString(a,"label"),market:this.safeString(a,"market"),event:this.safeString(a,"event"),info:e})}parseWalletEventTrade(e,t){let i,s,r=this.safeDict(e,"fill",{}),a=n.Y.stringDiv(this.safeString(r,"executedPriceWei"),"1000000000000000000"),o=n.Y.stringDiv(this.safeString(r,"executedSizeWei"),"1000000000000000000"),d=n.Y.stringDiv(this.safeString(r,"executedValueWei"),"1000000000000000000"),h=this.safeBool(e,"isMaker");void 0!==h&&(i=h?"maker":"taker");let c=this.safeDict(e,"fee");void 0!==c&&(s={currency:"COLLATERAL"===this.safeString(c,"type")?"USDT":void 0,cost:this.parseNumber(n.Y.stringDiv(this.safeString(c,"amountWei"),"1000000000000000000"))});let l=this.safeInteger(e,"timestamp");return this.safePredictionTrade({id:this.safeString(e,"settlementId"),order:this.safeString(e,"orderHash"),timestamp:l,datetime:this.iso8601(l),outcome:this.safeString(t,"outcome"),outcomeId:this.safeString(t,"outcomeId"),label:this.safeString(t,"label"),market:this.safeString(t,"market"),type:this.safeString(t,"type"),side:this.safeString(t,"side"),takerOrMaker:i,price:this.parseNumber(a),amount:this.parseNumber(o),cost:this.parseNumber(d),fee:s,info:e})}handleHeartbeat(e,t){this.spawn(this.pong,e,t)}async pong(e,t){let i={method:"heartbeat",data:this.safeInteger(t,"data")};try{await e.send(i)}catch(i){let t=new h.NetworkError(this.id+" pong failed - "+this.exceptionMessage(i));e.reset(t)}}handleMessage(e,t){if("R"===this.safeString(t,"type")){let i=this.safeString(t,"requestId"),s=this.indexBy(e.subscriptions,"id"),r=this.safeDict(s,i,{});return this.safeBool(t,"success",!1)?void(this.safeBool(r,"unsubscribe",!1)&&this.handleUnSubscription(e,r)):void this.handleSubscriptionError(e,t,r)}let i=this.safeString(t,"topic");if("heartbeat"===i)return void this.handleHeartbeat(e,t);if(void 0===i)return;let s=i.split("/"),r=this.safeString(s,0);"predictOrderbook"===r?this.handleOrderBook(e,t):"predictWalletEvents"===r&&this.handleWalletEvent(e,t)}nonce(){return this.milliseconds()}sign(e,t="predictfun",i="GET",s={},r,a){let o=this.safeBool(this.options,"sandboxMode",!1),n=this.apiKey;if(void 0===n&&!o)throw new h.AuthenticationError(this.id+' sign() requires the "apiKey" credential for all endpoints');let d="string"==typeof t?t:t[0],c=this.urls.api,l=this.safeString(c,d,c.predictfun)+"/"+this.implodeParams(e,s),u=this.omit(s,this.extractParams(e));"GET"===i&&Object.keys(u).length>0&&(l+="?"+this.urlencode(u));let f={};void 0===n||o||(f["x-api-key"]=n);let p=this.safeString(this.options,"jwtToken");void 0!==p&&this.inArray(e,["v1/orders","v1/orders/{hash}","v1/orders/remove","v1/orders/remove-by-hash","v1/account","v1/account/activity","v1/account/referral","v1/positions","v1/oauth/finalize","v1/oauth/orders","v1/oauth/orders/create","v1/oauth/orders/cancel","v1/oauth/positions"])&&(f.Authorization="Bearer "+p);let m=a;return"GET"!==i&&(o||this.checkRequiredCredentials(),f["Content-Type"]="application/json",m=this.json(s)),{url:l,method:i,body:m,headers:this.extend(void 0!==r?r:{},f)}}}i.d(t,{A:()=>c})},2214(e,t,i){"use strict";var s=i(6834),r=i(6885),a=i(7559),o=i(1093),n=i(7749),d=i(1697),h=i(1453);class c extends a.A{describe(){return this.deepExtend(super.describe(),{id:"sxbet",name:"SX Bet",countries:[],rateLimit:120,certified:!1,pro:!0,has:{CORS:void 0,spot:!1,margin:!1,swap:!1,future:!1,option:!1,approve:!0,cancelAllOrders:!0,cancelOrder:!0,cancelOrders:!0,createOrder:!0,fetchBalance:!0,fetchClosedOrders:!1,fetchEvent:!0,fetchEvents:!0,fetchMarkets:!0,fetchMyTrades:!0,fetchOHLCV:!1,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchPositions:!0,fetchSettlements:!0,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0,prediction:!0,watchMyTrades:!0,watchOrderBook:!0,watchOrders:!0,watchTicker:!0,watchTrades:!0},urls:{logo:"https://github.com/user-attachments/assets/6d1d1e37-2b9c-4011-93c6-c9c25cd2c2f7",api:{sxbet:"https://api.sx.bet",ws:"wss://realtime.sx.bet/connection/websocket"},test:{sxbet:"https://api.toronto.sx.bet",ws:"wss://realtime.toronto.sx.bet/connection/websocket"},www:"https://sx.bet",doc:["https://docs.sx.bet"]},api:{sxbet:{public:{get:{"metadata/obv3":{cost:1},"orderbook-v3/snapshot":{cost:1},"trades-v3/public":{cost:1},"markets/active":{cost:1},"markets/find":1,"markets/popular":1,"trades/consolidated":1,"trades/orders":1,"trades/portfolio/refunds":1,"fixture/active":1,"fixture/status":1,sports:1,leagues:1,"leagues/active":1,teams:1,"live-scores":1}},private:{get:{"user/realtime-token-v3/api-key":{cost:1},"user/proxy":{cost:1},"user/balance-v3":{cost:1},"user/transfer-to-proxy/pending":1,"user/transfer-to-proxy/status":1,"orders-v3":{cost:1},"orders-v3/{orderId}":{cost:1},"orders-v3/odds/best":{cost:1},"trades-v3":{cost:1},"fills-v3":{cost:1},"positions-v3":{cost:1}},delete:{"orders-v3":{cost:1},"orders-v3/event":{cost:1},"orders-v3/all":{cost:1}},post:{"orders-v3":{cost:1},"user/deploy-proxy":1,"user/transfer-to-proxy":{cost:1},"heartbeat/v3":1}}}},requiredCredentials:{apiKey:!0,secret:!1,walletAddress:!0,privateKey:!0},fees:{trading:{tierBased:!1,percentage:!0,maker:0,taker:0}},exceptions:{exact:{INSUFFICIENT_BALANCE:h.InsufficientFunds,INVALID_MARKET:h.BadRequest,ORDERS_ALREADY_EXIST:h.DuplicateOrderId,TOO_MANY_DIFFERENT_MARKETS:h.BadRequest,ORDERS_MUST_HAVE_IDENTICAL_MARKET:h.BadRequest,BAD_BASE_TOKEN:h.BadRequest,INSUFFICIENT_KYC:h.PermissionDenied,PROXY_NOT_DEPLOYED:h.AccountNotEnabled,INVALID_USER:h.AuthenticationError,BAD_AUTH:h.AuthenticationError,ERC20_PERMIT_BAD_SPENDER:h.BadRequest,BASE_TOKENS_NOT_SAME:h.BadRequest,MARKETS_NOT_SAME:h.BadRequest,DIRECTIONS_NOT_SAME:h.BadRequest,INVALID_ORDERS:h.OrderNotFillable,INVALID_ODDS:h.InvalidOrder,PERCENTAGEODDS_UNDEFINED_OR_MALFORMED:h.InvalidOrder,TOTAL_BET_SIZE_TOO_LOW:h.InvalidOrder,MATCH_STATE_INVALID:h.MarketClosed,PROXY_ACCOUNT_INVALID:h.BadRequest,RATE_LIMIT_ORDER_REQUEST_MARKET_COUNT:h.BadRequest,BOTH_SPORTXEVENTID_MARKETHASHES_PRESENT:h.BadRequest,BAD_MARKET_HASHES:h.BadRequest,"Order not found":h.OrderNotFound},broad:{"no longer supported":h.NotSupported,"must be":h.BadRequest,"Insufficient available balance":h.InsufficientFunds}},options:{marketsPageSize:100,maxMarketsPages:50,eventScopeParams:["leagueId","sportId"],chains:{4162:{rpcUrl:"https://rpc-rollup.sx.technology"},0x4bcc495:{rpcUrl:"https://rpc-rollup.toronto.sx.technology"}},approveDeadlineSeconds:7200,defaultOrderExpirySeconds:86400,bestOddsBatchSize:100,cancelOrdersBatchSize:100,tradesLimit:1e3,ordersLimit:1e3,myTradesLimit:1e3},streaming:{keepAlive:3e4}})}async fetchMarkets(e={}){let t=this.omit(e,["limit"]),i=this.safeInteger(e,"limit"),s=await this.fetchRawMarketsPaged(t,i),r=[],a=s.length;for(let e=0;e<a;e++)r.push(this.parseSxbetMarket(s[e]));let o=r.length;return void 0!==i&&o>i?this.arraySlice(r,0,i):r}async fetchRawMarketsPaged(e={},t){let i,s=this.safeInteger(this.options,"marketsPageSize",100),r=this.safeInteger(this.options,"maxMarketsPages",50),a=[],o=0;for(;;){let n={pageSize:s};void 0!==i&&(n.paginationKey=i);let d=await this.sxbetPublicGetMarketsActive(this.extend(n,e)),h=this.safeDict(d,"data",{}),c=this.safeList(h,"markets",[]),l=c.length;for(let e=0;e<l;e++)a.push(c[e]);i=this.safeString(h,"nextKey"),o=this.sum(o,1);let u=a.length;if(l<s||o>=r||void 0===i||void 0!==t&&u>=t)break}return a}filterRawMarketsByFixture(e,t){let i=[],s=e.length;for(let r=0;r<s;r++){let s=e[r];this.safeString(s,"sportXeventId")===t&&i.push(s)}return i}parseSxbetMarket(e){let t,i=this.safeString(e,"marketHash",""),s=this.safeString(e,"teamOneName"),r=this.safeString(e,"teamTwoName"),a=this.safeString(e,"outcomeOneName"),o=this.safeString(e,"outcomeTwoName"),n=this.shortenSlug(s+" "+r),d=this.parseToInt(i.length),h=i.slice(d-6),c=this.shortenSlug(a)+"_"+h,l=this.slugToMarketSymbol(n,c),u="ACTIVE"===this.safeStringUpper(e,"status");0!==this.safeInteger(e,"gameTime",0)&&(t=this.safeTimestamp(e,"gameTime"));let f=[a,o],p=[i,i+"-2"],m=[];for(let t=0;t<f.length;t++){let i=f[t],s=this.slugToOutcomeSymbol(n,c,i);m.push({id:p[t],outcomeId:p[t],outcome:s,market:l,label:i,active:u,winner:void 0,settleFraction:void 0,info:e})}return{id:i,market:l,base:"USDC",quote:"USDC",settle:void 0,baseId:i,quoteId:"USDC",settleId:void 0,type:"prediction",marketType:"binary",executionModel:"clob",spot:!1,margin:!1,swap:!1,future:!1,option:!1,prediction:!0,active:u,resolved:!1,resolvedOutcome:void 0,contract:!1,linear:void 0,inverse:void 0,contractSize:void 0,expiry:t,expiryDatetime:this.iso8601(t),strike:void 0,optionType:void 0,taker:0,maker:0,percentage:!0,tierBased:!1,feeSide:"get",precision:{amount:1e-6,price:.00125},limits:{leverage:{min:1,max:1},amount:{min:1,max:void 0},price:{min:0,max:1},cost:{min:1,max:void 0}},outcomes:m,info:e,created:void 0}}async fetchEvents(e={}){let t;this.requireEventQuery(e);let i=this.safeString2(e,"eventId","slug"),s=this.safeString(e,"leagueId"),r=this.safeString(e,"sportId"),a=this.parseSearchQueries(e),o=this.safeList(e,"tags",[]),n=o.length;for(let e=0;e<n;e++)a.push(o[e]);let d=this.omit(e,["eventId","slug","leagueId","sportId","query","queries","tags","status","sort","searchIn","limit"]);if(void 0!==i?(t=await this.fetchRawMarketsPaged(this.extend({sportXeventId:i},d),void 0),t=this.filterRawMarketsByFixture(t,i)):t=void 0!==s?await this.fetchRawMarketsPaged(this.extend({leagueId:s},d),void 0):void 0!==r?await this.fetchRawMarketsPaged(this.extend({sportId:r},d),void 0):await this.fetchRawMarketsPaged(d,void 0),a.length>0){let e=[],i=t.length;for(let s=0;s<i;s++)this.matchesEventQuery(t[s],a)&&e.push(t[s]);t=e}let h={},c=[],l=t.length;for(let e=0;e<l;e++){let i=t[e],s=this.safeString(i,"sportXeventId");void 0!==s&&(s in h||(h[s]=[],c.push(s)),h[s].push(i))}void 0===this.markets&&(this.markets=this.createSafeDictionary());let u=[],f=c.length;for(let e=0;e<f;e++){let t=c[e],i=this.parseEvent(t,h[t]),s=this.safeList(i,"markets",[]),r=s.length;for(let e=0;e<r;e++){let t=s[e];this.markets[t.market]=t}u.push(i)}this.populateOutcomes(),this.setEvents(u);let p=this.omit(e,["leagueId","sportId","query","queries","tags"]);return this.applyEventFetchParams(u,p,[])}async fetchEvent(e,t={}){let i=await this.fetchRawMarketsPaged(this.extend({sportXeventId:e},t),void 0);if(0===(i=this.filterRawMarketsByFixture(i,e)).length)throw new h.BadSymbol(this.id+" fetchEvent() could not find an active fixture "+e);let s=this.parseEvent(e,i);return this.indexEventOutcomes(s),this.setEvents([s]),s}matchesEventQuery(e,t){let i=[this.safeString(e,"teamOneName"),this.safeString(e,"teamTwoName"),this.safeString(e,"leagueLabel"),this.safeString(e,"sportLabel"),this.safeString(e,"outcomeOneName"),this.safeString(e,"outcomeTwoName")],s=t.length;for(let e=0;e<s;e++){let s=t[e].toLowerCase();if(""!==s)for(let e=0;e<i.length;e++){let t=i[e];if(void 0===t)continue;let r=t.toLowerCase();if(s.indexOf(r)>=0||r.indexOf(s)>=0)return!0}}return!1}parseEvent(e,t){let i,s,r,a,o,n,d=[],c=!1,l=t.length;for(let e=0;e<l;e++){let o=t[e],n=this.parseSxbetMarket(o);if(void 0===n)throw new h.ExchangeError(this.id+" parseEvent() could not resolve parsed market");d.push(n),!0===n.active&&(c=!0),void 0===s&&(s=this.safeString(o,"teamOneName"),r=this.safeString(o,"teamTwoName"),a=this.safeString(o,"leagueLabel"));let l=this.safeString(o,"gameTime");void 0!==l&&"0"!==l&&(void 0===i||l<i)&&(i=l)}let u=this.safeTimestamp({gameTime:i},"gameTime");return void 0!==s&&void 0!==r?(o=s+" vs "+r,n=this.shortenSlug(s+" "+r)):n=this.shortenSlug(e),{id:e,slug:e,event:n,title:o,description:void 0,category:a,tags:void 0,markets:d,mutuallyExclusive:!1,active:c,resolved:void 0,volume:void 0,liquidity:void 0,created:void 0,createdDatetime:void 0,end:u,endDatetime:this.iso8601(u),image:void 0,url:void 0,info:t}}async loadSxObv3Metadata(){let e=this.safeDict(this.options,"sxObv3Metadata");if(void 0!==e)return e;let t=await this.sxbetPublicGetMetadataObv3(),i=this.safeDict(t,"data",{});return this.options.sxObv3Metadata=i,i}roundOddsToLadder(e,t){let i=n.Y.stringDiv(t,"100000",10);return this.decimalToPrecision(e,1,i,4)}hashEip712Digest(e){return"0x"+this.hash(e,s.lY,"hex")}signDigest(e,t){let i=(0,o.h1)(e.slice(-64),t.slice(-64),r.bI,void 0),s=i.r,a=i.s;return"0x"+s.padStart(64,"0")+a.padStart(64,"0")+this.intToBase16(this.sum(27,i.v))}async fetchErc20Name(e,t){let i=await this.ethRpc(e,"eth_call",[{to:t,data:"0x06fdde03"},"latest"]),s=this.remove0xPrefix(i),r=s.slice(64,128),a=this.hexToInt(r),o=this.sum(128,2*a),n=s.slice(128,o);return this.decode(this.base16ToBinary(n))}hexToInt(e){let t=e.toLowerCase(),i=t.length,s=0;for(let e=0;e<i;e++){let i=t[e];s=16*s+"0123456789abcdef".indexOf(i)}return s}async fetchSxbetProxy(){let e=await this.sxbetPrivateGetUserProxy();return this.safeDict(e,"data",{})}async approve(e={}){this.checkRequiredCredentials();let t=this.safeNumber(e,"amount");if(void 0===t)throw new h.ArgumentsRequired(this.id+" approve() requires params.amount - the USDC amount to move into the proxy wallet");let i=await this.fetchSxbetProxy();if(!0!==this.safeBool(i,"deployed",!1)){await this.sxbetPrivatePostUserDeployProxy();for(let e=0;e<30;e++){await this.sleep(2e3);let e=await this.fetchSxbetProxy();if(this.safeBool(e,"deployed",!1))break}}let s=await this.loadSxObv3Metadata(),r=this.safeDict(s,"activeAsset",{}),a=this.safeInteger(s,"chainId"),o=this.safeString(r,"baseToken"),d=this.safeString(s,"transferToProxyExecutorAddress"),c=this.safeString(e,"tokenAddress",o);if(void 0===c)throw new h.BadRequest(this.id+" approve() could not resolve the base token address from /metadata/obv3");let[l,u]=this.handleOptionStringAndParams2(e,"approve","spender","transferToProxySpender",d);if(void 0===l)throw new h.BadRequest(this.id+" approve() could not resolve the transfer-to-proxy executor from /metadata/obv3 - pass params.spender");let f=this.safeDict(this.options,"chains",{}),p=this.safeDict(f,this.numberToString(a),{}),m=this.safeString(u,"rpcUrl",this.safeString(p,"rpcUrl"));if(void 0===m)throw new h.ArgumentsRequired(this.id+" approve() has no RPC endpoint configured for chainId "+this.numberToString(a)+" - pass params.rpcUrl");let g=this.walletAddress,v="0x7ecebe00"+this.padHexAddress(g),y=await this.ethRpc(m,"eth_call",[{to:c,data:v},"latest"]),b=this.hexToRlpBytes(y),w=""===b?"0":this.numberToString(this.hexToInt(b)),k=await this.fetchErc20Name(m,c),S=this.safeInteger(this.options,"approveDeadlineSeconds",7200),O=this.safeInteger(u,"deadline",this.sum(this.seconds(),S)),T=this.decimalToPrecision(n.Y.stringMul(this.numberToString(t),"1000000"),1,0,2),P=this.ethEncodeStructuredData({name:k,version:"1",chainId:a,verifyingContract:c},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:g,spender:l,value:T,nonce:w,deadline:O}),I=this.hashEip712Digest(P),A=this.signDigest(I,this.privateKey),x={owner:g,spender:l,tokenAddress:c,value:T,deadline:this.numberToString(O),signature:A},M=this.omit(u,["amount","tokenAddress","deadline","rpcUrl"]),_=await this.sxbetPrivatePostUserTransferToProxy(this.extend(x,M)),C=this.safeDict(_,"data",{});return{info:_,id:this.safeString(C,"sessionId")}}async createOrder(e,t,i,s,r,a={}){let o,d,c;this.checkRequiredCredentials(),await this.loadOutcome(e);let l=this.outcome(e);if("limit"!==t&&"market"!==t)throw new h.InvalidOrder(this.id+" createOrder() type must be 'limit' or 'market', got "+t);if(void 0===r)throw new h.ArgumentsRequired(this.id+" createOrder() requires a price - the implied probability of the requested outcome");if(!0===this.safeBool(a,"postOnly",!1))throw new h.NotSupported(this.id+" createOrder() does not support postOnly - GTC orders may cross on entry");if(void 0!==this.safeStringN(a,["triggerPrice","stopLossPrice","takeProfitPrice"]))throw new h.NotSupported(this.id+" createOrder() does not support trigger, stop-loss or take-profit orders");let u=this.safeString(l.info,"marketHash",""),f=this.safeString(l,"outcomeId"),p=f===u,m="buy"===i,g=m?p:!p,v=this.numberToString(r),y=m?v:n.Y.stringSub("1",v),b=await this.loadSxObv3Metadata(),w=this.safeDict(b,"domain",{}),k=this.safeDict(b,"activeAsset",{}),S=this.safeString(k,"baseToken"),O=this.numberToString(this.safeInteger(b,"oddsLadderStepSize",125)),T=this.roundOddsToLadder(y,O),P=this.decimalToPrecision(n.Y.stringMul(T,"100000000000000000000"),1,0,2),I=this.numberToString(s),A=this.decimalToPrecision(n.Y.stringMul(I,"1000000"),1,0,2),x=this.safeString(a,"salt",this.numberToString(this.milliseconds())),M=this.intToBase16(this.parseToInt(x)).padStart(64,"0"),_=this.safeInteger(this.options,"defaultOrderExpirySeconds",86400),C=this.safeInteger(a,"expiry",this.sum(this.seconds(),_)),B="IOC";"limit"===t&&(B="GTC");let[E,R]=this.handleOptionStringAndParams(a,"createOrder","timeInForce",B);if("market"===t&&"GTC"===E)throw new h.InvalidOrder(this.id+" createOrder() market orders cannot be GTC - use type 'limit' for a resting order");let L=this.walletAddress,N=this.ethEncodeStructuredData(w,{Order:[{name:"marketHash",type:"bytes32"},{name:"baseToken",type:"address"},{name:"totalBetSize",type:"uint256"},{name:"percentageOdds",type:"uint256"},{name:"salt",type:"uint256"},{name:"expiry",type:"uint256"},{name:"maker",type:"address"},{name:"isMakerBettingOutcomeOne",type:"bool"}]},{marketHash:u,baseToken:S,totalBetSize:A,percentageOdds:P,salt:x,expiry:C,maker:L,isMakerBettingOutcomeOne:g}),D=this.hashEip712Digest(N),q={marketHash:u,maker:L,totalBetSize:A,percentageOdds:P,salt:"0x"+M,expiry:C,baseToken:S,isMakerBettingOutcomeOne:g,timeInForce:E,orderSignature:this.signDigest(D,this.privateKey)},F=this.safeString(R,"clientOrderId");void 0!==F&&(q.clientOrderId=F);let V=this.safeBool(R,"useBetCredits");void 0!==V&&(q.useBetCredits=V);let G=this.safeString(R,"externalUserId");void 0!==G&&(q.externalUserId=G);let H=this.safeBool(R,"waitForOutcome",!0),U=this.omit(R,["salt","expiry","clientOrderId","waitForOutcome","useBetCredits","externalUserId"]),W=await this.sxbetPrivatePostOrdersV3(this.extend({orders:[q],waitForOutcome:H},U)),j=this.safeDict(W,"data",{}),K=this.safeList(j,"orders",[]),z=this.safeDict(K,0,{});if("FAILED"===this.safeStringUpper(z,"status")){let e=this.safeString(z,"reason","FAILED"),t=this.id+" createOrder() rejected: "+e;throw this.throwExactlyMatchedException(this.exceptions.exact,e,t),new h.InvalidOrder(t)}let Y=this.safeDict(z,"outcome"),X="1000000";if(void 0!==Y){let e=this.safeString(Y,"fillAmount"),t=this.safeString(Y,"remainingAmount");void 0!==e&&(o=this.parseNumber(n.Y.stringDiv(e,X,6))),void 0!==t&&(d=this.parseNumber(n.Y.stringDiv(t,X,6)));let i=this.safeStringUpper(Y,"state");"RESTED"===i||"PARTIAL_FILL_RESTED"===i?c="open":"FULLY_FILLED"===i?c="closed":"PARTIAL_FILL_DONE"===i?c="canceled":"CANCELLED"===i&&(c="EXPIRED"===this.safeStringUpper2(Y,"cancelReason","reason")?"expired":"canceled")}let Q=this.milliseconds();return this.safePredictionOrder({id:this.safeString2(z,"orderId","orderHash"),clientOrderId:this.safeString(z,"clientOrderId",F),info:W,timestamp:Q,datetime:this.iso8601(Q),status:c,filled:o,remaining:d,cost:o,outcome:this.safeString(l,"outcome"),outcomeId:f,label:this.safeString(l,"label"),market:this.safeString(l,"market"),type:t,timeInForce:E,side:i,price:this.parseNumber(T),amount:s,fee:void 0,trades:[]},l)}parseSxbetCancelResponse(e){let t=this.safeDict(e,"data",{}),i=[],s=this.safeList2(t,"cancelled","cancelledSubmitted",[]),r=s.length;for(let t=0;t<r;t++)i.push(this.safePredictionOrder({id:this.safeString(s[t],"orderId"),status:"canceled",info:e}));let a=this.safeList(t,"notCancelled",[]),o=a.length;for(let t=0;t<o;t++)i.push(this.safePredictionOrder({id:this.safeString(a[t],"orderId"),status:void 0,info:e}));let n=this.safeList(t,"unconfirmed",[]),d=n.length;for(let t=0;t<d;t++)i.push(this.safePredictionOrder({id:this.safeString(n[t],"orderId"),status:void 0,info:e}));return i}async cancelOrder(e,t,i={}){this.checkRequiredCredentials();let s=await this.sxbetPrivateDeleteOrdersV3(this.extend({orders:[{orderId:e}]},i)),r=this.parseSxbetCancelResponse(s);return this.safeDict(r,0)}async cancelOrders(e,t,i={}){this.checkRequiredCredentials();let s=e.length;if(0===s)throw new h.ArgumentsRequired(this.id+" cancelOrders() requires a non-empty ids argument");let r=this.safeInteger(this.options,"cancelOrdersBatchSize",100),a=this.parseToInt(this.sum(s,r-1)/r),o=[];for(let t=0;t<a;t++){let a=t*r,n=a+r;n>s&&(n=s);let d=[];for(let t=a;t<n;t++)d.push({orderId:e[t]});let h={orders:d},c=await this.sxbetPrivateDeleteOrdersV3(this.extend(h,i));o=this.arrayConcat(o,this.parseSxbetCancelResponse(c))}return o}async cancelAllOrders(e,t={}){let i;this.checkRequiredCredentials();let s=this.safeString2(t,"eventId","sportXeventId"),r=this.omit(t,["eventId","sportXeventId"]),a=void 0!==s;i=a?await this.sxbetPrivateDeleteOrdersV3Event(this.extend({eventId:s},r)):await this.sxbetPrivateDeleteOrdersV3All(r);let o=this.parseSxbetCancelResponse(i),n=this.safeBool(this.safeDict(i,"data",{}),"hasMore",!1),d=0;for(;!0===n&&d<50;){let e;if(a){let t={eventId:s};e=await this.sxbetPrivateDeleteOrdersV3Event(this.extend(t,r))}else e=await this.sxbetPrivateDeleteOrdersV3All(r);o=this.arrayConcat(o,this.parseSxbetCancelResponse(e)),n=this.safeBool(this.safeDict(e,"data",{}),"hasMore",!1),d=this.sum(d,1)}return o}parsePredictionOrder(e,t){let i,s=this.safeString2(e,"id","orderId"),r=this.safeString(e,"marketHash","");i=this.safeBool(e,"isBettingOutcomeOne",!0)?r:r+"-2";let a=this.safeOutcome(i,t),o="1000000",d=this.safeString(e,"percentageOdds"),h=void 0!==d?this.parseNumber(n.Y.stringDiv(d,"100000000000000000000")):void 0,c=this.safeString(e,"totalBetSize","0"),l=this.safeString(e,"remainingSize",c),u=n.Y.stringSub(c,l),f=this.parseNumber(n.Y.stringDiv(c,o,6)),p=this.parseNumber(n.Y.stringDiv(u,o,6)),m=this.parseNumber(n.Y.stringDiv(l,o,6)),g=this.safeStringUpper(e,"status"),v=this.safeStringUpper(e,"inactiveReason"),y="open";"INACTIVE"===g&&(y="FILLED"===v?"closed":"EXPIRED"===v?"expired":"canceled");let b=this.parse8601(this.safeString(e,"createdAt"));return this.safePredictionOrder({id:s,clientOrderId:this.safeString(e,"clientOrderId"),timestamp:b,datetime:this.iso8601(b),lastTradeTimestamp:this.parse8601(this.safeString(e,"updatedAt")),status:y,type:"limit",timeInForce:void 0,side:"buy",price:h,average:void 0,amount:f,filled:p,remaining:m,cost:void 0,fee:void 0,reduceOnly:void 0,postOnly:void 0,trades:[],outcome:this.safeString(a,"outcome"),outcomeId:this.safeString(a,"outcomeId",i),label:this.safeString(a,"label"),market:this.safeString(a,"market"),info:e},a)}clampSxbetPerPage(e){if(void 0!==e)return e>100?100:e}async fetchOpenOrders(e,t,i,s={}){let r,a={};void 0!==e&&(await this.loadOutcome(e),r=this.outcome(e),a.marketHash=this.safeString(r.info,"marketHash")),void 0!==i&&(a.perPage=this.clampSxbetPerPage(i));let o=await this.sxbetPrivateGetOrdersV3(this.extend(a,s)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"orders",[]);return this.parsePredictionOrders(d,r,t,i)}async fetchOrders(e,t,i,s={}){return await this.fetchOpenOrders(e,t,i,s)}async fetchOrder(e,t,i={}){let s;if(this.checkRequiredCredentials(),void 0===e)throw new h.ArgumentsRequired(this.id+" fetchOrder() requires an id argument");void 0!==t&&(await this.loadOutcome(t),s=this.outcome(t));let r=await this.sxbetPrivateGetOrdersV3OrderId(this.extend({orderId:e},i)),a=this.safeDict(r,"data",{}),o=this.safeDict(a,"order",a);return this.parsePredictionOrder(o,s)}async fetchTrades(e,t,i,s={}){if(void 0===e)throw new h.ArgumentsRequired(this.id+" fetchTrades() requires an outcome argument - the venue requires the trades listing to be scoped");await this.loadOutcome(e);let r=this.outcome(e),a={marketHash:this.safeString(r.info,"marketHash")};void 0!==i&&(a.perPage=this.clampSxbetPerPage(i));let o=await this.sxbetPublicGetTradesV3Public(this.extend(a,s)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"trades",[]),c=[],l=d.length;for(let e=0;e<l;e++)c.push(this.parseSxbetV3PublicTrade(d[e]));c=this.sortBy(c,"timestamp");let u=this.safeString(r,"outcome");return this.filterByValueSinceLimit(c,"outcome",u,t,i,"timestamp",!0)}async fetchMyTrades(e,t,i,s={}){let r;this.checkRequiredCredentials();let a={};void 0!==e&&(await this.loadOutcome(e),r=this.outcome(e)),void 0!==t&&(a.startDate=this.iso8601(t)),void 0!==i&&void 0===e&&(a.perPage=this.clampSxbetPerPage(i));let o=await this.sxbetPrivateGetFillsV3(this.extend(a,s)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"fills",[]),h=[],c=d.length;for(let e=0;e<c;e++)h.push(this.parseSxbetV3Fill(d[e]));h=this.sortBy(h,"timestamp");let l=void 0!==r?this.safeString(r,"outcome"):void 0;return this.filterByValueSinceLimit(h,"outcome",l,t,i,"timestamp",!0)}parseSxbetV3Fill(e,t){let i,s,r=this.safeString(e,"marketHash","");i=this.safeBool(e,"isBettingOutcomeOne",!0)?r:r+"-2";let a=this.safeOutcome(i,t),o=this.safeString(e,"fillOdds"),d=void 0!==o?this.parseNumber(n.Y.stringDiv(o,"100000000000000000000")):void 0,h=this.safeString(e,"fillAmount","0"),c=this.parseNumber(n.Y.stringDiv(h,"1000000",6)),l=this.parse8601(this.safeString(e,"createdAt")),u=this.safeBool(e,"isMaker");return void 0!==u&&(s=!0===u?"maker":"taker"),this.safePredictionTrade({id:this.safeString(e,"id"),info:e,timestamp:l,datetime:this.iso8601(l),outcome:this.safeString(a,"outcome"),outcomeId:this.safeString(a,"outcomeId",i),label:this.safeString(a,"label"),market:this.safeString(a,"market"),order:this.safeString(e,"orderId"),type:void 0,side:"buy",takerOrMaker:s,price:d,amount:c,cost:c,fee:void 0},t)}async fetchBalance(e={}){let t=await this.loadSxObv3Metadata(),i=this.safeDict(t,"activeAsset",{}),s=this.safeStringLower(i,"baseToken",""),r=await this.sxbetPrivateGetUserBalanceV3(e),a=this.safeDict(r,"data",{}),o=this.safeList(a,"balances",[]),d={info:r},h="1000000",c=o.length;for(let e=0;e<c;e++){let t=this.safeDict(o,e),i=this.safeStringLower(t,"tokenAddress",""),r=this.safeString(t,"tokenAddress","");i===s&&(r="USDC");let a=n.Y.stringDiv(this.safeString(t,"availableAmount","0"),h,6),c=n.Y.stringDiv(this.safeString(t,"escrowedAmount","0"),h,6);d[r]={free:this.parseNumber(a),used:this.parseNumber(c),total:this.parseNumber(n.Y.stringAdd(a,c))}}return this.safeBalance(d)}async fetchPositions(e,t={}){this.checkRequiredCredentials();let i=void 0===e?[]:e,s=i.length,r={};if(s>0){await this.loadOutcomes(i);for(let e=0;e<s;e++){let t=this.outcome(i[e]);r[this.safeString(t.info,"marketHash","")]=!0}}let a={status:this.safeString(t,"status","MATCHED,LOCKED")},o=this.omit(t,["status"]),n=await this.sxbetPrivateGetPositionsV3(this.extend(a,o)),d=this.safeDict(n,"data",{}),h=this.safeList(d,"positions",[]),c=[],l=h.length;for(let e=0;e<l;e++){let t=h[e],i=this.safeString(t,"marketHash","");s>0&&void 0===this.safeBool(r,i)||c.push(this.parseSxbetV3Position(t))}return c}parseSxbetV3Position(e){let t,i,s=this.safeString(e,"marketHash",""),r=this.safeBool(e,"isOutcomeOneMaxWin",!0);t=r?s:s+"-2";let a=this.safeOutcome(t),o="1000000",d=this.safeDict(e,"odds",{}),h=void 0!==(i=r?this.safeString(d,"outcomeOne"):this.safeString(d,"outcomeTwo"))?this.parseNumber(n.Y.stringDiv(i,"100000000000000000000")):void 0,c=this.safeString(e,"totalStake","0"),l=this.safeString(e,"pnl"),u=this.parse8601(this.safeString(e,"betTime"));return this.safePredictionPosition({outcome:this.safeString(a,"outcome"),outcomeId:this.safeString(a,"outcomeId",t),label:this.safeString(a,"label"),market:this.safeString(a,"market"),timestamp:u,datetime:this.iso8601(u),lastUpdateTimestamp:this.parse8601(this.safeString(e,"updatedAt")),contracts:this.parseNumber(n.Y.stringDiv(c,o,6)),entryPrice:h,markPrice:void 0,unrealizedPnl:void 0,realizedPnl:void 0!==l?this.parseNumber(n.Y.stringDiv(l,o,6)):void 0,side:"long",info:e})}async fetchSettlements(e,t,i,s={}){let r;this.checkRequiredCredentials();let a={status:"SETTLED"};if(void 0!==e){await this.loadOutcome(e);let t=this.outcome(e);a.marketHash=this.safeString(t.info,"marketHash",""),r=this.safeString(t,"outcomeId")}void 0!==t&&(a.startDate=this.iso8601(t)),void 0!==i&&void 0===e&&(a.perPage=this.clampSxbetPerPage(i));let o=await this.sxbetPrivateGetTradesV3(this.extend(a,s)),n=this.safeDict(o,"data",{}),d=this.safeList(n,"trades",[]),h=[],c=d.length;for(let e=0;e<c;e++){let t=this.parseSettlement(d[e]);(void 0===r||this.safeString(t,"outcomeId")===r)&&h.push(t)}return h}parseSettlement(e,t){let i,s,r,a,o=this.safeString(e,"marketHash",""),d=this.safeBool(e,"isBettingOutcomeOne",!0);i=d?o:o+"-2";let h=this.safeOutcome(i,t),c=this.safeDict(e,"settlement",{}),l=this.safeInteger(c,"outcome"),u=0===l;void 0===l||u||(s=l===(d?1:2));let f="1000000",p=n.Y.stringDiv(this.safeString(e,"totalStake","0"),f,6),m=n.Y.stringDiv(this.safeString(c,"settleReturnAmount","0"),f,6),g=n.Y.stringSub(m,p);if(u)r="VOID";else if(void 0!==l){let e=this.safeDict(h,"info",{}),t="outcomeTwoName";1===l&&(t="outcomeOneName"),r=this.safeString(e,t,this.numberToString(l))}let v=this.parse8601(this.safeString(c,"settleDate"));return void 0!==s&&(a=+(!0===s)),{info:e,id:this.safeString(e,"tradeId"),timestamp:v,datetime:this.iso8601(v),outcome:this.safeString(h,"outcome",i),outcomeId:this.safeString(h,"outcomeId",i),market:this.safeString(h,"market"),event:void 0,result:r,won:s,amount:this.parseNumber(p),price:a,cost:this.parseNumber(p),payout:this.parseNumber(m),pnl:this.parseNumber(g)}}async fetchSxbetBookSnapshot(e){let t=await this.sxbetPublicGetOrderbookV3Snapshot({marketHash:e});return this.safeDict(t,"data",{})}async fetchTicker(e,t={}){await this.loadOutcome(e);let i=this.outcome(e),s=this.safeString(i.info,"marketHash"),r=await this.fetchSxbetBookSnapshot(s),a=this.parseSxbetSnapshotBestOdds(r);return this.parsePredictionTicker(a,i)}async fetchSxbetBestOdds(e,t={}){let i={marketHashes:e.join(",")},s=await this.sxbetPrivateGetOrdersV3OddsBest(this.extend(i,t)),r=this.safeDict(s,"data",{});return this.safeList(r,"bestOdds",[])}parseSxbetSnapshotBestOdds(e){let t=this.safeList(e,"outcomeOne",[]),i=this.safeList(e,"outcomeTwo",[]),s=this.safeDict(t,0,{}),r=this.safeDict(i,0,{});return{marketHash:this.safeString(e,"marketHash"),outcomeOne:{percentageOdds:this.safeString(s,"percentageOdds")},outcomeTwo:{percentageOdds:this.safeString(r,"percentageOdds")}}}async fetchTickers(e,t={}){if(void 0===e)throw new h.ArgumentsRequired(this.id+" fetchTickers() requires an outcomes argument - sx.bet has thousands of markets and serves best odds per market list");let i=e.length,s=[],r={};for(let t=0;t<i;t++){await this.loadOutcome(e[t]);let i=this.outcome(e[t]),a=this.safeString(i.info,"marketHash","");void 0===this.safeBool(r,a)&&(r[a]=!0,s.push(a))}let a={},o=s.length;if(this.isEmptyString(this.apiKey)){for(let e=0;e<o;e++){let t=s[e],i=await this.fetchSxbetBookSnapshot(t);a[t]=this.parseSxbetSnapshotBestOdds(i)}return this.parseSxbetTickersByHash(e,a)}let n=this.safeInteger(this.options,"bestOddsBatchSize",100),d=this.parseToInt(this.sum(o,n-1)/n);for(let e=0;e<d;e++){let i=e*n,r=i+n;r>o&&(r=o);let d=this.arraySlice(s,i,r),h=await this.fetchSxbetBestOdds(d,t),c=h.length;for(let e=0;e<c;e++){let t=h[e],i=this.safeString(t,"marketHash");void 0!==i&&(a[i]=t)}}return this.parseSxbetTickersByHash(e,a)}parseSxbetTickersByHash(e,t){let i={},s=e.length;for(let r=0;r<s;r++){let s=this.outcome(e[r]),a=this.safeString(s.info,"marketHash",""),o=this.safeDict(t,a);if(void 0===o)continue;let n=this.parsePredictionTicker(o,s),d=this.safeString(n,"outcome");void 0!==d&&(i[d]=n)}return i}parsePredictionTicker(e,t){let i,s=this.safeOutcome(this.safeString(t,"outcome"),t),r=this.safeString(s,"outcomeId"),a=r===this.safeString(e,"marketHash"),o=this.safeDict(e,"outcomeOne",{}),d=this.safeDict(e,"outcomeTwo",{}),h=d;a&&(h=o);let c=o;a&&(c=d);let l="100000000000000000000",u=this.safeString(h,"percentageOdds"),f=this.safeString(c,"percentageOdds"),p=void 0!==u?this.parseNumber(n.Y.stringDiv(u,l)):void 0,m=void 0!==f?this.parseNumber(n.Y.stringSub("1",n.Y.stringDiv(f,l))):void 0,g=this.safeInteger(h,"updatedAt"),v=this.milliseconds(),y=void 0!==g?g:v;return void 0!==p&&void 0!==m&&(i=this.parseNumber(n.Y.stringDiv(n.Y.stringAdd(this.numberToString(p),this.numberToString(m)),"2"))),this.safePredictionTicker({outcome:this.safeString(s,"outcome"),outcomeId:r,label:this.safeString(s,"label"),market:this.safeString(s,"market"),timestamp:y,datetime:this.iso8601(y),high:void 0,low:void 0,bid:p,bidVolume:void 0,ask:m,askVolume:void 0,open:void 0,close:p,last:p,change:void 0,percentage:void 0,average:i,baseVolume:void 0,quoteVolume:void 0,info:e},t)}async fetchOrderBook(e,t,i={}){await this.loadOutcome(e);let s=this.outcome(e),r=this.safeString(s.info,"marketHash"),a=this.safeString(s,"outcomeId"),o=await this.sxbetPublicGetOrderbookV3Snapshot(this.extend({marketHash:r},i)),n=this.safeDict(o,"data",{}),d=this.parseSxbetV3BookSides(n,a===r),h=this.safeList(d,"bids",[]),c=this.safeList(d,"asks",[]);if(void 0!==t){let e=h.length,i=t;i>e&&(i=e),h=this.arraySlice(h,0,i);let s=c.length,r=t;r>s&&(r=s),c=this.arraySlice(c,0,r)}let l=this.milliseconds();return this.safePredictionOrderBook({outcome:this.safeString(s,"outcome",e),bids:h,asks:c,timestamp:l,datetime:this.iso8601(l),nonce:void 0},s)}parseSxbetV3BookSides(e,t){let i="100000000000000000000",s="1000000",r=t?this.safeList(e,"outcomeOne",[]):this.safeList(e,"outcomeTwo",[]),a=t?this.safeList(e,"outcomeTwo",[]):this.safeList(e,"outcomeOne",[]),o=[],d=r.length;for(let e=0;e<d;e++){let t=this.safeDict(r,e),a=this.safeString(t,"percentageOdds"),d=this.safeString(t,"size","0"),h=this.parseNumber(n.Y.stringDiv(a,i)),c=this.parseNumber(n.Y.stringDiv(d,s,6));o.push([h,c])}let h=[],c=a.length;for(let e=0;e<c;e++){let t=this.safeDict(a,e),r=this.safeString(t,"percentageOdds"),o=this.safeString(t,"size","0"),d=this.parseNumber(n.Y.stringSub("1",n.Y.stringDiv(r,i))),c=n.Y.stringDiv(i,r,12),l=n.Y.stringSub(n.Y.stringMul(o,c),o),u=this.parseNumber(n.Y.stringDiv(l,s,6));h.push([d,u])}return{bids:this.sortBy(o,0,!0),asks:this.sortBy(h,0)}}requestId(e){void 0===this.safeValue(this.options,"requestId")&&(this.options.requestId=this.createSafeDictionary());let t=this.options.requestId,i=this.safeInteger(t,e,0),s=this.sum(i,1);return void 0!==e&&(this.options.requestId[e]=s),s}registerSxbetWsRequest(e,t,i){void 0===this.safeDict(this.options,"wsPendingRequests")&&(this.options.wsPendingRequests=this.createSafeDictionary());let s=this.numberToString(e);this.options.wsPendingRequests[s]={messageHash:t,subscription:i}}async fetchSxbetRealtimeToken(){if(void 0===this.apiKey)throw new h.ArgumentsRequired(this.id+" websocket streaming requires the apiKey credential - the realtime token endpoint authenticates with the X-Api-Key header");let e=await this.sxbetPrivateGetUserRealtimeTokenV3ApiKey(),t=this.safeDict(e,"data",{});return this.safeString2(t,"token","realtimeToken",this.safeString(e,"token"))}async connectSxbetCentrifugo(e){let t=this.client(e);if(void 0===this.safeValue(t.subscriptions,"connect")){this.options.wsConnected=!1;let t=await this.fetchSxbetRealtimeToken(),i=this.requestId(e);return this.registerSxbetWsRequest(i,"centrifugoConnected","connect"),await this.watch(e,"centrifugoConnected",{connect:{token:t,name:"ccxt"},id:i},"connect")}if(!this.safeBool(this.options,"wsConnected",!1))return await t.future("centrifugoConnected")}async pong(e,t){await e.send("{}")}async subscribeSxbetChannel(e,t){let i=this.safeString(this.urls.api,"ws");await this.connectSxbetCentrifugo(i);let s=this.requestId(i);return this.registerSxbetWsRequest(s,e,t),await this.watch(i,e,{subscribe:{channel:t},id:s},t)}handleMessage(e,t){if("string"==typeof t){let i=t.split("\n"),s=i.length;for(let t=0;t<s;t++){let s=i[t];if(s.length>0){let t=JSON.parse(s);this.handleCentrifugoFrame(e,t)}}return}this.handleCentrifugoFrame(e,t)}handleCentrifugoFrame(e,t){if(0===Object.keys(t).length)return void this.spawn(this.pong,e,t);let i=this.safeString(t,"id"),s=this.safeDict(this.options,"wsPendingRequests",{}),r=this.safeDict(s,i);if(void 0!==this.safeDict(t,"error")){let a=new h.ExchangeError(this.id+" "+this.json(t));if(void 0!==r){let t=this.safeString(r,"messageHash"),o=this.safeString(r,"subscription");"connect"===o&&(this.options.wsConnected=!1),void 0!==o&&o in e.subscriptions&&delete e.subscriptions[o],this.options.wsPendingRequests=this.omit(s,i),e.reject(a,t)}else e.reject(a);return}if(void 0!==r&&(this.options.wsPendingRequests=this.omit(s,i)),void 0!==this.safeDict(t,"connect")){this.options.wsConnected=!0,e.resolve(!0,"centrifugoConnected");return}let a=this.safeDict(t,"push");if(void 0===a)return;let o=this.safeString(a,"channel");if(void 0===o)return;let n=this.safeDict(a,"pub",{}),d=this.safeValue(n,"data");if(void 0===d)return;let c=[];c=Array.isArray(d)?d:[d];let l=o.split(":"),u=this.safeString(l,0);"orderbook_v3"===u?this.handleOrderBook(e,c):"best_odds_v3"===u?this.handleTicker(e,c):"recent_trades_v3"===u?this.handleTrades(e,c):"account"===u&&(o.indexOf("orders_v3")>=0?this.handleOrder(e,c):o.indexOf("fills_v3")>=0&&this.handleMyTrade(e,c))}async watchOrderBook(e,t,i={}){await this.loadOutcome(e);let s=this.outcome(e),r=this.safeString(s,"outcome"),a=this.safeString(s.info,"marketHash"),o="orderbook_v3:"+a,n="orderbook::"+r,d=this.safeString(this.urls.api,"ws");await this.connectSxbetCentrifugo(d);let h=this.client(d),c=void 0===this.safeValue(h.subscriptions,o);if(void 0===this.safeValue(this.orderbooks,r)){void 0===this.safeDict(this.options,"wsWatchedBooks")&&(this.options.wsWatchedBooks=this.createSafeDictionary()),this.options.wsWatchedBooks[r]=a;let e=await this.fetchSxbetBookSnapshot(a);if(this.applySxbetWsSnapshot(e),void 0===this.safeValue(this.orderbooks,r)){let e=this.orderBook({});this.orderbooks[r]=e}}let l=this.requestId(d);this.registerSxbetWsRequest(l,n,o);let u=this.watch(d,n,{subscribe:{channel:o},id:l},o);return c&&h.resolve(this.safeValue(this.orderbooks,r),n),(await u).limit()}applySxbetWsSnapshot(e){let t=this.safeString(e,"marketHash"),i=this.safeString(e,"version",""),s=[];if(void 0===t)return s;void 0===this.safeDict(this.options,"wsBookVersions")&&(this.options.wsBookVersions=this.createSafeDictionary());let r=this.safeString(this.options.wsBookVersions,t,"");if(""!==r&&i<=r)return s;this.options.wsBookVersions[t]=i;let a=this.safeDict(this.options,"wsWatchedBooks",{}),o=Object.keys(a),n=this.milliseconds(),d=o.length;for(let i=0;i<d;i++){let r=o[i];if(this.safeString(a,r)!==t)continue;let d=this.outcome(r),h=this.safeString(d,"outcomeId")===t,c=this.parseSxbetV3BookSides(e,h),l=this.safeValue(this.orderbooks,r);void 0===l&&(l=this.orderBook({}),this.orderbooks[r]=l);let u={bids:this.safeList(c,"bids",[]),asks:this.safeList(c,"asks",[]),timestamp:n,datetime:this.iso8601(n),nonce:void 0};l.reset(u),s.push(r)}return s}handleOrderBook(e,t){let i=t.length;for(let s=0;s<i;s++){let i=this.applySxbetWsSnapshot(t[s]),r=i.length;for(let t=0;t<r;t++){let s=i[t];e.resolve(this.safeValue(this.orderbooks,s),"orderbook::"+s)}}}async watchTicker(e,t={}){await this.loadOutcome(e);let i=this.outcome(e),s=this.safeString(i,"outcome"),r=this.safeString(i.info,"marketHash"),a="ticker::"+s;void 0===this.safeDict(this.options,"wsWatchedTickers")&&(this.options.wsWatchedTickers=this.createSafeDictionary()),this.options.wsWatchedTickers[s]=r;let o=this.safeString(this.urls.api,"ws");await this.connectSxbetCentrifugo(o);let n=this.client(o),d="best_odds_v3:global",h=!1;if(void 0===this.safeValue(this.tickers,s)){let e=await this.fetchSxbetBookSnapshot(r),t=this.parseSxbetSnapshotBestOdds(e),a=this.parsePredictionTicker(t,i);this.tickers[s]=a,h=!0}let c=this.requestId(o);this.registerSxbetWsRequest(c,a,d);let l=this.watch(o,a,{subscribe:{channel:d},id:c},d);return h&&n.resolve(this.safeValue(this.tickers,s),a),await l}handleTicker(e,t){let i=this.safeDict(this.options,"wsWatchedTickers",{}),s=Object.keys(i),r=t.length;for(let a=0;a<r;a++){let r=this.safeDict(t,a),o=this.safeString(r,"marketHash");if(void 0===o)continue;let n=this.safeDict(r,"outcomeOne",{}),d=this.safeDict(r,"outcomeTwo",{}),h={marketHash:o,outcomeOne:{percentageOdds:this.safeString(n,"percentageOdds")},outcomeTwo:{percentageOdds:this.safeString(d,"percentageOdds")}},c=s.length;for(let t=0;t<c;t++){let r=s[t];if(this.safeString(i,r)!==o)continue;let a=this.outcome(r),n=this.parsePredictionTicker(h,a);this.tickers[r]=n,e.resolve(n,"ticker::"+r)}}}async watchTrades(e,t,i,s={}){await this.loadOutcome(e);let r=this.outcome(e),a=this.safeString(r,"outcome"),o=await this.subscribeSxbetChannel("trades::"+a,"recent_trades_v3:global");return this.filterBySinceLimit(o,t,i,"timestamp",!0)}parseSxbetV3PublicTrade(e){let t,i=this.safeString(e,"marketHash","");t=this.safeBool(e,"isBettingOutcomeOne",!0)?i:i+"-2";let s=this.safeOutcome(t),r=this.safeString(e,"weightedAverageOdds"),a=void 0!==r?this.parseNumber(n.Y.stringDiv(r,"100000000000000000000")):void 0,o=this.safeString(e,"totalStake","0"),d=this.parseNumber(n.Y.stringDiv(o,"1000000",6)),h=this.parse8601(this.safeString(e,"betTime"));return this.safePredictionTrade({id:this.safeString(e,"tradeId"),info:e,timestamp:h,datetime:this.iso8601(h),outcome:this.safeString(s,"outcome"),outcomeId:this.safeString(s,"outcomeId",t),label:this.safeString(s,"label"),market:this.safeString(s,"market"),order:void 0,type:void 0,side:"buy",takerOrMaker:void 0,price:a,amount:d,cost:d,fee:void 0})}handleTrades(e,t){let i=t.length;for(let s=0;s<i;s++){let i=this.safeDict(t[s],"trade",t[s]),r=this.parseSxbetV3PublicTrade(i),a=this.safeString(r,"outcome");if(void 0===a)continue;if(void 0===this.trades&&(this.trades=this.createSafeDictionary()),void 0===this.safeValue(this.trades,a)){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.trades[a]=new d.I3(e)}let o=this.trades[a];o.append(r),e.resolve(o,"trades::"+a)}}async watchMyTrades(e,t,i,s={}){if(void 0===this.walletAddress)throw new h.ArgumentsRequired(this.id+" watchMyTrades() requires a walletAddress");let r="myTrades";if(void 0!==e){await this.loadOutcome(e);let t=this.outcome(e);r="myTrades::"+this.safeString(t,"outcome")}let a="account:fills_v3_#"+this.walletAddress,o=await this.subscribeSxbetChannel(r,a);return this.filterBySinceLimit(o,t,i,"timestamp",!0)}handleMyTrade(e,t){let i=t.length;for(let s=0;s<i;s++){let i=this.safeDict(t[s],"fill",t[s]),r=this.parseSxbetV3Fill(i),a=this.safeString(r,"outcome");if(void 0===a)continue;if(void 0===this.myTrades){let e=this.safeInteger(this.options,"myTradesLimit",1e3);this.myTrades=new d.$0(e)}let o=this.myTrades;o.append(r),e.resolve(o,"myTrades"),e.resolve(o,"myTrades::"+a)}}async watchOrders(e,t,i,s={}){if(void 0===this.walletAddress)throw new h.ArgumentsRequired(this.id+" watchOrders() requires a walletAddress");let r="orders";if(void 0!==e){await this.loadOutcome(e);let t=this.outcome(e);r="orders::"+this.safeString(t,"outcome")}let a="account:orders_v3_#"+this.walletAddress,o=await this.subscribeSxbetChannel(r,a);return this.filterBySinceLimit(o,t,i,"timestamp",!0)}handleOrder(e,t){let i=t.length;for(let s=0;s<i;s++){let i=this.safeDict(t[s],"order",t[s]),r=this.parsePredictionOrder(i);if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new d.$0(e)}let a=this.orders;a.append(r),e.resolve(a,"orders");let o=this.safeString(r,"outcome");void 0!==o&&e.resolve(a,"orders::"+o)}}handleErrors(e,t,i,s,r,a,o,n,d){let c;if(void 0===o)return;let l=this.safeValue(o,"message");if(void 0===l)return;c=Array.isArray(l)?l.join(", "):l;let u=this.id+" "+a;if(this.throwExactlyMatchedException(this.exceptions.exact,c,u),this.throwBroadlyMatchedException(this.exceptions.broad,c,u),400===e)throw new h.BadRequest(u)}sign(e,t="sxbet",i="GET",s={},r,a){let o="string"==typeof t?t:t[0];if("private"===("string"==typeof t?"public":t[1])&&void 0===this.apiKey)throw new h.AuthenticationError(this.id+" "+e+" is a private endpoint and requires the apiKey credential (the x-sx-api-key header)");let n=this.urls.api,d=this.safeString(n,o,n.sxbet)+"/"+this.implodeParams(e,s),c=this.omit(s,this.extractParams(e)),l=this.extend({Accept:"application/json","Content-Type":"application/json"},void 0!==r?r:{});void 0!==this.apiKey&&(l["x-sx-api-key"]=this.apiKey);let u="GET"===i;"DELETE"===i&&(u=!("orders"in c));let f=a;if(u){let e=this.urlencode(c);""!==e&&(d+="?"+e)}else Object.keys(c).length>0&&(f=this.json(c));return{url:d,method:i,body:f,headers:l}}}i.d(t,{A:()=>c})},292(e,t,i){"use strict";var s=i(7040),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,createOrderWithTakeProfitAndStopLossWs:!1,createReduceOnlyOrderWs:!1,createStopLossOrderWs:!1,createTakeProfitOrderWs:!1,fetchPositionForSymbolWs:!1,fetchPositionsForSymbolWs:!1,fetchPositionsWs:!1,fetchPositionWs:!1,unWatchPositions:!1,watchBalance:!1,watchLiquidations:!1,watchLiquidationsForSymbols:!1,watchMarkPrice:!1,watchMarkPrices:!1,watchMyLiquidations:!1,watchMyLiquidationsForSymbols:!1,watchMyTrades:!0,watchOHLCV:!0,watchOrderBook:!0,watchOrders:!0,watchPosition:!1,watchPositions:!1,watchTicker:!0,watchTickers:!1,watchTrades:!0},urls:{api:{ws:{crypto:"wss://stream.data.alpaca.markets/v1beta2/crypto",trading:"wss://api.alpaca.markets/stream"}},test:{ws:{crypto:"wss://stream.data.alpaca.markets/v1beta2/crypto",trading:"wss://paper-api.alpaca.markets/stream"}}},options:{},streaming:{},exceptions:{ws:{exact:{}}}})}async watchTicker(e,t={}){let i=this.urls.api.ws.crypto;await this.authenticate(i),void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="ticker:"+s.symbol,a={action:"subscribe",quotes:[s.id]};return await this.watch(i,r,this.extend(a,t),r)}handleTicker(e,t){let i=this.parseTicker(t),s=i.symbol;void 0!==s&&(this.tickers[s]=i),e.resolve(i,"ticker:"+s)}parseTicker(e,t){let i=this.safeString(e,"S"),s=this.safeString(e,"t");return this.safeTicker({symbol:this.safeSymbol(i,t),timestamp:this.parse8601(s),datetime:s,high:void 0,low:void 0,bid:this.safeString(e,"bp"),bidVolume:this.safeString(e,"bs"),ask:this.safeString(e,"ap"),askVolume:this.safeString(e,"as"),vwap:void 0,open:void 0,close:void 0,last:void 0,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:void 0,quoteVolume:void 0,info:e},t)}async watchOHLCV(e,t="1m",i,s,r={}){let a=this.urls.api.ws.crypto;await this.authenticate(a),void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=o.symbol,d={action:"subscribe",bars:[o.id]},h="ohlcv:"+n,c=await this.watch(a,h,this.extend(d,r),h),l=s;return this.newUpdates&&(l=c.getLimit(n,s)),this.filterBySinceLimit(c,i,l,0,!0)}handleOHLCV(e,t){let i=this.safeString(t,"S"),s=this.safeSymbol(i),r=this.safeValue(this.ohlcvs,s);if(void 0===r){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);r=new a.TG(e),this.ohlcvs[s]=r}let o=this.parseOHLCV(t);r.append(o);let n="ohlcv:"+s;e.resolve(r,n)}async watchOrderBook(e,t,i={}){let s=this.urls.api.ws.crypto;await this.authenticate(s),void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a="orderbook:"+r.symbol,o={action:"subscribe",orderbooks:[r.id]};return(await this.watch(s,a,this.extend(o,i),a)).limit()}handleOrderBook(e,t){let i=this.safeString(t,"S"),s=this.safeSymbol(i),r=this.safeString(t,"t"),a=this.parse8601(r),o=this.safeBool(t,"r",!1);s in this.orderbooks||(this.orderbooks[s]=this.orderBook());let n=this.orderbooks[s];if(!0===o){let e=this.parseOrderBook(t,s,a,"b","a","p","s");n.reset(e)}else{let e=this.safeList(t,"a",[]),i=this.safeList(t,"b",[]);this.handleDeltas(n.asks,e),this.handleDeltas(n.bids,i),n.timestamp=a,n.datetime=r}let d="orderbook:"+s;this.orderbooks[s]=n,e.resolve(n,d)}handleDelta(e,t){let i=this.parseOrderBookBidAsk(t,"p","s");e.storeArray(i)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}async watchTrades(e,t,i,s={}){let r=this.urls.api.ws.crypto;await this.authenticate(r),void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n="trade:"+o,d={action:"subscribe",trades:[a.id]},h=await this.watch(r,n,this.extend(d,s),n),c=i;return this.newUpdates&&(c=h.getLimit(o,i)),this.filterBySinceLimit(h,t,c,"timestamp",!0)}handleTrades(e,t){let i=this.safeString(t,"S"),s=this.safeSymbol(i),r=this.safeValue(this.trades,s);if(void 0===r){let e=this.safeInteger(this.options,"tradesLimit",1e3);r=new a.I3(e),this.trades[s]=r}let o=this.parseTrade(t);r.append(o);let n="trade:"+s;e.resolve(r,n)}async watchMyTrades(e,t,i,s={}){let r=this.urls.api.ws.trading;await this.authenticate(r);let a="myTrades";void 0===this.markets&&await this.loadMarkets();let o=void 0!==e?this.symbol(e):void 0;void 0!==o&&(a+=":"+o);let n=await this.watch(r,a,this.extend({action:"listen",data:{streams:["trade_updates"]}},s),a),d=i;return this.newUpdates&&(d=n.getLimit(o,i)),this.filterBySinceLimit(n,t,d,"timestamp",!0)}async watchOrders(e,t,i,s={}){let r,a=this.urls.api.ws.trading;await this.authenticate(a),void 0===this.markets&&await this.loadMarkets();let o="orders";if(void 0!==e){let t=this.market(e);o="orders:"+(r=this.safeString(t,"symbol"))}let n=await this.watch(a,o,this.extend({action:"listen",data:{streams:["trade_updates"]}},s),o),d=i;return this.newUpdates&&(d=n.getLimit(r,i)),this.filterBySymbolSinceLimit(n,r,t,d,!0)}handleTradeUpdate(e,t){this.handleOrder(e,t),this.handleMyTrade(e,t)}handleOrder(e,t){let i=this.safeDict(t,"data",{}),s=this.safeDict(i,"order",{});if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}let r=this.orders,o=this.parseOrder(s);r.append(o);let n="orders";e.resolve(r,n),n="orders:"+o.symbol,e.resolve(r,n)}handleMyTrade(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"event");if("fill"!==s&&"partial_fill"!==s)return;let r=this.safeDict(i,"order",{}),o=this.myTrades;if(void 0===o){let e=this.safeInteger(this.options,"tradesLimit",1e3);o=new a.Pt(e)}let n=this.parseMyTrade(r);if(void 0===n)return;o.append(n);let d="myTrades:"+n.symbol;e.resolve(o,d),d="myTrades",e.resolve(o,d)}parseMyTrade(e,t){let i=this.safeString(e,"symbol"),s=this.safeString(e,"filled_at"),r=this.safeString(e,"type");if(void 0!==r)return r.indexOf("limit")>=0&&(r="limit"),this.safeTrade({id:this.safeString(e,"i"),info:e,timestamp:this.parse8601(s),datetime:s,symbol:this.safeSymbol(i,void 0,"/"),order:this.safeString(e,"id"),type:r,side:this.safeString(e,"side"),takerOrMaker:"market"===r?"taker":"maker",price:this.safeString(e,"filled_avg_price"),amount:this.safeString(e,"filled_qty"),cost:void 0,fee:void 0},t)}async authenticate(e,t={}){this.checkRequiredCredentials();let i="authenticated",s=this.client(e),r=s.reusableFuture(i);if(void 0===this.safeValue(s.subscriptions,i)){let t={action:"auth",key:this.apiKey,secret:this.secret};e===this.safeString(this.urls.api.ws,"trading")&&(t={action:"authenticate",data:{key_id:this.apiKey,secret_key:this.secret}}),this.watch(e,i,t,i,r)}return await r}handleErrorMessage(e,t){let i=this.safeString(t,"code"),s=this.safeString(t,"msg"),a=this.id+" code: "+i;throw void 0!==s&&(a=a+" message: "+s),new r.ExchangeError(a)}handleConnected(e,t){return t}handleCryptoMessage(e,t){for(let i=0;i<t.length;i++){let s=t[i],r=this.safeString(s,"T"),a=this.safeString(s,"msg");if("subscription"===r)return void this.handleSubscription(e,s);if("success"===r&&"connected"===a)return void this.handleConnected(e,s);if("success"===r&&"authenticated"===a)return void this.handleAuthenticate(e,s);let o={error:this.handleErrorMessage,b:this.handleOHLCV,q:this.handleTicker,t:this.handleTrades,o:this.handleOrderBook},n=this.safeValue(o,r);void 0!==n&&n.call(this,e,s)}}handleTradingMessage(e,t){let i=this.safeString(t,"stream"),s={authorization:this.handleAuthenticate,listening:this.handleSubscription,trade_updates:this.handleTradeUpdate},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}handleMessage(e,t){Array.isArray(t)?this.handleCryptoMessage(e,t):this.handleTradingMessage(e,t)}handleAuthenticate(e,t){let i=this.safeString(t,"T"),s=this.safeDict(t,"data",{}),a=this.safeString(s,"status");if("success"===i||"authorized"===a)return void e.futures.authenticated.resolve(t);throw new r.AuthenticationError(this.id+" failed to authenticate.")}handleSubscription(e,t){return t}}i.d(t,{A:()=>o})},9222(e,t,i){"use strict";var s=i(4721),r=i(8818),a=i(1697),o=i(1453);class n extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchTicker:!0,watchTickers:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOrders:!0,watchTrades:!0,watchTradesForSymbols:!1,watchPositions:!0,watchMyTrades:!0,watchBalance:!1,watchOHLCV:!0,watchOHLCVForSymbols:!0},urls:{logo:"https://omni.apex.exchange/assets/logo_content-CY9uyFbz.svg",api:{ws:{public:"wss://quote.omni.apex.exchange/realtime_public?v=2",private:"wss://quote.omni.apex.exchange/realtime_private?v=2"}},test:{ws:{public:"wss://qa-quote.omni.apex.exchange/realtime_public?v=2",private:"wss://qa-quote.omni.apex.exchange/realtime_private?v=2"}},www:"https://apex.exchange/",doc:"https://api-docs.pro.apex.exchange",fees:"https://apex-pro.gitbook.io/apex-pro/apex-omni-live-now/trading-perpetual-contracts/trading-fees",referral:"https://omni.apex.exchange/trade"},options:{},streaming:{ping:this.ping,keepAlive:18e3}})}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e);if(0===r.length)throw new o.ArgumentsRequired(this.id+" watchTradesForSymbols() requires a non-empty array of symbols");let a=this.getWsPublicUrl(),n=[],d=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.market(t),s="recentlyTrade.H."+this.safeString(i,"id2");n.push(s);let a="trade:"+t;d.push(a)}let h=await this.watchTopics(a,d,n,s),c=this.safeDict(h,0),l=this.safeString(c,"symbol"),u=i;return this.newUpdates&&(u=h.getLimit(l,i)),this.filterBySinceLimit(h,t,u,"timestamp",!0)}handleTrades(e,t){let i=this.safeList(t,"data",[]),s=this.safeString(t,"topic").split("."),r=this.safeString(s,2),o=this.safeMarket(r,void 0,void 0),n=o.symbol,d=this.safeValue(this.trades,n);if(void 0===d){let e=this.safeInteger(this.options,"tradesLimit",1e3);d=new a.I3(e),this.trades[n]=d}let h=i.length;for(let e=0;e<h;e++){let t=h-e-1,s=this.parseWsTrade(i[t],o);d.append(s)}let c="trade:"+n;e.resolve(d,c)}parseWsTrade(e,t){let i=this.safeStringN(e,["i","id","v"]),s=this.safeString2(e,"s","symbol"),r=this.safeMarket(s,t,void 0),a=r.symbol,o=this.safeIntegerN(e,["t","T","createdAt"]),n=this.safeStringLower2(e,"S","side"),d=this.safeString2(e,"p","price"),h=this.safeStringN(e,["q","v","size"]);return this.safeTrade({id:i,info:e,timestamp:o,datetime:this.iso8601(o),symbol:a,order:void 0,type:void 0,side:n,takerOrMaker:void 0,price:d,amount:h,cost:void 0,fee:void 0},r)}watchOrderBook(e,t,i={}){return this.watchOrderBookForSymbols([e],t,i)}async watchOrderBookForSymbols(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),0===e.length)throw new o.ArgumentsRequired(this.id+" watchOrderBookForSymbols() requires a non-empty array of symbols");let s=this.marketSymbols(e),r=this.getWsPublicUrl(),a=[],n=[],d=void 0===t?25:t;for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t),r="orderBook"+d.toString()+".H."+this.safeString(i,"id2");a.push(r);let o="orderbook:"+t;n.push(o)}return(await this.watchTopics(r,n,a,i)).limit()}async watchTopics(e,t,i,s={}){let r,a=this.client(e),o=[],n=0;for(let e=0;e<i.length;e++)t[e]in a.subscriptions||(o.push(i[e]),n+=1);return n>0&&(r=this.extend({op:"subscribe",args:o},s)),await this.watchMultiple(e,t,r,t)}getWsPublicUrl(){let e=this.safeString(this.options,"wsPublicUrl");if(void 0===e){let t=this.milliseconds().toString();e=this.safeString(this.urls.api.ws,"public")+"&timestamp="+t,this.options.wsPublicUrl=e}return e}getWsPrivateUrl(){let e=this.safeString(this.options,"wsPrivateUrl");if(void 0===e){let t=this.milliseconds().toString();e=this.safeString(this.urls.api.ws,"private")+"&timestamp="+t,this.options.wsPrivateUrl=e}return e}handleOrderBook(e,t){let i=this.safeString(t,"type"),s=this.safeDict(t,"data",{}),r=this.safeString(s,"s"),a=this.safeMarket(r,void 0,void 0).symbol,o=this.safeIntegerProduct(t,"ts",.001);a in this.orderbooks||(this.orderbooks[a]=this.orderBook());let n=this.orderbooks[a];if("snapshot"===i){let e=this.parseOrderBook(s,a,o,"b","a");n.reset(e)}else{let e=this.safeList(s,"a",[]),t=this.safeList(s,"b",[]);this.handleDeltas(n.asks,e),this.handleDeltas(n.bids,t),n.timestamp=o,n.datetime=this.iso8601(o)}let d="orderbook:"+a;this.orderbooks[a]=n,e.resolve(n,d)}handleDelta(e,t){let i=this.parseOrderBookBidAsk(t,0,1);e.storeArray(i)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r=this.getWsPublicUrl(),a="instrumentInfo.H."+this.safeString(i,"id2");return await this.watchTopics(r,["ticker:"+s],[a],t)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=[],r=this.getWsPublicUrl(),a=[];for(let e=0;e<i.length;e++){let t=i[e],r=this.market(t),o="instrumentInfo.H."+this.safeString(r,"id2");a.push(o);let n="ticker:"+t;s.push(n)}let o=await this.watchTopics(r,s,a,t);if(this.newUpdates){let e={},t=this.safeString(o,"symbol");return void 0!==t&&(e[t]=o),e}return this.filterByArray(this.tickers,"symbol",i)}handleTicker(e,t){let i,s=this.safeString(t,"topic",""),r=this.safeString(t,"type",""),a=this.safeDict(t,"data",{}),o=this.parseTicker(a);if("snapshot"===r)o=this.parseTicker(a),i=this.safeString(o,"symbol");else if("delta"===r){let e=s.split("."),t=e.length,r=this.safeString(e,t-1),n=this.safeMarket(r,void 0,void 0);i=this.safeString(n,"symbol");let d=this.safeDict(this.tickers,i,{}),h=this.safeDict(d,"info",{}),c=this.extend(h,a);o=this.parseTicker(c)}let n=this.safeIntegerProduct(t,"ts",.001);o.timestamp=n,o.datetime=this.iso8601(n),this.tickers[i]=o;let d="ticker:"+i;e.resolve(this.tickers[i],d)}async watchOHLCV(e,t="1m",i,s,r={}){return r.callerMethodName="watchOHLCV",(await this.watchOHLCVForSymbols([[e,t]],i,s,r))[e][t]}async watchOHLCVForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.getWsPublicUrl(),a=[],o=[];for(let t=0;t<e.length;t++){let i=this.safeList(e,t),s=this.safeString(i,0),r=this.market(s);s=r.id2;let n=this.safeString(i,1,"1"),d=this.safeString(this.timeframes,n,n);a.push("candle."+d+"."+s),o.push("ohlcv::"+r.symbol+"::"+n)}let[n,d,h]=await this.watchTopics(r,o,a,s),c=i;this.newUpdates&&(c=h.getLimit(n,i));let l=this.filterBySinceLimit(h,t,c,0,!0);return this.createOHLCVObject(n,d,l)}handleOHLCV(e,t){let i=this.safeList(t,"data",[]),s=this.safeString(t,"topic").split("."),r=s.length,o=this.safeString(s,1),n=this.findTimeframe(o),d=this.safeString(s,r-1),h=e.url.indexOf("spot")>-1,c="contract";h&&(c="spot");let l=this.safeMarket(d,void 0,void 0,c).symbol;if(l in this.ohlcvs||(this.ohlcvs[l]={}),!(n in this.ohlcvs[l])){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);this.ohlcvs[l][n]=new a.TG(e)}let u=this.ohlcvs[l][n];for(let e=0;e<i.length;e++){let t=this.parseWsOHLCV(i[e]);u.append(t)}let f=[l,n,u];e.resolve(f,"ohlcv::"+l+"::"+n)}parseWsOHLCV(e,t){return[this.safeInteger(e,"start"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber2(e,"volume","turnover")]}async watchMyTrades(e,t,i,s={}){let r,a="myTrades";void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(a+=":"+(r=this.symbol(e)));let o=this.getWsPrivateUrl();await this.authenticate(o);let n=await this.watchTopics(o,[a],["myTrades"],s),d=i;return this.newUpdates&&(d=n.getLimit(r,i)),this.filterBySymbolSinceLimit(n,r,t,d,!0)}async watchPositions(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a="";r=this.isEmpty(e)?e:this.marketSymbols(e),this.isEmpty(e)||(a="::"+r.join(","));let o=this.getWsPrivateUrl();a="positions"+a;let n=this.client(o);await this.authenticate(o),this.setPositionsCache(n,r);let d=this.positions;if(void 0===d){let e=await n.future("fetchPositionsSnapshot");return this.filterBySymbolsSinceLimit(e,r,t,i,!0)}let h=await this.watchTopics(o,[a],["positions"],s);return this.newUpdates?h:this.filterBySymbolsSinceLimit(d,r,t,i,!0)}async watchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a="orders";void 0!==e&&(a+=":"+(r=this.symbol(e)));let o=this.getWsPrivateUrl();await this.authenticate(o);let n=await this.watchTopics(o,[a],["orders"],s),d=i;return this.newUpdates&&(d=n.getLimit(r,i)),this.filterBySymbolSinceLimit(n,r,t,d,!0)}handleMyTrades(e,t){if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new a.Pt(e)}let i=this.myTrades,s={};for(let e=0;e<t.length;e++){let r=t[e],a=this.parseWsTrade(r);s[a.symbol]=!0,i.append(a)}let r=Object.keys(s);for(let t=0;t<r.length;t++){let s="myTrades:"+r[t];e.resolve(i,s)}e.resolve(i,"myTrades")}handleOrder(e,t){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}let i=this.orders,s={};for(let e=0;e<t.length;e++){let r=this.parseOrder(t[e]);s[r.symbol]=!0,i.append(r)}let r=Object.keys(s);for(let t=0;t<r.length;t++){let s="orders:"+r[t];e.resolve(i,s)}e.resolve(i,"orders")}setPositionsCache(e,t){if(void 0!==this.positions)return;let i="fetchPositionsSnapshot";i in e.futures||(e.future(i),this.spawn(this.loadPositionsSnapshot,e,i))}async loadPositionsSnapshot(e,t){let i=[this.fetchPositions()],s=await Promise.all(i);this.positions=new a.Hk;let r=this.positions;for(let e=0;e<s.length;e++){let t=s[e];for(let e=0;e<t.length;e++){let i=t[e];r.append(i)}}t in e.futures&&(e.futures[t].resolve(r),e.resolve(r,"positions"))}handlePositions(e,t){void 0===this.positions&&(this.positions=new a.Hk);let i=this.positions,s=[];for(let e=0;e<t.length;e++){let r=t[e],a=this.parsePosition(r),o=this.safeString(a,"side");s.push(a),void 0===o||""===o?(a.side="long",i.append(a),a.side="short",i.append(a),a.side=void 0):i.append(a)}let r=this.findMessageHashes(e,"positions::");for(let t=0;t<r.length;t++){let i=r[t],a=i.split("::")[1].split(","),o=this.filterByArray(s,"symbol",a,!1);this.isEmpty(o)||e.resolve(o,i)}e.resolve(s,"positions")}async authenticate(e,t={}){this.checkRequiredCredentials();let i=this.milliseconds().toString(),r="/ws/accounts",a=this.hmac(this.encode(i+"GET"+r),this.encode(this.stringToBase64(this.secret)),s.sc,"base64"),o="authenticated",n=this.client(e),d=n.reusableFuture(o);if(void 0===this.safeValue(n.subscriptions,o)){let t={op:"login",args:[JSON.stringify({type:"login",topics:["ws_zk_accounts_v3"],httpMethod:"GET",requestPath:r,apiKey:this.apiKey,passphrase:this.password,timestamp:i,signature:a})]};this.watch(e,o,t,o)}return await d}handleErrorMessage(e,t){let i=this.safeStringN(t,["code","ret_code","retCode"]);try{if(void 0!==i&&"0"!==i){let e=this.id+" "+this.json(t);this.throwExactlyMatchedException(this.exceptions.exact,i,e);let s=this.safeString2(t,"retMsg","ret_msg");throw this.throwBroadlyMatchedException(this.exceptions.broad,s,e),new o.ExchangeError(e)}let e=this.safeBool(t,"success");if(void 0!==e&&!0!==e){let e=this.safeString(t,"ret_msg"),i=this.safeDict(t,"request",{}),s=this.safeString(i,"op");if(void 0!==e&&e.indexOf("already subscribed")>=0)return!1;if("auth"===s)throw new o.AuthenticationError("Authentication failed: "+e);throw new o.ExchangeError(this.id+" "+e)}return!1}catch(i){if(i instanceof o.AuthenticationError){let t="authenticated";e.reject(i,t),t in e.subscriptions&&delete e.subscriptions[t]}else{let s=this.safeString(t,"reqId");e.reject(i,s)}return!0}}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;let i=this.safeString(t,"ret_msg"),s=this.safeInteger(t,"pong");if("pong"===i||void 0!==s)return void this.handlePong(e,t);let r=this.safeString2(t,"topic","op",""),a={ws_zk_accounts_v3:this.handleAccount,orderBook:this.handleOrderBook,depth:this.handleOrderBook,candle:this.handleOHLCV,kline:this.handleOHLCV,ticker:this.handleTicker,instrumentInfo:this.handleTicker,trade:this.handleTrades,recentlyTrade:this.handleTrades,pong:this.handlePong,auth:this.handleAuthenticate,ping:this.handlePing},o=this.safeValue(a,r);if(void 0!==o)return void o.call(this,e,t);let n=Object.keys(a);for(let i=0;i<n.length;i++){let s=n[i];if(r.indexOf(n[i])>=0)return void a[s].call(this,e,t)}"AUTH_RESP"===this.safeString(t,"type")&&this.handleAuthenticate(e,t)}ping(e){let t=this.milliseconds();return e.lastPong=t,{args:[t.toString()],op:"ping"}}async pong(e,t){let i=this.milliseconds();try{await e.send({args:[i.toString()],op:"pong"})}catch(i){let t=new o.NetworkError(this.id+" handlePing failed with error "+this.exceptionMessage(i));e.reset(t)}}handlePong(e,t){return e.lastPong=this.safeInteger(t,"pong",this.milliseconds()),t}handlePing(e,t){e.lastPong=this.milliseconds(),this.spawn(this.pong,e,t)}handleAccount(e,t){let i=this.safeDict(t,"contents",{}),s=this.safeList(i,"fills",[]);void 0!==s&&this.handleMyTrades(e,s);let r=this.safeList(i,"positions",[]);void 0!==r&&this.handlePositions(e,r);let a=this.safeList(i,"orders",[]);void 0!==a&&this.handleOrder(e,a)}handleAuthenticate(e,t){let i=this.safeBool(t,"success"),s=this.safeInteger(t,"retCode"),r="authenticated";if(!0===i||0===s)this.safeValue(e.futures,r).resolve(!0);else{let i=new o.AuthenticationError(this.id+" "+this.json(t));e.reject(i,r),r in e.subscriptions&&delete e.subscriptions[r]}return t}handleSubscriptionStatus(e,t){return t}}i.d(t,{A:()=>n})},8443(e,t,i){"use strict";var s=i(8695),r=i(7749),a=i(1453),o=i(1697);class n extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchBidsAsks:!0,watchMarkPrice:!0,watchMarkPrices:!0,watchTrades:!0,watchTradesForSymbols:!0,watchOrders:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOHLCV:!0,watchOHLCVForSymbols:!0,watchPositions:!0,watchTicker:!0,watchTickers:!0,watchMyTrades:!0,unWatchTicker:!0,unWatchTickers:!0,unWatchMarkPrice:!0,unWatchMarkPrices:!0,unWatchBidsAsks:!0,unWatchTrades:!0,unWatchTradesForSymbols:!0,unWatchOrderBook:!0,unWatchOrderBookForSymbols:!0,unWatchOHLCV:!0,unWatchOHLCVForSymbols:!0},urls:{api:{ws:{public:{spot:"wss://sstream.asterdex.com/stream",swap:"wss://fstream.asterdex.com/stream"},private:{spot:"wss://sstream.asterdex.com/ws",swap:"wss://fstream.asterdex.com/ws"}}}},options:{listenKey:{spot:void 0,swap:void 0},lastAuthenticatedTime:{spot:0,swap:0},listenKeyRefreshRate:{spot:36e5,swap:36e5},watchBalance:{fetchBalanceSnapshot:!1,awaitBalanceSnapshot:!0},wallet:"wb",watchPositions:{fetchPositionsSnapshot:!0,awaitPositionsSnapshot:!0}},streaming:{},exceptions:{}})}getAccountTypeFromUrl(e){return e.indexOf("fstream")>-1?"swap":"spot"}async watchTicker(e,t={}){t.callerMethodName="watchTicker",void 0===this.markets&&await this.loadMarkets();let i=this.safeSymbol(e);return(await this.watchTickers([i],t))[i]}async unWatchTicker(e,t={}){return t.callerMethodName="unWatchTicker",await this.unWatchTickers([e],t)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s=void 0===i?[]:i,r=this.getMarketFromSymbols(s),o=this.safeString(r,"type","swap"),n=s.length,[d,h]=this.handleParamString(t,"callerMethodName","watchTickers"),c=this.omit(h,"callerMethodName");if(0===n)throw new a.ArgumentsRequired(this.id+" "+d+"() requires a non-empty array of symbols");let l=this.safeString(this.urls.api.ws.public,o);if(void 0===l)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let u=[],f=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t);u.push(this.safeStringLower(i,"id")+"@ticker"),f.push("ticker:"+i.symbol)}let p=await this.watchMultiple(l,f,this.extend({method:"SUBSCRIBE",params:u},c),f);if(this.newUpdates){let e={},t=this.safeString(p,"symbol");return void 0!==t&&(e[t]=p),e}return this.filterByArray(this.tickers,"symbol",s)}async unWatchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s=void 0===i?[]:i,r=this.getMarketFromSymbols(s),o=this.safeString(r,"type","swap"),n=s.length,[d,h]=this.handleParamString(t,"callerMethodName","unWatchTickers"),c=this.omit(h,"callerMethodName");if(0===n)throw new a.ArgumentsRequired(this.id+" "+d+"() requires a non-empty array of symbols");let l=this.safeString(this.urls.api.ws.public,o);if(void 0===l)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let u=[],f=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t);u.push(this.safeStringLower(i,"id")+"@ticker"),f.push("unsubscribe:ticker:"+i.symbol)}return await this.watchMultiple(l,f,this.extend({method:"UNSUBSCRIBE",params:u},c),f)}async watchMarkPrice(e,t={}){t.callerMethodName="watchMarkPrice",void 0===this.markets&&await this.loadMarkets();let i=this.safeSymbol(e);return(await this.watchMarkPrices([i],t))[i]}async unWatchMarkPrice(e,t={}){return t.callerMethodName="unWatchMarkPrice",await this.unWatchMarkPrices([e],t)}async watchMarkPrices(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s=void 0===i?[]:i,r=this.getMarketFromSymbols(s),o=this.safeString(r,"type","swap"),n=s.length,[d,h]=this.handleParamString(t,"callerMethodName","watchMarkPrices"),c=this.omit(h,"callerMethodName");if(0===n)throw new a.ArgumentsRequired(this.id+" "+d+"() requires a non-empty array of symbols");let l=this.safeString(this.urls.api.ws.public,o);if(void 0===l)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let u=[],f=[],p=this.safeBool(c,"use1sFreq",!0);for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t),r="";!0===p&&(r="@1s"),u.push(this.safeStringLower(i,"id")+"@markPrice"+r),f.push("ticker:"+i.symbol)}let m=await this.watchMultiple(l,f,this.extend({method:"SUBSCRIBE",params:u},c),f);if(this.newUpdates){let e={},t=this.safeString(m,"symbol");return void 0!==t&&(e[t]=m),e}return this.filterByArray(this.tickers,"symbol",s)}async unWatchMarkPrices(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s=void 0===i?[]:i,r=this.getMarketFromSymbols(s),o=this.safeString(r,"type","swap"),n=s.length,[d,h]=this.handleParamString(t,"callerMethodName","unWatchMarkPrices"),c=this.omit(h,"callerMethodName");if(0===n)throw new a.ArgumentsRequired(this.id+" "+d+"() requires a non-empty array of symbols");let l=this.safeString(this.urls.api.ws.public,o);if(void 0===l)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let u=[],f=[],p=this.safeBool(c,"use1sFreq",!0);for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t),r="";!0===p&&(r="@1s"),u.push(this.safeStringLower(i,"id")+"@markPrice"+r),f.push("unsubscribe:ticker:"+i.symbol)}return await this.watchMultiple(l,f,this.extend({method:"UNSUBSCRIBE",params:u},c),f)}handleTicker(e,t){let i=this.getAccountTypeFromUrl(e.url),s=this.parseWsTicker(t,i),r=s.symbol;void 0!==r&&(this.tickers[r]=s,e.resolve(this.tickers[r],"ticker:"+r))}parseWsTicker(e,t){let i=this.safeString(e,"e"),s=this.safeString(e,"s"),r=this.safeInteger(e,"E"),a=this.safeMarket(s,void 0,void 0,t),o=this.safeString(e,"c");return"markPriceUpdate"===i?this.safeTicker({symbol:a.symbol,timestamp:r,datetime:this.iso8601(r),info:e,markPrice:this.safeString(e,"p"),indexPrice:this.safeString(e,"i")}):this.safeTicker({symbol:a.symbol,timestamp:r,datetime:this.iso8601(r),high:this.safeString(e,"h"),low:this.safeString(e,"l"),bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:this.safeString(e,"w"),open:this.safeString(e,"o"),close:o,last:o,previousClose:void 0,change:this.safeString(e,"p"),percentage:this.safeString(e,"P"),average:void 0,baseVolume:this.safeString(e,"v"),quoteVolume:this.safeString(e,"q"),info:e},a)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s=void 0===i?[]:i,r=this.getMarketFromSymbols(s),o=this.safeString(r,"type","swap");if(0===s.length)throw new a.ArgumentsRequired(this.id+" watchBidsAsks() requires a non-empty array of symbols");let n=this.safeString(this.urls.api.ws.public,o);if(void 0===n)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let d=[],h=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t);d.push(this.safeStringLower(i,"id")+"@bookTicker"),h.push("bidask:"+i.symbol)}let c=await this.watchMultiple(n,h,this.extend({method:"SUBSCRIBE",params:d},t),h);if(this.newUpdates){let e={},t=this.safeString(c,"symbol");return void 0!==t&&(e[t]=c),e}return this.filterByArray(this.bidsasks,"symbol",s)}async unWatchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s=void 0===i?[]:i,r=this.getMarketFromSymbols(s),o=this.safeString(r,"type","swap");if(0===s.length)throw new a.ArgumentsRequired(this.id+" unWatchBidsAsks() requires a non-empty array of symbols");let n=this.safeString(this.urls.api.ws.public,o);if(void 0===n)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let d=[],h=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t);d.push(this.safeStringLower(i,"id")+"@bookTicker"),h.push("unsubscribe:bidask:"+i.symbol)}return await this.watchMultiple(n,h,this.extend({method:"UNSUBSCRIBE",params:d},t),h)}handleBidAsk(e,t){let i=this.getAccountTypeFromUrl(e.url),s=this.safeString(t,"s"),r=this.safeMarket(s,void 0,void 0,i),a=this.parseWsBidAsk(t,r),o=a.symbol;void 0!==o&&(this.bidsasks[o]=a),e.resolve(a,"bidask:"+o)}parseWsBidAsk(e,t){let i,s=this.safeInteger(e,"T");return void 0!==t&&(i=t.symbol),this.safeTicker({symbol:i,timestamp:s,datetime:this.iso8601(s),ask:this.safeString(e,"a"),askVolume:this.safeString(e,"A"),bid:this.safeString(e,"b"),bidVolume:this.safeString(e,"B"),info:e},t)}async watchTrades(e,t,i,s={}){return s.callerMethodName="watchTrades",await this.watchTradesForSymbols([e],t,i,s)}async unWatchTrades(e,t={}){return t.callerMethodName="unWatchTrades",await this.unWatchTradesForSymbols([e],t)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!0,!0,!0),o=this.getMarketFromSymbols(r),n=this.safeString(o,"type","swap"),d=r.length,[h,c]=this.handleParamString(s,"callerMethodName","watchTradesForSymbols"),l=this.omit(c,"callerMethodName");if(0===d)throw new a.ArgumentsRequired(this.id+" "+h+"() requires a non-empty array of symbols");let u=this.safeString(this.urls.api.ws.public,n);if(void 0===u)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let f=[],p=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.market(t),s=this.safeStringLower(i,"id");void 0!==s&&(f.push(s+"@aggTrade"),p.push("trade::"+i.symbol))}let m=await this.watchMultiple(u,p,this.extend({method:"SUBSCRIBE",params:f,id:1},l),p),g=this.safeDict(m,0),v=this.safeString(g,"symbol"),y=i;return this.newUpdates&&(y=m.getLimit(v,i)),this.filterBySinceLimit(m,t,y,"timestamp",!0)}async unWatchTradesForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s=this.getMarketFromSymbols(i),r=this.safeString(s,"type","swap"),o=i.length,[n,d]=this.handleParamString(t,"callerMethodName","unWatchTradesForSymbols"),h=this.omit(d,"callerMethodName");if(0===o)throw new a.ArgumentsRequired(this.id+" "+n+"() requires a non-empty array of symbols");let c=this.safeString(this.urls.api.ws.public,r);if(void 0===c)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let l=[],u=[];for(let e=0;e<i.length;e++){let t=i[e],s=this.market(t);l.push(this.safeStringLower(s,"id")+"@aggTrade"),u.push("unsubscribe:trade:"+s.symbol)}return await this.watchMultiple(c,u,this.extend({method:"UNSUBSCRIBE",params:l},h),u)}handleTrade(e,t){let i=this.getAccountTypeFromUrl(e.url),s=this.safeString(t,"s"),r=this.safeMarket(s,void 0,void 0,i),a=this.parseWsTrade(t,r),n=a.symbol;if(void 0===n)return;if(!(n in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.trades[n]=new o.I3(e)}let d=this.trades[n];d.append(a),e.resolve(d,"trade::"+n)}parseWsTrade(e,t){let i,s,a,o,n=this.safeString(e,"e"),d=this.safeString2(e,"t","a"),h=this.safeInteger(e,"T"),c=this.safeString2(e,"L","p");i="trade"===n||"aggTrade"===n?this.safeString(e,"q"):this.safeString(e,"l");let l=this.safeString(e,"Y");void 0===l&&void 0!==c&&void 0!==i&&(l=r.Y.stringMul(c,i));let u=this.safeString(e,"s");s=void 0===t?this.safeString(this.options,"defaultType","spot"):this.safeString(t,"type");let f=this.safeSymbol(u,t,void 0,s),p=this.safeStringLower(e,"S"),m=this.safeString(e,"i");"m"in e&&(void 0===p&&(p=this.safeBool(e,"m",!1)?"sell":"buy"),a=this.safeBool(e,"m",!1)?"maker":"taker");let g=this.safeString(e,"n");if(void 0!==g){let t=this.safeString(e,"N");o={cost:g,currency:this.safeCurrencyCode(t)}}let v=this.safeStringLower(e,"o");return this.safeTrade({info:e,timestamp:h,datetime:this.iso8601(h),symbol:f,id:d,order:m,type:v,takerOrMaker:a,side:p,price:c,amount:i,cost:l,fee:o})}async watchOrderBook(e,t,i={}){return i.callerMethodName="watchOrderBook",await this.watchOrderBookForSymbols([e],t,i)}async unWatchOrderBook(e,t={}){return t.callerMethodName="unWatchOrderBook",await this.unWatchOrderBookForSymbols([e],t)}async watchOrderBookForSymbols(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!0,!0,!0),r=this.getMarketFromSymbols(s),o=this.safeString(r,"type","swap"),n=s.length,[d,h]=this.handleParamString(i,"callerMethodName","watchOrderBookForSymbols"),c=this.omit(h,"callerMethodName");if(0===n)throw new a.ArgumentsRequired(this.id+" "+d+"() requires a non-empty array of symbols");let l=this.safeString(this.urls.api.ws.public,o);if(void 0===l)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let u=[],f=[],p=20;(5===t||10===t||20===t)&&(p=t);for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t);u.push(this.safeStringLower(i,"id")+"@depth"+p.toString()),f.push("orderbook:"+i.symbol)}return(await this.watchMultiple(l,f,this.extend({method:"SUBSCRIBE",params:u},c),f)).limit()}async unWatchOrderBookForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0,!0),s=this.getMarketFromSymbols(i),r=this.safeString(s,"type","swap"),o=i.length,[n,d]=this.handleParamString(t,"callerMethodName","unWatchOrderBookForSymbols"),h=this.omit(d,"callerMethodName");if(0===o)throw new a.ArgumentsRequired(this.id+" "+n+"() requires a non-empty array of symbols");let c=this.safeString(this.urls.api.ws.public,r);if(void 0===c)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let l=[],u=[],f=this.safeNumber(h,"limit"),p=this.omit(h,"limit");(void 0===f||5!==f&&10!==f&&20!==f)&&(f=20);for(let e=0;e<i.length;e++){let t=i[e],s=this.market(t);l.push(this.safeStringLower(s,"id")+"@depth"+f),u.push("unsubscribe:orderbook:"+s.symbol)}return await this.watchMultiple(c,u,this.extend({method:"UNSUBSCRIBE",params:l},p),u)}handleOrderBook(e,t){let i=this.getAccountTypeFromUrl(e.url),s=this.safeString(t,"s"),r=this.safeInteger(t,"T"),a=this.safeMarket(s,void 0,void 0,i).symbol;a in this.orderbooks||(this.orderbooks[a]=this.orderBook());let o=this.orderbooks[a],n=this.parseOrderBook(t,a,r,"b","a");o.reset(n);let d="orderbook:"+a;this.orderbooks[a]=o,e.resolve(o,d)}async watchOHLCV(e,t="1m",i,s,r={}){r.callerMethodName="watchOHLCV",void 0===this.markets&&await this.loadMarkets();let a=this.safeSymbol(e);return(await this.watchOHLCVForSymbols([[a,t]],i,s,r))[a][t]}async unWatchOHLCV(e,t="1m",i={}){return i.callerMethodName="unWatchOHLCV",await this.unWatchOHLCVForSymbols([[e,t]],i)}async watchOHLCVForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=e.length,[o,n]=this.handleParamString(s,"callerMethodName","watchOHLCVForSymbols"),d=this.omit(n,"callerMethodName");if(0===r)throw new a.ArgumentsRequired(this.id+" "+o+"() requires a non-empty array of symbols");let h=this.getListFromObjectValues(e,0),c=this.marketSymbols(h,void 0,!1,!0,!0),l=this.market(c[0]),u=this.safeString(l,"type","swap"),f=this.safeString(this.urls.api.ws.public,u);if(void 0===f)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let p=[],m=[];for(let t=0;t<e.length;t++){let i,s=this.safeList(e,t),r=this.safeString(s,0);if(void 0===r)continue;let a=this.market(r);r=this.safeString(a,"symbol");let o=this.safeString(s,1);i=void 0===o?void 0:this.safeString(this.timeframes,o,o),p.push(this.safeStringLower(a,"id")+"@kline_"+i),m.push("ohlcv:"+a.symbol+":"+o)}let[g,v,y]=await this.watchMultiple(f,m,this.extend({method:"SUBSCRIBE",params:p},d),m),b=i;this.newUpdates&&(b=y.getLimit(g,i));let w=this.filterBySinceLimit(y,t,b,0,!0);return this.createOHLCVObject(g,v,w)}async unWatchOHLCVForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=e.length,[s,r]=this.handleParamString(t,"callerMethodName","unWatchOHLCVForSymbols"),o=this.omit(r,"callerMethodName");if(0===i)throw new a.ArgumentsRequired(this.id+" "+s+"() requires a non-empty array of symbols");let n=this.getListFromObjectValues(e,0),d=this.marketSymbols(n,void 0,!1,!0,!0),h=this.market(d[0]),c=this.safeString(h,"type","swap"),l=this.safeString(this.urls.api.ws.public,c);if(void 0===l)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let u=[],f=[];for(let t=0;t<e.length;t++){let i,s=this.safeList(e,t),r=this.safeString(s,0);if(void 0===r)continue;let a=this.market(r);r=this.safeString(a,"symbol");let o=this.safeString(s,1);i=void 0===o?void 0:this.safeString(this.timeframes,o,o),u.push(this.safeStringLower(a,"id")+"@kline_"+i),f.push("unsubscribe:ohlcv:"+a.symbol+":"+o)}return await this.watchMultiple(l,f,this.extend({method:"UNSUBSCRIBE",params:u},o),f)}handleOHLCV(e,t){let i=this.getAccountTypeFromUrl(e.url),s=this.safeString(t,"s"),r=this.safeMarket(s,void 0,void 0,i).symbol,a=this.safeDict(t,"k"),n=this.safeString(a,"i"),d=this.findTimeframe(n);if(void 0===d)return;let h=this.safeDict(this.ohlcvs,r);if(void 0===h&&(this.ohlcvs[r]={}),void 0===this.safeValue(h,d)){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);this.ohlcvs[r][d]=new o.TG(e)}let c=this.ohlcvs[r][d],l=this.parseWsOHLCV(a);c.append(l);let u="ohlcv:"+r+":"+d,f=[r,d,c];e.resolve(f,u)}parseWsOHLCV(e,t){return[this.safeInteger(e,"t"),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}async authenticate(e="spot",t={}){let i=this.milliseconds(),s=this.safeDict(this.options,"lastAuthenticatedTime",{}),r=this.safeInteger(s,e,0),o=this.safeDict(this.options,"listenKeyRefreshRate",{}),n=this.safeInteger(o,e,36e5);if(i-r>n){let s="authenticate:"+e,r=this.client("authenticationFlights");if(s in r.futures)return void await r.future(s);let o=r.reusableFuture(s);try{let o={};o="spot"===e?await this.sapiPrivatePostV3ListenKey(t):await this.fapiPrivatePostV3ListenKey(t);let d=this.safeString(o,"listenKey");if(void 0===d)throw new a.AuthenticationError(this.id+" authenticate() received an empty listenKey");this.options.listenKey[e]=d,this.options.lastAuthenticatedTime[e]=i;let h=this.extend({type:e},t);this.delay(n,this.keepAliveListenKey,h),r.resolve(d,s)}catch(e){r.reject(e,s)}await o}}async keepAliveListenKey(e={}){let t=this.safeString(e,"type","spot"),i=this.safeDict(this.options,"listenKey",{}),s=this.safeString(i,t);if(void 0===s)return;try{"spot"===t?await this.sapiPrivatePutV3ListenKey():await this.fapiPrivatePutV3ListenKey()}catch(a){let e=this.safeString(this.urls.api.ws.private,t)+"/"+s,i=this.client(e),r=Object.keys(i.futures);for(let e=0;e<r.length;e++){let t=r[e];i.reject(a,t)}this.options.listenKey[t]=void 0,this.options.lastAuthenticatedTime[t]=0;return}let r=this.safeDict(this.options,"listenKeyRefresh",{}),a=this.safeInteger(r,"listenKeyRefreshRate",36e5);this.delay(a,this.keepAliveListenKey,e)}getPrivateUrl(e="spot"){let t=this.safeDict(this.options,"listenKey",{}),i=this.safeString(t,e);return this.safeString(this.urls.api.ws.private,e)+"/"+i}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t,[i,s]=this.handleMarketTypeAndParams("watchBalance",void 0,e,t);if(void 0===t)throw new a.ArgumentsRequired(this.id+" watchBalance() requires a market type");await this.authenticate(i,s);let r=this.getPrivateUrl(i),o=this.client(r);this.setBalanceCache(o,i);let n=this.safeDict(this.options,"watchBalance"),d=this.safeBool(n,"fetchBalanceSnapshot",!1),h=this.safeBool(n,"awaitBalanceSnapshot",!0);!0===d&&!0===h&&await o.future(i+":fetchBalanceSnapshot");let c=i+":balance";return await this.watch(r,c,void 0,i)}setBalanceCache(e,t){if(t in e.subscriptions&&t in this.balance)return;let i=this.safeDict(this.options,"watchBalance");if(!0===this.safeBool(i,"fetchBalanceSnapshot",!1)){let i=t+":fetchBalanceSnapshot";i in e.futures||(e.future(i),this.spawn(this.loadBalanceSnapshot,e,i,t))}else this.balance[t]={}}async loadBalanceSnapshot(e,t,i){let s=await this.fetchBalance({type:i});this.balance[i]=this.extend(s,this.safeDict(this.balance,i,{})),t in e.futures&&(e.futures[t].resolve(),e.resolve(this.balance[i],i+":balance"))}handleBalance(e,t){let i=this.getAccountTypeFromUrl(e.url);void 0===this.balance[i]&&(this.balance[i]={}),this.balance[i].info=t;let s=this.safeDict(t,"a",t),r=this.safeList(s,"B",[]),a=this.safeString(this.options,"wallet","wb");for(let e=0;e<r.length;e++){let t=r[e],s=this.safeString(t,"a"),o=this.safeCurrencyCode(s),n=this.account();n.free=this.safeString(t,"f"),n.used=this.safeString(t,"l"),n.total=this.safeString(t,a),void 0!==i&&void 0!==o&&(this.balance[i][o]=n)}let o=this.safeInteger(s,"E");this.balance[i].timestamp=o,this.balance[i].datetime=this.iso8601(o),this.balance[i]=this.safeBalance(this.balance[i]),e.resolve(this.balance[i],i+":balance")}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r="swap";await this.authenticate(r,s);let a=this.getPrivateUrl(r),o=this.client(a);this.setPositionsCache(o);let n=[],d="positions",h=this.marketSymbols(e,"swap",!0,!0);if(void 0===h)n.push(d);else for(let e=0;e<h.length;e++){let t=h[e];n.push(d+"::"+t)}let c=this.handleOption("watchPositions","fetchPositionsSnapshot",!0),l=this.handleOption("watchPositions","awaitPositionsSnapshot",!0),u=this.positions;if(!0===c&&!0===l&&void 0===u){let e=await o.future("fetchPositionsSnapshot");return this.filterBySymbolsSinceLimit(e,h,t,i,!0)}let f=await this.watchMultiple(a,n,void 0,[r]);return this.newUpdates?f:this.filterBySymbolsSinceLimit(u,h,t,i,!0)}setPositionsCache(e){if(void 0===this.positions)if(!0===this.handleOption("watchPositions","fetchPositionsSnapshot",!1)){let t="fetchPositionsSnapshot";t in e.futures||(e.future(t),this.spawn(this.loadPositionsSnapshot,e,t))}else this.positions=new o.Hk}async loadPositionsSnapshot(e,t){let i=await this.fetchPositions();this.positions=new o.Hk;let s=this.positions;for(let e=0;e<i.length;e++){let t=i[e],r=this.safeNumber(t,"contracts",0);void 0!==r&&r>0&&s.append(t)}t in e.futures&&(e.futures[t].resolve(s),e.resolve(s,"positions"))}handlePositions(e,t){let i="positions";void 0===this.positions&&(this.positions=new o.Hk);let s=this.positions,r=this.safeDict(t,"a",{}),a=this.safeList(r,"P",[]),n=[];for(let e=0;e<a.length;e++){let i=a[e],r=this.parseWsPosition(i),o=this.safeInteger(t,"E");r.timestamp=o,r.datetime=this.iso8601(o),n.push(r),s.append(r)}let d=this.findMessageHashes(e,i);if(!this.isEmpty(d)){for(let t=0;t<n.length;t++){let s=n[t],r=i+"::"+this.safeString(s,"symbol");e.resolve(s,r)}e.resolve(n,"positions")}}parseWsPosition(e,t){let i=this.safeString(e,"s"),s=this.safeString(e,"pa"),a=r.Y.stringAbs(this.safeString(e,"pa")),o=this.safeStringLower(e,"ps"),n=!0;return"both"===o&&(n=!1,r.Y.stringEq(s,"0")||(o=r.Y.stringLt(s,"0")?"short":"long")),this.safePosition({info:e,id:void 0,symbol:this.safeSymbol(i,void 0,void 0,"swap"),notional:void 0,marginMode:this.safeString(e,"mt"),liquidationPrice:void 0,entryPrice:this.safeNumber(e,"ep"),unrealizedPnl:this.safeNumber(e,"up"),percentage:void 0,contracts:this.parseNumber(a),contractSize:void 0,markPrice:void 0,side:o,hedged:n,timestamp:void 0,datetime:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,collateral:void 0,initialMargin:void 0,initialMarginPercentage:void 0,leverage:void 0,marginRatio:void 0})}async watchOrders(e,t,i,s={}){let r,o;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e),o=this.safeString(r,"symbol"));let n="orders",d,[h,c]=this.handleMarketTypeAndParams("watchOrders",r,s,d);if(void 0===d)throw new a.ArgumentsRequired(this.id+" watchOrders() requires a market type");await this.authenticate(h,c),void 0!==r&&(n+="::"+o);let l=this.getPrivateUrl(h),u=this.client(l);this.setBalanceCache(u,h);let f=await this.watchMultiple(l,[n],void 0,[h]),p=i;return this.newUpdates&&(p=f.getLimit(o,i)),this.filterBySymbolSinceLimit(f,o,t,p,!0)}async watchMyTrades(e,t,i,s={}){let r,o;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e),o=this.safeString(r,"symbol"));let n="myTrades",d,[h,c]=this.handleMarketTypeAndParams("watchMyTrades",r,s,d);if(void 0===d)throw new a.ArgumentsRequired(this.id+" watchMyTrades() requires a market type");await this.authenticate(h,c),void 0!==r&&(n+="::"+o);let l=this.getPrivateUrl(h),u=this.client(l);this.setBalanceCache(u,h);let f=await this.watchMultiple(l,[n],void 0,[h]),p=i;return this.newUpdates&&(p=f.getLimit(o,i)),this.filterBySymbolSinceLimit(f,o,t,p,!0)}handleOrderUpdate(e,t){let i=this.safeDict(t,"o",t),s=this.safeString(t,"e"),r=t;("ORDER_TRADE_UPDATE"===s||"ALGO_UPDATE"===s)&&(r=i),this.handleOrder(e,i),this.handleMyTrade(e,r)}handleMyTrade(e,t){let i="myTrades";if("TRADE"===this.safeString(t,"x")){let s=e.url.indexOf("fstream")>=0,r="spot";s&&(r="swap");let a=this.safeMarketStructure({type:r}),n=this.parseWsTrade(t,a),d=this.safeString(n,"order"),h=this.safeDict(n,"fee",{});h=this.extend({},h);let c=this.safeString(n,"symbol");if(void 0!==d&&void 0!==h&&void 0!==c){let e=this.orders;if(void 0!==e){let t=this.safeDict(e.hashmap,c,{}),i=this.safeDict(t,d);if(void 0!==i){let e=this.safeList(i,"fees",[]),t=this.safeDict(i,"fee");if(this.isEmpty(e))if(void 0!==t)if(this.safeString(t,"currency")===this.safeString(h,"currency")){let e=this.sum(t.cost,h.cost),s=this.currencyToPrecision(h.currency,e);i.fee.cost=void 0===s?void 0:parseFloat(s)}else void 0===this.safeString(t,"currency")?i.fee=h:(i.fees=[t,h],i.fee=void 0);else i.fee=h;else{let t=!0;for(let s=0;s<e.length;s++){let r=e[s];if(this.safeString(r,"currency")===this.safeString(h,"currency")){let e=this.sum(h.cost,r.cost),a=this.currencyToPrecision(h.currency,e);i.fees[s].cost=void 0===a?void 0:parseFloat(a),t=!1;break}}t&&i.fees.push(h)}let s=this.safeList(i,"trades",[]);s.push(n),i.trades=s}}}if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new o.Pt(e)}this.myTrades.append(n),e.resolve(this.myTrades,i);e.resolve(this.myTrades,i+"::"+c)}}handleOrder(e,t){let i="orders",s=this.getMarketFromOrder(e,t);if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}let r=this.orders,a=this.parseWsOrder(t,s),n=s.symbol;r.append(a);let d=this.findMessageHashes(e,i);if(!this.isEmpty(d)){let t=i+"::"+n;e.resolve(r,t),e.resolve(r,i)}}parseWsOrder(e,t){let i,s,a=this.safeString(e,"x"),o=this.safeString(e,"s"),n=this.safeMarket(o,t),d=this.safeInteger(e,"O"),h=this.safeInteger(e,"T");"NEW"===a||"AMENDMENT"===a||"CANCELED"===a?void 0===d&&(d=h):"TRADE"===a&&(i=h);let c=this.safeString(e,"n");if(void 0!==c&&r.Y.stringGt(c,"0")){let t=this.safeString(e,"N");s={cost:c,currency:this.safeCurrencyCode(t)}}let l=this.safeString(e,"X"),u=this.parseOrderStatus(l),f=this.safeString2(e,"C","caid");(void 0===f||0===f.length)&&(f=this.safeString(e,"c"));let p=this.safeStringN(e,["P","sp","tp"]),m=this.safeString(e,"f");return"GTX"===m&&(m="PO"),this.safeOrder({info:e,symbol:n.symbol,id:this.safeString2(e,"i","aid"),clientOrderId:f,timestamp:d,datetime:this.iso8601(d),lastTradeTimestamp:i,lastUpdateTimestamp:h,type:this.parseOrderType(this.safeStringLower(e,"o")),timeInForce:m,postOnly:void 0,reduceOnly:this.safeBool(e,"R"),side:this.safeStringLower(e,"S"),price:this.safeString(e,"p"),stopPrice:p,triggerPrice:p,amount:this.safeString(e,"q"),cost:this.safeString(e,"Z"),average:this.safeString(e,"ap"),filled:this.safeString(e,"z"),remaining:void 0,status:u,fee:s,trades:void 0})}getMarketFromOrder(e,t){let i=this.safeString(t,"s"),s=this.getAccountTypeFromUrl(e.url);return this.safeMarket(i,void 0,void 0,s)}handleBalanceAndPosition(e,t){this.handleBalance(e,t),this.handlePositions(e,t)}handleMessage(e,t){let i=this.safeDict(t,"data",t),s=this.safeString(i,"e"),r={"24hrTicker":this.handleTicker,aggTrade:this.handleTrade,depthUpdate:this.handleOrderBook,kline:this.handleOHLCV,markPriceUpdate:this.handleTicker,bookTicker:this.handleBidAsk,outboundAccountPosition:this.handleBalance,ACCOUNT_UPDATE:this.handleBalanceAndPosition,executionReport:this.handleOrderUpdate,ORDER_TRADE_UPDATE:this.handleOrderUpdate},a=void 0===s?void 0:this.safeValue(r,s);void 0!==a&&a.call(this,e,i)}}i.d(t,{A:()=>n})},6476(e,t,i){"use strict";var s=i(7468),r=i(9264),a=i(1453),o=i(1697),n=i(1093);class d extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!1,watchBidsAsks:!0,watchMyTrades:!1,watchOHLCV:!0,watchOHLCVForSymbols:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOrders:!0,watchPositions:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!0,unwatchBidsAsks:!0,unwatchOHLCV:!0,unwatchOHLCVForSymbols:!0,unwatchOrderBook:!0,unwatchOrderBookForSymbols:!0,unwatchTicker:!0,unwatchTickers:!0,unWatchTrades:!0,unWatchTradesForSymbols:!0,unWatchOrders:!0,unWatchPositions:!0},urls:{api:{ws:{public:"wss://ws.backpack.exchange",private:"wss://ws.backpack.exchange"}}},options:{timeframes:{}},streaming:{ping:this.ping,keepAlive:119e3}})}async watchPublic(e,t,i={},s=!1){void 0===this.markets&&await this.loadMarkets();let r=this.urls.api.ws.public,a="SUBSCRIBE";s&&(a="UNSUBSCRIBE");let o={method:a,params:e},n=this.deepExtend(o,i);return s?void this.handleUnsubscriptions(r,t,n):await this.watchMultiple(r,t,n,t)}async watchPrivate(e,t,i={},r=!1){this.checkRequiredCredentials();let a=this.urls.api.ws.private,o=this.nonce().toString(),d="SUBSCRIBE";r&&(d="UNSUBSCRIBE");let h=this.safeString2(this.options,"recvWindow","X-Window","5000"),c=this.base64ToBinary(this.secret),l=this.arraySlice(c,0,32),u=(0,n.q4)(this.encode("instruction=subscribe&timestamp="+o+"&window="+h),l,s.ev),f={method:d,params:e,signature:[this.apiKey,u,o,h]},p=this.deepExtend(f,i);return r?void this.handleUnsubscriptions(a,t,p):await this.watchMultiple(a,t,p,t)}handleUnsubscriptions(e,t,i){let s=this.client(e);this.watchMultiple(e,t,i,t);for(let e=0;e<t.length;e++){let i=t[e],r=i.replace("unsubscribe:","");if(this.cleanUnsubscription(s,r,i),i.indexOf("ticker")>=0){let e=i.replace("unsubscribe:ticker:","");e in this.tickers&&delete this.tickers[e]}else if(i.indexOf("bidask")>=0){let e=i.replace("unsubscribe:bidask:","");e in this.bidsasks&&delete this.bidsasks[e]}else if(i.indexOf("candles")>=0){let e=i.split(":"),t=this.safeString(e,2),s=this.safeString(e,3);void 0!==t&&void 0!==s&&t in this.ohlcvs&&s in this.ohlcvs[t]&&delete this.ohlcvs[t][s]}else if(i.indexOf("orderbook")>=0){let e=i.replace("unsubscribe:orderbook:","");e in this.orderbooks&&delete this.orderbooks[e]}else if(i.indexOf("trades")>=0){let e=i.replace("unsubscribe:trades:","");e in this.trades&&delete this.trades[e]}else if(i.indexOf("orders")>=0)if("unsubscribe:orders"===i){let e=this.orders;if(void 0!==e){let t=Object.keys(e);for(let i=0;i<t.length;i++){let s=t[i];delete e[s]}}}else{let e=i.replace("unsubscribe:orders:",""),t=this.orders;void 0!==t&&e in t&&delete t[e]}else if(i.indexOf("positions")>=0)if("unsubscribe:positions"===i){let e=Object.keys(this.positions);for(let t=0;t<e.length;t++){let i=e[t];delete this.positions[i]}}else{let e=i.replace("unsubscribe:positions:","");e in this.positions&&delete this.positions[e]}}}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r="ticker."+i.id;return await this.watchPublic([r],["ticker:"+s],t)}unWatchTicker(e,t={}){return this.unWatchTickers([e],t)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=[],r=[];for(let e=0;e<i.length;e++){let t=i[e],a=this.marketId(t);s.push("ticker:"+t),r.push("ticker."+a)}return await this.watchPublic(r,s,t),this.filterByArray(this.tickers,"symbol",i)}async unWatchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=[],r=[];for(let e=0;e<i.length;e++){let t=i[e],a=this.marketId(t);s.push("ticker."+a),r.push("unsubscribe:ticker:"+t)}return await this.watchPublic(s,r,t,!0)}handleTicker(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"s"),r=this.safeMarket(s),a=this.safeSymbol(s,r),o=this.parseWsTicker(i,r);this.tickers[a]=o,e.resolve(o,"ticker:"+a)}parseWsTicker(e,t){let i=this.safeInteger(e,"E",0),s=this.parseToInt(i/1e3),r=this.safeString(e,"s"),a=this.safeMarket(r,t),o=this.safeSymbol(r,a),n=this.safeString(e,"c"),d=this.safeString(e,"o");return this.safeTicker({symbol:o,timestamp:s,datetime:this.iso8601(s),high:this.safeNumber(e,"h"),low:this.safeNumber(e,"l"),bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:d,close:n,last:n,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"v"),quoteVolume:this.safeString(e,"V"),info:e},a)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=[],r=[];for(let e=0;e<i.length;e++){let t=i[e],a=this.marketId(t);s.push("bookTicker."+a),r.push("bidask:"+t)}return await this.watchPublic(s,r,t),this.filterByArray(this.bidsasks,"symbol",i)}async unWatchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=[],r=[];for(let e=0;e<i.length;e++){let t=i[e],a=this.marketId(t);s.push("bookTicker."+a),r.push("unsubscribe:bidask:"+t)}return await this.watchPublic(s,r,t,!0)}handleBidAsk(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"s"),r=this.safeMarket(s),a=this.safeSymbol(s,r),o=this.parseWsBidAsk(i,r);this.bidsasks[a]=o,e.resolve(o,"bidask:"+a)}parseWsBidAsk(e,t){let i=this.safeString(e,"s"),s=this.safeMarket(i,t),r=this.safeString(s,"symbol"),a=this.safeInteger(e,"E",0),o=this.parseToInt(a/1e3),n=this.safeString(e,"a"),d=this.safeString(e,"A"),h=this.safeString(e,"b"),c=this.safeString(e,"B");return this.safeTicker({symbol:r,timestamp:o,datetime:this.iso8601(o),ask:n,askVolume:d,bid:h,bidVolume:c,info:e},s)}async watchOHLCV(e,t="1m",i,s,r={}){return(await this.watchOHLCVForSymbols([[e,t]],i,s,r))[e][t]}unWatchOHLCV(e,t="1m",i={}){return this.unWatchOHLCVForSymbols([[e,t]],i)}async watchOHLCVForSymbols(e,t,i,s={}){if(0===e.length||!Array.isArray(e[0]))throw new a.ArgumentsRequired(this.id+" watchOHLCVForSymbols() requires a an array of symbols and timeframes, like  ['ETH/USDC', '1m']");void 0===this.markets&&await this.loadMarkets();let r=[],o=[];for(let t=0;t<e.length;t++){let i=this.safeList(e,t),s=this.safeString(i,0),a=this.market(s),n=this.safeString(i,1),d=this.safeString(this.timeframes,n,n);r.push("kline."+d+"."+a.id),o.push("candles:"+a.symbol+":"+d)}let[n,d,h]=await this.watchPublic(r,o,s),c=i;this.newUpdates&&(c=h.getLimit(n,i));let l=this.filterBySinceLimit(h,t,c,0,!0);return this.createOHLCVObject(n,d,l)}async unWatchOHLCVForSymbols(e,t={}){if(0===e.length||!Array.isArray(e[0]))throw new a.ArgumentsRequired(this.id+" unWatchOHLCVForSymbols() requires a an array of symbols and timeframes, like  ['ETH/USDC', '1m']");void 0===this.markets&&await this.loadMarkets();let i=[],s=[];for(let t=0;t<e.length;t++){let r=this.safeList(e,t),a=this.safeString(r,0),o=this.market(a),n=this.safeString(r,1),d=this.safeString(this.timeframes,n,n);i.push("kline."+d+"."+o.id),s.push("unsubscribe:candles:"+o.symbol+":"+d)}return await this.watchPublic(i,s,t,!0)}handleOHLCV(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"s"),r=this.market(s).symbol,a=this.safeString(t,"stream","").split("."),n=this.safeString(a,1,"");if(r in this.ohlcvs||(this.ohlcvs[r]={}),!(n in this.ohlcvs[r])){let e=this.safeInteger(this.options,"OHLCVLimit",1e3),t=new o.TG(e);this.ohlcvs[r][n]=t}let d=this.ohlcvs[r][n],h=this.parseWsOHLCV(i);d.append(h),e.resolve([r,n,d],"candles:"+r+":"+n)}parseWsOHLCV(e,t){return[this.parse8601(this.safeString(e,"T")),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}unWatchTrades(e,t={}){return this.unWatchTradesForSymbols([e],t)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e);if(0===r.length)throw new a.ArgumentsRequired(this.id+" watchTradesForSymbols() requires a non-empty array of symbols");let o=[],n=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.marketId(t);o.push("trade."+i),n.push("trades:"+t)}let d=await this.watchPublic(o,n,s),h=this.safeDict(d,0),c=this.safeString(h,"symbol"),l=i;this.newUpdates&&(l=d.getLimit(c,i));let u=this.filterBySinceLimit(d,t,l,"timestamp",!0);return this.sortBy(u,"timestamp")}async unWatchTradesForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e);if(0===i.length)throw new a.ArgumentsRequired(this.id+" unWatchTradesForSymbols() requires a non-empty array of symbols");let s=[],r=[];for(let e=0;e<i.length;e++){let t=i[e],a=this.marketId(t);s.push("trade."+a),r.push("unsubscribe:trades:"+t)}return await this.watchPublic(s,r,t,!0)}handleTrades(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"s"),r=this.market(s),a=r.symbol;if(!(a in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3),t=new o.I3(e);this.trades[a]=t}let n=this.trades[a],d=this.parseWsTrade(i,r);n.append(d),e.resolve(n,"trades:"+a),e.resolve(n,"trades")}parseWsTrade(e,t){let i,s,r,a=this.safeInteger(e,"E",0),o=this.parseToInt(a/1e3),n=this.safeString(e,"t"),d=this.safeString(e,"s"),h=this.safeMarket(d,t),c=this.safeBool(e,"m");void 0!==c&&(s="taker",i=c?"sell":"buy");let l=this.safeString(e,"p"),u=this.safeString(e,"q");return r="buy"===i?this.safeString(e,"b"):this.safeString(e,"a"),this.safeTrade({info:e,id:n,timestamp:o,datetime:this.iso8601(o),symbol:h.symbol,order:r,type:void 0,side:i,takerOrMaker:s,price:l,amount:u,cost:void 0,fee:{currency:void 0,cost:void 0}},h)}watchOrderBook(e,t,i={}){return this.watchOrderBookForSymbols([e],t,i)}async watchOrderBookForSymbols(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!1),r=this.marketIds(s),a=[],o=[];for(let e=0;e<s.length;e++){let t=s[e];a.push("orderbook:"+t);let i="depth."+r[e];o.push(i)}return(await this.watchPublic(o,a,i)).limit()}unWatchOrderBook(e,t={}){return this.unWatchOrderBookForSymbols([e],t)}async unWatchOrderBookForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=this.marketIds(i),r=[],a=[];for(let e=0;e<i.length;e++){let t=i[e];r.push("unsubscribe:orderbook:"+t);let o="depth."+s[e];a.push(o)}return await this.watchPublic(a,r,t,!0)}handleOrderBook(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"s"),r=this.safeSymbol(s);r in this.orderbooks||(this.orderbooks[r]=this.orderBook());let a=this.orderbooks[r],o=this.safeInteger(a,"nonce"),n=this.safeInteger(i,"u"),d="orderbook:"+r;if(void 0===o){a.cache.length===this.handleOption("watchOrderBook","snapshotDelay",10)&&this.spawn(this.loadOrderBook,e,d,r,null,{}),a.cache.push(i);return}void 0!==n&&o>n||(this.handleBookDelta(a,i),e.resolve(a,d))}handleBookDelta(e,t){let i=this.parseToInt(this.safeInteger(t,"T",0)/1e3);e.timestamp=i,e.datetime=this.iso8601(i),e.nonce=this.safeInteger(t,"u");let s=this.safeList(t,"b",[]),r=this.safeList(t,"a",[]),a=e.bids,o=e.asks;this.handleBidAsks(a,s),this.handleBidAsks(o,r)}handleBidAsks(e,t){for(let i=0;i<t.length;i++){let s=this.parseOrderBookBidAsk(t[i]);e.storeArray(s)}}getCacheIndex(e,t){let i=this.safeDict(t,0),s=this.safeInteger(e,"nonce"),r=this.safeInteger(i,"U");if(void 0===s)return t.length;if(void 0===r||s<r-1)return -1;for(let e=0;e<t.length;e++){let i=this.safeDict(t,e),r=this.safeInteger(i,"U"),a=this.safeInteger(i,"u");if(void 0===r||void 0===a)break;if(s>=r-1&&s<a)return e}return t.length}async watchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a=void 0!==r?this.safeString(r,"symbol"):e,o="account.orderUpdate",n="orders";void 0!==r&&(o="account.orderUpdate."+r.id,n="orders:"+a);let d=await this.watchPrivate([o],[n],s),h=i;return this.newUpdates&&(h=d.getLimit(a,i)),this.filterBySymbolSinceLimit(d,a,t,h,!0)}async unWatchOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(i=this.market(e));let s=void 0!==i?i.symbol:e,r="account.orderUpdate",a="unsubscribe:orders";return void 0!==i&&(r="account.orderUpdate."+i.id,a="unsubscribe:orders:"+s),await this.watchPrivate([r],[a],t,!0)}handleOrder(e,t){let i="orders",s=this.safeDict(t,"data",{}),r=this.safeString(s,"s"),a=this.safeMarket(r),n=a.symbol,d=this.parseWsOrder(s,a),h=this.orders;if(void 0===h){let e=this.safeInteger(this.options,"ordersLimit",1e3);h=new o.Pt(e),this.orders=h}h.append(d),e.resolve(h,i),e.resolve(h,i+":"+n)}parseWsOrder(e,t){let i,s=this.safeString(e,"i"),r=this.safeString(e,"c"),a=this.safeInteger(e,"E",0),o=this.parseToInt(a/1e3),n=this.parseWsOrderStatus(this.safeString(e,"X"),t),d=this.safeString(e,"s"),h=this.safeMarket(d,t),c=h.symbol,l=this.safeStringLower(e,"o"),u=this.safeString(e,"f"),f=this.parseWsOrderSide(this.safeString(e,"S")),p=this.safeString(e,"p"),m=this.safeNumber(e,"P"),g=this.safeString(e,"q"),v=this.safeString(e,"Z"),y=this.safeString(e,"l"),b=this.safeString(e,"N");return void 0!==b&&(i={currency:b,cost:void 0}),this.safeOrder({id:s,clientOrderId:r,timestamp:o,datetime:this.iso8601(o),lastTradeTimestamp:void 0,status:n,symbol:c,type:l,timeInForce:u,side:f,price:p,stopPrice:void 0,triggerPrice:m,average:void 0,amount:g,cost:v,filled:y,remaining:void 0,fee:i,trades:void 0,info:e},h)}parseWsOrderStatus(e,t){return this.safeString({New:"open",Filled:"closed",Cancelled:"canceled",Expired:"canceled",PartiallyFilled:"open",TriggerPending:"open",TriggerFailed:"rejected"},e,e)}parseWsOrderSide(e){return this.safeString({Bid:"buy",Ask:"sell"},e,e)}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e),a=[],o=[];if(void 0!==r)for(let e=0;e<r.length;e++){let t=r[e];a.push("positions:"+t),o.push("account.positionUpdate."+this.marketId(t))}else a.push("positions"),o.push("account.positionUpdate");let n=await this.watchPrivate(o,a,s);return this.newUpdates?n:this.filterBySymbolsSinceLimit(this.positions,r,t,i,!0)}async unWatchPositions(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=[],r=[];if(void 0!==i)for(let e=0;e<i.length;e++){let t=i[e];s.push("unsubscribe:positions:"+t),r.push("account.positionUpdate."+this.marketId(t))}else s.push("unsubscribe:positions"),r.push("account.positionUpdate");return await this.watchPrivate(r,s,t,!0)}handlePositions(e,t){let i="positions",s=this.safeDict(t,"data",{});void 0===this.positions&&(this.positions=new o.Pt);let r=this.positions,a=this.parseWsPosition(s),n=this.safeInteger(s,"E",0),d=this.parseToInt(n/1e3);a.timestamp=d,a.datetime=this.iso8601(d),r.append(a);let h=i+":"+a.symbol;e.resolve([a],i),e.resolve([a],h)}parseWsPosition(e,t){let i=this.safeString(e,"i"),s=this.safeString(e,"s"),r=this.safeMarket(s,t).symbol,a=this.safeString(e,"n"),o=this.safeString(e,"l"),n=this.safeString(e,"b"),d=this.safeString(e,"p"),h=this.safeString(e,"P"),c=this.safeString(e,"Q"),l=this.safeString(e,"M"),u=this.safeNumber(e,"q"),f=!1,p="long";void 0!==u?u<0&&(p="short"):(f=void 0,p=void 0);let m=this.safeInteger(e,"E",0),g=this.parseToInt(m/1e3),v=this.safeNumber(e,"m"),y=this.safeNumber(e,"f");return this.safePosition({info:e,id:i,symbol:r,notional:a,marginMode:void 0,liquidationPrice:o,entryPrice:n,realizedPnl:d,unrealizedPnl:h,percentage:void 0,contracts:c,contractSize:void 0,markPrice:l,side:p,hedged:f,timestamp:g,datetime:this.iso8601(g),maintenanceMargin:void 0,maintenanceMarginPercentage:v,collateral:void 0,initialMargin:void 0,initialMarginPercentage:y,leverage:void 0,marginRatio:void 0})}handleMessage(e,t){if(!0!==this.handleErrorMessage(e,t))return;let i=this.safeDict(t,"data"),s=this.safeString(i,"e");"ticker"===s?this.handleTicker(e,t):"bookTicker"===s?this.handleBidAsk(e,t):"kline"===s?this.handleOHLCV(e,t):"trade"===s?this.handleTrades(e,t):"depth"===s?this.handleOrderBook(e,t):"orderAccepted"===s||"orderUpdate"===s||"orderFill"===s||"orderCancelled"===s||"orderExpired"===s||"orderModified"===s||"triggerPlaced"===s||"triggerFailed"===s?this.handleOrder(e,t):("positionAdjusted"===s||"positionOpened"===s||"positionClosed"===s||"positionUpdated"===s)&&this.handlePositions(e,t)}handleErrorMessage(e,t){let i=this.safeDict(t,"error",{}),s=this.safeInteger(i,"code");try{if(void 0!==s){let e=this.safeString(i,"message");throw new a.ExchangeError(this.id+" "+e)}}catch(t){e.reject(t)}return!0}}i.d(t,{A:()=>d})},5284(e,t,i){"use strict";var s=i(3906),r=i(6192);class a extends s.A{describe(){let e=new r.A().describe(),t=super.describeData(),i=this.deepExtend(e,t);return this.deepExtend(i,{id:"bequant",name:"Bequant",countries:["MT"],pro:!0,urls:{logo:"https://user-images.githubusercontent.com/1294454/55248342-a75dfe00-525a-11e9-8aa2-05e9dca943c6.jpg",api:{public:"https://api.bequant.io/api/3",private:"https://api.bequant.io/api/3",ws:{public:"wss://api.bequant.io/api/3/ws/public",private:"wss://api.bequant.io/api/3/ws/trading"}},www:"https://bequant.io",doc:["https://api.bequant.io/"],fees:["https://bequant.io/fees-and-limits"],referral:"https://bequant.io"}})}}i.d(t,{A:()=>a})},7802(e,t,i){"use strict";var s=i(4721),r=i(7468),a=i(2222),o=i(7749),n=i(1453),d=i(1697),h=i(8748),c=i(1093);class l extends a.A{describe(){let e=super.describe();return this.deepExtend(e,this.describeData())}describeData(){return{has:{ws:!0,watchBalance:!0,watchLiquidations:!0,watchLiquidationsForSymbols:!0,watchMyLiquidations:!0,watchMyLiquidationsForSymbols:!0,watchBidsAsks:!0,watchMyTrades:!0,watchOHLCV:!0,watchOHLCVForSymbols:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOrders:!0,watchOrdersForSymbols:!0,watchPositions:!0,watchTicker:!0,watchTickers:!0,watchMarkPrices:!0,watchMarkPrice:!0,watchTrades:!0,watchTradesForSymbols:!0,createOrderWs:!0,editOrderWs:!0,cancelOrderWs:!0,cancelOrdersWs:!1,cancelAllOrdersWs:!0,fetchBalanceWs:!0,fetchDepositsWs:!1,fetchMarketsWs:!1,fetchMyTradesWs:!0,fetchOHLCVWs:!0,fetchOrderBookWs:!0,fetchOpenOrdersWs:!0,fetchOrderWs:!0,fetchOrdersWs:!0,fetchPositionWs:!0,fetchPositionForSymbolWs:!0,fetchPositionsWs:!0,fetchTickerWs:!0,fetchTradesWs:!0,fetchTradingFeesWs:!1,fetchWithdrawalsWs:!1,unWatchTicker:!0,unWatchTickers:!0,unWatchOHLCV:!0,unWatchOHLCVForSymbols:!0,unWatchOrderBook:!0,unWatchOrderBookForSymbols:!0,unWatchTrades:!0,unWatchTradesForSymbols:!0,unWatchMyTrades:!1,unWatchOrders:!1,unWatchPositions:!1,unWatchMarkPrices:!0,unWatchMarkPrice:!0,unWatchBidsAsks:!0},urls:{test:{ws:{spot:"wss://stream.testnet.binance.vision/ws",margin:"wss://stream.testnet.binance.vision/ws",future:"wss://fstream.binancefuture.com/ws",delivery:"wss://dstream.binancefuture.com/ws","ws-api":{spot:"wss://ws-api.testnet.binance.vision/ws-api/v3",future:"wss://testnet.binancefuture.com/ws-fapi/v1",delivery:"wss://testnet.binancefuture.com/ws-dapi/v1"}}},demo:{ws:{spot:"wss://demo-stream.binance.com/ws",margin:"wss://demo-stream.binance.com/ws",future:"wss://fstream.binancefuture.com/ws",delivery:"wss://dstream.binancefuture.com/ws","ws-api":{spot:"wss://demo-ws-api.binance.com/ws-api/v3",future:"wss://testnet.binancefuture.com/ws-fapi/v1",delivery:"wss://testnet.binancefuture.com/ws-dapi/v1"}}},api:{ws:{spot:"wss://stream.binance.com:9443/ws",margin:"wss://stream.binance.com:9443/ws",future:"wss://fstream.binance.com/ws",delivery:"wss://dstream.binance.com/ws",stock:"wss://nbstream.binance.com/equity/ws",option:"wss://fstream.binance.com/public/ws",optionMarket:"wss://fstream.binance.com/market/ws",optionPrivate:"wss://fstream.binance.com/private/ws","ws-api":{spot:"wss://ws-api.binance.com:443/ws-api/v3",future:"wss://ws-fapi.binance.com/ws-fapi/v1",delivery:"wss://ws-dapi.binance.com/ws-dapi/v1"},papi:"wss://fstream.binance.com/pm/ws"}},doc:"https://developers.binance.com/en"},streaming:{keepAlive:18e4},options:{returnRateLimits:!1,streamLimits:{spot:50,margin:50,future:50,delivery:50,stock:50,option:50,optionMarket:50},subscriptionLimitByStream:{spot:200,margin:200,future:200,delivery:200,stock:200,option:200,optionMarket:200},streamBySubscriptionsHash:this.createSafeDictionary(),streamIndex:-1,watchOrderBookRate:"100",liquidationsLimit:1e3,myLiquidationsLimit:1e3,tradesLimit:1e3,ordersLimit:1e3,OHLCVLimit:1e3,requestId:this.createSafeDictionary(),watchOrderBookLimit:1e3,watchTrades:{name:"trade"},watchTicker:{name:"ticker"},watchTickers:{name:"miniTicker"},watchOHLCV:{name:"kline"},watchOrderBook:{maxRetries:3,checksum:!0},option:{listenKey:void 0,lastAuthenticatedTime:0},watchBalance:{fetchBalanceSnapshot:!1,awaitBalanceSnapshot:!0},watchLiquidationsForSymbols:{defaultType:"swap"},watchPositions:{fetchPositionsSnapshot:!0,awaitPositionsSnapshot:!0},wallet:"wb",listenKeyRefreshRate:12e5,stockListenKeyRefreshRate:12e5,ws:{cost:5},tickerChannelsMap:{price:"price",quote:"quote","24hrTicker":"ticker","24hrMiniTicker":"miniTicker",markPriceUpdate:"markPrice",markPrice:"markPrice","1hTicker":"ticker_1h","4hTicker":"ticker_4h","1dTicker":"ticker_1d",bookTicker:"bookTicker"}}}}requestId(e){let t=this.safeDict(this.options,"requestId",this.createSafeDictionary()),i=this.safeInteger(t,e,0),s=this.sum(i,1);return this.options.requestId[e]=s,s}isSpotUrl(e){return e.url.indexOf("/stream")>-1||e.url.indexOf("demo-stream")>-1}stream(e,t,i=1){let s=this.safeDict(this.options,"streamBySubscriptionsHash",this.createSafeDictionary()),r=this.safeString(s,t);if(void 0===r){let s=this.safeInteger(this.options,"streamIndex",-1),a=this.safeDict(this.options,"streamLimits"),o=(s+=1)%this.safeInteger(a,e);this.options.streamIndex=s,r=this.numberToString(o),void 0!==t&&(this.options.streamBySubscriptionsHash[t]=r),void 0===this.safeDict(this.options,"numSubscriptionsByStream")&&(this.options.numSubscriptionsByStream=this.createSafeDictionary());let d=this.safeInteger(this.options.numSubscriptionsByStream,r,0);if(d+i>this.safeInteger(this.options.subscriptionLimitByStream,e,200))throw new n.BadRequest(this.id+" reached the limit of subscriptions by stream. Increase the number of streams, or increase the stream limit or subscription limit by stream if the exchange allows.");this.options.numSubscriptionsByStream[r]=d+i}return r}getWsUrl(e,t){if("option"===e||"optionMarket"===e||"optionPrivate"===e)return this.urls.api.ws[e];let i=this.urls.api.ws[e];if("future"===e){if(i.split("://").length>2)return i;if(i.endsWith("/ws"))return i.slice(0,i.length-3)+"/"+t+"/ws"}return i}getFutureWsCategory(e){return"depth"===e||"rpiDepth"===e||"bookTicker"===e||"trade"===e?"public":"market"}getPrivateWsUrl(e,t){if(void 0===t)throw new n.AuthenticationError(this.id+" getPrivateWsUrl() requires a listenKey from authenticate()");if("future"===e)return this.getWsUrl(e,"private")+"?listenKey="+t;let i=this.safeString(this.urls.api.ws,e);if(void 0===i)throw new n.ExchangeError(this.id+" getPrivateWsUrl() has no websocket url for this market type");return i+"/"+t}getStockWsUrl(e="market"){let t=this.urls.api.ws.stock;return"combined"===e?t.replace("/ws","/stream"):t}getStockTickerFromSymbol(e){let t=this.market(e),i=this.safeString2(t,"base","id");return void 0===i?void 0:i.toLowerCase()}getStockUnifiedSymbol(e,t){if(void 0===e)return;let i=t;void 0===t&&(i="USDC");let s=this.safeSymbol(e,void 0,"/","spot");return void 0!==s&&s.indexOf("/")>=0?s:e+"/"+i}async watchStockMarketStream(e,t,i={}){let s=this.getStockWsUrl("market"),r=this.requestId(s),a=this.omit(i,["stock","name","callerMethodName","type","subType","symbol","timeframe"]);return await this.watchMultiple(s,t,this.extend({method:"SUBSCRIBE",params:e,id:r},a),t,{id:r})}watchLiquidations(e,t,i,s={}){return this.watchLiquidationsForSymbols([e],t,i,s)}async watchLiquidationsForSymbols(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=[],o=[],d="liquidations",h=this.marketSymbols(e,void 0,!0,!0);if(this.isEmpty(h))a.push("!forceOrder@arr"),o.push("liquidations");else{for(let e=0;e<h.length;e++){let t=this.market(h[e]);a.push(t.lowercaseId+"@forceOrder"),o.push("liquidations::"+h[e])}d+="::"+h.join(",")}this.isEmpty(h)||(r=this.getMarketFromSymbols(h));let c=this.resolveAuthType("watchLiquidationsForSymbols",r,s),l=c[0],u=c[2];if("spot"===l)throw new n.BadRequest(this.id+" watchLiquidationsForSymbols is not supported for spot symbols");if("option"===l)throw new n.NotSupported(this.id+" watchLiquidationsForSymbols() does not support options markets, there is no public liquidation stream for eOptions");let f=a.length,p=this.getWsUrl(l,this.getFutureWsCategory("forceOrder"))+"/"+this.stream(l,d,f),m=this.requestId(p),g=await this.watchMultiple(p,o,this.extend({method:"SUBSCRIBE",params:a,id:m},u),a,{id:m});return this.newUpdates?g:this.filterBySymbolsSinceLimit(this.liquidations,h,t,i,!0)}handleLiquidation(e,t){let i=this.safeDict(t,"o",{}),s=this.safeString(i,"s"),r=this.safeMarket(s,void 0,"","contract"),a=r.symbol,o=this.parseWsLiquidation(i,r);if(void 0===this.liquidations){let e=this.safeInteger(this.options,"liquidationsLimit",1e3);this.liquidations=new d.I3(e)}this.liquidations.append(o),e.resolve([o],"liquidations"),e.resolve([o],"liquidations::"+a)}parseWsLiquidation(e,t){let i=this.safeString(e,"s"),s=this.safeMarket(i,t,void 0,"swap"),r=this.safeInteger(e,"T");return this.safeLiquidation({info:e,symbol:this.safeSymbol(i,s),contracts:this.safeNumber(e,"l"),contractSize:this.safeNumber(s,"contractSize"),price:this.safeNumber(e,"ap"),side:this.safeStringLower(e,"S"),baseValue:void 0,quoteValue:void 0,timestamp:r,datetime:this.iso8601(r)})}watchMyLiquidations(e,t,i,s={}){return this.watchMyLiquidationsForSymbols([e],t,i,s)}async watchMyLiquidationsForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!0,!0,!0),a=this.getMarketFromSymbols(r),o=["myLiquidations"];if(!this.isEmpty(r))for(let e=0;e<r.length;e++){let t=r[e];o.push("myLiquidations::"+t)}let[n,d,h]=this.resolveAuthType("watchMyLiquidationsForSymbols",a,s);await this.authenticate(this.extend({type:n,subType:d},h));let c=this.options[n].listenKey,l=this.getPrivateWsUrl(n,c),u=await this.watchMultiple(l,o,void 0,[n]);return this.newUpdates?u:this.filterBySymbolsSinceLimit(this.liquidations,r,t,i)}handleMyLiquidation(e,t){if("LIQUIDATION"!==this.safeString(t,"o"))return;let i=this.safeString(t,"s"),s=this.safeMarket(i,void 0,void 0,"swap"),r=this.safeSymbol(i,s),a=this.parseWsLiquidation(t,s),o=this.myLiquidations;if(void 0===o){let e=this.safeInteger(this.options,"myLiquidationsLimit",1e3);o=new d.I3(e)}o.append(a),this.myLiquidations=o,e.resolve([a],"myLiquidations"),e.resolve([a],"myLiquidations::"+r)}watchOrderBook(e,t,i={}){return this.watchOrderBookForSymbols([e],t,i)}async watchOrderBookForSymbols(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!1,!0,!0),r=this.market(s[0]),a=r.type;!0===r.option?a="option":!0===r.contract&&(a=!0===r.linear?"future":"delivery");let o="depth",d="multipleOrderbook";if(void 0!==s){if(s.length>200)throw new n.BadRequest(this.id+" watchOrderBookForSymbols() accepts 200 symbols at most. To watch more symbols call watchOrderBookForSymbols() multiple times");d+="::"+s.join(",")}let[h,c]=this.handleOptionStringAndParams(i,"watchOrderBookForSymbols","watchOrderBookRate","100"),l=h,[u,f]=this.handleOptionBoolAndParams(c,"watchOrderBookForSymbols","rpi",!1);u&&"future"===a&&(o="rpiDepth",l="500");let p=[],m=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t);m.push("orderbook::"+t);let r=i.lowercaseId+"@"+o;if(void 0===l)throw new n.ArgumentsRequired(this.id+" watchOrderBookForSymbols() watchOrderBookRate is required");let a=r+"@"+l.toString()+"ms";p.push(a)}let g=m.length,v=this.getWsUrl(a,this.getFutureWsCategory(o))+"/"+this.stream(a,d,g),y=this.requestId(v),b={id:y.toString(),name:o,symbols:s,method:this.handleOrderBookSubscription,limit:t,type:a,params:f};return(await this.watchMultiple(v,m,this.extend({method:"SUBSCRIBE",params:p,id:y},f),m,b)).limit()}async unWatchOrderBookForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1,!0,!0),s=this.market(i[0]),r=s.type;!0===s.option?r="option":!0===s.contract&&(r=!0===s.linear?"future":"delivery");let a="multipleOrderbook";void 0!==i&&(a+="::"+i.join(","));let o=this.safeString(this.options,"watchOrderBookRate","100"),n=[],d=[],h=[];for(let e=0;e<i.length;e++){let t=i[e],s=this.market(t);d.push("orderbook::"+t),h.push("unsubscribe:orderbook:"+t);let r=s.lowercaseId+"@depth@"+o+"ms";n.push(r)}let c=d.length,l=this.getWsUrl(r,this.getFutureWsCategory("depth"))+"/"+this.stream(r,a,c),u=this.requestId(l),f={unsubscribe:!0,id:u.toString(),symbols:i,subMessageHashes:d,messageHashes:h,topic:"orderbook"};return await this.watchMultiple(l,h,this.extend({method:"UNSUBSCRIBE",params:n,id:u},t),h,f)}unWatchOrderBook(e,t={}){return this.unWatchOrderBookForSymbols([e],t)}async fetchOrderBookWs(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r={symbol:s.id};void 0!==t&&(r.limit=t);let a=this.getMarketType("fetchOrderBookWs",s,i);if("future"!==a)throw new n.BadRequest(this.id+" fetchOrderBookWs only supports swap markets");let o=this.safeString(this.urls.api.ws["ws-api"],a);if(void 0===o)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let d=this.requestId(o).toString(),[h,c]=this.handleOptionBoolAndParams(i,"fetchOrderBookWs","returnRateLimits",!1);r.returnRateLimits=h;let l=this.omit(c,"test"),u={id:d,method:"depth",params:this.signParams(this.extend(r,l))},f={method:this.handleFetchOrderBook},p=await this.watch(o,d,u,d,f);return p.symbol=s.symbol,p}handleFetchOrderBook(e,t){let i=this.safeString(t,"id"),s=this.safeDict(t,"result"),r=this.safeInteger(s,"T"),a=this.parseOrderBook(s,void 0,r);a.nonce=this.safeInteger2(s,"lastUpdateId","u"),e.resolve(a,i)}async fetchOrderBookSnapshot(e,t,i){let s=this.safeString(i,"symbol"),r="orderbook::"+s;try{let t=this.safeInteger(this.options,"watchOrderBookLimit",1e3),a=this.safeString(i,"type"),o=this.safeInteger(i,"limit",t),n=this.safeDict(i,"params"),d=await this.fetchRestOrderBookSafe(s,o,n);if(void 0===this.safeValue(this.orderbooks,s))return;let h=this.safeValue(this.orderbooks,s);h.reset(d);let c=h.cache;h.cache=[];for(let t=0;t<c.length;t++){let i=c[t],s=this.safeInteger(i,"U"),r=this.safeInteger(i,"u");if(void 0===s||void 0===r)continue;let o=this.safeInteger(i,"pu");if("future"===a){if(r<h.nonce)continue;(s<=h.nonce&&r>=h.nonce||o===h.nonce)&&this.handleOrderBookMessage(e,i,h)}else{if(r<=h.nonce)continue;s-1<=h.nonce&&r-1>=h.nonce&&this.handleOrderBookMessage(e,i,h)}}void 0!==s&&(this.orderbooks[s]=h),e.resolve(h,r)}catch(t){delete e.subscriptions[r],e.reject(t,r)}}handleDelta(e,t){let i=this.safeFloat(t,0),s=this.safeFloat(t,1);e.store(i,s)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}handleOrderBookMessage(e,t,i){let s=this.safeInteger(t,"u");this.handleDeltas(i.asks,this.safeList(t,"a",[])),this.handleDeltas(i.bids,this.safeList(t,"b",[])),i.nonce=s;let r=this.safeInteger(t,"E");return i.timestamp=r,i.datetime=this.iso8601(r),i}handleOrderBook(e,t){let i=this.safeString(t,"s"),s=this.isSpotUrl(e),r="swap";s&&(r="spot");let a=this.safeMarket(i,void 0,void 0,r).symbol,o="orderbook::"+a;if(!(a in this.orderbooks))return;let d=this.orderbooks[a],h=this.safeInteger(d,"nonce");if(void 0===h)d.cache.push(t);else try{let i=this.safeInteger(t,"U");if(void 0===i)return;let s=this.safeInteger(t,"u");if(void 0===s)return;let r=this.safeInteger(t,"pu");if(void 0===r){if(s>h){let r=this.safeInteger(d,"timestamp");if(void 0===r?i-1<=h&&s-1>=h:i-1===h)this.handleOrderBookMessage(e,t,d),h<this.safeInteger(d,"nonce",0)&&e.resolve(d,o);else{let e=this.handleOption("watchOrderBook","checksum",!0);if(!0===e)throw new n.ChecksumError(this.id+" "+this.orderbookChecksumMessage(a))}}}else if(s>=h)if(i<=h||r===h)this.handleOrderBookMessage(e,t,d),h<=this.safeInteger(d,"nonce",0)&&e.resolve(d,o);else{let e=this.handleOption("watchOrderBook","checksum",!0);if(!0===e)throw new n.ChecksumError(this.id+" "+this.orderbookChecksumMessage(a))}}catch(t){a in this.orderbooks&&delete this.orderbooks[a],o in e.subscriptions&&delete e.subscriptions[o],e.reject(t,o)}}handleOrderBookSubscription(e,t,i){let s=this.safeInteger(this.options,"watchOrderBookLimit",1e3),r=this.safeString(i,"symbol"),a=this.safeList(i,"symbols",[r]),o=this.safeInteger(i,"limit",s);for(let s=0;s<a.length;s++){let r=a[s];r in this.orderbooks&&delete this.orderbooks[r],this.orderbooks[r]=this.orderBook({},o);let n=this.extend(i,{symbol:r});this.spawn(this.fetchOrderBookSnapshot,e,t,n)}}handleSubscriptionStatus(e,t){let i=this.safeString(t,"id"),s=this.indexBy(e.subscriptions,"id"),r=this.safeDict(s,i,{}),a=this.safeValue(r,"method");return void 0!==a&&a.call(this,e,t,r),!0===this.safeBool(r,"unsubscribe",!1)&&this.handleUnSubscription(e,r),t}handleUnSubscription(e,t){let i=this.safeList(t,"messageHashes",[]),s=this.safeList(t,"subMessageHashes",[]);for(let t=0;t<i.length;t++){let r=i[t],a=s[t];this.cleanUnsubscription(e,a,r)}this.cleanCache(t)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!1,!0,!0),a="multipleTrades";if(void 0!==r){if(r.length>200)throw new n.BadRequest(this.id+" watchTradesForSymbols() accepts 200 symbols at most. To watch more symbols call watchTradesForSymbols() multiple times");a+="::"+r.join(",")}let[o,d]=this.handleOptionStringAndParams(s,"watchTradesForSymbols","name","trade"),h=this.omit(d,"callerMethodName"),c=this.market(r[0]),l=c.type,u=c.option;!0===u?l="option":!0===c.contract&&(l=!0===c.linear?"future":"delivery");let f=[],p=[];if(!0===u){let e={};for(let t=0;t<r.length;t++){let i=r[t],s=this.market(i);f.push("trade::"+i);let a=this.safeStringLower(s,"baseId","")+""+this.safeStringLower(s,"quoteId","");a in e||(e[a]=!0,p.push(a+"@optionTrade"))}}else for(let e=0;e<r.length;e++){let t=r[e],i=this.market(t);f.push("trade::"+t);let s=i.lowercaseId+"@"+o;p.push(s)}let m=this.omit(h,"type"),g=p.length,v=this.getWsUrl(l,this.getFutureWsCategory(o))+"/"+this.stream(l,a,g),y=this.requestId(v),b=await this.watchMultiple(v,f,this.extend({method:"SUBSCRIBE",params:p,id:y},m),f,{id:y}),w=this.safeDict(b,0),k=this.safeString(w,"symbol"),S=i;return this.newUpdates&&(S=b.getLimit(k,i)),this.filterBySinceLimit(b,t,S,"timestamp",!0)}async unWatchTradesForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1,!0,!0),s="multipleTrades";if(void 0!==i){if(i.length>200)throw new n.BadRequest(this.id+" watchTradesForSymbols() accepts 200 symbols at most. To watch more symbols call watchTradesForSymbols() multiple times");s+="::"+i.join(",")}let[r,a]=this.handleOptionStringAndParams(t,"watchTradesForSymbols","name","trade"),o=this.omit(a,"callerMethodName"),d=this.market(i[0]),h=d.type,c=d.option;!0===c?h="option":!0===d.contract&&(h=!0===d.linear?"future":"delivery");let l=[],u=[],f=[];if(!0===c){let e={};for(let t=0;t<i.length;t++){let s=i[t],r=this.market(s);l.push("trade::"+s),f.push("unsubscribe:trade:"+s);let a=this.safeStringLower(r,"baseId","")+""+this.safeStringLower(r,"quoteId","");a in e||(e[a]=!0,u.push(a+"@optionTrade"))}}else for(let e=0;e<i.length;e++){let t=i[e],s=this.market(t);l.push("trade::"+t),f.push("unsubscribe:trade:"+t);let a=s.lowercaseId+"@"+r;u.push(a)}let p=this.omit(o,"type"),m=u.length,g=this.getWsUrl(h,this.getFutureWsCategory(r))+"/"+this.stream(h,s,m),v=this.requestId(g),y={unsubscribe:!0,id:v.toString(),subMessageHashes:l,messageHashes:f,symbols:i,topic:"trades"};return await this.watchMultiple(g,f,this.extend({method:"UNSUBSCRIBE",params:u,id:v},p),f,y)}unWatchTrades(e,t={}){return this.unWatchTradesForSymbols([e],t)}async watchTrades(e,t,i,s={}){return s.callerMethodName="watchTrades",await this.watchTradesForSymbols([e],t,i,s)}parseWsTrade(e,t){let i,s,r="TRADE"===this.safeString(e,"x");if(!r)return this.parseTrade(e,t);let a=this.safeString2(e,"t","a"),n=this.safeInteger(e,"T"),d=this.safeString2(e,"L","p"),h=this.safeString(e,"q");r&&(h=this.safeString(e,"l",h));let c=this.safeString(e,"Y");void 0===c&&void 0!==d&&void 0!==h&&(c=o.Y.stringMul(d,h));let l=this.safeString(e,"s"),u="spot";"ps"in e&&(u="contract");let f=u;void 0!==t&&(f=this.safeString(t,"type"));let p=this.safeSymbol(l,t,void 0,f),m=this.safeStringLower(e,"S"),g=this.safeString(e,"i");"m"in e&&(void 0===m&&(m=this.safeBool(e,"m",!1)?"sell":"buy"),i=this.safeBool(e,"m",!1)?"maker":"taker");let v=this.safeString(e,"n");if(void 0!==v){let t=this.safeString(e,"N");s={cost:v,currency:this.safeCurrencyCode(t)}}let y=this.safeStringLower(e,"o");return this.safeTrade({info:e,timestamp:n,datetime:this.iso8601(n),symbol:p,id:a,order:g,type:y,takerOrMaker:i,side:m,price:d,amount:h,cost:c,fee:s})}handleTrade(e,t){let i=this.safeString(t,"s"),s=this.isSpotUrl(e),r="contract";s&&(r="spot");let a=this.safeMarket(i,void 0,void 0,r),o=a.symbol,n="trade::"+o,h=this.parseWsTrade(t,a),c=this.safeValue(this.trades,o);if(void 0===c){let e=this.safeInteger(this.options,"tradesLimit",1e3);c=new d.I3(e)}c.append(h),this.trades[o]=c,e.resolve(c,n)}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e).symbol,[o,d]=this.handleOptionAndParams(r,"watchOHLCV","stock");if(!0===o){if("5m"!==t&&"1h"!==t&&"1d"!==t&&"1w"!==t&&"1M"!==t)throw new n.BadRequest(this.id+" watchOHLCV only supports 5m, 1h, 1d, 1w, and 1M timeframes");d.stock=!0}return d.callerMethodName="watchOHLCV",(await this.watchOHLCVForSymbols([[a,t]],i,s,d))[a][t]}async watchOHLCVForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"watchOHLCVForSymbols","stock",!1);if(r){let s=[],r=[];for(let t=0;t<e.length;t++){let i=e[t],a=this.symbol(i[0]),o=this.market(a),d=this.safeString2(o,"base","id"),h=void 0===d?"":d.toLowerCase(),c=i[1],l=this.safeString(this.timeframes,c,c);if("5m"!==l&&"1h"!==l&&"1d"!==l&&"1w"!==l&&"1M"!==l)throw new n.BadRequest(this.id+" watchOHLCVForSymbols only supports 5m, 1h, 1d, 1w, and 1M timeframes");s.push(h+"@kline_"+l),r.push("ohlcv::"+o.symbol+"::"+c)}let[o,d,h]=await this.watchStockMarketStream(s,r,a),c=i;this.newUpdates&&(c=h.getLimit(o,i));let l=this.filterBySinceLimit(h,t,c,0,!0);return this.createOHLCVObject(o,d,l)}let[d,h]=this.handleParamString2(a,"channel","name","kline"),c=this.getListFromObjectValues(e,0),l=this.marketSymbols(c,void 0,!1,!1,!0),u=this.market(l[0]),f=u.type,p=f;!0===u.option?(f="option",p="optionMarket"):!0===u.contract&&(p=f=!0===u.linear?"future":"delivery");let m="spot"===f,[g,v]=this.handleParamString(h,"timezone"),y=void 0!==g&&("+08:00"===g||o.Y.stringEq(g,"8")),b=[],w=[];for(let t=0;t<e.length;t++){let i=e[t],s=i[0],r=i[1],a=this.safeString(this.timeframes,r,r),o=this.market(s),h=o.lowercaseId;if(void 0===h)throw new n.ArgumentsRequired(this.id+" watchOHLCVForSymbols() marketId is required");"indexPriceKline"===d&&(h=h.replace("_perp",""));let c="";y&&m&&(c="@+08:00"),b.push(h+"@"+d+"_"+a+c),w.push("ohlcv::"+o.symbol+"::"+r)}let k=this.getWsUrl(p,this.getFutureWsCategory(d))+"/"+this.stream(p,"multipleOHLCV"),S=this.requestId(k),O=this.omit(v,"callerMethodName"),[T,P,I]=await this.watchMultiple(k,w,this.extend({method:"SUBSCRIBE",params:b,id:S},O),w,{id:S}),A=i;this.newUpdates&&(A=I.getLimit(T,i));let x=this.filterBySinceLimit(I,t,A,0,!0);return this.createOHLCVObject(T,P,x)}async unWatchOHLCVForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleParamString2(t,"channel","name","kline"),r=this.getListFromObjectValues(e,0),a=this.marketSymbols(r,void 0,!1,!1,!0),d=this.market(a[0]),h=d.type,c=h;!0===d.option?(h="option",c="optionMarket"):!0===d.contract&&(c=h=!0===d.linear?"future":"delivery");let l="spot"===h,[u,f]=this.handleParamString(s,"timezone"),p=void 0!==u&&("+08:00"===u||o.Y.stringEq(u,"8")),m=[],g=[],v=[];for(let t=0;t<e.length;t++){let s=e[t],r=s[0],a=s[1],o=this.safeString(this.timeframes,a,a),d=this.market(r),h=d.lowercaseId;if(void 0===h)throw new n.ArgumentsRequired(this.id+" unWatchOHLCVForSymbols() marketId is required");"indexPriceKline"===i&&(h=h.replace("_perp",""));let c="";p&&l&&(c="@+08:00"),m.push(h+"@"+i+"_"+o+c),g.push("ohlcv::"+d.symbol+"::"+a),v.push("unsubscribe::ohlcv::"+d.symbol+"::"+a)}let y=this.getWsUrl(c,this.getFutureWsCategory(i))+"/"+this.stream(c,"multipleOHLCV"),b=this.requestId(y),w={unsubscribe:!0,id:b.toString(),symbols:r,symbolsAndTimeframes:e,subMessageHashes:g,messageHashes:v,topic:"ohlcv"},k=this.omit(f,"callerMethodName");return await this.watchMultiple(y,v,this.extend({method:"UNSUBSCRIBE",params:m,id:b},k),v,w)}async unWatchOHLCV(e,t="1m",i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e).symbol;return i.callerMethodName="watchOHLCV",await this.unWatchOHLCVForSymbols([[s,t]],i)}handleOHLCV(e,t){let i=this.safeString(t,"e");i=this.safeString({indexPrice_kline:"indexPriceKline",markPrice_kline:"markPriceKline"},i,i);let s=this.safeDict(t,"k"),r=this.safeString2(s,"s","ps");"indexPriceKline"===i&&(r=this.safeString(t,"ps"));let a=this.safeString(s,"i"),o=this.findTimeframe(a),n=[this.safeInteger(s,"t"),this.safeFloat(s,"o"),this.safeFloat(s,"h"),this.safeFloat(s,"l"),this.safeFloat(s,"c"),this.safeFloat(s,"v")],h=this.isSpotUrl(e),c="contract";h&&(c="spot");let l=this.safeSymbol(r,void 0,void 0,c),u="ohlcv::"+l+"::"+o;this.ohlcvs[l]=this.safeDict(this.ohlcvs,l,{});let f=this.safeValue(this.safeDict(this.ohlcvs,l),o);if(void 0===f){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);f=new d.TG(e),void 0!==l&&void 0!==o&&(this.ohlcvs[l][o]=f)}f.append(n);let p=[l,o,f];e.resolve(p,u)}async fetchTickerWs(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={symbol:i.id},r=this.getMarketType("fetchTickerWs",i,t);if("future"!==r)throw new n.BadRequest(this.id+" fetchTickerWs only supports swap markets");let a=this.safeString(this.urls.api.ws["ws-api"],r);if(void 0===a)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let o=this.requestId(a).toString(),d={method:this.handleTickerWs},[h,c]=this.handleOptionBoolAndParams(t,"fetchTickerWs","returnRateLimits",!1);s.returnRateLimits=h;let l=this.omit(c,"test"),[u,f]=this.handleOptionStringAndParams(l,"fetchTickerWs","method","ticker.book"),p={id:o,method:u,params:this.signParams(this.extend(s,f))};return await this.watch(a,o,p,o,d)}async fetchOHLCVWs(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=this.getMarketType("fetchOHLCVWs",a,r);if("spot"!==o&&"future"!==o)throw new n.BadRequest(this.id+" fetchOHLCVWs only supports spot or swap markets");let d=this.safeString(this.urls.api.ws["ws-api"],o);if(void 0===d)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let h=this.requestId(d).toString(),[c,l]=this.handleOptionBoolAndParams(r,"fetchOHLCVWs","returnRateLimits",!1),u={symbol:this.marketId(e),returnRateLimits:c,interval:this.timeframes[t]},f=this.safeInteger(l,"until"),p=this.omit(l,"until");void 0!==i&&(u.startTime=i),void 0!==s&&(u.limit=s),void 0!==f&&(u.endTime=f);let m={id:h,method:"klines",params:this.extend(u,p)},g={method:this.handleFetchOHLCV};return await this.watch(d,h,m,h,g)}handleFetchOHLCV(e,t){let i=this.safeList(t,"result"),s=this.parseOHLCVs(i),r=this.safeString(t,"id");e.resolve(s,r)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.symbol(e);return(await this.watchTickers([i],this.extend(t,{callerMethodName:"watchTicker"})))[i]}async watchMarkPrice(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.symbol(e);return(await this.watchMarkPrices([i],this.extend(t,{callerMethodName:"watchMarkPrice"})))[i]}async watchMarkPrices(e,t={}){let[i,s]=this.handleOptionStringAndParams(t,"watchMarkPrices","name","markPrice"),r=await this.watchMultiTickerHelper("watchMarkPrices",i,e,s);return this.newUpdates?r:this.filterByArray(this.tickers,"symbol",e)}async watchTickers(e,t={}){let[i,s]=this.handleOptionBoolAndParams(t,"watchTickers","stock",!1),r=e;if(i){if(void 0===e)throw new n.ArgumentsRequired(this.id+" watchTickers() with stock stream requires symbols");r=this.marketSymbols(e,void 0,!1,!1,!0);let t=await this.watchStockMarketStream(["price"],["stock:price"],s);return this.newUpdates?t:this.filterByArray(this.tickers,"symbol",r)}let[a,o]=this.handleOptionStringAndParams(s,"watchTickers","name","miniTicker");if("bookTicker"===a)throw new n.BadRequest(this.id+" deprecation notice - to subscribe for bids-asks, use watch_bids_asks() method instead");let d=await this.watchMultiTickerHelper("watchTickers",a,r,o);return this.newUpdates?d:this.filterByArray(this.tickers,"symbol",r)}async unWatchTickers(e,t={}){let[i,s]=this.handleOptionStringAndParams(t,"watchTickers","name","ticker");if("bookTicker"===i)throw new n.BadRequest(this.id+" deprecation notice - to subscribe for bids-asks, use watch_bids_asks() method instead");return await this.watchMultiTickerHelper("unWatchTickers",i,e,s,!0)}async unWatchMarkPrices(e,t={}){let[i,s]=this.handleOptionStringAndParams(t,"watchMarkPrices","name","markPrice");return void 0===this.markets&&await this.loadMarkets(),await this.watchMultiTickerHelper("unWatchMarkPrices",i,e,s,!0)}unWatchMarkPrice(e,t={}){return this.unWatchMarkPrices([e],t)}async unWatchBidsAsks(e,t={}){return await this.watchMultiTickerHelper("unWatchBidsAsks","bookTicker",e,t,!0)}unWatchTicker(e,t={}){return this.unWatchTickers([e],t)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionBoolAndParams(t,"watchBidsAsks","stock",!1);if(i){if(void 0===e)throw new n.ArgumentsRequired(this.id+" watchBidsAsks() with stock stream requires symbols");let t=this.marketSymbols(e,void 0,!1,!1,!0),i=[],r=[];for(let e=0;e<t.length;e++){let s=this.getStockTickerFromSymbol(t[e]);i.push(s+"@quote"),r.push("stock:quote:"+t[e])}let a=await this.watchStockMarketStream(i,r,s);return this.newUpdates?a:this.filterByArray(this.bidsasks,"symbol",t)}let r=this.marketSymbols(e,void 0,!0,!1,!0),a=await this.watchMultiTickerHelper("watchBidsAsks","bookTicker",r,s);return this.newUpdates?a:this.filterByArray(this.bidsasks,"symbol",r)}async watchMultiTickerHelper(e,t,i,s={},r=!1){let a,o,d,h;void 0===this.markets&&await this.loadMarkets();let c=this.marketSymbols(i,void 0,!0,!1,!0),l="bookTicker"===t,u="markPrice"===t,f=this.safeBool(s,"use1sFreq",!0),p=void 0!==c;void 0!==c&&(a=this.market(c[0]));let m=this.safeString(this.options,"defaultType");u&&"option"!==m&&(o="swap");let[g,v]=this.handleMarketTypeAndParams(e,a,s,o),[y,b]=this.handleSubTypeAndParams(e,a,v),w=u&&"option"===g;if("option"===g)d=w?"optionMarket":"option";else if(this.isLinear(g,y))d="future";else if(this.isInverse(g,y))d="delivery";else if("spot"===g)d=g;else throw new n.NotSupported(this.id+" "+e+"() does not support options markets");let k="option"===g&&!u&&!l;if(u&&!this.inArray(g,["swap","future","option"]))throw new n.NotSupported(this.id+" "+e+"() does not support "+g+" markets yet");let S=[],O=[],T=[],P="";if(u&&!w&&(P=!0===f?"@1s":""),h=l?"bidask":u?"markPrice":"ticker",void 0!==c){let e={};for(let i=0;i<c.length;i++){let s=c[i],a=this.market(s);if(O.push(h+":"+t+"@"+s),r&&T.push("unsubscribe::"+h+":"+t+"@"+s),w){let t=this.safeStringLower(a,"baseId","")+""+this.safeStringLower(a,"quoteId","");t in e||(e[t]=!0,S.push(t+"@optionMarkPrice"))}else if(k){let t=this.safeString(a,"id","").split("-"),i=this.safeString(t,1),s=this.safeStringLower(a,"baseId","")+""+this.safeStringLower(a,"quoteId","")+"@optionTicker@"+i;s in e||(e[s]=!0,S.push(s))}else{let e=a.lowercaseId;S.push(e+"@"+t+P)}}}else if("option"===g){let i=this.safeStringLower(b,"underlying");if(void 0===i)throw new n.ArgumentsRequired(this.id+" "+e+'() requires either symbols or params["underlying"] for eOptions');if(k){let t=this.safeString(b,"expirationDate");if(void 0===t)throw new n.ArgumentsRequired(this.id+" "+e+'() requires params["expirationDate"] (e.g. "260227") for eOptions tickers when no symbols are provided');S.push(i+"@optionTicker@"+t)}else S.push(i+"@optionMarkPrice");O.push(h+"s:"+t),T.push("unsubscribe::"+t)}else if(l){if("spot"===g)throw new n.ArgumentsRequired(this.id+" "+e+"() requires symbols for this channel for spot markets");S.push("!"+t),O.push(h+"s:"+t),T.push("unsubscribe::"+t)}else u?S.push("!"+t+"@arr"+P):S.push("!"+t+"@arr"),O.push(h+"s:"+t),T.push("unsubscribe::"+t);let I=t;void 0!==c&&(I=t+"::"+c.join(","));let A=this.getWsUrl(d,this.getFutureWsCategory(t))+"/"+this.stream(d,I),x=this.requestId(A),M=O,_={id:x};r&&(_={unsubscribe:!0,id:x.toString(),subMessageHashes:O,messageHashes:T,symbols:c,topic:"ticker"},M=T);let C=M;w&&!r&&(C=[h+"s:"+t]);let B=await this.watchMultiple(A,C,this.deepExtend({method:r?"UNSUBSCRIBE":"SUBSCRIBE",params:S,id:x},b),M,_);if(r||!p||w)return B;{let e={},t=this.safeString(B,"symbol");return void 0!==t&&(e[t]=B),e}}parseWsTicker(e,t){let i,s=this.safeString2(e,"s","symbol"),r=this.safeSymbol(s,void 0,void 0,t),a=this.safeString(e,"e","bookTicker");if("24hrTicker"===a&&(a="ticker"),"markPriceUpdate"===a||"markPrice"===a)return this.safeTicker({symbol:r,timestamp:this.safeInteger(e,"E"),datetime:this.iso8601(this.safeInteger(e,"E")),info:e,markPrice:this.safeString2(e,"mp","p"),indexPrice:this.safeString(e,"i")});i="bookTicker"===a?this.safeInteger2(e,"E","time"):this.safeIntegerN(e,["C","E","time"]);let n=this.safeMarket(s,void 0,void 0,t),d=this.safeString2(e,"c","price"),h=this.safeString(e,"v"),c=this.safeString(e,"q");if(!0===n.inverse){let t=h;h=c;let i=this.safeString(e,"w");c=void 0===i?o.Y.stringMul(t,this.safeString(n,"contractSize")):o.Y.stringMul(h,i)}return this.safeTicker({symbol:r,timestamp:i,datetime:this.iso8601(i),high:this.safeString(e,"h"),low:this.safeString(e,"l"),bid:this.safeString2(e,"b","bidPrice"),bidVolume:this.safeString2(e,"B","bidQty"),ask:this.safeString2(e,"a","askPrice"),askVolume:this.safeString2(e,"A","askQty"),vwap:this.safeString(e,"w"),open:this.safeString(e,"o"),close:d,last:d,previousClose:this.safeString(e,"x"),change:this.safeString(e,"p"),percentage:this.safeString(e,"P"),average:void 0,baseVolume:h,quoteVolume:c,info:e},n)}handleTickerWs(e,t){let i=this.safeString(t,"id"),s=this.safeDict(t,"result",{}),r=this.parseWsTicker(s,"future");e.resolve(r,i)}handleBidsAsks(e,t){this.handleTickersAndBidsAsks(e,t,"bidasks")}handleTickers(e,t){this.handleTickersAndBidsAsks(e,t,"tickers")}handleMarkPrices(e,t){this.handleTickersAndBidsAsks(e,t,"markPrices")}handleTickersAndBidsAsks(e,t,i){let s,r,a="bidasks"===i;s=a?"bidask":"markPrices"===i?"markPrice":"ticker";let o=[],n=[],d={};Array.isArray(t)?n=t:n.push(t);for(let t=0;t<n.length;t++){let i=this.safeDict(n,t),h=this.safeString(i,"e");if(a&&(h="bookTicker"),void 0===(r=this.safeString(this.options.tickerChannelsMap,h,h)))continue;let c=this.safeString(i,"s"),l=this.safeList(this.markets_by_id,c),u=1===(void 0===l?0:l.length)?this.safeDict(l,0):void 0,f=this.isSpotUrl(e),p="contract";f&&(p="spot");let m=void 0!==u?u.type:p,g=this.parseWsTicker(i,m),v=g.symbol;void 0!==v&&(d[v]=g),a?void 0!==v&&(this.bidsasks[v]=g):void 0!==v&&(this.tickers[v]=g);let y=s+":"+r+"@"+v;o.push(y),e.resolve(g,y)}if(o.length>0){let t=s+"s:"+r;e.resolve(d,t)}}signParams(e={}){let t;this.checkRequiredCredentials();let i=this.safeInteger(this.options,"recvWindow");void 0!==i&&(e.recvWindow=i);let a=this.safeInteger(e,"recvWindow");void 0!==a&&(e.recvWindow=a);let o=this.extend({timestamp:this.nonce(),apiKey:this.apiKey},e);o=this.keysort(o);let n=this.rawencode(o);return t=this.secret.indexOf("PRIVATE KEY")>-1?this.secret.length>120?(0,h.n)(n,this.secret,s.sc):(0,c.q4)(this.encode(n),this.secret,r.ev):this.hmac(this.encode(n),this.encode(this.secret),s.sc),o.signature=t,o}async ensureUserDataStreamWsSubscribeSignature(e="spot"){let t=this.safeString(this.urls.api.ws["ws-api"],e);if(void 0===t)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let i=this.client(t),s=Object.keys(i.subscriptions);if(this.getAccountTypeFromSubscriptions(s)===e)return;let r="authenticate:signature:"+e;if(r in i.futures)return void await i.future(r);i.future(r),i.subscriptions[e]=!0;let a=this.requestId(t).toString(),o={id:a,method:"userDataStream.subscribe.signature",params:this.signParams({})},d={id:a,method:this.handleUserDataStreamSubscribe,subscription:e};try{await this.watch(t,a,o,a,d),i.resolve(e,r)}catch(t){throw delete i.subscriptions[e],i.reject(t,r),t}}handleUserDataStreamSubscribe(e,t){let i=this.safeString(t,"id"),s=Object.keys(e.subscriptions),r=this.getAccountTypeFromSubscriptions(s),a=this.safeDict(t,"result",{});if(void 0===this.safeInteger(a,"subscriptionId")){delete e.subscriptions[r];let s=new n.ExchangeError(this.id+" user data stream subscribe failed "+this.json(t));e.reject(s,r),e.reject(s,i);return}e.resolve(t,i)}async ensureUserDataStreamWsSubscribeListenToken(e="margin",t={}){let i=this.safeString(this.urls.api.ws["ws-api"],"spot");if(void 0===i)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let s=this.safeDict(this.options,e,{}),r=this.safeInteger(s,"lastAuthenticatedTime",0),a=this.safeInteger(this.options,"listenTokenRefreshRate",828e5),o=this.milliseconds();if(o-r>a+1e4){let r=this.client(i),a="authenticate:"+e+":listenToken";if(a in r.futures)return void await r.future(a);r.future(a);try{let d=this.safeString(t,"symbol"),h=this.safeBool(t,"isIsolated",!1),c=this.safeInteger(t,"validity"),l={};if(!0===h){if(void 0===d)throw new n.ArgumentsRequired(this.id+" ensureUserDataStreamWsSubscribeListenToken() requires a symbol argument for isolated margin mode");l.symbol=this.marketId(d),l.isIsolated=!0}void 0!==c&&(l.validity=c);let u=await this.sapiPostUserListenToken(l),f=this.safeString(u,"token");if(void 0===f)throw new n.AuthenticationError(this.id+" ensureUserDataStreamWsSubscribeListenToken() failed to obtain a listenToken");let p=this.safeInteger(u,"expirationTime"),m=this.requestId(i).toString(),g={id:m,method:this.handleUserDataStreamSubscribe,subscription:e};if(await this.watch(i,m,{id:m,method:"userDataStream.subscribe.listenToken",params:{listenToken:f}},m,g),this.options[e]=this.extend(s,{listenToken:f,expirationTime:p,lastAuthenticatedTime:o,symbol:d,isIsolated:h,validity:c}),void 0!==p){let i=p-o-6e4;if(i>0){let s=this.extend(t,{type:e});this.delay(i,this.renewListenToken,s)}}r.resolve(f,a)}catch(t){throw this.options[e]=this.extend(s,{lastAuthenticatedTime:0}),r.reject(t,a),t}}}async renewListenToken(e={}){let t=this.safeString(e,"type","margin"),i=this.safeDict(this.options,t,{}),s=this.safeString(i,"symbol"),r=this.safeBool(i,"isIsolated",!1),a=this.safeInteger(i,"validity"),o={};void 0!==s&&(o.symbol=s),!0===r&&(o.isIsolated=r),void 0!==a&&(o.validity=a),await this.ensureUserDataStreamWsSubscribeListenToken(t,o)}async authenticate(e={}){let t=this.milliseconds(),i=this.resolveAuthType("authenticate",void 0,e),s=i[0],r=i[2],[a,o]=this.handleOptionBoolAndParams2(r,"authenticate","papi","portfolioMargin",!1);if("spot"===s)return void await this.ensureUserDataStreamWsSubscribeSignature("spot");let[d,h]=this.handleMarginModeAndParams("authenticate",o),c="isolated"===d,l=this.safeString(h,"symbol");if("margin"===s||c){let e={};void 0!==l&&(e.symbol=l),c&&(e.isIsolated=!0),await this.ensureUserDataStreamWsSubscribeListenToken("margin",e);return}let u=this.omit(h,"symbol"),f="stock"===s,p=this.safeDict(this.options,s,{}),m=this.safeInteger(p,"lastAuthenticatedTime",0),g="listenKeyRefreshRate";f&&(g="stockListenKeyRefreshRate");let v=this.safeInteger(this.options,g,12e5);if(t-m>v+1e4){let e="authenticate:"+s,i=this.client("authenticationFlights");if(e in i.futures)return void await i.future(e);let r=i.reusableFuture(e);try{let r;if(f){let e=this.omit(u,["stock","name","callerMethodName","type","subType","symbol","timeframe"]);r=await this.sapiPostEquityListenKey(e)}else r=a?await this.papiPostListenKey(u):"future"===s?await this.fapiPrivatePostListenKey(u):"delivery"===s?await this.dapiPrivatePostListenKey(u):"option"===s?await this.eapiPrivatePostListenKey(u):await this.publicPostUserDataStream(u);let o=this.safeString(r,"listenKey");if(void 0===o)throw new n.AuthenticationError(this.id+" authenticate() received an empty listenKey");this.options[s]=this.extend(p,{listenKey:o,lastAuthenticatedTime:t});let d=u;f?d=this.extend(u,{type:"stock",defaultType:"stock"}):a&&(d=this.extend(u,{portfolioMargin:!0})),this.delay(v,this.keepAliveListenKey,d),i.resolve(o,e)}catch(t){i.reject(t,e)}await r}}async keepAliveListenKey(e={}){let t=this.safeString2(this.options,"defaultType","authenticate","spot");t=this.safeString(e,"type",t);let[i,s]=this.handleOptionBoolAndParams2(e,"keepAliveListenKey","papi","portfolioMargin",!1),r=this.handleSubTypeAndParams("keepAliveListenKey",void 0,s)[0];if("option"!==t&&"stock"!==t&&(this.isLinear(t,r)?t="future":this.isInverse(t,r)&&(t="delivery")),"margin"===t)return;let a="stock"===t,o=this.safeDict(this.options,t,{}),n=this.safeString(o,"listenKey");if(void 0===n)return;let d={},h=this.omit(s,["type","symbol"]),c=this.milliseconds();try{if(a){let e=this.omit(h,["stock","name","callerMethodName","subType","timeframe"]);await this.sapiPostEquityListenKey(e)}else i?await this.papiPutListenKey(this.extend(d,h)):"future"===t?await this.fapiPrivatePutListenKey(this.extend(d,h)):"delivery"===t?await this.dapiPrivatePutListenKey(this.extend(d,h)):"option"===t?await this.eapiPrivatePutListenKey(this.extend(d,h)):(d.listenKey=n,await this.publicPutUserDataStream(this.extend(d,h)))}catch(n){let e;if(a)e=this.getStockWsUrl("user");else{let s=t;i&&(s="papi"),"option"===t&&(s="optionPrivate");let r=this.options[t].listenKey;e=this.getPrivateWsUrl(s,r)}let s=this.client(e),r=Object.keys(s.futures);for(let e=0;e<r.length;e++){let t=r[e];s.reject(n,t)}this.options[t]=this.extend(o,{listenKey:void 0,lastAuthenticatedTime:0});return}this.options[t]=this.extend(o,{listenKey:n,lastAuthenticatedTime:c});let l=Object.values(this.clients),u="listenKeyRefreshRate";a&&(u="stockListenKeyRefreshRate");let f=this.safeInteger(this.options,u,12e5),p=h;a?p=this.extend(h,{type:"stock"}):i&&(p=this.extend(h,{portfolioMargin:!0}));for(let e=0;e<l.length;e++){let i=this.safeDict(l,e),s=Object.keys(this.safeDict(i,"subscriptions",{}));for(let e=0;e<s.length;e++)if(s[e]===t)return void this.delay(f,this.keepAliveListenKey,p)}}setBalanceCache(e,t,i=!1){if(t in e.subscriptions&&t in this.balance)return;let s=this.safeDict(this.options,"watchBalance");if(!0===this.safeBool(s,"fetchBalanceSnapshot",!1)){let s=t+":fetchBalanceSnapshot";s in e.futures||(e.future(s),this.spawn(this.loadBalanceSnapshot,e,s,t,i))}else this.balance[t]={}}async loadBalanceSnapshot(e,t,i,s){let r={type:i};!0===s&&(r.portfolioMargin=!0);let a=await this.fetchBalance(r);this.balance[i]=this.extend(a,this.safeDict(this.balance,i,{})),t in e.futures&&(e.futures[t].resolve(),e.resolve(this.balance[i],i+":balance"))}async fetchBalanceWs(e={}){void 0===this.markets&&await this.loadMarkets();let t=this.getMarketType("fetchBalanceWs",void 0,e);if("spot"!==t&&"future"!==t&&"delivery"!==t)throw new n.BadRequest(this.id+" fetchBalanceWs only supports spot or swap markets");let i=this.safeString(this.urls.api.ws["ws-api"],t);if(void 0===i)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let s=this.requestId(i).toString(),[r,a]=this.handleOptionBoolAndParams(e,"fetchBalanceWs","returnRateLimits",!1),[o,d]=this.handleOptionStringAndParams(a,"fetchBalanceWs","method","account.status"),h={id:s,method:o,params:this.signParams(this.extend({returnRateLimits:r},d))},c={method:"account.status"===o?this.handleAccountStatusWs:this.handleBalanceWs};return await this.watch(i,s,h,s,c)}handleBalanceWs(e,t){let i,s=this.safeString(t,"id");if(Array.isArray(t.result))i=this.safeList(t,"result",[]);else{let e=this.safeDict(t,"result",{});i=this.safeList(e,"assets",[])}let r=this.parseBalanceCustom(i);e.resolve(r,s)}handleAccountStatusWs(e,t){let i=this.safeString(t,"id"),s=this.safeDict(t,"result",{}),r=this.parseBalanceCustom(s);e.resolve(r,i)}fetchPositionWs(e,t={}){return this.fetchPositionsWs([e],t)}async fetchPositionsWs(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={},r=this.marketSymbols(e,"swap",!0,!0,!0);void 0!==r&&1===r.length&&(s.symbol=(i=this.market(r[0])).id);let a=this.getMarketType("fetchPositionsWs",i,t);if(void 0===r&&"spot"===a&&(a="future"),"future"!==a&&"delivery"!==a)throw new n.BadRequest(this.id+" fetchPositionsWs only supports swap markets");let o=this.safeString(this.urls.api.ws["ws-api"],a);if(void 0===o)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let d=this.requestId(o).toString(),[h,c]=this.handleOptionBoolAndParams(t,"fetchPositionsWs","returnRateLimits",!1);s.returnRateLimits=h;let[l,u]=this.handleOptionStringAndParams(c,"fetchPositionsWs","method","account.position"),f={id:d,method:l,params:this.signParams(this.extend(s,u))},p={method:this.handlePositionsWs},m=await this.watch(o,d,f,d,p);return this.filterByArrayPositions(m,"symbol",r)}handlePositionsWs(e,t){let i=this.safeString(t,"id"),s=this.safeList(t,"result",[]),r=[];for(let e=0;e<s.length;e++){let t=this.parsePositionRisk(s[e]),i=this.safeString(t,"entryPrice");"0"!==i&&"0.0"!==i&&"0.00000000"!==i&&r.push(t)}e.resolve(r,i)}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i,s]=this.resolveAuthType("watchBalance",void 0,e);await this.authenticate(this.extend({type:t,subType:i},s));let r=this.handleOptionBoolAndParams2(s,"watchBalance","papi","portfolioMargin",!1)[0],a="",o=t;if("spot"===t||"margin"===t)a=this.urls.api.ws["ws-api"].spot;else{if(r)o="papi";else if("option"===t){if(!0===this.safeBool(this.options,"enableDemoTrading",!1)||this.isSandboxModeEnabled)throw new n.NotSupported(this.id+" watchBalance() does not support option markets in demo/testnet mode");o="optionPrivate"}a=this.getPrivateWsUrl(o,this.options[t].listenKey)}let d=this.client(a);this.setBalanceCache(d,t,r),this.setPositionsCache(d,t,void 0,r);let h=this.safeDict(this.options,"watchBalance"),c=this.safeBool(h,"fetchBalanceSnapshot",!1),l=this.safeBool(h,"awaitBalanceSnapshot",!0);!0===c&&!0===l&&await d.future(t+":fetchBalanceSnapshot");let u=t+":balance";return await this.watch(a,u,void 0,t)}handleBalance(e,t){let i=this.safeString(this.options,"wallet","wb"),s=Object.keys(e.subscriptions),r=this.getAccountTypeFromSubscriptions(s);void 0===this.balance[r]&&(this.balance[r]={}),this.balance[r].info=t;let a=this.safeString(t,"e"),n=this.safeDict(t,"a",t);if("balanceUpdate"===a){let e=this.safeString(t,"a"),i=this.safeCurrencyCode(e),s=this.account(),a=this.safeString(t,"d");if(void 0!==r&&void 0!==i&&i in this.balance[r]){let e=this.balance[r][i].free;"string"!=typeof e&&(e=this.numberToString(e)),s.free=o.Y.stringAdd(e,a)}else s.free=a;void 0!==r&&void 0!==i&&(this.balance[r][i]=s)}else{let e=this.safeList(n,"B");if(void 0===e)return;for(let t=0;t<e.length;t++){let s=e[t],a=this.safeString(s,"a"),o=this.safeCurrencyCode(a),n=this.account();n.free=this.safeString(s,"f"),n.used=this.safeString(s,"l"),n.total=this.safeString(s,i),void 0!==r&&void 0!==o&&(this.balance[r][o]=n)}}let d=this.safeInteger(n,"E");this.balance[r].timestamp=d,this.balance[r].datetime=this.iso8601(d),this.balance[r]=this.safeBalance(this.balance[r]),e.resolve(this.balance[r],r+":balance")}getAccountTypeFromSubscriptions(e){let t="";for(let i=0;i<e.length;i++){let s=e[i];if("spot"===s||"margin"===s||"future"===s||"delivery"===s||"option"===s){t=s;break}}return t}resolveAuthType(e,t,i={}){let[s,r]=this.handleMarketTypeAndParams(e,t,i),[a,o]=this.handleSubTypeAndParams(e,t,r),n=s;return"option"!==n&&"stock"!==n&&(this.isLinear(n,a)?n="future":this.isInverse(n,a)&&(n="delivery")),[n,a,o]}getMarketType(e,t,i={}){let s,r={};[s,r]=this.handleMarketTypeAndParams(e,t,i);let a=this.handleSubTypeAndParams(e,t,r)[0];return this.isLinear(s,a)?s="future":this.isInverse(s,a)&&(s="delivery"),s}async createOrderWs(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),d=this.getMarketType("createOrderWs",o,a);if("spot"!==d&&"future"!==d&&"delivery"!==d)throw new n.BadRequest(this.id+" createOrderWs only supports spot or swap markets");let h=this.safeString(this.urls.api.ws["ws-api"],d);if(void 0===h)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let c=this.requestId(h).toString(),l=this.safeBool2(a,"sor","SOR",!1),u=this.omit(a,"sor","SOR"),f=this.isConditionalOrder(u);if(!0===o.inverse&&f)throw new n.NotSupported(this.id+" createOrderWs() does not support conditional orders for inverse markets, the exchange only accepts them through the REST API, use createOrder() instead");let p=!0===o.linear&&(!0===o.swap||!0===o.future)&&f,m=this.createOrderRequest(e,t,i,s,r,this.extend(u,{isAlgoOrder:p})),[g,v]=this.handleOptionBoolAndParams(u,"createOrderWs","returnRateLimits",!1);m.returnRateLimits=g;let y=this.safeBool(v,"test",!1),b=this.omit(v,"test");p&&(m.algoType="CONDITIONAL");let w={id:c,method:"order.place",params:this.signParams(this.extend(m,b))};!0===y&&(!0===l?w.method="sor.order.test":w.method="order.test"),p&&(w.method="algoOrder.place");let k={method:this.handleOrderWs};return await this.watch(h,c,w,c,k)}handleOrderWs(e,t){let i=this.safeString(t,"id"),s=this.safeDict(t,"result",{}),r=this.parseOrder(s);e.resolve(r,i)}handleOrdersWs(e,t){let i=this.safeString(t,"id"),s=this.safeList(t,"result",[]),r=this.parseOrders(s);e.resolve(r,i)}async editOrderWs(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets();let d=this.market(t),h=this.getMarketType("editOrderWs",d,o);if("spot"!==h&&"future"!==h&&"delivery"!==h)throw new n.BadRequest(this.id+" editOrderWs only supports spot or swap markets");let c=this.safeString(this.urls.api.ws["ws-api"],h);if(void 0===c)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let l=this.requestId(c).toString(),u="future"===h||"delivery"===h,f={};f="spot"===h?this.editSpotOrderRequest(e,t,i,s,r,a,o):this.editContractOrderRequest(e,t,i,s,r,a,o);let[p,m]=this.handleOptionBoolAndParams(o,"editOrderWs","returnRateLimits",!1);f.returnRateLimits=p;let g={id:l,method:u?"order.modify":"order.cancelReplace",params:this.signParams(this.extend(f,m))},v={method:this.handleEditOrderWs};return await this.watch(c,l,g,l,v)}handleEditOrderWs(e,t){let i,s=this.safeString(t,"id"),r=this.safeDict(t,"result",{}),a=this.safeDict(r,"newOrderResponse");i=void 0!==a?this.parseOrder(a):this.parseOrder(r),e.resolve(i,s)}async cancelOrderWs(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===t)throw new n.BadRequest(this.id+" cancelOrderWs requires a symbol");let s=this.market(t),r=this.getMarketType("cancelOrderWs",s,i),a=this.safeString(this.urls.api.ws["ws-api"],r);if(void 0===a)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let o=this.requestId(a).toString(),[d,h]=this.handleOptionBoolAndParams(i,"cancelOrderWs","returnRateLimits",!1),c={symbol:this.marketId(t),returnRateLimits:d},l=this.safeBoolN(h,["stop","trigger","conditional"]),u=this.safeStringN(h,["clientAlgoId","origClientOrderId","clientOrderId"]),f=!0===s.linear&&!0===s.swap&&!0===l;void 0!==u?!0===f?c.clientAlgoId=u:c.origClientOrderId=u:!0===f?c.algoId=this.numberToString(e):c.orderId=this.numberToString(e);let p=this.omit(h,["origClientOrderId","clientOrderId","stop","trigger","conditional"]),m={id:o,method:"order.cancel",params:this.signParams(this.extend(c,p))};!0===f&&(m.method="algoOrder.cancel");let g={method:this.handleOrderWs};return await this.watch(a,o,m,o,g)}async cancelAllOrdersWs(e,t={}){if(void 0===e)throw new n.ArgumentsRequired(this.id+" cancelAllOrdersWs() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.getMarketType("cancelAllOrdersWs",i,t);if("spot"!==s)throw new n.BadRequest(this.id+" cancelAllOrdersWs only supports spot markets");let r=this.safeString(this.urls.api.ws["ws-api"],s);if(void 0===r)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let a=this.requestId(r).toString(),[o,d]=this.handleOptionBoolAndParams(t,"cancelAllOrdersWs","returnRateLimits",!1),h={symbol:this.marketId(e),returnRateLimits:o},c={id:a,method:"openOrders.cancelAll",params:this.signParams(this.extend(h,d))},l={method:this.handleOrdersWs};return await this.watch(r,a,c,a,l)}async fetchOrderWs(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===t)throw new n.BadRequest(this.id+" cancelOrderWs requires a symbol");let s=this.market(t),r=this.getMarketType("fetchOrderWs",s,i);if("spot"!==r&&"future"!==r&&"delivery"!==r)throw new n.BadRequest(this.id+" fetchOrderWs only supports spot or swap markets");let a=this.safeString(this.urls.api.ws["ws-api"],r);if(void 0===a)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let o=this.requestId(a).toString(),[d,h]=this.handleOptionBoolAndParams(i,"fetchOrderWs","returnRateLimits",!1),c={symbol:this.marketId(t),returnRateLimits:d},l=this.safeString2(h,"origClientOrderId","clientOrderId");void 0!==l?c.origClientOrderId=l:c.orderId=this.numberToString(e);let u={id:o,method:"order.status",params:this.signParams(this.extend(c,h))},f={method:this.handleOrderWs};return await this.watch(a,o,u,o,f)}async fetchOrdersWs(e,t,i,s={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new n.BadRequest(this.id+" fetchOrdersWs requires a symbol");let r=this.market(e),a=this.getMarketType("fetchOrdersWs",r,s);if("spot"!==a)throw new n.BadRequest(this.id+" fetchOrdersWs only supports spot markets");let o=this.safeString(this.urls.api.ws["ws-api"],a);if(void 0===o)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let d=this.requestId(o).toString(),[h,c]=this.handleOptionBoolAndParams(s,"fetchOrdersWs","returnRateLimits",!1),l={symbol:this.marketId(e),returnRateLimits:h},u={id:d,method:"allOrders",params:this.signParams(this.extend(l,c))},f={method:this.handleOrdersWs},p=await this.watch(o,d,u,d,f);return this.filterBySymbolSinceLimit(p,e,t,i)}async fetchClosedOrdersWs(e,t,i,s={}){let r=await this.fetchOrdersWs(e,t,i,s),a=[];for(let e=0;e<r.length;e++){let t=r[e];"closed"===t.status&&a.push(t)}return a}async fetchOpenOrdersWs(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=this.getMarketType("fetchOpenOrdersWs",r,s);if("spot"!==a)throw new n.BadRequest(this.id+" fetchOpenOrdersWs only supports spot markets");let o=this.safeString(this.urls.api.ws["ws-api"],a);if(void 0===o)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let d=this.requestId(o).toString(),[h,c]=this.handleOptionBoolAndParams(s,"fetchOpenOrdersWs","returnRateLimits",!1),l={returnRateLimits:h};void 0!==e&&(l.symbol=this.marketId(e));let u={id:d,method:"openOrders.status",params:this.signParams(this.extend(l,c))},f={method:this.handleOrdersWs},p=await this.watch(o,d,u,d,f);return this.filterBySymbolSinceLimit(p,e,t,i)}async watchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=this.handleOptionBoolAndParams(s,"watchOrders","stock",!1);if(a){await this.authenticate(this.extend(o,{type:"stock"}));let s=this.safeDict(this.options,"stock",{}),r=this.safeString(s,"listenKey");if(void 0===r)throw new n.BadRequest(this.id+" watchOrders() failed to initialize stock listenKey");let a=this.getStockWsUrl("user"),d=this.requestId(a),h="orders";void 0!==e&&(h="orders:"+this.symbol(e));let c=this.omit(o,["stock","name","callerMethodName","type","subType","symbol","timeframe"]),l=await this.watch(a,h,this.extend({method:"SUBSCRIBE",params:[r+"@orderReport"],id:d},c),h,{id:d}),u=i;return this.newUpdates&&(u=l.getLimit(e,i)),this.filterBySymbolSinceLimit(l,e,t,u,!0)}let d="orders",h=void 0!==e?this.symbol(e):e;void 0!==e&&(r=this.market(e),d+=":"+h);let[c,l,u]=this.resolveAuthType("watchOrders",r,o),f=this.extend(u,{type:c,symbol:h,subType:l});await this.authenticate(f);let[p,m]=this.handleMarginModeAndParams("watchOrders",f),g=c;("margin"===c||"spot"===c&&void 0!==p)&&(g="spot");let v=this.handleOptionBoolAndParams2(m,"watchOrders","papi","portfolioMargin",!1)[0],y="";if("spot"===c||"margin"===c)y=this.urls.api.ws["ws-api"].spot;else{if(v)g="papi";else if("option"===c){if(!0===this.safeBool(this.options,"enableDemoTrading",!1)||this.isSandboxModeEnabled)throw new n.NotSupported(this.id+" watchOrders() does not support option markets in demo/testnet mode");g="optionPrivate"}y=this.getPrivateWsUrl(g,this.options[c].listenKey)}let b=this.client(y);this.setBalanceCache(b,c,v),this.setPositionsCache(b,c,void 0,v);let w=await this.watch(y,d,void 0,c),k=i;return this.newUpdates&&(k=w.getLimit(h,i)),this.filterBySymbolSinceLimit(w,h,t,k,!0)}parseWsOrder(e,t){let i,s;if("orderReport"===this.safeString(e,"e")){let t,i=this.safeString(e,"b");void 0!==i&&0===i.indexOf("EQ_")&&(i=i.slice(3)),void 0===i&&(i=this.safeString(e,"symbol"));let s=this.safeString(e,"q","USDC"),r=this.getStockUnifiedSymbol(i,s),a=this.safeStringLower(e,"s"),n=this.safeString({accepted:"open",new:"open",partially_filled:"open",filled:"closed",canceled:"canceled",rejected:"rejected",expired:"expired"},a,a),d=this.safeString(e,"Q"),h=this.safeString(e,"fq");void 0!==d&&void 0!==h&&(t=o.Y.stringSub(d,h));let c=this.safeInteger(e,"T"),l=this.safeInteger(e,"U",c);return this.safeOrder({info:e,symbol:r,id:this.safeString(e,"i"),timestamp:c,datetime:this.iso8601(c),lastUpdateTimestamp:l,type:this.parseOrderTypeByMarket(this.safeStringLower(e,"o"),"spot"),timeInForce:void 0,postOnly:void 0,reduceOnly:void 0,side:this.safeStringLower(e,"S"),price:this.safeString(e,"p"),stopPrice:void 0,triggerPrice:void 0,amount:d,cost:this.safeString(e,"FN"),average:void 0,filled:h,remaining:t,status:n,fee:void 0,trades:void 0})}let r=this.safeString(e,"x"),a=this.safeString(e,"s"),n="spot";"ps"in e&&(n="contract");let d=this.safeSymbol(a,void 0,void 0,n),h=this.safeInteger(e,"O"),c=this.safeInteger(e,"T");if("NEW"===r||"AMENDMENT"===r||"CANCELED"===r?void 0===h&&(h=c):"TRADE"===r&&(i=c),"aid"in e&&void 0===h){let t=this.safeString(e,"X");("NEW"===t||"CANCELED"===t)&&(h=c)}let l=this.safeString(e,"n");if(void 0!==l&&o.Y.stringGt(l,"0")){let t=this.safeString(e,"N");s={cost:l,currency:this.safeCurrencyCode(t)}}let u=this.safeString(e,"X"),f=this.parseOrderStatus(u),p=this.safeString2(e,"C","caid");(void 0===p||0===p.length)&&(p=this.safeString(e,"c"));let m=this.omitZero(this.safeStringN(e,["P","sp","tp"])),g=this.safeStringLower(e,"o"),v=this.inArray(g,["take_profit","take_profit_market","take_profit_limit"])?m:void 0,y=this.safeString(e,"f");return"GTX"===y&&(y="PO"),this.safeOrder({info:e,symbol:d,id:this.safeString2(e,"i","aid"),clientOrderId:p,timestamp:h,datetime:this.iso8601(h),lastTradeTimestamp:i,lastUpdateTimestamp:c,type:this.parseOrderTypeByMarket(g,n),timeInForce:y,postOnly:void 0,reduceOnly:this.safeBool(e,"R"),side:this.safeStringLower(e,"S"),price:this.safeString(e,"p"),stopPrice:m,triggerPrice:m,takeProfitPrice:v,amount:this.safeString(e,"q"),cost:this.safeString(e,"Z"),average:this.safeString(e,"ap"),filled:this.safeString(e,"z"),remaining:void 0,status:f,fee:s,trades:void 0})}handleOrderUpdate(e,t){let i=this.safeString(t,"e");if("orderReport"===i)return void this.handleOrder(e,t);let s=t;(("ORDER_TRADE_UPDATE"===i||"ALGO_UPDATE"===i)&&(s=this.safeDict(t,"o",t),"ALGO_UPDATE"!==i||"T"in s||(s.T=this.safeInteger(t,"T"))),("ORDER_TRADE_UPDATE"===i||"ALGO_UPDATE"===i)&&Array.isArray(this.safeValue(t,"o")))?this.handleOptionsOrderUpdate(e,t):(this.handleMyTrade(e,s),this.handleOrder(e,s),this.handleMyLiquidation(e,s))}handleStockPrice(e,t){let i=this.safeList(t,"rates",[]),s={};for(let t=0;t<i.length;t++){let r=this.safeDict(i,t,{}),a=this.safeString(r,"s"),o=this.getStockUnifiedSymbol(a,"USDC");if(void 0===o)continue;let n=this.safeInteger(r,"t"),d=this.safeTicker({symbol:o,timestamp:n,datetime:this.iso8601(n),last:this.safeString(r,"p"),close:this.safeString(r,"p"),previousClose:this.safeString(r,"pc"),info:r});this.tickers[o]=d,s[o]=d,e.resolve(d,"stock:price:"+o)}e.resolve(s,"stock:price")}handleStockQuote(e,t){let i=this.safeString(t,"s"),s=this.getStockUnifiedSymbol(i,"USDC");if(void 0===s)return;let r=this.safeInteger2(t,"E","T"),a=this.safeTicker({symbol:s,timestamp:r,datetime:this.iso8601(r),bid:this.safeString(t,"bp"),ask:this.safeString(t,"ap"),bidVolume:this.safeString(t,"bs"),askVolume:this.safeString(t,"as"),info:t});this.bidsasks[s]=a,e.resolve(a,"stock:quote:"+s)}handleOptionsOrderUpdate(e,t){let i=this.safeList(t,"o",[]);for(let t=0;t<i.length;t++){let s=this.safeDict(i,t),r=this.safeList(s,"fi",[]),a=this.safeString(s,"q","0"),n="BUY";o.Y.stringLt(a,"0")&&(n="SELL");let d=o.Y.stringAbs(a),h="NEW";r.length>0&&(h="TRADE");let c={s:this.safeString(s,"s"),i:this.safeString(s,"oid"),c:this.safeString(s,"c"),S:n,o:this.safeString(s,"oty"),f:this.safeString(s,"tif"),q:d,p:this.safeString(s,"p"),X:this.safeString(s,"S"),x:h,z:this.safeString(s,"e"),Z:this.safeString(s,"ec"),n:this.safeString(s,"f"),T:this.safeInteger(s,"t"),O:this.safeInteger(s,"T")};this.handleOrder(e,c);for(let t=0;t<r.length;t++){let i=this.safeDict(r,t),a="MAKER"===this.safeString(i,"m"),o={x:"TRADE",s:this.safeString(s,"s"),t:this.safeString(i,"t"),L:this.safeString(i,"p"),l:this.safeString(i,"q"),T:this.safeInteger(i,"T"),m:a,n:this.safeString(i,"f"),i:this.safeString(s,"oid"),S:n,o:this.safeString(s,"oty")};this.handleMyTrade(e,o)}}}async watchPositions(e,t,i,s={}){let r,a,o,d;void 0===this.markets&&await this.loadMarkets();let h="",c=this.marketSymbols(e);if(!this.isEmpty(c)){if(r=this.getMarketFromSymbols(c),void 0===c)throw new n.ArgumentsRequired(this.id+" watchPositions() symbols is required");h="::"+c.join(",")}[a,o,d]=this.resolveAuthType("watchPositions",r,s),("spot"===a||"margin"===a)&&(a="inverse"===o?"delivery":"future");let l={};l.type=a,l.subType=o,await this.authenticate(this.extend(l,d)),h=a+":positions"+h;let u=this.handleOptionBoolAndParams2(d,"watchPositions","papi","portfolioMargin",!1)[0],f=a;if(u)f="papi";else if("option"===a){if(!0===this.safeBool(this.options,"enableDemoTrading",!1)||this.isSandboxModeEnabled)throw new n.NotSupported(this.id+" watchPositions() does not support option markets in demo/testnet mode");f="optionPrivate"}let p=this.getPrivateWsUrl(f,this.options[a].listenKey),m=this.client(p);this.setBalanceCache(m,a,u),this.setPositionsCache(m,a,c,u);let g=this.handleOption("watchPositions","fetchPositionsSnapshot",!0),v=this.handleOption("watchPositions","awaitPositionsSnapshot",!0),y=this.safeValue(this.positions,a);if(!0===g&&!0===v&&void 0===y){let e=await m.future(a+":fetchPositionsSnapshot");return this.filterBySymbolsSinceLimit(e,c,t,i,!0)}let b=await this.watch(p,h,void 0,a);return this.newUpdates?b:this.filterBySymbolsSinceLimit(y,c,t,i,!0)}setPositionsCache(e,t,i,s=!1){if("spot"!==t){if(void 0===this.positions&&(this.positions={}),!(t in this.positions))if(!0===this.handleOption("watchPositions","fetchPositionsSnapshot",!1)){let i=t+":fetchPositionsSnapshot";i in e.futures||(e.future(i),this.spawn(this.loadPositionsSnapshot,e,i,t,s))}else this.positions[t]=new d.Hk}}async loadPositionsSnapshot(e,t,i,s){let r={type:i};!0===s&&(r.portfolioMargin=!0);let a=await this.fetchPositions(void 0,r);this.positions[i]=new d.Hk;let o=this.positions[i];for(let e=0;e<a.length;e++){let t=a[e],i=this.safeNumber(t,"contracts",0);void 0!==i&&i>0&&o.append(t)}t in e.futures&&(e.futures[t].resolve(o),e.resolve(o,i+":position"))}handlePositions(e,t){let i=Object.keys(e.subscriptions),s=this.getAccountTypeFromSubscriptions(i);void 0===this.positions&&(this.positions={}),s in this.positions||(this.positions[s]=new d.Hk);let r=this.positions[s],a=this.safeDict(t,"a",{}),o=this.safeList(a,"P",[]),n=[];for(let e=0;e<o.length;e++){let i=this.safeDict(o,e),s=this.parseWsPosition(i),a=this.safeInteger(t,"E");s.timestamp=a,s.datetime=this.iso8601(a),n.push(s),r.append(s)}let h=this.findMessageHashes(e,s+":positions::");for(let t=0;t<h.length;t++){let i=h[t],s=i.split("::")[1].split(","),r=this.filterByArray(n,"symbol",s,!1);this.isEmpty(r)||e.resolve(r,i)}e.resolve(n,s+":positions")}parseWsPosition(e,t){let i=this.safeString(e,"s"),s=this.safeString(e,"pa"),r=o.Y.stringAbs(this.safeString(e,"pa")),a=this.safeStringLower(e,"ps"),n=!0;return"both"===a&&(n=!1,o.Y.stringEq(s,"0")||(a=o.Y.stringLt(s,"0")?"short":"long")),this.safePosition({info:e,id:void 0,symbol:this.safeSymbol(i,void 0,void 0,"swap"),notional:void 0,marginMode:this.safeString(e,"mt"),liquidationPrice:void 0,entryPrice:this.safeNumber(e,"ep"),unrealizedPnl:this.safeNumber(e,"up"),percentage:void 0,contracts:this.parseNumber(r),contractSize:void 0,markPrice:void 0,side:a,hedged:n,timestamp:void 0,datetime:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,collateral:void 0,initialMargin:void 0,initialMarginPercentage:void 0,leverage:void 0,marginRatio:void 0})}parseWsOptionsPosition(e,t){let i,s=this.safeString(e,"s"),r=this.safeString(e,"c"),a=o.Y.stringAbs(r);return void 0!==r&&(o.Y.stringLt(r,"0")?i="short":o.Y.stringGt(r,"0")&&(i="long")),this.safePosition({info:e,id:void 0,symbol:this.safeSymbol(s,t,void 0,"option"),notional:this.safeString(e,"p"),marginMode:void 0,liquidationPrice:void 0,entryPrice:this.safeNumber(e,"a"),unrealizedPnl:void 0,percentage:void 0,contracts:this.parseNumber(a),contractSize:void 0,markPrice:void 0,side:i,hedged:!1,timestamp:void 0,datetime:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,collateral:void 0,initialMargin:void 0,initialMarginPercentage:void 0,leverage:void 0,marginRatio:void 0})}async fetchMyTradesWs(e,t,i,s={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new n.BadRequest(this.id+" fetchMyTradesWs requires a symbol");let r=this.market(e),a=this.getMarketType("fetchMyTradesWs",r,s);if("spot"!==a&&"future"!==a)throw new n.BadRequest(this.id+" fetchMyTradesWs does not support "+a+" markets");let o=this.safeString(this.urls.api.ws["ws-api"],a);if(void 0===o)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let d=this.requestId(o).toString(),[h,c]=this.handleOptionBoolAndParams(s,"fetchMyTradesWs","returnRateLimits",!1),l={symbol:this.marketId(e),returnRateLimits:h};if(void 0!==t&&(l.startTime=t),void 0!==i&&(l.limit=i),void 0!==this.safeInteger(c,"fromId")&&void 0!==t)throw new n.BadRequest(this.id+" fetchMyTradesWs does not support fetching by both fromId and since parameters at the same time");let u={id:d,method:"myTrades",params:this.signParams(this.extend(l,c))},f={method:this.handleTradesWs},p=await this.watch(o,d,u,d,f);return this.filterBySymbolSinceLimit(p,e,t,i)}async fetchTradesWs(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=this.getMarketType("fetchTradesWs",r,s);if("spot"!==a&&"future"!==a)throw new n.BadRequest(this.id+" fetchTradesWs does not support "+a+" markets");let o=this.safeString(this.urls.api.ws["ws-api"],a);if(void 0===o)throw new n.ExchangeError(this.id+" has no websocket url for this endpoint");let d=this.requestId(o).toString(),[h,c]=this.handleOptionBoolAndParams(s,"fetchTradesWs","returnRateLimits",!1),l={symbol:this.marketId(e),returnRateLimits:h};void 0!==i&&(l.limit=i);let u={id:d,method:"trades.historical",params:this.extend(l,c)},f={method:this.handleTradesWs},p=await this.watch(o,d,u,d,f);return this.filterBySinceLimit(p,t,i)}handleTradesWs(e,t){let i=this.safeString(t,"id"),s=this.safeList(t,"result",[]),r=this.parseTrades(s);e.resolve(r,i)}async watchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a=void 0!==e?this.symbol(e):e,[o,d,h]=this.resolveAuthType("watchMyTrades",r,s),c="myTrades",l={};void 0!==a&&void 0!==r&&(c+=":"+a,l={type:r.type,symbol:a});let u=this.extend(h,l);await this.authenticate(this.extend({type:o,subType:d},u));let f=o;"margin"===o&&(f="spot");let p=this.handleOptionBoolAndParams2(u,"watchMyTrades","papi","portfolioMargin",!1)[0],m="";if("spot"===o||"margin"===o)m=this.urls.api.ws["ws-api"].spot;else{if(p)f="papi";else if("option"===o){if(!0===this.safeBool(this.options,"enableDemoTrading",!1)||this.isSandboxModeEnabled)throw new n.NotSupported(this.id+" watchMyTrades() does not support option markets in demo/testnet mode");f="optionPrivate"}m=this.getPrivateWsUrl(f,this.options[o].listenKey)}let g=this.client(m);this.setBalanceCache(g,o,p),this.setPositionsCache(g,o,void 0,p);let v=await this.watch(m,c,void 0,o),y=i;return this.newUpdates&&(y=v.getLimit(a,i)),this.filterBySymbolSinceLimit(v,a,t,y,!0)}handleMyTrade(e,t){let i="myTrades";if("TRADE"===this.safeString(t,"x")){let s=this.parseWsTrade(t),r=this.safeString(s,"order"),a=this.safeDict(s,"fee",{});a=this.extend({},a);let o=this.safeString(s,"symbol");if(void 0!==r&&void 0!==a&&void 0!==o){let e=this.orders;if(void 0!==e){let t=this.safeDict(e.hashmap,o,{}),i=this.safeDict(t,r);if(void 0!==i){let e=this.safeValue(i,"fees"),o=this.safeDict(i,"fee");if(this.isEmpty(e))if(void 0!==o)if(this.safeString(o,"currency")===this.safeString(a,"currency")){let e=this.sum(o.cost,a.cost),t=this.currencyToPrecision(a.currency,e);void 0===t&&(t="0"),i.fee.cost=parseFloat(t)}else void 0===o.currency?i.fee=a:(i.fees=[o,a],i.fee=void 0);else i.fee=a;else{let t=!0;for(let s=0;s<e.length;s++){let r=e[s];if(this.safeString(r,"currency")===this.safeString(a,"currency")){let e=this.sum(a.cost,r.cost),o=this.currencyToPrecision(a.currency,e);void 0===o&&(o="0"),i.fees[s].cost=parseFloat(o),t=!1;break}}t&&i.fees.push(a)}let n=this.safeList(i,"trades",[]);n.push(s),i.trades=n,t[r]=i}}}if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new d.Pt(e)}this.myTrades.append(s),e.resolve(this.myTrades,i);e.resolve(this.myTrades,i+":"+o)}}handleOrder(e,t){let i=this.parseWsOrder(t),s=this.safeString(i,"symbol"),r=this.safeString(i,"id");if(void 0!==s){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new d.Pt(e)}let t=this.orders,a=this.safeDict(t.hashmap,s,{}),o=this.safeDict(a,r);if(void 0!==o){let e=this.safeValue(o,"fee");void 0!==e&&(i.fee=e);let t=this.safeList(o,"fees");void 0!==t&&(i.fees=t),i.trades=this.safeValue(o,"trades"),void 0===this.safeInteger(i,"timestamp")&&(i.timestamp=this.safeInteger(o,"timestamp"),i.datetime=this.safeString(o,"datetime"))}t.append(i);e.resolve(t,"orders"),e.resolve(t,"orders:"+s)}}handleAcountUpdate(e,t){this.handleBalance(e,t),this.handlePositions(e,t)}handleOptionsAccountUpdate(e,t){let i="option";void 0===this.balance[i]&&(this.balance[i]={}),this.balance[i].info=t;let s=this.safeList(t,"B",[]);for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),r=this.safeString(t,"a"),a=this.safeCurrencyCode(r);if(void 0!==a){let e=this.account();e.total=this.safeString(t,"b"),this.balance[i][a]=e}}let r=this.safeInteger(t,"E");this.balance[i].timestamp=r,this.balance[i].datetime=this.iso8601(r),this.balance[i]=this.safeBalance(this.balance[i]),e.resolve(this.balance[i],i+":balance"),void 0===this.positions&&(this.positions={}),i in this.positions||(this.positions[i]=new d.Hk);let a=this.positions[i],o=this.safeList(t,"P",[]),n=[];for(let e=0;e<o.length;e++){let t=this.safeDict(o,e),i=this.parseWsOptionsPosition(t);i.timestamp=r,i.datetime=this.iso8601(r),n.push(i),a.append(i)}let h=this.findMessageHashes(e,i+":positions::");for(let t=0;t<h.length;t++){let i=h[t],s=i.split("::")[1].split(","),r=this.filterByArray(n,"symbol",s,!1);this.isEmpty(r)||e.resolve(r,i)}e.resolve(n,i+":positions")}handleWsError(e,t){let i=this.safeString(t,"id"),s=!1,r=this.safeDict(t,"error",{}),a=this.safeInteger(r,"code"),o=this.safeString(r,"msg");try{this.handleErrors(void 0===a?0:a,o,e.url,"",{},this.json(r),r,{},{})}catch(r){s=!0,e.reject(r,i);let t=Object.keys(e.subscriptions);for(let s=0;s<t.length;s++){let a=t[s],o=this.safeString(e.subscriptions[a],"id"),n=this.safeString(e.subscriptions[a],"subscription");i===o&&(e.reject(r,a),void 0!==n&&delete e.subscriptions[n])}}if(!s){let s=new n.ExchangeError(this.id+" "+this.json(t));e.reject(s,i)}let d=this.safeString(r,"code");if(void 0!==d&&"5"===d[0]){let i=new n.ExchangeError(this.id+" "+this.json(t));e.reset(i)}}handleEventStreamTerminated(e,t){let i=this.safeString(t,"e"),s=Object.keys(e.subscriptions),r=this.getAccountTypeFromSubscriptions(s);if("eventStreamTerminated"===i){delete e.subscriptions[r];let i=new n.ExchangeError(this.id+" user data event stream terminated "+this.json(t));e.reject(i,r)}}handleMessage(e,t){let i=void 0!==this.safeString(t,"stream")?this.safeDict(t,"data",t):t,s=this.safeDict(i,"event"),r=void 0!==s?s:i,a=this.safeDict(r,"data"),o=void 0!==a?a:r,n=this.safeString(o,"status");if(void 0!==this.safeDict(o,"error")||void 0!==n&&"200"!==n)return void this.handleWsError(e,o);let d=this.safeString(o,"id"),h=this.safeDict(e.subscriptions,d),c=this.safeValue(h,"method");if(void 0!==c)return void c.call(this,e,o);let l={depthUpdate:this.handleOrderBook,trade:this.handleTrade,aggTrade:this.handleTrade,price:this.handleStockPrice,quote:this.handleStockQuote,optionTrade:this.handleTrade,markPrice:this.handleMarkPrices,kline:this.handleOHLCV,markPrice_kline:this.handleOHLCV,indexPrice_kline:this.handleOHLCV,"1hTicker@arr":this.handleTickers,"4hTicker@arr":this.handleTickers,"1dTicker@arr":this.handleTickers,"24hrTicker@arr":this.handleTickers,"24hrMiniTicker@arr":this.handleTickers,"1hTicker":this.handleTickers,"4hTicker":this.handleTickers,"1dTicker":this.handleTickers,"24hrTicker":this.handleTickers,"24hrMiniTicker":this.handleTickers,markPriceUpdate:this.handleMarkPrices,"markPriceUpdate@arr":this.handleMarkPrices,"markPrice@arr":this.handleMarkPrices,bookTicker:this.handleBidsAsks,outboundAccountPosition:this.handleBalance,balanceUpdate:this.handleBalance,ACCOUNT_UPDATE:this.handleAcountUpdate,BALANCE_POSITION_UPDATE:this.handleOptionsAccountUpdate,executionReport:this.handleOrderUpdate,orderReport:this.handleOrderUpdate,ORDER_TRADE_UPDATE:this.handleOrderUpdate,ALGO_UPDATE:this.handleOrderUpdate,forceOrder:this.handleLiquidation,eventStreamTerminated:this.handleEventStreamTerminated,externalLockUpdate:this.handleBalance},u=this.safeString(o,"e");if(Array.isArray(o)){let e=this.safeDict(o,0);u=this.safeString(e,"e")+"@arr"}if(void 0===(c=this.safeValue(l,u))){if(void 0!==this.safeString(o,"id"))return void this.handleSubscriptionStatus(e,o);void 0===u&&"a"in o&&"b"in o&&this.handleBidsAsks(e,o)}else c.call(this,e,o)}}i.d(t,{A:()=>l})},4264(e,t,i){"use strict";var s=i(7802),r=i(5164);class a extends s.A{describe(){let e=new r.A().describe(),t=super.describeData(),i=this.deepExtend(e,t);return this.deepExtend(i,{id:"binancecoinm",name:"Binance COIN-M",urls:{logo:"https://user-images.githubusercontent.com/1294454/117738721-668c8d80-b205-11eb-8c49-3fad84c4a07f.jpg",doc:"https://developers.binance.com/en"},options:{fetchMarkets:{types:["inverse"]},defaultSubType:"inverse"}})}}i.d(t,{A:()=>a})},3402(e,t,i){"use strict";var s=i(7802),r=i(3942);class a extends s.A{describe(){let e=new r.A().describe(),t=super.describeData(),i=this.deepExtend(e,t);return this.deepExtend(i,{id:"binanceus",name:"Binance US",countries:["US"],certified:!1,urls:{logo:"https://user-images.githubusercontent.com/1294454/65177307-217b7c80-da5f-11e9-876e-0b748ba0a358.jpg",api:{ws:{spot:"wss://stream.binance.us:9443/ws"},web:"https://www.binance.us",sapi:"https://api.binance.us/sapi/v1",wapi:"https://api.binance.us/wapi/v3",public:"https://api.binance.us/api/v3",private:"https://api.binance.us/api/v3",v3:"https://api.binance.us/api/v3",v1:"https://api.binance.us/api/v1"},www:"https://www.binance.us",referral:"https://www.binance.us/?ref=35005074",doc:"https://github.com/binance-us/binance-official-api-docs",fees:"https://www.binance.us/en/fee/schedule"},has:{createOrderWithTakeProfitAndStopLossWs:!1,createReduceOnlyOrderWs:!1,createStopLossOrderWs:!1,createTakeProfitOrderWs:!1,fetchPositionForSymbolWs:!1,fetchPositionsForSymbolWs:!1,fetchPositionsWs:!1,fetchPositionWs:!1,unWatchPositions:!1,watchLiquidations:!1,watchLiquidationsForSymbols:!1,watchMarkPrice:!1,watchMarkPrices:!1,watchMyLiquidations:!1,watchMyLiquidationsForSymbols:!1,watchPosition:!1,watchPositions:!1},options:{quoteOrderQty:!1,defaultType:"spot",fetchMarkets:{types:["spot"]}}})}}i.d(t,{A:()=>a})},905(e,t,i){"use strict";var s=i(7802),r=i(4965),a=i(1453);class o extends s.A{describe(){let e=new r.A().describe(),t=super.describeData(),i=this.deepExtend(e,t);return this.deepExtend(i,{id:"binanceusdm",name:"Binance USDⓈ-M",urls:{logo:"https://user-images.githubusercontent.com/1294454/117738721-668c8d80-b205-11eb-8c49-3fad84c4a07f.jpg",doc:"https://developers.binance.com/en"},options:{fetchMarkets:{types:["linear"]},defaultSubType:"linear"},exceptions:{exact:{"-5021":a.InvalidOrder,"-5022":a.InvalidOrder,"-5028":a.InvalidOrder}}})}}i.d(t,{A:()=>o})},9926(e,t,i){"use strict";var s=i(5938),r=i(1453),a=i(7749),o=i(1697);class n extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchTrades:!0,watchTradesForSymbols:!1,watchOrderBook:!0,watchOrderBookForSymbols:!1,watchOHLCV:!0,watchOHLCVForSymbols:!1,watchOrders:!0,watchMyTrades:!0,watchTicker:!0,watchTickers:!1,watchBalance:!0,watchPositions:!0,unWatchOHLCV:!0,unWatchOrderBook:!0,unWatchTicker:!0,unWatchTrades:!0},urls:{test:{ws:{linear:"wss://vst-open-api-ws.bingx.com/swap-market"}},api:{ws:{spot:"wss://open-api-ws.bingx.com/market",linear:"wss://open-api-swap.bingx.com/swap-market",inverse:"wss://open-api-cswap-ws.bingx.com/market"}}},options:{listenKeyRefreshRate:354e4,ws:{gunzip:!0},swap:{timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","12h":"12h","1d":"1d","3d":"3d","1w":"1w","1M":"1M"}},spot:{timeframes:{"1m":"1min","5m":"5min","15m":"15min","30m":"30min","1h":"60min","1d":"1day"}},watchBalance:{fetchBalanceSnapshot:!0,awaitBalanceSnapshot:!0},watchPositions:{fetchPositionsSnapshot:!0,awaitPositionsSnapshot:!1},watchOrderBook:{depth:100},watchTrades:{ignoreDuplicates:!0}},streaming:{keepAlive:18e5}})}async unWatch(e,t,i,s,r,a,o,n={}){let d,h,c,l;[d,l]=this.handleMarketTypeAndParams(o,a,n),[h,l]=this.handleSubTypeAndParams(o,a,l,"linear"),c="swap"===d?this.safeString(this.urls.api.ws,h):this.safeString(this.urls.api.ws,d);let u=this.uuid(),f=[];void 0!==a&&f.push(a.symbol);let p={unsubscribe:!0,id:u,subMessageHashes:[t],messageHashes:[e],symbols:f,topic:r},m=this.safeList(l,"symbolsAndTimeframes");return void 0!==m&&(p.symbolsAndTimeframes=m,l=this.omit(l,"symbolsAndTimeframes")),await this.watch(c,e,this.extend({id:u,dataType:s,reqType:"unsub"},l),i,p)}async watchTicker(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),[r,a]=this.handleMarketTypeAndParams("watchTicker",s,t),[o,n]=this.handleSubTypeAndParams("watchTicker",s,a,"linear");i="swap"===r?this.safeString(this.urls.api.ws,o):this.safeString(this.urls.api.ws,r);let d=s.id+"@ticker",h=this.getMessageHash("ticker",this.safeString(s,"symbol")),c=this.uuid(),l={id:c,dataType:d};return"swap"===r&&(l.reqType="sub"),await this.watch(i,h,this.extend(l,n),h,{unsubscribe:!1,id:c})}async unWatchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.id+"@ticker",r=this.getMessageHash("ticker",this.safeString(i,"symbol")),a="unsubscribe::"+r;return await this.unWatch(a,r,a,s,"ticker",i,"unWatchTicker",t)}handleTicker(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"s"),r=e.url.indexOf("swap")>=0,a="spot";r&&(a="swap");let o=this.safeMarket(s,void 0,void 0,a),n=o.symbol,d=this.safeString(this.urls.api.ws,"inverse"),h=void 0!==d&&0===e.url.indexOf(d),c=this.parseWsTicker(i,o,h);this.tickers[n]=c,e.resolve(c,this.getMessageHash("ticker",n)),"all@ticker"===this.safeString(t,"dataType")&&e.resolve(c,this.getMessageHash("ticker"))}parseWsTicker(e,t,i){let s=this.safeInteger(e,"C"),r=this.safeString(e,"s"),a=this.safeMarket(r,t),o=this.safeString(e,"c"),n=(void 0===i?!0===a.inverse:i)?"m":"v";return this.safeTicker({symbol:a.symbol,timestamp:s,datetime:this.iso8601(s),high:this.safeString(e,"h"),low:this.safeString(e,"l"),bid:this.safeString(e,"B"),bidVolume:this.safeString(e,"b"),ask:this.safeString(e,"A"),askVolume:this.safeString(e,"a"),vwap:void 0,open:this.safeString(e,"o"),close:o,last:o,previousClose:void 0,change:this.safeString(e,"p"),percentage:void 0,average:void 0,baseVolume:this.safeString(e,n),quoteVolume:this.safeString(e,"q"),info:e},a)}getOrderBookLimitByMarketType(e,t){return void 0===t?100:"swap"===e||"future"===e?this.findNearestCeiling([5,10,20,50,100],t):"spot"===e?this.findNearestCeiling([20,100],t):t}getMessageHash(e,t,i){let s=e;return void 0!==t?s+="::"+t:s+="s",void 0!==i&&(s+="::"+i),s}async watchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,[n,d]=this.handleMarketTypeAndParams("watchTrades",a,s),[h,c]=this.handleSubTypeAndParams("watchTrades",a,d,"linear");r="swap"===n?this.safeString(this.urls.api.ws,h):this.safeString(this.urls.api.ws,n);let l=a.id+"@trade",u="trade::"+o,f=this.uuid(),p={id:f,dataType:l};"swap"===n&&(p.reqType="sub");let m=await this.watch(r,u,this.extend(p,c),u,{unsubscribe:!1,id:f}),g=i;this.newUpdates&&(g=m.getLimit(o,i));let v=this.filterBySinceLimit(m,t,g,"timestamp",!0);if(!0===this.handleOption("watchTrades","ignoreDuplicates",!0)){let e=this.removeRepeatedTradesFromArray(v);return this.sortBy(e,"timestamp")}return v}async unWatchTrades(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.id+"@trade",r=this.getMessageHash("trade",this.safeString(i,"symbol")),a="unsubscribe::"+r;return await this.unWatch(a,r,a,s,"trades",i,"unWatchTrades",t)}handleTrades(e,t){let i,s=this.safeValue(t,"data",[]),r=this.safeString(t,"dataType","").split("@")[0],a=e.url.indexOf("swap")>=0,n="spot";a&&(n="swap");let d=this.safeMarket(r,void 0,void 0,n),h=d.symbol,c="trade::"+h;i=Array.isArray(s)?this.parseTrades(s,d):[this.parseTrade(s,d)];let l=this.safeValue(this.trades,h);if(void 0===l){let e=this.safeInteger(this.options,"tradesLimit",1e3);l=new o.I3(e),this.trades[h]=l}for(let e=0;e<i.length;e++)l.append(i[e]);e.resolve(l,c)}async watchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),[a,o]=this.handleMarketTypeAndParams("watchOrderBook",r,i),[n,d]=this.handleSubTypeAndParams("watchOrderBook",r,o,"linear");s="swap"===a?this.safeString(this.urls.api.ws,n):this.safeString(this.urls.api.ws,a);let h=this.safeDict(this.options,"watchOrderBook",{}),c=this.safeInteger(h,"depth",100),l=r.id+"@depth"+this.numberToString(c),u=this.getMessageHash("orderbook",this.safeString(r,"symbol")),f=this.uuid(),p={id:f,dataType:l};"swap"===a&&(p.reqType="sub");let m={};return m=!0===r.inverse?{id:f,unsubscribe:!1,count:t,params:d}:{id:f,unsubscribe:!1,level:t,params:d},(await this.watch(s,u,this.deepExtend(p,d),l,m)).limit()}async unWatchOrderBook(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.safeDict(this.options,"watchOrderBook",{}),r=this.safeInteger(s,"depth",100),a=i.id+"@depth"+this.numberToString(r),o="unsubscribe::"+a;return await this.unWatch(o,a,o,a,"orderbook",i,"unWatchOrderBook",t)}handleDelta(e,t){let i=this.safeFloat2(t,0,"p"),s=this.safeFloat2(t,1,"a");e.store(i,s)}handleOrderBook(e,t){let i,s=this.safeDict(t,"data",{}),r=this.safeString(t,"dataType",""),a=r.split("@")[0],o="all"===a,n=this.safeString(s,"symbol",a),d=e.url.indexOf("swap")>=0,h="spot";d&&(h="swap");let c=this.safeMarket(n,void 0,void 0,h),l=c.symbol,u=this.safeValue(this.orderbooks,l);if(void 0===u){let t=this.safeDict(e.subscriptions,r),i=this.safeInteger(t,"limit",100);this.orderbooks[l]=this.orderBook({},i)}u=this.orderbooks[l];let f=this.safeInteger2(t,"timestamp","ts");f=this.safeInteger2(s,"timestamp","ts",f),(i=!0===c.inverse?this.parseOrderBook(s,l,f,"bids","asks","p","a"):this.parseOrderBook(s,l,f,"bids","asks",0,1)).nonce=this.safeInteger(s,"lastUpdateId"),u.reset(i);let p=this.getMessageHash("orderbook",l);if(e.resolve(u,p),o){let t=this.getMessageHash("orderbook");e.resolve(u,t)}}parseWsOHLCV(e,t){let i=this.safeBool(t,"spot",!1),s=this.safeBool(t,"inverse",!1),r="T";return i&&(r="t"),this.safeBool(t,"swap",!1)&&(r=s?"t":"T"),[this.safeInteger(e,r),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}handleOHLCV(e,t){let i,s=e.url.indexOf("swap")>=0,r=this.safeString(t,"dataType",""),a=r.split("@")[0],n="all"===a,d=this.safeString(t,"s",a),h="spot";s&&(h="swap");let c=this.safeMarket(d,void 0,void 0,h);if(s)i=!0===c.inverse?[this.safeDict(t,"data",{})]:this.safeList(t,"data",[]);else{let e=this.safeDict(t,"data",{});i=[this.safeDict(e,"K",{})]}let l=c.symbol;this.ohlcvs[l]=this.safeDict(this.ohlcvs,l,{});let u=r.split("_")[1],f=this.safeDict(this.options,h),p=this.safeDict(f,"timeframes",{}),m=this.findTimeframe(u,p);if(void 0===this.safeValue(this.ohlcvs[l],u)){let t=this.safeDict(e.subscriptions,r),i=this.safeInteger(t,"limit",this.safeInteger(this.options,"OHLCVLimit",1e3));this.ohlcvs[l][m]=new o.TG(i)}let g=this.ohlcvs[l][m];for(let e=0;e<i.length;e++){let t=i[e],s=this.parseWsOHLCV(t,c);g.append(s)}let v=[l,m,g],y=this.getMessageHash("ohlcv",l,m);if(e.resolve(v,y),n){let t=this.getMessageHash("ohlcv",void 0,m);e.resolve(v,t)}}async watchOHLCV(e,t="1m",i,s,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.market(e),[d,h]=this.handleMarketTypeAndParams("watchOHLCV",n,a),[c,l]=this.handleSubTypeAndParams("watchOHLCV",n,h,"linear");if(void 0===(o="swap"===d?this.safeString(this.urls.api.ws,c):this.safeString(this.urls.api.ws,d)))throw new r.BadRequest(this.id+" watchOHLCV is not supported for "+d+" markets.");let u=this.safeDict(this.options,d,{}),f=this.safeDict(u,"timeframes",{}),p=this.safeString(f,t,t),m=this.getMessageHash("ohlcv",this.safeString(n,"symbol"),t),g=n.id+"@kline_"+p,v=this.uuid(),y={id:v,dataType:g};"swap"===d&&(y.reqType="sub");let b=(await this.watch(o,m,this.extend(y,l),g,{id:v,unsubscribe:!1,interval:p,params:l}))[2],w=s;return this.newUpdates&&(w=b.getLimit(e,s)),this.filterBySinceLimit(b,i,w,0,!0)}async unWatchOHLCV(e,t="1m",i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=this.safeDict(this.options,s.type,{}),a=this.safeDict(r,"timeframes",{}),o=this.safeString(a,t,t),n=s.id+"@kline_"+o,d="unsubscribe::"+n;return i.symbolsAndTimeframes=[[s.symbol,t]],await this.unWatch(d,n,d,n,"ohlcv",s,"unWatchOHLCV",i)}async watchOrders(e,t,i,s={}){let a,o,n;void 0===this.markets&&await this.loadMarkets(),await this.authenticate(),void 0!==e&&(a=this.market(e));let d=void 0!==a?this.safeString(a,"symbol"):e,[h,c]=this.handleMarketTypeAndParams("watchOrders",a,s),l=this.handleSubTypeAndParams("watchOrders",a,c,"linear")[0],u="spot"===h,f="swap:private";u&&(f="spot:private");let p="swap:order";u&&(p="spot:order"),void 0!==a&&(p+=":"+d);let m=this.uuid();if("swap"===h){if("inverse"===l)throw new r.NotSupported(this.id+" watchOrders is not supported for inverse swap markets yet");o=this.safeString(this.urls.api.ws,l)}else o=this.safeString(this.urls.api.ws,h),n={id:m,reqType:"sub",dataType:"spot.executionReport"};let g=this.safeString(this.options,"listenKey");if(void 0===o||void 0===g)throw new r.AuthenticationError(this.id+" watchOrders() requires a websocket URL and a listen key");let v=o+"?listenKey="+g,y=await this.watch(v,p,n,f,{unsubscribe:!1,id:m}),b=i;return this.newUpdates&&(b=y.getLimit(d,i)),this.filterBySymbolSinceLimit(y,d,t,b,!0)}async watchMyTrades(e,t,i,s={}){let a,o;void 0===this.markets&&await this.loadMarkets(),await this.authenticate(),void 0!==e&&(a=this.market(e));let n=void 0!==a?this.safeString(a,"symbol"):e,[d,h]=this.handleMarketTypeAndParams("watchMyTrades",a,s),c=this.handleSubTypeAndParams("watchMyTrades",a,h,"linear")[0],l="spot"===d,u="swap:private";l&&(u="spot:private");let f="swap:mytrades";l&&(f="spot:mytrades"),void 0!==a&&(f+=":"+n);let p=this.uuid(),m={};if("swap"===d){if("inverse"===c)throw new r.NotSupported(this.id+" watchMyTrades is not supported for inverse swap markets yet");o=this.safeString(this.urls.api.ws,c)}else o=this.safeString(this.urls.api.ws,d),m={id:p,reqType:"sub",dataType:"spot.executionReport"};let g=this.safeString(this.options,"listenKey");if(void 0===o||void 0===g)throw new r.AuthenticationError(this.id+" watchMyTrades() requires a websocket URL and a listen key");let v=o+"?listenKey="+g,y=await this.watch(v,f,m,u,{unsubscribe:!1,id:p}),b=i;return this.newUpdates&&(b=y.getLimit(n,i)),this.filterBySymbolSinceLimit(y,n,t,b,!0)}async watchBalance(e={}){let t,i;void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let[s,a]=this.handleMarketTypeAndParams("watchBalance",void 0,e),[o,n]=this.handleSubTypeAndParams("watchBalance",void 0,a,"linear"),d="spot"===s,h="swap:balance";d&&(h="spot:balance");let c="swap:private";d&&(c="spot:balance");let l=this.uuid();if("swap"===s){if("inverse"===o)throw new r.NotSupported(this.id+" watchBalance is not supported for inverse swap markets yet");i=this.safeString(this.urls.api.ws,o)}else i=this.safeString(this.urls.api.ws,s),t={id:l,dataType:"ACCOUNT_UPDATE"};let u=this.safeString(this.options,"listenKey");if(void 0===i||void 0===u)throw new r.AuthenticationError(this.id+" watchBalance() requires a websocket URL and a listen key");let f=i+"?listenKey="+u,p=this.client(f);this.setBalanceCache(p,s,o,c,n);let[m,g]=this.handleOptionBoolAndParams(n,"watchBalance","fetchBalanceSnapshot",!0),v=this.handleOptionBoolAndParams(g,"watchBalance","awaitBalanceSnapshot",!1)[0];return m&&v&&await p.future(s+":fetchBalanceSnapshot"),await this.watch(f,h,t,c,{unsubscribe:!1,id:l})}setBalanceCache(e,t,i,s,r){if(!(s in e.subscriptions))if(this.handleOptionBoolAndParams(r,"watchBalance","fetchBalanceSnapshot",!0)[0]){let s=t+":fetchBalanceSnapshot";s in e.futures||(e.future(s),this.spawn(this.loadBalanceSnapshot,e,s,t,i))}else this.balance[t]={}}async loadBalanceSnapshot(e,t,i,s){let r=await this.fetchBalance({type:i,subType:s});this.balance[i]=this.extend(r,this.safeDict(this.balance,i,{})),t in e.futures&&(e.futures[t].resolve(),e.resolve(this.balance[i],i+":balance"))}async watchPositions(e,t,i,s={}){let a;void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let o="",n=this.marketSymbols(e);void 0===n||this.isEmpty(n)||(a=this.getMarketFromSymbols(n),o="::"+n.join(","));let[d,h]=this.handleMarketTypeAndParams("watchPositions",a,s,"swap"),[c,l]=this.handleSubTypeAndParams("watchPositions",a,h,"linear");if("spot"===d)throw new r.NotSupported(this.id+" watchPositions is not supported for spot markets");if("inverse"===c)throw new r.NotSupported(this.id+" watchPositions is not supported for inverse swap markets yet");o="swap:positions"+o;let u=this.safeString(this.urls.api.ws,c),f=this.safeString(this.options,"listenKey");if(void 0===u||void 0===f)throw new r.AuthenticationError(this.id+" watchPositions() requires a websocket URL and a listen key");let p=u+"?listenKey="+f,m=this.client(p);this.setPositionsCache(m,d,n);let[g,v]=this.handleOptionBoolAndParams(l,"watchPositions","fetchPositionsSnapshot",!0),y=this.handleOptionBoolAndParams(v,"watchPositions","awaitPositionsSnapshot",!1)[0],b=this.uuid();if(g&&y&&void 0===this.positions){let e=await m.future(d+":fetchPositionsSnapshot");return this.filterBySymbolsSinceLimit(e,n,t,i,!0)}let w=await this.watch(p,o,void 0,"swap:private",{unsubscribe:!1,id:b});return this.newUpdates?w:this.filterBySymbolsSinceLimit(this.positions,n,t,i,!0)}setPositionsCache(e,t,i){if(void 0===this.positions)if(!0===this.handleOption("watchPositions","fetchPositionsSnapshot",!0)){let i=t+":fetchPositionsSnapshot";i in e.futures||(e.future(i),this.spawn(this.loadPositionsSnapshot,e,i,t))}else this.positions=new o.Hk}async loadPositionsSnapshot(e,t,i){let s=await this.fetchPositions(void 0,{type:i,subType:"linear"});this.positions=new o.Hk;let r=this.positions;for(let e=0;e<s.length;e++){let t=s[e];this.safeNumber(t,"contracts",0)>0&&r.append(t)}t in e.futures&&(e.futures[t].resolve(r),e.resolve(r,"swap:positions"))}parseWsPosition(e,t){let i=this.safeString(e,"s"),s=this.safeString(e,"pa"),r=a.Y.stringAbs(s),o=this.safeStringLower(e,"ps"),n=!0;"both"===o&&(n=!1,a.Y.stringEq(s,"0")||(o=a.Y.stringLt(s,"0")?"short":"long"));let d=this.safeString(e,"mt"),h="isolated"===d?this.safeNumber(e,"iw"):void 0;return this.safePosition({info:e,id:void 0,symbol:this.safeSymbol(i,void 0,void 0,"swap"),notional:void 0,marginMode:d,liquidationPrice:void 0,entryPrice:this.safeNumber(e,"ep"),unrealizedPnl:this.safeNumber(e,"up"),percentage:void 0,contracts:this.parseNumber(r),contractSize:void 0,markPrice:void 0,side:o,hedged:n,timestamp:void 0,datetime:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,collateral:h,initialMargin:void 0,initialMarginPercentage:void 0,leverage:void 0,marginRatio:void 0})}handlePositions(e,t){void 0===this.positions&&(this.positions=new o.Hk);let i=this.positions,s=this.safeDict(t,"a",{});if(!("P"in s))return;let r=this.safeList(s,"P",[]),a=[];for(let e=0;e<r.length;e++){let s=r[e],o=this.parseWsPosition(s);if(void 0===this.safeString(o,"symbol"))continue;let n=this.safeInteger(t,"E");o.timestamp=n,o.datetime=this.iso8601(n),a.push(o),i.append(o)}let n=this.findMessageHashes(e,"swap:positions::");for(let t=0;t<n.length;t++){let i=n[t],s=i.split("::")[1].split(","),r=this.filterByArray(a,"symbol",s,!1);this.isEmpty(r)||e.resolve(r,i)}e.resolve(a,"swap:positions")}handleErrorMessage(e,t){let i=this.safeString(t,"code");try{if(void 0!==i){let e=this.id+" "+this.json(t);this.throwExactlyMatchedException(this.exceptions.exact,i,e)}}catch(t){e.reject(t)}return!0}async keepAliveListenKey(e={}){let t=this.safeString(this.options,"listenKey");if(void 0===t)return;try{await this.userAuthPrivatePutUserDataStream({listenKey:t})}catch(i){let e=["spot","linear","inverse"];for(let s=0;s<e.length;s++){let r=e[s],a=this.safeString(this.urls.api.ws,r);if(void 0===a)continue;let o=a+"?listenKey="+t,n=this.client(o),d=Object.keys(n.futures);for(let e=0;e<d.length;e++){let t=d[e];n.reject(i,t)}}this.options.listenKey=void 0,this.options.lastAuthenticatedTime=0;return}let i=this.safeInteger(this.options,"listenKeyRefreshRate",36e5);this.delay(i,this.keepAliveListenKey,e)}async authenticate(e={}){let t=this.milliseconds(),i=this.safeInteger(this.options,"lastAuthenticatedTime",0),s=this.safeInteger(this.options,"listenKeyRefreshRate",36e5);if(t-i>s){let i="authenticate",a=this.client("authenticationFlights");if(i in a.futures)return void await a.future(i);let o=a.reusableFuture(i);try{let o=await this.userAuthPrivatePostUserDataStream(),n=this.safeString(o,"listenKey");if(void 0===n)throw new r.AuthenticationError(this.id+" authenticate() received an empty listenKey");this.options.listenKey=n,this.options.lastAuthenticatedTime=t,this.delay(s,this.keepAliveListenKey,e),a.resolve(n,i)}catch(e){a.reject(e,i)}await o}}async pong(e,t){try{if("Ping"===t)await e.send("Pong");else{let i=this.safeString(t,"ping"),s=this.safeString(t,"time");await e.send({pong:i,time:s})}}catch(i){let t=new r.NetworkError(this.id+" pong failed with error "+this.exceptionMessage(i));e.reset(t)}}handleOrder(e,t){let i="dataType"in t,s=this.safeDict2(t,"data","o",{});if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}let r=this.orders,a=this.parseOrder(s);if(!i){let e=this.safeInteger(t,"T");if(void 0!==e&&e>0){let t=this.safeString(a,"id");if(void 0!==t)for(let i=0;i<r.length;i++){let s=r[i];if(this.safeString(s,"id")===t&&this.safeString(s,"symbol")===this.safeString(a,"symbol")){let t=this.safeInteger(s,"lastUpdateTimestamp");if(void 0!==t&&e<t)return;break}}a.lastUpdateTimestamp=e}}r.append(a);let n=a.symbol,d="swap:order";i&&(d="spot:order"),e.resolve(r,d),e.resolve(r,d+":"+n)}handleMyTrades(e,t){let i="dataType"in t,s=this.safeDict2(t,"data","o",{}),r=this.myTrades;if(void 0===r){let e=this.safeInteger(this.options,"tradesLimit",1e3);r=new o.Pt(e),this.myTrades=r}let a="swap";i&&(a="spot");let n=this.safeString(s,"s"),d=this.safeMarket(n,void 0,"-",a),h=this.parseTrade(s,d),c=h.symbol,l="swap:mytrades";i&&(l="spot:mytrades"),r.append(h),e.resolve(r,l),e.resolve(r,l+":"+c)}handleBalance(e,t){let i=this.safeDict(t,"a",{}),s=this.safeList(i,"B",[]),r=this.safeInteger2(t,"T","E"),a=this.safeString(this.urls.api.ws,"spot"),o=void 0!==a&&0===e.url.indexOf(a),n="swap";o&&(n="spot"),n in this.balance||(this.balance[n]={}),this.balance[n].info=s,this.balance[n].timestamp=r,this.balance[n].datetime=this.iso8601(r);for(let e=0;e<s.length;e++){let t=s[e],i=this.safeString(t,"a"),r=this.safeCurrencyCode(i),a=this.account();a.info=t,a.used=this.safeString(t,"lk"),a.free=this.safeString(t,"wb"),void 0!==r&&(this.balance[n][r]=a)}this.balance[n]=this.safeBalance(this.balance[n]),e.resolve(this.balance[n],n+":balance")}handleMessage(e,t){if("string"==typeof t){"Ping"===t&&this.spawn(this.pong,e,t);return}if(!this.handleErrorMessage(e,t))return;if("ping"in t)return void this.spawn(this.pong,e,t);let i=this.safeString(t,"dataType","");if(i.indexOf("@depth")>=0)return void this.handleOrderBook(e,t);if(i.indexOf("@ticker")>=0)return void this.handleTicker(e,t);if(i.indexOf("@trade")>=0)return void this.handleTrades(e,t);if(i.indexOf("@kline")>=0)return void this.handleOHLCV(e,t);if(i.indexOf("executionReport")>=0){let i=this.safeDict(t,"data",{});"TRADE"===this.safeString(i,"x")&&this.handleMyTrades(e,t),this.handleOrder(e,t);return}let s=this.safeString(t,"e");if("ACCOUNT_UPDATE"===s&&(this.handleBalance(e,t),this.handlePositions(e,t)),"ORDER_TRADE_UPDATE"===s){this.handleOrder(e,t);let i=this.safeDict(t,"o",{}),s=this.safeString(i,"x"),r=this.safeString(i,"X"),a="FILLED"===r;if("TRADE"===s&&"PARTIALLY_FILLED"===r){let e=this.safeString(i,"s");a=!0===this.safeMarket(e,void 0,"-","swap").linear&&void 0!==this.safeString(i,"l")&&void 0!==this.safeString(i,"L")}"TRADE"===s&&a&&this.handleMyTrades(e,t)}let r=this.safeDict(t,"data"),a=this.safeString(r,"e");"24hTicker"===a&&this.handleTicker(e,t),""===i&&void 0===a&&void 0===s&&this.handleSubscriptionStatus(e,t)}handleSubscriptionStatus(e,t){let i=this.safeString(t,"id"),s=this.indexBy(e.subscriptions,"id"),r=this.safeDict(s,i,{});return!0===this.safeBool(r,"unsubscribe",!1)&&this.handleUnSubscription(e,r),t}handleUnSubscription(e,t){let i=this.safeList(t,"messageHashes",[]),s=this.safeList(t,"subMessageHashes",[]);for(let t=0;t<i.length;t++){let r=i[t],a=s[t];this.cleanUnsubscription(e,a,r)}this.cleanCache(t)}}i.d(t,{A:()=>n})},5019(e,t,i){"use strict";var s=i(4721),r=i(7967),a=i(7749),o=i(1453),n=i(1697);class d extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchTicker:!0,watchTickers:!1,watchOrderBook:!0,watchTrades:!0,watchTradesForSymbols:!1,watchMyTrades:!0,watchBalance:!0,watchOHLCV:!0,watchOrders:!0,unWatchTicker:!0,unWatchTrades:!0,unWatchOHLCV:!0,unWatchOrderBook:!0},urls:{api:{ws:{public:"wss://api-pub.bitfinex.com/ws/2",private:"wss://api.bitfinex.com/ws/2"}}},options:{watchOrderBook:{prec:"P0",freq:"F0",checksum:!0},ordersLimit:1e3}})}async subscribe(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(t).id,r=this.urls.api.ws.public,a=this.client(r),o=e+":"+s,n=await this.watch(r,o,this.deepExtend({event:"subscribe",channel:e,symbol:s},i),o,{checksum:!1});if(!0===this.safeBool(this.options,"checksum",!0)&&"book"===e){let e=a.subscriptions[o];void 0!==e&&!0!==e.checksum&&(a.subscriptions[o].checksum=!0,await a.send({event:"conf",flags:131072}))}return n}async unSubscribe(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(i).id,a=this.urls.api.ws.public,o=this.client(a),n=e+":"+r,d="unsubscribe:"+e+":"+r,h=this.safeString(o.subscriptions,"unsubscribe:"+t+":"+i),c="unsubscribe:"+h;return o.subscriptions[c]=n,await this.watch(a,d,this.deepExtend({event:"unsubscribe",chanId:h},s),d,{messageHashes:[d],subMessageHashes:[n],topic:t,unsubscribe:!0,symbols:[i]})}async subscribePrivate(e){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let t=this.urls.api.ws.private;return await this.watch(t,e,void 0,1)}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n=this.safeString(this.timeframes,t,t),d="candles",h="trade:"+n+":"+a.id,c=d+":"+n+":"+a.id,l=this.urls.api.ws.public,u=await this.watch(l,c,this.deepExtend({event:"subscribe",channel:d,key:h},r),c),f=s;return this.newUpdates&&(f=u.getLimit(o,s)),this.filterBySinceLimit(u,i,f,0,!0)}async unWatchOHLCV(e,t="1m",i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=s.symbol,a=this.safeString(this.timeframes,t,t),o="candles:"+a+":"+s.id,n="unsubscribe:"+o,d=this.urls.api.ws.public,h=this.client(d),c="unsubscribe:trade:"+a+":"+s.id,l=this.safeString(h.subscriptions,c),u="unsubscribe:"+l;return h.subscriptions[u]=o,await this.watch(d,n,this.deepExtend({event:"unsubscribe",chanId:l},i),n,{messageHashes:[n],subMessageHashes:[o],topic:"ohlcv",unsubscribe:!0,symbols:[r]})}handleOHLCV(e,t,i){let s=this.safeList(t,1,[]),r=[];r=Array.isArray(this.safeList(s,0))?s:[s];let a=this.safeString(i,"channel"),o=this.safeString(i,"key",""),d=o.split(":"),h=this.safeString(d,1),c=o;c=(c=c.replace("trade:","")).replace(h+":","");let l=this.safeMarket(c),u=this.findTimeframe(h),f=l.symbol,p=a+":"+h+":"+c;this.ohlcvs[f]=this.safeDict(this.ohlcvs,f,{});let m=this.safeValue(this.ohlcvs[f],u);if(void 0===m){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);m=new n.TG(e),this.ohlcvs[f][u]=m}let g=r.length;for(let e=0;e<g;e++){let t=r[g-e-1],i=this.parseOHLCV(t,l);m.append(i)}e.resolve(m,p)}async watchTrades(e,t,i,s={}){let r=await this.subscribe("trades",e,s),a=i;return this.newUpdates&&(a=r.getLimit(e,i)),this.filterBySinceLimit(r,t,a,"timestamp",!0)}unWatchTrades(e,t={}){return this.unSubscribe("trades","trades",e,t)}async watchMyTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r="myTrade";void 0!==e&&(r+=":"+this.market(e).id);let a=await this.subscribePrivate(r),o=i;return this.newUpdates&&(o=a.getLimit(e,i)),this.filterBySymbolSinceLimit(a,e,t,o,!0)}watchTicker(e,t={}){return this.subscribe("ticker",e,t)}unWatchTicker(e,t={}){return this.unSubscribe("ticker","ticker",e,t)}handleMyTrade(e,t,i={}){let s="myTrade",r=this.safeList(t,2),a=this.parseWsTrade(r),o=a.symbol,d=s+":"+this.market(o).id;if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new n.Pt(e)}let h=this.myTrades;h.append(a),this.myTrades=h,e.resolve(h,s),e.resolve(h,d)}handleTrades(e,t,i){let s=this.safeString(i,"channel"),r=this.safeString(i,"symbol"),a=this.safeMarket(r),o=this.safeInteger(this.options,"tradesLimit",1e3),d=a.symbol,h=this.safeValue(this.trades,d);if(void 0===h&&(h=new n.I3(o),this.trades[d]=h),2===t.length){let e=this.safeList(t,1,[]),i=e.length;for(let t=0;t<i;t++){let s=i-t-1,r=this.parseWsTrade(e[s],a);h.append(r)}}else{if("tu"===this.safeString(t,1))return;let e=this.safeList(t,2,[]),i=this.parseWsTrade(e,a);h.append(i)}void 0!==s&&e.resolve(h,s+":"+r)}parseWsTrade(e,t){let i,s,r,o,n,d=e.length<=8;d||(i=this.safeString(e,1));let h=this.safeMarket(i,t);i=h.id;let c=this.safeString(e,6);void 0!==c&&(c.indexOf("LIMIT")>-1?c="limit":c.indexOf("MARKET")>-1&&(c="market")),d||(s=this.safeString(e,3));let l=this.safeString(e,0),u=this.safeInteger(e,d?1:2),f=this.safeString(e,d?3:5),p=this.safeString(e,d?2:4),m=this.parseNumber(a.Y.stringAbs(p));void 0!==m&&(r=a.Y.stringGt(p,"0")?"buy":"sell");let g=this.safeSymbol(i,h),v=this.safeString(e,9);if(void 0!==v){let t=this.safeString(e,10);o={cost:v,currency:this.safeCurrencyCode(t)}}let y=this.safeInteger(e,8);return void 0!==y&&(n=-1===y?"taker":"maker"),this.safeTrade({info:e,timestamp:u,datetime:this.iso8601(u),symbol:g,id:l,order:s,type:c,takerOrMaker:n,side:r,price:f,amount:m,cost:void 0,fee:o},h)}handleTicker(e,t,i){let s=this.safeValue(t,1),r=this.safeString(i,"symbol"),a=this.safeMarket(r),o=this.safeSymbol(r),n=this.parseWsTicker(s,a),d="ticker:"+r;this.tickers[o]=n,e.resolve(n,d)}parseWsTicker(e,t){let i=this.safeMarket(void 0,t),s=i.symbol,r=this.safeString(e,6),o=this.safeString(e,4);return this.safeTicker({symbol:s,timestamp:void 0,datetime:void 0,high:this.safeString(e,8),low:this.safeString(e,9),bid:this.safeString(e,0),bidVolume:this.safeString(e,1),ask:this.safeString(e,2),askVolume:this.safeString(e,3),vwap:void 0,open:void 0,close:r,last:r,previousClose:void 0,change:o,percentage:a.Y.stringMul(this.safeString(e,5),"100"),average:void 0,baseVolume:this.safeString(e,7),quoteVolume:void 0,info:e},i)}async watchOrderBook(e,t,i={}){if(void 0!==t&&25!==t&&100!==t)throw new o.ExchangeError(this.id+" watchOrderBook limit argument must be undefined, 25 or 100");let s=this.safeDict(this.options,"watchOrderBook",{}),r={prec:this.safeString(s,"prec","P0"),freq:this.safeString(s,"freq","F0")};return void 0!==t&&(r.len=t),(await this.subscribe("book",e,this.deepExtend(r,i))).limit()}handleOrderBook(e,t,i){let s=this.safeString(i,"symbol"),r=this.safeSymbol(s),o="book:"+s,n="R0"===this.safeString(i,"prec","P0");if(r in this.orderbooks){let i=this.orderbooks[r],s=t[1],d=this.orderbooks[r];if(n){let e=this.safeString(s,1),t=s[2],i=d[t<0?"asks":"bids"],r=a.Y.stringGt(e,"0")?t<0?-t:t:"0",o=this.safeString(s,0);i.storeArray([this.parseNumber(e),this.parseNumber(r),o])}else{let e=this.safeString(s,2),t=this.safeString(s,1),i=this.safeString(s,0),r=a.Y.stringLt(e,"0")?a.Y.stringNeg(e):e;d[a.Y.stringLt(e,"0")?"asks":"bids"].storeArray([this.parseNumber(i),this.parseNumber(r),this.parseNumber(t)])}e.resolve(i,o)}else{let s=this.safeInteger(i,"len");n?this.orderbooks[r]=this.indexedOrderBook({},s):this.orderbooks[r]=this.countedOrderBook({},s);let a=this.orderbooks[r];if(n){let e=t[1];for(let t=0;t<e.length;t++){let i=e[t],s=i[2],r=s<0?-s:s,o=a[s<0?"asks":"bids"],n=this.safeString(i,0),d=this.safeFloat(i,1);o.storeArray([d,r,n])}}else{let e=t[1];for(let t=0;t<e.length;t++){let i=this.safeList(e,t),s=this.safeNumber(i,2);if(void 0===s)continue;let r=this.safeNumber(i,1),o=this.safeNumber(i,0),n=s<0?-s:s;a[s<0?"asks":"bids"].storeArray([o,n,r])}}a.symbol=r,e.resolve(a,o)}}handleChecksum(e,t,i){let s=this.safeString(i,"symbol"),r=this.safeSymbol(s),a="book:"+s,n=this.safeDict(this.orderbooks,r);if(void 0===n)return;let d=[],h=n.bids,c=n.asks,l=2*("R0"===this.safeString(i,"prec","P0"));for(let e=0;e<25;e++){let t=this.safeList(h,e),i=this.safeList(c,e);if(void 0!==t&&(d.push(this.numberToString(h[e][l])),d.push(this.numberToString(h[e][1]))),void 0!==i){d.push(this.numberToString(c[e][l]));let t=c[e][1];d.push(this.numberToString(-t))}}let u=d.join(":"),f=this.crc32(u,!0);if(this.safeInteger(t,2)!==f&&(delete e.subscriptions[a],delete this.orderbooks[r],!0===this.handleOption("watchOrderBook","checksum",!0))){let t=new o.ChecksumError(this.id+" "+this.orderbookChecksumMessage(r));e.reject(t,a)}}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=this.safeString(e,"wallet","exchange");return await this.subscribePrivate("balance:"+t)}handleBalance(e,t,i){let s=this.safeString(t,1),r=[];r="ws"===s?this.safeList(t,2):[this.safeValue(t,2)];let a={};for(let e=0;e<r.length;e++){let i=r[e],s=this.safeString(i,1),o=this.safeCurrencyCode(s),n=this.parseWsBalance(i),d=this.safeString(i,0),h=this.safeDict(this.balance,d,{});void 0!==o&&(h[o]=n),h.info=t,this.balance[d]=this.safeBalance(h),a[d]=!0}let o=Object.keys(a);for(let t=0;t<o.length;t++){let i=o[t],s="balance:"+i;e.resolve(this.balance[i],s)}}parseWsBalance(e){let t=this.safeString(e,2),i=this.safeString(e,4),s=this.account();return void 0!==i&&(s.free=i),s.total=t,s}handleSystemStatus(e,t){return t}handleUnsubscriptionStatus(e,t){let i="unsubscribe:"+this.safeString(t,"chanId"),s=this.safeString(e.subscriptions,i),r=this.safeDict(e.subscriptions,"unsubscribe:"+s);delete e.subscriptions[i];let a=this.safeList(r,"messageHashes",[]),o=this.safeList(r,"subMessageHashes",[]);for(let t=0;t<a.length;t++){let i=a[t],s=o[t];this.cleanUnsubscription(e,s,i)}return this.cleanCache(r),!0}handleSubscriptionStatus(e,t){let i=this.safeString(t,"chanId");e.subscriptions[i]=t;let s=this.safeString({book:"orderbook",candles:"ohlcv",ticker:"ticker",trades:"trades"},this.safeString(t,"channel"));if("key"in t){let s=this.safeString(t,"key");e.subscriptions["unsubscribe:"+s]=i}else{let r=this.safeString(t,"symbol"),a=this.safeSymbol(r);void 0!==s&&(e.subscriptions["unsubscribe:"+s+":"+a]=i)}return t}async authenticate(e={}){let t=this.urls.api.ws.private,i=this.client(t),r="authenticated",a=i.reusableFuture(r);if(void 0===this.safeValue(i.subscriptions,r)){let i=this.incrementingNonce(),a="AUTH"+i.toString(),o=this.hmac(this.encode(a),this.encode(this.secret),s.qt,"hex"),n={apiKey:this.apiKey,authSig:o,authNonce:i,authPayload:a,event:"auth"},d=this.extend(n,e);this.watch(t,r,d,r)}return await a}handleAuthenticationMessage(e,t){let i="authenticated";if("OK"===this.safeString(t,"status"))this.safeValue(e.futures,i).resolve(!0);else{let s=new o.AuthenticationError(this.json(t));e.reject(s,i),i in e.subscriptions&&delete e.subscriptions[i]}}async watchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r="orders";void 0!==e&&(r+=":"+this.market(e).id);let a=await this.subscribePrivate(r),o=i;return this.newUpdates&&(o=a.getLimit(e,i)),this.filterBySymbolSinceLimit(a,e,t,o,!0)}handleOrders(e,t,i){let s=this.safeList(t,2,[]),r=this.safeString(t,1);if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new n.Pt(e)}let a=this.orders,o={};if("os"===r){if(0===s.length)return;for(let e=0;e<s.length;e++){let t=s[e],i=this.parseWsOrder(t);o[i.symbol]=!0,a.append(i)}}else{let e=this.parseWsOrder(s);a.append(e),o[e.symbol]=!0}let d="orders";e.resolve(this.orders,d);let h=Object.keys(o);for(let t=0;t<h.length;t++){let i=h[t],s=d+":"+this.market(i).id;e.resolve(this.orders,s)}}parseWsOrderStatus(e){return this.safeString({ACTIVE:"open",CANCELED:"canceled",EXECUTED:"closed",PARTIALLY:"open"},e,e)}parseWsOrder(e,t){let i=this.safeString(e,0),s=this.safeString(e,1),r=this.safeString(e,3),o=this.safeSymbol(r),n=this.safeMarket(o),d=this.safeString(e,7),h="buy";a.Y.stringLt(d,"0")&&(d=a.Y.stringAbs(d),h="sell");let c=a.Y.stringAbs(this.safeString(e,6)),l=this.safeString(e,8,"");l.indexOf("LIMIT")>-1?l="limit":l.indexOf("MARKET")>-1&&(l="market");let u=this.safeString(e,13,"").split(" "),f=this.safeString(u,0),p=this.parseWsOrderStatus(f),m=this.safeString(e,16),g=this.safeInteger2(e,5,4),v=this.safeString(e,17),y=this.omitZero(this.safeString(e,18));return this.safeOrder({info:e,id:i,clientOrderId:s,timestamp:g,datetime:this.iso8601(g),lastTradeTimestamp:void 0,symbol:o,type:l,side:h,price:m,stopPrice:y,triggerPrice:y,average:v,amount:d,remaining:c,filled:void 0,status:p,fee:void 0,cost:void 0,trades:void 0},n)}handleMessage(e,t){let i=this.safeString(t,0);if(Array.isArray(t)){let s;if("hb"===t[1])return;let r=this.safeDict(e.subscriptions,i,{}),a=this.safeString(r,"channel"),o=this.safeString(t,1),n={book:this.handleOrderBook,cs:this.handleChecksum,candles:this.handleOHLCV,ticker:this.handleTicker,trades:this.handleTrades},d={os:this.handleOrders,ou:this.handleOrders,on:this.handleOrders,oc:this.handleOrders,wu:this.handleBalance,ws:this.handleBalance,tu:this.handleMyTrade};void 0!==(s="0"===i?this.safeValue(d,o):this.safeValue2(n,o,a))&&s.call(this,e,t,r)}else{let i=this.safeString(t,"event");if(void 0!==i){let s={info:this.handleSystemStatus,subscribed:this.handleSubscriptionStatus,unsubscribed:this.handleUnsubscriptionStatus,auth:this.handleAuthenticationMessage},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}}}}i.d(t,{A:()=>d})},1179(e,t,i){"use strict";var s=i(4721),r=i(8271),a=i(1453),o=i(7749),n=i(1697);class d extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,createOrderWs:!1,editOrderWs:!1,fetchOpenOrdersWs:!1,fetchOrderWs:!1,cancelOrderWs:!1,cancelOrdersWs:!1,cancelAllOrdersWs:!1,watchBalance:!0,watchMyTrades:!0,watchOHLCV:!0,watchOHLCVForSymbols:!1,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOrders:!0,watchTicker:!0,watchTickers:!0,watchBidsAsks:!0,watchTrades:!0,watchTradesForSymbols:!0,watchPositions:!0},urls:{api:{ws:{public:"wss://ws.bitget.com/v2/ws/public",private:"wss://ws.bitget.com/v2/ws/private",utaPublic:"wss://ws.bitget.com/v3/ws/public",utaPrivate:"wss://ws.bitget.com/v3/ws/private"},demo:{public:"wss://wspap.bitget.com/v2/ws/public",private:"wss://wspap.bitget.com/v2/ws/private",utaPublic:"wss://wspap.bitget.com/v3/ws/public",utaPrivate:"wss://wspap.bitget.com/v3/ws/private"}}},options:{tradesLimit:1e3,OHLCVLimit:1e3,timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1H","4h":"4H","6h":"6H","12h":"12H","1d":"1D","1w":"1W"},watchTrades:{ignoreDuplicates:!0}},streaming:{ping:this.ping},exceptions:{ws:{exact:{30001:a.BadRequest,30002:a.AuthenticationError,30003:a.BadRequest,30004:a.AuthenticationError,30005:a.AuthenticationError,30006:a.RateLimitExceeded,30007:a.RateLimitExceeded,30011:a.AuthenticationError,30012:a.AuthenticationError,30013:a.AuthenticationError,30014:a.BadRequest,30015:a.AuthenticationError,30016:a.BadRequest},broad:{}}}})}getInstType(e,t,i=!1,s={}){let r=void 0===t||!0===t.swap||!0===t.future,a=[void 0,{}],o=(a=r?this.handleProductTypeAndParams(t,s):["SPOT",s])[0],n=a[1],[d,h]=this.handleOptionStringAndParams(n,e,"instType",o),c=d;return i&&void 0!==d&&(c=d.toLowerCase()),[c,h]}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,[r,a]=this.handleOptionBoolAndParams(t,"watchTicker","uta",!1),[o,n]=this.getInstType("watchTicker",i,r,a),d={instType:o},h="channel";r&&(h="topic");let c="instId";return r&&(c="symbol"),d[h]="ticker",d[c]=i.id,await this.watchPublic(r,"ticker:"+s,d,n)}unWatchTicker(e,t={}){return this.unWatchChannel(e,"ticker","ticker","watchTicker",t)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=void 0===i?[]:i,r=this.market(s[0]),[a,o]=this.handleOptionBoolAndParams(t,"watchTickers","uta",!1),[n,d]=this.getInstType("watchTickers",r,a,o),h=[],c=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t),r={instType:n},o="channel";a&&(o="topic");let d="instId";a&&(d="symbol"),r[o]="ticker",r[d]=i.id,h.push(r),c.push("ticker:"+t)}let l=await this.watchPublicMultiple(a,c,h,d);if(this.newUpdates){let e={},t=this.safeString(l,"symbol");return void 0!==t&&(e[t]=l),e}return this.filterByArray(this.tickers,"symbol",s)}handleTicker(e,t){this.handleBidAsk(e,t);let i=this.parseWsTicker(t),s=i.symbol;void 0!==s&&(this.tickers[s]=i),e.resolve(i,"ticker:"+s)}parseWsTicker(e,t){let i=this.safeDict(e,"arg",{}),s=this.safeList(e,"data",[]),r=this.safeDict(s,0,{}),a=this.safeInteger(e,"ts"),n=this.safeInteger(r,"ts",a),d=this.safeStringLower(i,"instType"),h="contract";"spot"===d&&(h="spot");let c=this.safeString(i,"symbol"),l=this.safeString(r,"instId",c),u=this.safeMarket(l,t,void 0,h),f=this.safeString2(r,"lastPr","lastPrice"),p=this.safeString2(r,"price24hPcnt","change24h"),m=o.Y.stringMul(p,"100");return this.safeTicker({symbol:u.symbol,timestamp:n,datetime:this.iso8601(n),high:this.safeString2(r,"high24h","highPrice24h"),low:this.safeString2(r,"low24h","lowPrice24h"),bid:this.safeString2(r,"bidPr","bid1Price"),bidVolume:this.safeString2(r,"bidSz","bid1Size"),ask:this.safeString2(r,"askPr","ask1Price"),askVolume:this.safeString2(r,"askSz","ask1Size"),vwap:void 0,open:this.safeString2(r,"open24h","openPrice24h"),close:f,last:f,previousClose:void 0,change:void 0,percentage:m,average:void 0,baseVolume:this.safeString2(r,"baseVolume","volume24h"),quoteVolume:this.safeString2(r,"quoteVolume","turnover24h"),info:r},u)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=void 0===i?[]:i,r=this.market(s[0]),[a,o]=this.handleOptionBoolAndParams(t,"watchBidsAsks","uta",!1),[n,d]=this.getInstType("watchBidsAsks",r,a,o),h=[],c=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t),r={instType:n},o="channel";a&&(o="topic");let d="instId";a&&(d="symbol"),r[o]="ticker",r[d]=i.id,h.push(r),c.push("bidask:"+t)}let l=await this.watchPublicMultiple(a,c,h,d);if(this.newUpdates){let e={},t=this.safeString(l,"symbol");return void 0!==t&&(e[t]=l),e}return this.filterByArray(this.bidsasks,"symbol",s)}handleBidAsk(e,t){let i=this.parseWsBidAsk(t),s=i.symbol;void 0!==s&&(this.bidsasks[s]=i),e.resolve(i,"bidask:"+s)}parseWsBidAsk(e,t){let i=this.safeDict(e,"arg",{}),s=this.safeList(e,"data",[]),r=this.safeDict(s,0,{}),a=this.safeInteger(e,"ts"),o=this.safeInteger(r,"ts",a),n=this.safeStringLower(i,"instType"),d="contract";"spot"===n&&(d="spot");let h=this.safeString(i,"symbol"),c=this.safeString(r,"instId",h),l=this.safeMarket(c,t,void 0,d);return this.safeTicker({symbol:l.symbol,timestamp:o,datetime:this.iso8601(o),ask:this.safeString2(r,"askPr","ask1Price"),askVolume:this.safeString2(r,"askSz","ask1Size"),bid:this.safeString2(r,"bidPr","bid1Price"),bidVolume:this.safeString2(r,"bidSz","bid1Size"),info:r},l)}async watchOHLCV(e,t="1m",i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=o.symbol,d=this.safeDict(this.options,"timeframes"),h=this.safeString(d,t),[c,l]=this.handleOptionBoolAndParams(r,"watchOHLCV","uta",!1),[u,f]=this.getInstType("watchOHLCV",o,c,l),p=f;c&&(p=this.extend(f,{uta:!0}));let m={instType:u};c?(m.topic="kline",m.symbol=o.id,m.interval=h,a="kline:"+n):(m.channel="candle"+h,m.instId=o.id,a="candles:"+t+":"+n);let g=await this.watchPublic(c,a,m,p),v=s;return this.newUpdates&&(v=g.getLimit(n,s)),this.filterBySinceLimit(g,i,v,0,!0)}async unWatchOHLCV(e,t="1m",i={}){let s,r;void 0===this.markets&&await this.loadMarkets();let a=this.safeDict(this.options,"timeframes"),o=this.safeString(a,t),n=this.market(e),d=this.handleOptionBoolAndParams(i,"watchOHLCV","uta",!1)[0],[h,c]=this.getInstType("watchOHLCV",n,d,i),l=c;d&&(l=this.extend(c,{uta:!0,interval:o}));let u={instType:h};return d?(u.topic=s="kline",u.symbol=n.id,u.interval=o,r=s+e):(u.channel=s="candle"+o,u.instId=n.id,r="candles:"+o),await this.unWatchChannel(e,s,r,"watchOHLCV",l)}handleOHLCV(e,t){let i,s,r=this.safeDict(t,"arg",{}),a=this.safeStringLower(r,"instType"),o="contract";"spot"===a&&(o="spot");let d=this.safeString2(r,"instId","symbol"),h=this.safeMarket(d,void 0,void 0,o),c=h.symbol;this.ohlcvs[c]=this.safeDict(this.ohlcvs,c,{});let l=this.safeString2(r,"channel","topic",""),u=this.safeString(r,"interval");void 0===u?(i=!1,u=l.replace("candle","")):i=!0;let f=this.safeDict(this.options,"timeframes"),p=this.findTimeframe(u,f);if(void 0===p)return;let m=this.safeValue(this.safeDict(this.ohlcvs,c),p);if(void 0===m){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);m=new n.TG(e),this.ohlcvs[c][p]=m}let g=this.safeList(t,"data",[]);for(let e=0;e<g.length;e++){let t=this.parseWsOHLCV(g[e],h);m.append(t)}s=i?"kline:"+c:"candles:"+p+":"+c,e.resolve(m,s)}parseWsOHLCV(e,t){let i=5;return void 0!==t&&!0===t.inverse&&(i=6),[this.safeInteger2(e,"start",0),this.safeNumber2(e,"open",1),this.safeNumber2(e,"high",2),this.safeNumber2(e,"low",3),this.safeNumber2(e,"close",4),this.safeNumber2(e,"volume",i)]}watchOrderBook(e,t,i={}){return this.watchOrderBookForSymbols([e],t,i)}async unWatchOrderBook(e,t={}){void 0===this.markets&&await this.loadMarkets();let i="books",s=this.safeInteger(t,"limit"),r=1===s||5===s||15===s||50===s,a=t;return r&&(a=this.omit(t,"limit")),r&&(i+=s.toString()),await this.unWatchChannel(e,i,"orderbook","watchOrderBook",a)}async unWatchChannel(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o="unsubscribe:"+i+":"+a.symbol,[n,d]=this.handleOptionBoolAndParams(r,s,"uta",!1),[h,c]=this.getInstType(s,a,n,d),l=c;n&&(l=this.omit(this.extend(c,{uta:!0}),"interval"));let u={instType:h};return n?(u.topic=t,u.symbol=a.id,u.interval=this.safeString(c,"interval","1m")):(u.channel=t,u.instId=a.id),await this.unWatchPublic(n,o,u,l)}async watchOrderBookForSymbols(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e),r="books",a=!0;(1===t||5===t||15===t||50===t)&&(r+=t.toString(),a=!1);let o=[],n=[],[d,h]=this.handleOptionBoolAndParams(i,"watchOrderBookForSymbols","uta",!1),c=h;for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t),[a,h]=this.getInstType("watchOrderBookForSymbols",i,d,c);c=h;let l={instType:a},u="channel";d&&(u="topic");let f="instId";d&&(f="symbol"),l[u]=r,l[f]=i.id,o.push(l),n.push("orderbook:"+t)}d&&(c.uta=!0);let l=await this.watchPublicMultiple(d,n,o,c);return a?l.limit():l}handleOrderBook(e,t){let i=this.safeDict(t,"arg"),s=this.safeString2(i,"channel","topic",""),r=this.safeStringLower(i,"instType"),a="contract";"spot"===r&&(a="spot");let o=this.safeString2(i,"instId","symbol"),n=this.safeMarket(o,void 0,void 0,a).symbol,d="orderbook:"+n,h=this.safeList(t,"data"),c=this.safeDict(h,0,{}),l=this.safeInteger(c,"ts");if("books"===s){if(!(n in this.orderbooks)){let e=this.countedOrderBook({});e.symbol=n,this.orderbooks[n]=e}let i=this.orderbooks[n],s=this.safeList2(c,"asks","a",[]),r=this.safeList2(c,"bids","b",[]);this.handleDeltas(i.asks,s),this.handleDeltas(i.bids,r),i.timestamp=l,i.datetime=this.iso8601(l);let a=this.handleOption("watchOrderBook","checksum",!0),o="snapshot"===this.safeString(t,"action"),h=this.safeInteger(c,"checksum");if(!o&&!0===a&&void 0!==h){let t=i.asks,s=i.bids,r=t.length,a=s.length,o=[];for(let e=0;e<25;e++)e<a&&(o.push(s[e][2][0]),o.push(s[e][2][1])),e<r&&(o.push(t[e][2][0]),o.push(t[e][2][1]));let c=o.join(":");if(this.crc32(c,!0)!==h)return void this.spawn(this.handleCheckSumError,e,n,d)}}else{let e=this.orderBook({}),t="bids",i="asks";"a"in c&&!("asks"in c)&&(i="a"),"b"in c&&!("bids"in c)&&(t="b");let s=this.parseOrderBook(c,n,l,t,i);e.reset(s),this.orderbooks[n]=e}e.resolve(this.orderbooks[n],d)}async handleCheckSumError(e,t,i){await this.unWatchOrderBook(t);let s=new a.ChecksumError(this.id+" "+this.orderbookChecksumMessage(t));e.reject(s,i)}handleDelta(e,t){let i=this.parseOrderBookBidAsk(t,0,1);i.push(t),e.storeArray(i)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){if(0===e.length)throw new a.ArgumentsRequired(this.id+" watchTradesForSymbols() requires a non-empty array of symbols");void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e),[o,n]=this.handleOptionBoolAndParams(s,"watchTradesForSymbols","uta",!1),d=n,h=[],c=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.market(t),[s,a]=this.getInstType("watchTradesForSymbols",i,o,d);d=a;let n={instType:s},l="channel";o&&(l="topic");let u="instId";o&&(u="symbol"),n[l]=o?"publicTrade":"trade",n[u]=i.id,h.push(n),c.push("trade:"+t)}let l=d;o&&(l=this.extend(d,{uta:!0}));let u=await this.watchPublicMultiple(o,c,h,l),f=this.safeDict(u,0),p=this.safeString(f,"symbol"),m=i;this.newUpdates&&(m=u.getLimit(p,i));let g=this.filterBySinceLimit(u,t,m,"timestamp",!0);if(!0===this.handleOption("watchTrades","ignoreDuplicates",!0)){let e=this.removeRepeatedTradesFromArray(g);return this.sortBy(e,"timestamp")}return g}async unWatchTrades(e,t={}){let i=this.handleOptionBoolAndParams(t,"watchTrades","uta",!1)[0],s="trade";return i&&(s="publicTrade"),await this.unWatchChannel(e,s,"trade","watchTrades",t)}handleTrades(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeStringLower(i,"instType"),r="contract";"spot"===s&&(r="spot");let a=this.safeString2(i,"instId","symbol"),o=this.safeMarket(a,void 0,void 0,r),d=o.symbol,h=this.safeValue(this.trades,d);if(void 0===h){let e=this.safeInteger(this.options,"tradesLimit",1e3);h=new n.I3(e),this.trades[d]=h}let c=this.safeList(t,"data",[]),l=c.length;for(let e=0;e<l;e++){let t=c[l-e-1],i=this.parseWsTrade(t,o);h.append(i)}let u="trade:"+d;e.resolve(h,u)}parseWsTrade(e,t){let i,s=this.safeString2(e,"symbol","instId"),r=this.safeString(e,"posMode"),a=this.safeString(e,"category"),n=this.safeMarket(void 0===t?s:void 0,t,void 0,void 0!==a?"SPOT"!==a?"contract":"spot":void 0!==r?"contract":"spot"),d=this.safeIntegerN(e,["uTime","cTime","ts","T","execTime"]),h=this.safeList(e,"feeDetail",[]),c=this.safeDict(h,0);if(void 0!==c){let e=this.safeString(c,"feeCoin"),t=this.safeCurrencyCode(e);i={cost:o.Y.stringAbs(this.safeString2(c,"totalFee","fee")),currency:t}}return this.safeTrade({info:e,id:this.safeStringN(e,["tradeId","i","execId"]),order:this.safeString2(e,"orderId","L"),timestamp:d,datetime:this.iso8601(d),symbol:n.symbol,type:this.safeString(e,"orderType"),side:this.safeString2(e,"side","S"),takerOrMaker:this.safeString(e,"tradeScope"),price:this.safeStringN(e,["priceAvg","price","execPrice","P"]),amount:this.safeStringN(e,["size","baseVolume","execQty","v"]),cost:this.safeStringN(e,["amount","quoteVolume","execValue"]),fee:i},n)}async watchPositions(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a="",o="USDT-FUTURES",[n,d]=this.handleOptionBoolAndParams(s,"watchPositions","uta",!1),h=this.marketSymbols(e),c=void 0!==h&&!this.isEmpty(h);c&&(r=this.getMarketFromSymbols(h));let l=d;c&&([o,l]=this.getInstType("watchPositions",r,n,d)),n&&(o="UTA"),a=o+":positions"+a;let u={instType:o},f="channel";n&&(f="topic");let p="positions";n&&(p="position"),u[f]=p;let m=l;n&&(m=this.extend(l,{uta:!0})),n||(u.instId="default");let g=await this.watchPrivate(n,a,"positions",u,m);return this.newUpdates?g:this.filterBySymbolsSinceLimit(g,h,t,i,!0)}handlePositions(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeString(i,"instType","");void 0===this.positions&&(this.positions={});let r=this.safeString(t,"action");s in this.positions&&"snapshot"!==r||(this.positions[s]=new n.Hk);let a=this.positions[s],o=this.safeList(t,"data",[]),d=[];for(let e=0;e<o.length;e++){let t=o[e],i=this.safeString2(t,"instId","symbol"),s=this.safeMarket(i,void 0,void 0,"contract"),r=this.parseWsPosition(t,s);d.push(r),a.append(r)}let h=this.findMessageHashes(e,s+":positions::");for(let t=0;t<h.length;t++){let i=h[t],s=i.split("::")[1].split(","),r=this.filterByArray(d,"symbol",s,!1);this.isEmpty(r)||e.resolve(r,i)}e.resolve(d,s+":positions")}parseWsPosition(e,t){let i,s=this.safeString2(e,"instId","symbol"),r=this.safeString(e,"marginMode"),a=this.getSupportedMapping(r,{crossed:"cross",isolated:"isolated"}),n=this.safeString2(e,"posMode","holdMode"),d=!1;"hedge_mode"===n&&(d=!0);let h=this.safeIntegerN(e,["updatedTime","uTime","cTime","createdTime"]),c=this.safeString2(e,"unrealizedPLR","profitRate"),l=o.Y.stringMul(c,"100");return void 0!==t&&(i=t.contractSize),this.safePosition({info:e,id:this.safeString(e,"posId"),symbol:this.safeSymbol(s,t,void 0,"contract"),notional:void 0,marginMode:a,liquidationPrice:this.safeNumber2(e,"liquidationPrice","liqPrice"),entryPrice:this.safeNumber2(e,"openPriceAvg","avgPrice"),unrealizedPnl:this.safeNumber2(e,"unrealizedPL","unrealisedPnl"),percentage:this.parseNumber(l),contracts:this.safeNumber2(e,"total","size"),contractSize:i,markPrice:this.safeNumber(e,"markPrice"),side:this.safeString2(e,"holdSide","posSide"),hedged:d,timestamp:h,datetime:this.iso8601(h),maintenanceMargin:void 0,maintenanceMarginPercentage:this.safeNumber2(e,"keepMarginRate","mmr"),collateral:this.safeNumber(e,"available"),initialMargin:this.safeNumber(e,"marginSize"),initialMarginPercentage:void 0,leverage:this.safeNumber(e,"leverage"),marginRatio:this.safeNumber(e,"marginRate")})}async watchOrders(e,t,i,s={}){let r,a,o;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.isTriggerOrder(s),h="order";!0===n&&(h="triggerOrder");let c="order:trades";void 0!==e&&(r=this.market(e),o=this.safeString(r,"symbol"),a=this.safeString(r,"id"),h=h+":"+o);let[l,u]=this.handleOptionBoolAndParams(d,"watchOrders","uta",!1),f=this.safeString(u,"productType"),[p,m]=this.handleMarketTypeAndParams("watchOrders",r,u),[g,v]=this.handleSubTypeAndParams("watchOrders",r,m,"linear");("spot"===p||"margin"===p)&&void 0===o&&(a="default"),void 0===f&&"spot"!==p&&void 0===o?h=h+":"+g:"USDT-FUTURES"===f?h+=":linear":"COIN-FUTURES"===f?h+=":inverse":"USDC-FUTURES"===f&&(h+=":usdcfutures");let y="SPOT",b=v;(void 0!==r||"spot"!==p)&&([y,b]=this.getInstType("watchOrders",r,l,v)),"spot"===p&&void 0!==o&&(c=c+":"+o),!0===n&&(c+=":stop");let w="default";("spot"===p||"margin"===p)&&(w=a);let k="orders";!0===n&&(k="orders-algo");let[S,O]=this.handleMarginModeAndParams("watchOrders",b);void 0!==S&&(y="MARGIN",h=h+":"+S,k="isolated"===S?"orders-isolated":"orders-crossed"),l&&(y="UTA",k="order"),c=c+":"+y;let T={instType:y},P="channel";l&&(P="topic"),T[P]=k;let I=O;l&&(I=this.extend(O,{uta:!0})),l||(T.instId=w);let A=await this.watchPrivate(l,h,c,T,I),x=i;return this.newUpdates&&(x=A.getLimit(o,i)),this.filterBySymbolSinceLimit(A,o,t,x,!0)}handleOrder(e,t){let i,s=this.safeDict(t,"arg",{}),r=this.safeString2(s,"channel","topic",""),a=this.safeStringLower(s,"instType"),o=this.safeString(s,"instId");i="spot"===a||"margin"===a?"spot":"contract";let d=this.safeList(t,"data",[]),h=this.safeDict(d,0,{}),c=this.safeStringLower(h,"category",a);if("uta"===a&&(i="spot"===c||"margin"===c?"spot":"contract"),void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new n.Pt(e),this.triggerOrders=new n.Pt(e)}let l="orders-algo"===r||"ordersAlgo"===r,u=l?this.triggerOrders:this.orders,f="order";l&&(f="triggerOrder");let p={};for(let e=0;e<d.length;e++){let t=d[e],s=this.safeString2(t,"instId","symbol",o),r=this.safeMarket(s,void 0,void 0,i),a=this.parseWsOrder(t,r);u.append(a);let n=a.symbol;void 0!==n&&(p[n]=!0)}let m=Object.keys(p);for(let t=0;t<m.length;t++){let i=f+":"+m[t];"orders-crossed"===r?i+=":cross":"orders-isolated"===r&&(i+=":isolated"),e.resolve(u,i)}e.resolve(u,f),"usdt-futures"===c&&e.resolve(u,"order:linear"),"coin-futures"===c&&e.resolve(u,"order:inverse"),"usdc-futures"===c&&e.resolve(u,"order:usdcfutures")}parseWsOrder(e,t){let i,s,r,a,n,d,h=!("posMode"in e),c="loanType"in e,l=this.safeStringLower(e,"category");"spot"===l&&(h=!0),"margin"===l&&(c=!0);let u=this.safeString2(e,"instId","symbol"),f=this.safeMarket(u,t),p=this.safeInteger2(e,"cTime","createdTime"),m=f.symbol,g=this.safeString2(e,"status","orderStatus"),v=this.safeList(e,"feeDetail",[]),y=this.safeDict(v,0),b=this.safeString(y,"fee");if(void 0!==b){let e=this.safeString(y,"feeCoin");i={cost:this.parseNumber(o.Y.stringAbs(b)),currency:this.safeCurrencyCode(e)}}let w=this.safeNumber(e,"triggerPrice"),k=void 0!==w;k?h&&k&&(s=this.safeNumber(e,"executePrice")):s=this.safeNumber(e,"price");let S=this.safeStringLowerN(e,["priceAvg","fillPrice","avgPrice"]),O=void 0===S?void 0:this.omitZero(S),T=this.safeString(e,"side"),P=this.safeString(e,"orderType"),I=this.omitZero(this.safeString2(e,"accBaseVolume","cumExecQty")),A=this.omitZero(this.safeString2(e,"newSize","cumExecValue")),x="market"===P,M="buy"===T,_=this.safeString2(e,"accBaseVolume","cumExecQty");if(h)if(c)r=this.safeString2(e,"baseSize","qty"),_=this.safeString2(e,"baseVolume","cumExecQty"),n=this.safeString2(e,"fillTotalAmount","cumExecValue");else{let t=this.safeString(e,"baseVolume");a=void 0!==t?t:_,x?M?(r=I,n=A):r=A:r=this.safeString2(e,"newSize","qty")}else a=this.safeString2(e,"baseVolume","cumExecQty"),r=this.safeString2(e,"size","qty"),n=this.safeString2(e,"fillNotionalUsd","cumExecValue");return d=o.Y.stringSub(r,_),this.safeOrder({info:e,symbol:m,id:this.safeString(e,"orderId"),clientOrderId:this.safeString(e,"clientOid"),timestamp:p,datetime:this.iso8601(p),lastTradeTimestamp:this.safeInteger2(e,"uTime","updatedTime"),type:P,timeInForce:this.safeStringUpper2(e,"force","timeInForce"),postOnly:void 0,side:T,price:s,triggerPrice:w,amount:r,cost:n,average:O,filled:a,remaining:d,status:this.parseWsOrderStatus(g),fee:i,trades:void 0},f)}parseWsOrderStatus(e){return this.safeString({new:"open",live:"open",partially_filled:"open",filled:"closed",cancelled:"canceled",not_trigger:"open"},e,e)}async watchMyTrades(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o="myTrades";void 0!==e&&(r=this.market(e),o=o+":"+(a=this.safeString(r,"symbol")));let[n,d]=this.handleMarketTypeAndParams("watchMyTrades",r,s),[h,c]=this.handleOptionBoolAndParams(d,"watchMyTrades","uta",!1),l="SPOT",u=c;(void 0!==r||"spot"!==n)&&([l,u]=this.getInstType("watchMyTrades",r,h,c)),h&&(l="UTA");let f="fill:"+l,p={instType:l},m="channel";h&&(m="topic"),p[m]="fill";let g=u;h&&(g=this.extend(u,{uta:!0})),h||(p.instId="default");let v=await this.watchPrivate(h,o,f,p,g),y=i;return this.newUpdates&&(y=v.getLimit(a,i)),this.filterBySymbolSinceLimit(v,a,t,y,!0)}handleMyTrades(e,t){if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new n.I3(e)}let i=this.myTrades,s=this.safeList(t,"data",[]),r=s.length,a=this.safeDict(t,"arg",{}),o=this.safeStringLower(a,"instType");for(let t=0;t<r;t++){let r,a=s[t];if("uta"===o){let e=this.safeStringLower(a,"category"),t="contract";("spot"===e||"margin"===e)&&(t="spot");let i=this.safeString2(a,"instId","symbol");r=this.safeMarket(i,void 0,void 0,t)}let n=this.parseWsTrade(a,r);i.append(n);let d="myTrades:"+n.symbol;e.resolve(i,d)}e.resolve(i,"myTrades")}async watchBalance(e={}){let t,[i,s]=this.handleOptionBoolAndParams(e,"watchBalance","uta",!1),[r,a]=this.handleMarketTypeAndParams("watchBalance",void 0,s),[o,n]=this.handleMarginModeAndParams("watchBalance",a),d="account";"swap"===r||"future"===r?t="USDT-FUTURES":void 0!==o?(t="MARGIN",i||(d="isolated"===o?"account-isolated":"account-crossed")):i||(t="SPOT");let[h,c]=this.handleOptionStringAndParams(n,"watchBalance","instType",t),l=h;i&&(l="UTA");let u={instType:l},f="channel";i&&(f="topic"),u[f]=d;let p=c;i&&(p=this.extend(c,{uta:!0})),i||(u.coin="default");let m="balance:"+(void 0===l?"":l.toLowerCase());return await this.watchPrivate(i,m,m,u,p)}handleBalance(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeStringLower(i,"instType"),r=this.safeList(t,"data",[]);for(let e=0;e<r.length;e++){let t=r[e];if("uta"===s){let e=this.safeList(t,"coin",[]);for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s=this.safeString(i,"coin"),r=this.safeCurrencyCode(s),a=this.account();void 0!==r&&r in this.balance&&(a=this.balance[r]);let n=this.safeString(i,"borrow"),d=this.safeString(i,"debts");(void 0!==n||void 0!==d)&&(a.debt=o.Y.stringAdd(n,d)),a.free=this.safeString(i,"available"),a.used=this.safeString(i,"locked"),a.total=this.safeString(i,"balance"),void 0!==r&&(this.balance[r]=a)}}else{let e=this.safeString2(t,"coin","marginCoin"),i=this.safeCurrencyCode(e),s=this.account();void 0!==i&&i in this.balance&&(s=this.balance[i]);let r=this.safeString(t,"borrow");if(void 0!==r){let e=this.safeString(t,"interest");s.debt=o.Y.stringAdd(r,e)}let a="available";"maxTransferOut"in t&&(a="maxTransferOut"),s.free=this.safeString(t,a),s.total=this.safeString(t,"equity"),s.used=this.safeString(t,"frozen"),void 0!==i&&(this.balance[i]=s)}}this.balance.info=t,this.balance=this.safeBalance(this.balance),e.resolve(this.balance,"balance:"+s)}async watchPublic(e,t,i,s={}){let r=!0===e?this.urls.api.ws.utaPublic:this.urls.api.ws.public;if(!0===this.safeBool2(this.options,"sandboxMode","sandbox",!1)){let t=this.safeString(i,"instType");"SCOIN-FUTURES"!==t&&"SUSDT-FUTURES"!==t&&"SUSDC-FUTURES"!==t&&(r=!0===e?this.urls.api.demo.utaPublic:this.urls.api.demo.public)}let a=this.extend({op:"subscribe",args:[i]},s);return await this.watch(r,t,a,t)}async unWatchPublic(e,t,i,s={}){let r=!0===e?this.urls.api.ws.utaPublic:this.urls.api.ws.public;if(!0===this.safeBool2(this.options,"sandboxMode","sandbox",!1)){let t=this.safeString(i,"instType");"SCOIN-FUTURES"!==t&&"SUSDT-FUTURES"!==t&&"SUSDC-FUTURES"!==t&&(r=!0===e?this.urls.api.demo.utaPublic:this.urls.api.demo.public)}let a=this.extend({op:"unsubscribe",args:[i]},s);return await this.watch(r,t,a,t)}async watchPublicMultiple(e,t,i,s={}){let r=!0===e?this.urls.api.ws.utaPublic:this.urls.api.ws.public;if(!0===this.safeBool2(this.options,"sandboxMode","sandbox",!1)){let t=this.safeDict(i,0,{}),s=this.safeString(t,"instType");"SCOIN-FUTURES"!==s&&"SUSDT-FUTURES"!==s&&"SUSDC-FUTURES"!==s&&(r=!0===e?this.urls.api.demo.utaPublic:this.urls.api.demo.public)}let a=this.extend({op:"subscribe",args:i},s);return await this.watchMultiple(r,t,a,t)}async authenticate(e={}){this.checkRequiredCredentials();let t=this.safeString(e,"url",""),i=this.client(t),r="authenticated",a=i.reusableFuture(r);if(void 0===this.safeValue(i.subscriptions,r)){let i=this.seconds().toString(),a=this.hmac(this.encode(i+"GET/user/verify"),this.encode(this.secret),s.sc,"base64"),o={op:"login",args:[{apiKey:this.apiKey,passphrase:this.password,timestamp:i,sign:a}]},n=this.extend(o,e);this.watch(t,r,n,r)}return await a}async watchPrivate(e,t,i,s,r={}){let a=!0===e?this.urls.api.ws.utaPrivate:this.urls.api.ws.private;if(!0===this.safeBool2(this.options,"sandboxMode","sandbox",!1)){let t=this.safeString(s,"instType");"SCOIN-FUTURES"!==t&&"SUSDT-FUTURES"!==t&&"SUSDC-FUTURES"!==t&&(a=!0===e?this.urls.api.demo.utaPrivate:this.urls.api.demo.private)}await this.authenticate({url:a});let o=this.extend({op:"subscribe",args:[s]},r);return await this.watch(a,t,o,i)}handleAuthenticate(e,t){this.safeValue(e.futures,"authenticated").resolve(!0)}handleErrorMessage(e,t){let i=this.safeString(t,"event");try{if("error"===i){let e=this.safeString(t,"code"),i=this.id+" "+this.json(t);this.throwExactlyMatchedException(this.exceptions.ws.exact,e,i);let s=this.safeString(t,"msg","");throw this.throwBroadlyMatchedException(this.exceptions.ws.broad,s,i),new a.ExchangeError(i)}return!1}catch(t){if(t instanceof a.AuthenticationError){let i="authenticated";e.reject(t,i),i in e.subscriptions&&delete e.subscriptions[i]}else e.reject(t);return!0}}handleMessage(e,t){if("string"==typeof t){"pong"===t&&this.handlePong(e,t);return}if(!0===this.handleErrorMessage(e,t))return;if("pong"===this.safeString(t,"message"))return void this.handlePong(e,t);let i=this.safeString(t,"event");if("login"===i)return void this.handleAuthenticate(e,t);if("subscribe"===i)return void this.handleSubscriptionStatus(e,t);if("unsubscribe"===i)return void this.handleUnSubscriptionStatus(e,t);let s={ticker:this.handleTicker,trade:this.handleTrades,publicTrade:this.handleTrades,fill:this.handleMyTrades,order:this.handleOrder,orders:this.handleOrder,ordersAlgo:this.handleOrder,"orders-algo":this.handleOrder,"orders-crossed":this.handleOrder,"orders-isolated":this.handleOrder,account:this.handleBalance,position:this.handlePositions,positions:this.handlePositions,"account-isolated":this.handleBalance,"account-crossed":this.handleBalance,kline:this.handleOHLCV},r=this.safeDict(t,"arg",{}),a=this.safeString2(r,"channel","topic",""),o=this.safeValue(s,a);void 0!==o&&o.call(this,e,t),a.indexOf("candle")>=0&&this.handleOHLCV(e,t),a.indexOf("books")>=0&&this.handleOrderBook(e,t)}ping(e){return"ping"}handlePong(e,t){return e.lastPong=this.milliseconds(),t}handleSubscriptionStatus(e,t){return t}handleOrderBookUnSubscription(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeStringLower(i,"instType"),r="contract";"spot"===s&&(r="spot");let o=this.safeString2(i,"instId","symbol"),n=this.safeMarket(o,void 0,void 0,r),d=n.symbol,h="unsubscribe:orderbook:"+n.symbol,c="orderbook:"+d;d in this.orderbooks&&delete this.orderbooks[d],c in e.subscriptions&&delete e.subscriptions[c],h in e.subscriptions&&delete e.subscriptions[h];let l=new a.UnsubscribeError(this.id+" orderbook "+d);c in e.futures&&e.reject(l,c),e.resolve(!0,h)}handleTradesUnSubscription(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeStringLower(i,"instType"),r="contract";"spot"===s&&(r="spot");let o=this.safeString2(i,"instId","symbol"),n=this.safeMarket(o,void 0,void 0,r),d=n.symbol,h="unsubscribe:trade:"+n.symbol,c="trade:"+d;d in this.trades&&delete this.trades[d],c in e.subscriptions&&delete e.subscriptions[c],h in e.subscriptions&&delete e.subscriptions[h];let l=new a.UnsubscribeError(this.id+" trades "+d);c in e.futures&&e.reject(l,c),e.resolve(!0,h)}handleTickerUnSubscription(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeStringLower(i,"instType"),r="contract";"spot"===s&&(r="spot");let o=this.safeString2(i,"instId","symbol"),n=this.safeMarket(o,void 0,void 0,r),d=n.symbol,h="unsubscribe:ticker:"+n.symbol,c="ticker:"+d;d in this.tickers&&delete this.tickers[d],c in e.subscriptions&&delete e.subscriptions[c],h in e.subscriptions&&delete e.subscriptions[h];let l=new a.UnsubscribeError(this.id+" ticker "+d);c in e.futures&&e.reject(l,c),e.resolve(!0,h)}handleOHLCVUnSubscription(e,t){let i,s,r,a=this.safeDict(t,"arg",{}),o=this.safeStringLower(a,"instType"),n="contract";"spot"===o&&(n="spot");let d=this.safeString2(a,"instId","symbol"),h=this.safeString2(a,"channel","topic",""),c=this.safeString(a,"interval");void 0===c?(i=!1,c=h.replace("candle","")):i=!0;let l=this.safeDict(this.options,"timeframes"),u=this.findTimeframe(c,l),f=this.safeMarket(d,void 0,void 0,n).symbol;i?(s="unsubscribe:kline:"+f,r="kline:"+f):(s="unsubscribe:candles:"+u+":"+f,r="candles:"+u+":"+f),f in this.ohlcvs&&void 0!==u&&u in this.ohlcvs[f]&&delete this.ohlcvs[f][u],this.cleanUnsubscription(e,r,s)}handleUnSubscriptionStatus(e,t){let i=this.safeList(t,"args");void 0===i&&(i=[this.safeDict(t,"arg",{})]);for(let s=0;s<i.length;s++){let r=this.safeDict(i,s),a=this.safeString2(r,"channel","topic","");a.indexOf("books")>=0?this.handleOrderBookUnSubscription(e,t):a.indexOf("trade")>=0||a.indexOf("publicTrade")>=0?this.handleTradesUnSubscription(e,t):a.indexOf("ticker")>=0?this.handleTickerUnSubscription(e,t):a.indexOf("candle")>=0?this.handleOHLCVUnSubscription(e,t):a.indexOf("kline")>=0&&this.handleOHLCVUnSubscription(e,t)}return t}}i.d(t,{A:()=>d})},479(e,t,i){"use strict";var s=i(4721),r=i(3267),a=i(1697),o=i(1453),n=i(8748);class d extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchOrders:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchOrderBook:!0,watchOHLCV:!1},urls:{api:{ws:{public:"wss://pubwss.bithumb.com/pub/ws",publicV2:"wss://ws-api.bithumb.com/websocket/v1",privateV2:"wss://ws-api.bithumb.com/websocket/v2/private",publicGen2:"wss://ws-api.bithumb.com/websocket/v1",privateGen2:"wss://ws-api.bithumb.com/websocket/v2/private"}}},options:{},streaming:{keepAlive:3e4,maxPingPongMisses:2},exceptions:{}})}async pong(e,t){let i=this.safeInteger(t,"ping");void 0!==i?await e.send({pong:i}):await e.send("PONG")}handlePing(e,t){this.spawn(this.pong,e,t)}handlePong(e,t){e.lastPong=this.milliseconds()}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionIntegerAndParams(t,"watchTicker","generation",2),r=2===i,a=r?this.urls.api.ws.publicGen2:this.urls.api.ws.public,o=this.market(e),n="ticker:"+o.symbol,d=this.safeString(s,"tickTypes","24H"),h=this.omit(s,"tickTypes"),c={type:"ticker",symbols:[o.base+"_"+o.quote],tickTypes:[d]};if(r){let e=this.getGen2MarketId(o);return c=[{ticket:this.uuid()},this.extend({type:"ticker",codes:[e]},h)],await this.watch(a,n,c,n)}return await this.watch(a,n,this.extend(c,h),n)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionIntegerAndParams(t,"watchTickers","generation",2),r=2===i,a=this.marketSymbols(e,void 0,!1,!0,!0),n=void 0===a?0:a.length;if(r&&0===n)throw new o.ArgumentsRequired(this.id+" watchTickers() requires symbols for the generation 2 API");let d=void 0===a?this.symbols:a,h=d.length,c=r?this.urls.api.ws.publicGen2:this.urls.api.ws.public,l=[],u=[];for(let e=0;e<h;e++){let t,i=d[e],s=this.market(i);t=r?this.getGen2MarketId(s):s.base+"_"+s.quote,l.push(t),u.push("ticker:"+s.symbol)}let f=this.safeString(s,"tickTypes","24H"),p=this.omit(s,"tickTypes"),m={type:"ticker",symbols:l,tickTypes:[f]};m=r?[{ticket:this.uuid()},this.extend({type:"ticker",codes:l},p)]:this.extend(m,p);let g=await this.watchMultiple(c,u,m,u);if(this.newUpdates){let e={},t=this.safeString(g,"symbol");return void 0!==t&&(e[t]=g),e}return this.filterByArray(this.tickers,"symbol",d)}handleTicker(e,t){let i,s,r=this.safeDict(t,"content"),a=void 0===r;i=a?t:r;let o=this.safeString2(i,"symbol","code");if(void 0===o||void 0===(s=a?this.safeSymbol(o,void 0,"-"):this.safeSymbol(o,void 0,"_")))return;let n=this.parseWsTicker(i);this.tickers[s]=n,e.resolve(this.tickers[s],"ticker:"+s)}parseWsTicker(e,t){let i=this.safeString(e,"code");if(void 0!==i)return e.market=this.safeString(e,"market",i),this.parseTicker(e,t);let s=this.safeString(e,"date",""),r=this.safeString(e,"time",""),a=s.slice(0,4)+"-"+s.slice(4,6)+"-"+s.slice(6,8)+"T"+r.slice(0,2)+":"+r.slice(2,4)+":"+r.slice(4,6),o=this.parse8601(a);void 0!==o&&(o-=324e5);let n=this.safeString(e,"symbol");return this.safeTicker({symbol:this.safeSymbol(n,t,"_"),timestamp:o,datetime:this.iso8601(o),high:this.safeString(e,"highPrice"),low:this.safeString(e,"lowPrice"),bid:void 0,bidVolume:this.safeString(e,"buyVolume"),ask:void 0,askVolume:this.safeString(e,"sellVolume"),vwap:void 0,open:this.safeString(e,"openPrice"),close:this.safeString(e,"closePrice"),last:void 0,previousClose:this.safeString(e,"prevClosePrice"),change:this.safeString(e,"chgAmt"),percentage:this.safeString(e,"chgRate"),average:void 0,baseVolume:this.safeString(e,"volume"),quoteVolume:this.safeString(e,"value"),info:e},t)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleOptionIntegerAndParams(i,"watchOrderBook","generation",2),a=2===s,o=a?this.urls.api.ws.publicGen2:this.urls.api.ws.public,n=this.market(e),d="orderbook:"+n.symbol,h={type:"orderbookdepth",symbols:[n.base+"_"+n.quote]};if(a){let e=this.getGen2MarketId(n);h=[{ticket:this.uuid()},this.extend({type:"orderbook",codes:[e]},r)]}else h=this.extend(h,r);return(await this.watch(o,d,h,d)).limit()}handleOrderBook(e,t){let i,s=this.safeDict(t,"content");if(void 0!==s){let t=this.safeList(s,"list",[]),i=this.safeDict(t,0,{}),r=this.safeString(i,"symbol");if(void 0===r)return;let a=this.safeSymbol(r,void 0,"_"),o=this.safeString(s,"datetime");if(void 0===o)return;let n=this.parseToInt(o.slice(0,13));if(!(a in this.orderbooks)){let e=this.orderBook();e.symbol=a,this.orderbooks[a]=e}let d=this.orderbooks[a];this.handleBookDeltas(d,t),d.timestamp=n,d.datetime=this.iso8601(n),e.resolve(d,"orderbook:"+a);return}let r=this.safeString(t,"code"),a=this.safeSymbol(r,void 0,"-");if(void 0===a)return;let o=this.safeString(t,"stream_type"),n=this.safeDict(this.options,"watchOrderBook",{}),d=this.safeInteger(n,"limit",1e3);a in this.orderbooks&&"SNAPSHOT"!==o||(this.orderbooks[a]=this.orderBook({},d));let h=this.orderbooks[a];h.reset({}),h.symbol=a;let c=h.bids,l=h.asks,u=this.safeList(t,"orderbook_units",[]);for(let e=0;e<u.length;e++){let t=this.safeDict(u,e),i=this.safeNumber(t,"bid_price"),s=this.safeNumber(t,"bid_size"),r=this.safeNumber(t,"ask_price"),a=this.safeNumber(t,"ask_size");void 0!==i&&void 0!==s&&c.store(i,s),void 0!==r&&void 0!==a&&l.store(r,a)}let f=this.safeString2(t,"timestamp","datetime");void 0!==f&&(i=this.parseToInt(f.slice(0,13))),void 0===i&&(i=this.milliseconds()),h.timestamp=i,h.datetime=this.iso8601(i);let p="orderbook:"+a;e.resolve(h,p)}handleBookDelta(e,t){let i=this.safeString(t,"orderType"),s="asks";"bid"===i&&(s="bids");let r=this.parseOrderBookBidAsk(t,"price","quantity");e[s].storeArray(r)}handleBookDeltas(e,t){for(let i=0;i<t.length;i++)this.handleBookDelta(e,t[i])}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionIntegerAndParams(s,"watchTrades","generation",2),o=2===r,n=o?this.urls.api.ws.publicGen2:this.urls.api.ws.public,d=this.market(e),h=d.symbol,c="trade:"+h,l={type:"transaction",symbols:[d.base+"_"+d.quote]};if(o){let e=this.getGen2MarketId(d);l=[{ticket:this.uuid()},this.extend({type:"trade",codes:[e]},a)]}else l=this.extend(l,a);let u=await this.watch(n,c,l,c),f=i;return this.newUpdates&&(f=u.getLimit(h,i)),this.filterBySinceLimit(u,t,f,"timestamp",!0)}handleTrades(e,t){let i=this.safeDict(t,"content"),s=this.safeList(i,"list");void 0===s&&(s=[t]);for(let t=0;t<s.length;t++){let i,r=s[t],o=this.safeString2(r,"symbol","code");if(void 0===o)continue;i=void 0!==this.safeString(r,"code")?this.safeSymbol(o,void 0,"-"):this.safeSymbol(o,void 0,"_");let n=this.parseWsTrade(r),d=this.safeString(n,"symbol",i);if(!(d in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3),t=new a.I3(e);this.trades[d]=t}let h=this.trades[d];h.append(n);let c="trade:"+d;e.resolve(h,c)}}parseWsTrade(e,t){let i=this.safeString(e,"code");if(void 0!==i){let s=this.safeInteger(e,"trade_timestamp"),r=this.extend(e,{market:i,timestamp:s});return this.parseTrade(r,t)}let s=this.safeString(e,"symbol"),r=this.safeString(e,"contDtm"),a=this.parseToInt(this.parse8601(r))-324e5,o=this.safeString(e,"buySellGb");return this.safeTrade({id:void 0,info:e,timestamp:a,datetime:this.iso8601(a),symbol:this.safeSymbol(s,t,"_"),order:void 0,type:void 0,side:"1"===o?"buy":"sell",takerOrMaker:void 0,price:this.safeString(e,"contPrice"),amount:this.safeString(e,"contQty"),cost:this.safeString(e,"contAmt"),fee:void 0},t)}handleErrorMessage(e,t){let i=this.safeDict(t,"error");if(void 0!==i){let t,s=this.safeString(i,"name","Error"),r=this.safeString(i,"message","");return t=r.length>0?" "+r:"",e.reject(new o.ExchangeError(this.id+" websocket error "+s+t)),!1}if(!("status"in t))return!0;let s=this.safeString(t,"status");try{if("UP"===s||"0000"===s)return!0;if("0000"!==s){let e=this.safeString(t,"resmsg");throw new o.ExchangeError(this.id+" "+e)}return!0}catch(t){return e.reject(t),!1}}async watchBalance(e={}){if(void 0===this.markets&&await this.loadMarkets(),2!==this.handleOptionIntegerAndParams(e,"watchBalance","generation",2)[0])throw new o.BadRequest(this.id+" watchBalance() is only supported for the generation 2 API");await this.authenticate();let t=this.urls.api.ws.privateGen2,i="myAsset",s=this.buildGen2SubscriptionRequest(i,{type:i});return await this.watch(t,i,s,i)}handleBalance(e,t){let i=this.safeList(t,"assets",[]);void 0===this.balance&&(this.balance={});for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),s=this.safeString(t,"currency"),r=this.safeCurrencyCode(s),a=this.account();a.free=this.safeString(t,"balance"),a.used=this.safeString(t,"locked"),void 0!==r&&(this.balance[r]=a)}this.balance.info=t;let s=this.safeInteger(t,"timestamp");this.balance.timestamp=s,this.balance.datetime=this.iso8601(s),this.balance=this.safeBalance(this.balance),e.resolve(this.balance,"myAsset")}buildGen2SubscriptionRequest(e,t){let i=this.safeDict(this.options,"ws",{}),s=this.safeDict(i,"gen2Subscriptions",{});s[e]=t,i.gen2Subscriptions=s,this.options.ws=i;let r=[{ticket:"ccxt"}],a=Object.keys(s);for(let e=0;e<a.length;e++)r.push(s[a[e]]);return r}async authenticate(e={}){this.checkRequiredCredentials();let t=this.safeDict(this.options,"ws",{});if(void 0===this.safeString(t,"token")){let e={access_key:this.apiKey,nonce:this.uuid(),timestamp:this.milliseconds()},i=(0,n.a)(e,this.encode(this.secret),s.sc);t.token=i,t.options={headers:{authorization:"Bearer "+i}},this.options.ws=t}let i=this.urls.api.ws.privateGen2;return this.client(i)}async watchOrders(e,t,i,s={}){let r;if(void 0===this.markets&&await this.loadMarkets(),2!==this.handleOptionIntegerAndParams(s,"watchOrders","generation",2)[0])throw new o.BadRequest(this.id+" watchOrders() is only supported for the generation 2 API");await this.authenticate();let a=this.urls.api.ws.privateGen2,n="myOrder",d=this.safeList(s,"codes",[]),h=this.buildGen2SubscriptionRequest(n,{type:n,codes:d});if(void 0!==e){let t=this.market(e);n=n+":"+(r=this.safeString(t,"symbol"))}let c=await this.watch(a,n,h,n),l=i;return this.newUpdates&&(l=c.getLimit(r,i)),this.filterBySymbolSinceLimit(c,r,t,l,!0)}handleOrders(e,t){let i="myOrder",s=this.parseWsOrder(t),r=this.safeString(s,"symbol");if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}let o=this.orders;o.append(s),e.resolve(o,i),e.resolve(o,i+":"+r)}parseWsOrder(e,t){let i,s,r,a=this.safeString(e,"code"),o=this.safeSymbol(a,t,"-"),n=this.safeInteger(e,"order_timestamp"),d=this.safeString(e,"ask_bid"),h=this.safeStringLower(e,"side");void 0!==d&&(h="BID"===d?"buy":"sell");let c=this.safeString(e,"order_type");"limit"===c?i="limit":"price"===c?i="market":"market"===c&&(i="market");let l=this.safeString(e,"state");"wait"===l||"trade"===l?s="open":"done"===l?s="closed":"cancel"===l&&(s="canceled");let u=this.safeString2(e,"price","order_price"),f=this.safeString2(e,"volume","order_quantity"),p=this.safeString(e,"remaining_volume"),m=this.safeString(e,"executed_volume"),g=this.safeString(e,"executed_funds"),v=this.safeString(e,"paid_fee");if(void 0!==v){let e=this.safeMarket(a,t);r={cost:v,currency:this.safeString(e,"quote")}}return this.safeOrder({info:e,id:this.safeString2(e,"uuid","order_id"),clientOrderId:void 0,timestamp:n,datetime:this.iso8601(n),lastTradeTimestamp:this.safeInteger(e,"trade_timestamp"),symbol:o,type:i,timeInForce:void 0,postOnly:void 0,side:h,price:u,stopPrice:void 0,triggerPrice:void 0,amount:f,cost:g,average:void 0,filled:m,remaining:p,status:s,fee:r,trades:void 0},t)}handleMessage(e,t){if("string"==typeof t){let i=t.toLowerCase();return"pong"===i?void this.handlePong(e,t):"ping"===i?void this.handlePing(e,t):void 0}if("UP"===this.safeString(t,"status")||"pong"in t||"PINGPONG"in t)return void this.handlePong(e,t);if("ping"in t)return void this.handlePing(e,t);if(!0!==this.handleErrorMessage(e,t))return;let i=this.safeString(t,"type");if(void 0!==i){let s={ticker:this.handleTicker,orderbookdepth:this.handleOrderBook,orderbook:this.handleOrderBook,transaction:this.handleTrades,trade:this.handleTrades,myAsset:this.handleBalance,myOrder:this.handleOrders},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}}}i.d(t,{A:()=>d})},5707(e,t,i){"use strict";var s=i(4721),r=i(2847),a=i(1453),o=i(1697);class n extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchMyTrades:!0,watchOHLCV:!1,watchOrderBook:!0,watchOrders:!1,watchTicker:!0,watchTickers:!1,watchTrades:!0,watchTradesForSymbols:!1},urls:{ws:{public:"wss://stream.bitopro.com:443/ws/v1/pub",private:"wss://stream.bitopro.com:443/ws/v1/pub/auth"}},requiredCredentials:{apiKey:!0,secret:!0,login:!0},options:{tradesLimit:1e3,ordersLimit:1e3,ws:{options:{headers:{}}}}})}async watchPublic(e,t,i){let s=this.safeString(this.urls.ws,"public");if(void 0===s)throw new a.ExchangeError(this.id+" watchPublic() has no public websocket url");return await this.watch(s+"/"+e+"/"+i,t,void 0,t)}async watchOrderBook(e,t,i={}){let s;if(void 0!==t&&5!==t&&10!==t&&20!==t&&50!==t&&100!==t&&500!==t&&1e3!==t)throw new a.ExchangeError(this.id+" watchOrderBook limit argument must be undefined, 5, 10, 20, 50, 100, 500 or 1000");void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o=r.symbol;return s=void 0===t?r.id:r.id+":"+this.numberToString(t),(await this.watchPublic("order-books","ORDER_BOOK:"+o,s)).limit()}handleOrderBook(e,t){let i=this.safeString(t,"pair"),s=this.safeMarket(i,void 0,"_").symbol,r=this.safeString(t,"event"),a=this.safeValue(this.orderbooks,s);void 0===a&&(a=this.orderBook({}));let o=this.safeInteger(t,"timestamp"),n=this.parseOrderBook(t,s,o,"bids","asks","price","amount");if(a.reset(n),void 0!==r){let t=r+":"+s;e.resolve(a,t)}}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o=await this.watchPublic("trades","TRADE:"+a,r.id),n=i;return this.newUpdates&&(n=o.getLimit(a,i)),this.filterBySinceLimit(o,t,n,"timestamp",!0)}handleTrade(e,t){let i=this.safeString(t,"pair"),s=this.safeMarket(i,void 0,"_"),r=s.symbol,a=this.safeString(t,"event"),n=this.safeList(t,"data",[]),d=this.parseTrades(n,s),h=this.safeValue(this.trades,r);if(void 0===h){let e=this.safeInteger(this.options,"tradesLimit",1e3);h=new o.I3(e)}for(let e=0;e<d.length;e++)h.append(d[e]);this.trades[r]=h,void 0!==a&&e.resolve(h,a+":"+r)}async watchMyTrades(e,t,i,s={}){this.checkRequiredCredentials(),void 0===this.markets&&await this.loadMarkets();let r="USER_TRADE";void 0!==e&&(r=r+":"+this.market(e).symbol);let o=this.safeString(this.urls.ws,"private");if(void 0===o)throw new a.ExchangeError(this.id+" watchMyTrades() has no private websocket url");let n=o+"/user-trades";this.authenticate(n);let d=await this.watch(n,r,void 0,r),h=i;return this.newUpdates&&(h=d.getLimit(e,i)),this.filterBySinceLimit(d,t,h,"timestamp",!0)}handleMyTrade(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"base"),r=this.safeString(i,"quote"),a=this.safeCurrencyCode(s),n=this.safeCurrencyCode(r);if(void 0===a||void 0===n)return;let d=this.symbol(a+"/"+n),h=this.safeString(t,"event");if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new o.Pt(e)}let c=this.myTrades,l=this.parseWsTrade(i);c.append(l),e.resolve(c,h),void 0!==h&&e.resolve(c,h+":"+d)}parseWsTrade(e,t){let i,s,r,a=this.safeString(e,"matchID"),o=this.safeString(e,"orderID"),n=this.safeTimestamp(e,"transactionTimestamp"),d=this.safeString(e,"base"),h=this.safeString(e,"quote"),c=this.safeCurrencyCode(d),l=this.safeCurrencyCode(h);void 0!==c&&void 0!==l&&(i=this.symbol(c+"/"+l));let u=this.safeMarket(i,t),f=this.safeString(e,"price"),p=this.safeStringLower(e,"orderType"),m=this.safeString(e,"side");void 0!==m&&("ask"===m?m="sell":"bid"===m&&(m="buy"));let g=this.safeString(e,"volume"),v=this.safeString(e,"fee"),y=this.safeCurrencyCode(this.safeString(e,"feeCurrency"));void 0!==v&&(s={cost:v,currency:y,rate:void 0});let b=this.safeBool(e,"isMaker");return void 0!==b&&(r=!0===b?"maker":"taker"),this.safeTrade({id:a,info:e,order:o,timestamp:n,datetime:this.iso8601(n),symbol:i,takerOrMaker:r,type:p,side:m,price:f,amount:g,cost:void 0,fee:s},u)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol;return await this.watchPublic("tickers","TICKER:"+s,i.id)}handleTicker(e,t){let i=this.safeStringLower(t,"pair");if(void 0===i)return;let s=this.safeMarket(i,void 0,"_"),r=s.symbol,a=this.safeString(t,"event"),o=this.parseTicker(t,s);o.symbol=this.safeString(s,"symbol");let n=this.safeInteger(t,"timestamp");o.timestamp=n,o.datetime=this.iso8601(n),this.tickers[r]=o,void 0!==a&&e.resolve(o,a+":"+r)}authenticate(e){if(void 0!==this.clients&&e in this.clients)return;this.checkRequiredCredentials();let t=this.milliseconds(),i=this.json({nonce:t,identity:this.login}),r=this.stringToBase64(i),a=this.hmac(this.encode(r),this.encode(this.secret),s.qt);this.extendExchangeOptions({ws:{options:{headers:{}}}});let o=this.options.ws.options.headers,n={"X-BITOPRO-API":"ccxt","X-BITOPRO-APIKEY":this.apiKey,"X-BITOPRO-PAYLOAD":r,"X-BITOPRO-SIGNATURE":a};this.options.ws.options.headers=n,this.client(e),this.options.ws.options.headers=o}async watchBalance(e={}){this.checkRequiredCredentials(),void 0===this.markets&&await this.loadMarkets();let t="ACCOUNT_BALANCE",i=this.safeString(this.urls.ws,"private");if(void 0===i)throw new a.ExchangeError(this.id+" watchBalance() has no private websocket url");let s=i+"/account-balance";return this.authenticate(s),await this.watch(s,t,void 0,t)}handleBalance(e,t){let i=this.safeString(t,"event"),s=this.safeDict(t,"data",{}),r=this.safeInteger(t,"timestamp"),a=this.safeString(t,"datetime"),o=Object.keys(s),n={info:s,timestamp:r,datetime:a};for(let e=0;e<o.length;e++){let t=this.safeString(o,e),i=this.safeDict(s,t,{}),r=this.safeString(i,"currency"),a=this.safeCurrencyCode(r),d=this.account();d.free=this.safeString(i,"available"),d.total=this.safeString(i,"amount"),void 0!==a&&(n[a]=d)}this.balance=this.safeBalance(n),e.resolve(this.balance,i)}handleMessage(e,t){let i={TRADE:this.handleTrade,TICKER:this.handleTicker,ORDER_BOOK:this.handleOrderBook,ACCOUNT_BALANCE:this.handleBalance,USER_TRADE:this.handleMyTrade},s=this.safeString(t,"event"),r=this.safeValue(i,s);void 0!==r&&r.call(this,e,t)}}i.d(t,{A:()=>n})},7363(e,t,i){"use strict";var s=i(7551),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchTicker:!0,watchTickers:!1,watchTrades:!0,watchMyTrades:!1,watchOrders:!0,watchOrderBook:!0,watchOHLCV:!0},urls:{api:{open:"https://open.bitrue.com",ws:{public:"wss://ws.bitrue.com/market/ws",futurePublic:"wss://fmarket-ws.bitrue.com/kline-api/ws",private:"wss://wsapi.bitrue.com"}}},api:{open:{v1:{private:{post:{"poseidon/api/v1/listenKey":{cost:1}},put:{"poseidon/api/v1/listenKey/{listenKey}":{cost:1}},delete:{"poseidon/api/v1/listenKey/{listenKey}":{cost:1}}}}}},options:{listenKeyRefreshRate:18e5,ws:{gunzip:!0},futuresTimeframes:{"1m":"1min","5m":"5min","15m":"15min","30m":"30min","1h":"60min","2h":"2h","4h":"4h","1d":"1day","1w":"1week"}}})}async watchBalance(e={}){let t=await this.authenticate(),i="balance",s=this.deepExtend({event:"sub",params:{channel:"user_balance_update"}},e);return await this.watch(t,i,s,i)}handleBalance(e,t){let i=this.safeList(t,"B",[]);this.parseWSBalances(i),e.resolve(this.balance,"balance")}parseWSBalances(e){this.balance.info=e;for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),s=this.safeString(i,"a"),r=this.safeCurrencyCode(s),a=this.account(),o=this.safeString(i,"F"),n=this.safeString(i,"L"),d=this.safeInteger(i,"T",0),h=this.safeInteger(i,"t",0),c=0!==d,l=0!==h;(c||l)&&(c&&(a.free=o),l&&(a.used=n),void 0!==r&&(this.balance[r]=a))}this.balance=this.safeBalance(this.balance)}async watchOrders(e,t,i,s={}){let r;if(void 0===this.markets&&await this.loadMarkets(),void 0!==e){let t=this.market(e);r=this.safeString(t,"symbol")}let a=await this.authenticate(),o="orders",n=this.deepExtend({event:"sub",params:{channel:"user_order_update"}},s),d=await this.watch(a,o,n,o),h=i;return this.newUpdates&&(h=d.getLimit(r,i)),this.filterBySymbolSinceLimit(d,r,t,h,!0)}handleOrder(e,t){let i=this.parseWsOrder(t);if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}this.orders.append(i),e.resolve(this.orders,"orders")}parseWsOrder(e,t){let i=this.safeInteger(e,"E"),s=this.safeStringUpper(e,"s"),r=this.safeString(e,"o"),a=this.safeInteger(e,"S"),o="sell";1===a&&(o="buy");let n=this.safeString(e,"X"),d=this.safeString(e,"N");return this.safeOrder({info:e,id:this.safeString(e,"i"),clientOrderId:this.safeString(e,"c"),timestamp:i,datetime:this.iso8601(i),lastTradeTimestamp:this.safeInteger(e,"T"),symbol:this.safeSymbol(s,t),type:this.parseWsOrderType(r),timeInForce:void 0,postOnly:void 0,side:o,price:this.safeString(e,"p"),triggerPrice:void 0,amount:this.safeString(e,"q"),cost:this.safeString(e,"Y"),average:void 0,filled:this.safeString(e,"z"),remaining:void 0,status:this.parseWsOrderStatus(n),fee:{currency:this.safeCurrencyCode(d),cost:this.safeNumber(e,"n")}},t)}async watchOrderBook(e,t,i={}){let s,r,a;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n="orderbook:"+o.symbol;if(!0===o.swap){let e="e_"+this.safeStringLower(o,"baseId")+this.safeStringLower(o,"quoteId");r="market_"+e+"_depth_step0",a=e,s=this.urls.api.ws.futurePublic}else{let e=this.safeStringLower(o,"id");r="market_"+e+"_simple_depth_step0",a=e,s=this.urls.api.ws.public}let d={event:"sub",params:{cb_id:a,channel:r}},h=this.deepExtend(d,i);return await this.watch(s,n,h,n)}handleOrderBook(e,t){let i,s=this.safeString(t,"channel").split("_"),r="e"===this.safeString(s,1);if(r){let e=this.safeStringLower(s,2);i=this.findSwapMarketByWsBaseQuote(e)}else{let e=this.safeStringUpper(s,1);i=this.safeMarket(e)}let a=i.symbol,o=this.safeInteger(t,"ts"),n=this.safeDict(t,"tick",{}),d=n;if(r){let e=this.safeList(n,"asks",[]),t=this.safeList(n,"buys",[]);d={asks:this.parseContractBidsAsks(e,a),buys:this.parseContractBidsAsks(t,a)}}a in this.orderbooks||(this.orderbooks[a]=this.orderBook());let h=this.orderbooks[a],c=this.parseOrderBook(d,a,o,"buys","asks");h.reset(c);let l="orderbook:"+a;e.resolve(h,l)}findSwapMarketByWsBaseQuote(e){let t=this.markets;if(void 0===t)return;let i=Object.keys(t);for(let s=0;s<i.length;s++){let a=t[i[s]];if(!this.safeBool(a,"swap",!1))continue;let o=this.safeStringLower(a,"baseId"),n=this.safeStringLower(a,"quoteId");if(void 0===o||void 0===n)throw new r.ExchangeError(this.id+" findSwapMarketByWsBaseQuote() market "+i[s]+" has no baseId or quoteId");if(o+n===e)return a}}parseContractBidsAsks(e,t){let i=[];for(let s=0;s<e.length;s++){let r=this.safeList(e,s),a=this.safeNumber(r,0),o=this.safeNumber(r,1),n=this.convertFromRawQuantity(t,o);i.push([a,n])}return i}convertFromRawQuantity(e,t){if(void 0===t)return;let i=this.market(e);return!0!==i.contract?t:t*this.safeNumber(i,"contractSize",1)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol;if(!0!==a.swap)throw new r.NotSupported(this.id+" watchTrades is only supported for swap markets");let n="e_"+this.safeStringLower(a,"baseId")+this.safeStringLower(a,"quoteId"),d="trades:"+o,h=this.urls.api.ws.futurePublic,c=this.deepExtend({event:"sub",params:{cb_id:n,channel:"market_"+n+"_trade_ticker"}},s),l=await this.watch(h,d,c,d),u=i;return this.newUpdates&&(u=l.getLimit(o,i)),this.filterBySinceLimit(l,t,u,"timestamp",!0)}handleTrades(e,t){let i=this.safeString(t,"channel").split("_"),s=this.safeStringLower(i,2),r=this.findSwapMarketByWsBaseQuote(s);if(void 0===r)return;let o=r.symbol,n=this.safeDict(t,"tick",{}),d=this.safeList(n,"data",[]),h=!1,c=this.safeValue(this.trades,o);for(let e=0;e<d.length;e++){if(void 0===c){let e=this.safeInteger(this.options,"tradesLimit",1e3);c=new a.I3(e),this.trades[o]=c}let t=this.parseWsTrade(d[e],r);c.append(t),h=!0}h&&e.resolve(c,"trades:"+o)}parseWsTrade(e,t){let i=t.symbol,s=this.safeInteger(e,"ts"),r=this.safeStringLower(e,"side"),a=this.safeString(e,"price"),o=this.safeNumber(e,"vol"),n=this.convertFromRawQuantity(i,o);return this.safeTrade({info:e,id:void 0,timestamp:s,datetime:this.iso8601(s),symbol:i,order:void 0,type:void 0,side:r,takerOrMaker:"taker",price:a,amount:this.numberToString(n),cost:void 0,fee:void 0},t)}async watchOHLCV(e,t="1m",i,s,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=o.symbol;if(!0!==o.swap)throw new r.NotSupported(this.id+" watchOHLCV is only supported for swap markets");let d=this.safeDict(this.options,"futuresTimeframes",{}),h=this.safeString(d,t);if(void 0===h)throw new r.NotSupported(this.id+" watchOHLCV does not support timeframe "+t);let c="e_"+this.safeStringLower(o,"baseId")+this.safeStringLower(o,"quoteId"),l="ohlcv:"+n+":"+t,u=this.urls.api.ws.futurePublic,f=this.deepExtend({event:"sub",params:{cb_id:c,channel:"market_"+c+"_kline_"+h}},a),p=await this.watch(u,l,f,l),m=s;return this.newUpdates&&(m=p.getLimit(n,s)),this.filterBySinceLimit(p,i,m,0,!0)}handleOHLCV(e,t){let i=this.safeString(t,"channel").split("_"),s=this.safeStringLower(i,2),r=this.findSwapMarketByWsBaseQuote(s);if(void 0===r)return;let o=r.symbol,n=this.safeString(i,4),d=this.safeDict(this.options,"futuresTimeframes",{}),h=this.findTimeframe(n,d),c=this.safeDict(t,"tick");if(void 0===c)return;let l=this.parseWsOHLCV(c,r);if(o in this.ohlcvs||(this.ohlcvs[o]={}),!(h in this.ohlcvs[o])){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);this.ohlcvs[o][h]=new a.TG(e)}let u=this.ohlcvs[o][h];u.append(l),e.resolve(u,"ohlcv:"+o+":"+h)}parseWsOHLCV(e,t){let i=t.symbol,s=this.safeInteger(e,"id"),r=this.safeNumber(e,"open"),a=this.safeNumber(e,"high"),o=this.safeNumber(e,"low"),n=this.safeNumber(e,"close"),d=this.safeNumber(e,"vol");return[void 0===s?void 0:1e3*s,r,a,o,n,this.convertFromRawQuantity(i,d)]}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol;if(!0!==i.swap)throw new r.NotSupported(this.id+" watchTicker is only supported for swap markets");let a="e_"+this.safeStringLower(i,"baseId")+this.safeStringLower(i,"quoteId"),o="ticker:"+s,n=this.urls.api.ws.futurePublic,d=this.deepExtend({event:"sub",params:{cb_id:a,channel:"market_"+a+"_ticker"}},t);return await this.watch(n,o,d,o)}handleTicker(e,t){let i=this.safeString(t,"channel").split("_"),s=this.safeStringLower(i,2),r=this.findSwapMarketByWsBaseQuote(s);if(void 0===r)return;let a=r.symbol,o=this.safeDict(t,"tick");if(void 0===o)return;let n=this.safeInteger(t,"ts"),d=this.parseWsTicker(o,r,n);this.tickers[a]=d,e.resolve(d,"ticker:"+a)}parseWsTicker(e,t,i){let s=t.symbol,r=this.safeNumber(e,"vol"),a=this.safeNumber(e,"amount"),o=this.convertFromRawQuantity(s,r),n=this.convertFromRawQuantity(s,a),d=this.safeNumber(e,"close"),h=this.safeNumber(e,"rose");return this.safeTicker({info:e,symbol:s,timestamp:i,datetime:this.iso8601(i),high:this.safeNumber(e,"high"),low:this.safeNumber(e,"low"),bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:this.safeNumber(e,"open"),close:d,last:d,previousClose:void 0,change:void 0,percentage:void 0===h?void 0:100*h,average:void 0,baseVolume:o,quoteVolume:n},t)}parseWsOrderType(e){return this.safeString({1:"limit",2:"market",3:"limit"},e,e)}parseWsOrderStatus(e){return this.safeString({0:"open",1:"open",2:"closed",3:"open",4:"canceled",7:"open"},e,e)}handlePing(e,t){this.spawn(this.pong,e,t)}async pong(e,t){let i=this.safeInteger(t,"ping");await e.send({pong:i})}handleMessage(e,t){if("channel"in t){let i=this.safeString(t,"channel");i.indexOf("_depth_step")>-1?this.handleOrderBook(e,t):i.indexOf("_trade_ticker")>-1?this.handleTrades(e,t):i.indexOf("_kline_")>-1?this.handleOHLCV(e,t):i.indexOf("_ticker")>-1&&this.handleTicker(e,t)}else if("ping"in t)this.handlePing(e,t);else{let i=this.safeString(t,"e"),s={BALANCE:this.handleBalance,ORDER:this.handleOrder},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}}async authenticate(e={}){if(void 0===this.safeString(this.options,"listenKey")){let t="authenticateFlight",i=this.client("authenticationFlights");if(t in i.futures)return await i.future(t),this.safeString(this.options,"listenKeyUrl");let s=i.reusableFuture(t);try{let s=await this.openV1PrivatePostPoseidonApiV1ListenKey(e),a=this.safeDict(s,"data",{}),o=this.safeString(a,"listenKey");if(void 0===o)throw new r.AuthenticationError(this.id+" authenticate() received an empty listenKey");this.options.listenKey=o;let n=this.safeString(this.urls.api.ws,"private");if(void 0===n)throw new r.ExchangeError(this.id+" authenticate() has no private websocket url");this.options.listenKeyUrl=n+"/stream?listenKey="+o,i.resolve(o,t)}catch(e){i.reject(e,t)}await s;let a=this.safeInteger(this.options,"listenKeyRefreshRate",18e5);this.delay(a,this.keepAliveListenKey)}return this.safeString(this.options,"listenKeyUrl")}async keepAliveListenKey(e={}){let t=this.safeString(this.options,"listenKey");try{await this.openV1PrivatePutPoseidonApiV1ListenKeyListenKey(this.extend({listenKey:t},e))}catch(e){this.options.listenKey=void 0,this.options.listenKeyUrl=void 0;return}let i=this.safeInteger(this.options,"listenKeyRefreshRate",18e5);this.delay(i,this.keepAliveListenKey)}}i.d(t,{A:()=>o})},2652(e,t,i){"use strict";var s=i(2056),r=i(1453),a=i(1697),o=i(7749);class n extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!1,watchFundingRate:!0,watchFundingRates:!1,watchMyTrades:!0,watchOrderBook:!0,watchOrders:!0,watchTrades:!0,watchTradesForSymbols:!1,watchOHLCV:!1,watchTicker:!1,watchTickers:!1,unWatchMyTrades:!0,unWatchOrderBook:!0,unWatchOrders:!0,unWatchTrades:!0},urls:{api:{ws:"wss://ws.bitstamp.net"}},options:{expiresIn:"",userId:"",wsSessionToken:"",watchOrderBook:{snapshotDelay:6,snapshotMaxRetries:3},tradesLimit:1e3,OHLCVLimit:1e3},exceptions:{exact:{4009:r.AuthenticationError}}})}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="orderbook:"+s.symbol,a="diff_order_book_"+s.id,o=this.urls.api.ws,n=this.extend({event:"bts:subscribe",data:{channel:a}},i);return(await this.watch(o,r,n,r)).limit()}async unWatchOrderBook(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r="diff_order_book_"+i.id;return await this.unWatchChannel(r,"orderbook:"+s,"orderbook",[s],t)}async unWatchChannel(e,t,i,s,r={}){let a=this.urls.api.ws,o="unsubscribe:"+e;return await this.watch(a,o,this.extend({event:"bts:unsubscribe",data:{channel:e}},r),o,{subHash:t,topic:i,symbols:s})}handleOrderBook(e,t){let i=this.safeString(t,"channel");if(void 0===i)return;let s=i.split("_"),r=this.safeString(s,3),a=this.safeSymbol(r),o=this.safeValue(this.orderbooks,a),n=this.safeInteger(o,"nonce"),d=this.safeDict(t,"data"),h=this.safeInteger(d,"microtimestamp");if(void 0===h)return;let c="orderbook:"+a;if(void 0===n){o.cache.length===this.handleOption("watchOrderBook","snapshotDelay",6)&&this.spawn(this.loadOrderBook,e,c,a,null,{}),o.cache.push(d);return}n>=h||(this.handleBookDelta(o,d),e.resolve(o,c))}handleBookDelta(e,t){let i=this.safeTimestamp(t,"timestamp");e.timestamp=i,e.datetime=this.iso8601(i),e.nonce=this.safeInteger(t,"microtimestamp");let s=this.safeList(t,"bids",[]),r=this.safeList(t,"asks",[]),a=e.bids,o=e.asks;this.handleBidAsks(a,s),this.handleBidAsks(o,r)}handleBidAsks(e,t){for(let i=0;i<t.length;i++){let s=this.parseOrderBookBidAsk(t[i]);e.storeArray(s)}}getCacheIndex(e,t){let i=this.safeDict(t,0),s=this.safeInteger(i,"microtimestamp");if(void 0===s)return -1;let r=this.safeInteger(e,"nonce");if(void 0===r||r<s)return -1;for(let e=0;e<t.length;e++){let i=this.safeDict(t,e);if(this.safeInteger(i,"microtimestamp")===r)return e+1}return t.length}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o="trades:"+a,n=this.urls.api.ws,d="live_trades_"+r.id,h=this.extend({event:"bts:subscribe",data:{channel:d}},s),c=await this.watch(n,o,h,o),l=i;return this.newUpdates&&(l=c.getLimit(a,i)),this.filterBySinceLimit(c,t,l,"timestamp",!0)}async unWatchTrades(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r="live_trades_"+i.id;return await this.unWatchChannel(r,"trades:"+s,"trades",[s],t)}parseWsTrade(e,t){let i=this.safeInteger(e,"microtimestamp",0),s=this.safeString(e,"id"),r=this.parseToInt(i/1e3),a=this.safeString(e,"price"),o=this.safeString(e,"amount"),n=this.safeMarket(void 0,t),d=n.symbol,h=this.safeInteger(e,"type"),c="sell";return 0===h&&(c="buy"),this.safeTrade({info:e,timestamp:r,datetime:this.iso8601(r),symbol:d,id:s,order:void 0,type:void 0,takerOrMaker:void 0,side:c,price:a,amount:o,cost:void 0,fee:void 0},n)}handleTrade(e,t){let i=this.safeString(t,"channel");if(void 0===i)return;let s=i.split("_"),r=this.safeString(s,2),o=this.safeMarket(r),n=o.symbol,d="trades:"+n,h=this.safeDict(t,"data"),c=this.parseWsTrade(h,o),l=this.safeValue(this.trades,n);if(void 0===l){let e=this.safeInteger(this.options,"tradesLimit",1e3);l=new a.I3(e),this.trades[n]=l}l.append(c),e.resolve(l,d)}async watchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="fundingRate:"+i.symbol,r=this.urls.api.ws,a="funding_rate_"+i.id,o=this.extend({event:"bts:subscribe",data:{channel:a}},t);return await this.watch(r,s,o,s)}handleFundingRate(e,t){let i=this.safeString(t,"channel");if(void 0===i)return;let s=i.split("_"),r=this.safeString(s,2),a=this.safeMarket(r),o=a.symbol,n=this.safeDict(t,"data",{}),d=this.parseFundingRate(n,a);this.fundingRates[o]=d,e.resolve(d,"fundingRate:"+o)}async watchOrders(e,t,i,s={}){if(void 0===e)throw new r.ArgumentsRequired(this.id+" watchOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n="private-my_orders",d=n+"_"+a.id,h=await this.subscribePrivate({symbol:o,limit:i,type:n,params:s},d,s),c=i;return this.newUpdates&&(c=h.getLimit(o,i)),this.filterBySinceLimit(h,t,c,"timestamp",!0)}async unWatchOrders(e,t={}){if(void 0===e)throw new r.ArgumentsRequired(this.id+" unWatchOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol;await this.authenticate();let a=this.safeString(this.options,"userId");if(void 0===a)throw new r.AuthenticationError(this.id+" unWatchOrders() requires a userId from authenticate()");let o="private-my_orders_"+i.id+"-"+a;return await this.unWatchChannel(o,o,"orders",[s],t)}async watchMyTrades(e,t,i,s={}){if(void 0===e)throw new r.ArgumentsRequired(this.id+" watchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n="private-my_trades",d=n+"_"+a.id,h=await this.subscribePrivate({symbol:o,limit:i,type:n,params:s},d,s),c=i;return this.newUpdates&&(c=h.getLimit(o,i)),this.filterBySymbolSinceLimit(h,o,t,c,!0)}async unWatchMyTrades(e,t={}){if(void 0===e)throw new r.ArgumentsRequired(this.id+" unWatchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol;await this.authenticate();let a=this.safeString(this.options,"userId");if(void 0===a)throw new r.AuthenticationError(this.id+" unWatchMyTrades() requires a userId from authenticate()");let o="private-my_trades_"+i.id+"-"+a;return await this.unWatchChannel(o,o,"myTrades",[s],t)}handleMyTrades(e,t){let i=this.safeString(t,"channel"),s=this.safeDict(t,"data",{}),r=void 0===i?void 0:this.safeDict(e.subscriptions,i),o=this.safeString(r,"symbol");if(void 0===o)return;let n=this.market(o);if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new a.Pt(e)}let d=this.myTrades,h=this.parseWsMyTrade(s,n);d.append(h),e.resolve(d,i)}parseWsMyTrade(e,t){let i,s=this.safeInteger(e,"microtimestamp",0),r=this.parseToInt(s/1e3),a=this.safeMarket(void 0,t),o=a.symbol,n=this.safeString(e,"fee");return void 0!==n&&(i={cost:n,currency:a.quote}),this.safeTrade({info:e,id:this.safeString2(e,"id_str","id"),order:this.safeString(e,"order_id"),timestamp:r,datetime:this.iso8601(r),symbol:o,type:void 0,side:this.safeString(e,"side"),takerOrMaker:void 0,price:this.safeString(e,"price"),amount:this.safeString(e,"amount"),cost:void 0,fee:i},a)}handleOrders(e,t){let i=this.safeString(t,"channel"),s=this.safeDict(t,"data",{}),r=void 0===i?void 0:this.safeDict(e.subscriptions,i),o=this.safeString(r,"symbol");if(void 0===o)return;let n=this.safeInteger(this.options,"ordersLimit",1e3);void 0===this.orders&&(this.orders=new a.Pt(n));let d=this.orders,h=this.market(o);s.event=this.safeString(t,"event");let c=this.parseWsOrder(s,h);d.append(c),e.resolve(this.orders,i)}parseWsOrder(e,t){let i,s,r,a,n=this.safeString(e,"id_str"),d=this.safeStringLower(e,"order_type"),h="buy";"1"===d&&(h="sell");let c=this.safeStringLower(e,"order_subtype");"0"===c?i="limit":"2"===c?i="market":"4"===c?(i="limit",s="IOC"):"6"===c?(i="limit",s="FOK"):"8"===c&&(i="limit",s="GTD");let l=this.safeString(e,"price_str"),u=this.safeString(e,"amount_str"),f=this.safeString(e,"amount_at_create"),p=u;void 0!==f&&(p=f,r=u);let m=this.safeString(e,"amount_traded"),g=this.safeString(e,"event");o.Y.stringEq(m,p)?a="closed":"order_deleted"===g&&(a="canceled");let v=this.safeString(e,"stop_price"),y=this.safeTimestamp(e,"datetime"),b=this.safeMarket(void 0,t),w=b.symbol;return this.safeOrder({info:e,symbol:w,id:n,clientOrderId:this.safeString(e,"client_order_id"),timestamp:y,datetime:this.iso8601(y),lastTradeTimestamp:void 0,type:i,timeInForce:s,postOnly:void 0,side:h,price:l,stopPrice:v,triggerPrice:v,amount:p,cost:void 0,average:void 0,filled:m,remaining:r,status:a,fee:void 0,trades:void 0},b)}handleOrderBookSubscription(e,t){let i=this.safeString(t,"channel");if(void 0===i)return;let s=i.split("_"),r=this.safeString(s,3),a=this.safeSymbol(r);this.orderbooks[a]=this.orderBook()}handleSubscriptionStatus(e,t){let i=this.safeString(t,"channel");void 0!==i&&i.indexOf("order_book")>-1&&this.handleOrderBookSubscription(e,t)}handleUnsubscriptionStatus(e,t){let i=this.safeString(t,"channel");if(void 0===i)return;let s="unsubscribe:"+i,r=this.safeDict(e.subscriptions,s);if(void 0===r)return;let o=this.safeString(r,"subHash"),n=this.safeString(r,"topic"),d=this.safeList(r,"symbols",[]);if("orders"===n&&void 0!==this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3),t=new a.Pt(e);this.orders=this.pruneCachedBySymbols(t,this.orders,d)}else if("myTrades"===n&&void 0!==this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3),t=new a.Pt(e);this.myTrades=this.pruneCachedBySymbols(t,this.myTrades,d)}else this.cleanCache(r);this.cleanUnsubscription(e,o,s)}pruneCachedBySymbols(e,t,i){let s=this.toArray(t);for(let t=0;t<s.length;t++){let r=s[t],a=this.safeString(r,"symbol");this.inArray(a,i)||e.append(r)}return e}handleSubject(e,t){let i=this.safeString(t,"channel");if(void 0===i)return;let s={live_trades:this.handleTrade,diff_order_book:this.handleOrderBook,funding_rate:this.handleFundingRate,"private-my_orders":this.handleOrders,"private-my_trades":this.handleMyTrades},r=Object.keys(s);for(let a=0;a<r.length;a++){let o=r[a];i.indexOf(o)>-1&&s[o].call(this,e,t)}}handleErrorMessage(e,t){if("bts:error"===this.safeString(t,"event")){let e=this.id+" "+this.json(t),i=this.safeDict(t,"data",{}),s=this.safeNumber(i,"code");this.throwExactlyMatchedException(this.exceptions.exact,s,e)}return!0}handleMessage(e,t){if(!0!==this.handleErrorMessage(e,t))return;let i=this.safeString(t,"event");"bts:subscription_succeeded"===i?this.handleSubscriptionStatus(e,t):"bts:unsubscription_succeeded"===i?this.handleUnsubscriptionStatus(e,t):this.handleSubject(e,t)}async authenticate(e={}){this.checkRequiredCredentials();let t=this.milliseconds(),i=this.safeInteger(this.options,"expiresIn");if(void 0===i||t>i){let i="authenticateFlight",s=this.client("authenticationFlights");if(i in s.futures)return void await s.future(i);let a=s.reusableFuture(i);try{let a=await this.privatePostWebsocketsToken(e),o=this.safeString(a,"token");if(void 0===o)throw new r.AuthenticationError(this.id+" authenticate() received an empty token");let n=this.safeString(a,"user_id"),d=this.safeIntegerProduct(a,"valid_sec",1e3);this.options.expiresIn=this.sum(t,d),this.options.userId=n,this.options.wsSessionToken=o,s.resolve(o,i)}catch(e){s.reject(e,i)}await a}}async subscribePrivate(e,t,i={}){let s=this.urls.api.ws;await this.authenticate();let a=this.safeString(this.options,"userId");if(void 0===a)throw new r.AuthenticationError(this.id+" subscribePrivate() requires a userId from authenticate()");let o=t+"-"+a,n={event:"bts:subscribe",data:{channel:o,auth:this.options.wsSessionToken}};return e.messageHash=o,await this.watch(s,o,this.extend(n,i),o,e)}}i.d(t,{A:()=>n})},85(e,t,i){"use strict";var s=i(7081),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchOrderBook:!0,watchTickers:!1,watchTicker:!0,watchTrades:!0,watchTradesForSymbols:!1,watchBalance:!1,watchOHLCV:!0},urls:{api:{ws:{api:{public:"wss://{hostname}/ws",private:"wss://{hostname}/ws/v2"}}}},options:{tradesLimit:1e3,OHLCVLimit:1e3,api:"api",ws:{gunzip:!0}}})}requestId(){this.lockId();let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,this.unlockId(),e.toString()}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r="market."+i.id+".detail",a=this.safeString(this.options,"api","api"),o={hostname:this.hostname},n=this.implodeParams(this.urls.api.ws[a].public,o),d=this.requestId();return await this.watch(n,r,this.extend({sub:r,id:d},t),r,{id:d,messageHash:r,symbol:s,params:t})}handleTicker(e,t){let i=this.safeDict(t,"tick",{}),s=this.safeString(t,"ch");if(void 0===s)return t;let r=s.split("."),a=this.safeString(r,1),o=this.safeMarket(a),n=this.parseTicker(i,o),d=this.safeInteger(t,"ts");n.timestamp=d,n.datetime=this.iso8601(d);let h=n.symbol;return this.tickers[h]=n,e.resolve(n,s),t}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o="market."+r.id+".trade.detail",n=this.safeString(this.options,"api","api"),d={hostname:this.hostname},h=this.implodeParams(this.urls.api.ws[n].public,d),c=this.requestId(),l=await this.watch(h,o,this.extend({sub:o,id:c},s),o,{id:c,messageHash:o,symbol:a,params:s}),u=i;return this.newUpdates&&(u=l.getLimit(a,i)),this.filterBySinceLimit(l,t,u,"timestamp",!0)}handleTrades(e,t){let i=this.safeDict(t,"tick",{}),s=this.safeList(i,"data",[]),r=this.safeString(t,"ch");if(void 0===r)return t;let o=r.split("."),n=this.safeString(o,1),d=this.safeMarket(n),h=d.symbol,c=this.safeValue(this.trades,h);if(void 0===c){let e=this.safeInteger(this.options,"tradesLimit",1e3);c=new a.I3(e),this.trades[h]=c}for(let e=0;e<s.length;e++){let t=this.parseTrade(s[e],d);c.append(t)}return e.resolve(c,r),t}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n=this.safeString(this.timeframes,t,t),d="market."+a.id+".kline."+n,h=this.safeString(this.options,"api","api"),c={hostname:this.hostname},l=this.implodeParams(this.urls.api.ws[h].public,c),u=this.requestId(),f=await this.watch(l,d,this.extend({sub:d,id:u},r),d,{id:u,messageHash:d,symbol:o,timeframe:t,params:r}),p=s;return this.newUpdates&&(p=f.getLimit(o,s)),this.filterBySinceLimit(f,i,p,0,!0)}handleOHLCV(e,t){let i=this.safeString(t,"ch");if(void 0===i)return;let s=i.split("."),r=this.safeString(s,1),o=this.safeMarket(r),n=o.symbol,d=this.safeString(s,3),h=this.findTimeframe(d);this.ohlcvs[n]=this.safeDict(this.ohlcvs,n,{});let c=this.safeValue(this.ohlcvs[n],h);if(void 0===c){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);c=new a.TG(e),this.ohlcvs[n][h]=c}let l=this.safeDict(t,"tick"),u=this.parseOHLCV(l,o);c.append(u),e.resolve(c,i)}async watchOrderBook(e,t,i={}){if(void 0!==t&&150!==t)throw new r.ExchangeError(this.id+" watchOrderBook accepts limit = 150 only");void 0===this.markets&&await this.loadMarkets();let s=this.market(e),a=s.symbol,o=void 0===t?150:t,n="market."+s.id+".mbp."+o.toString(),d=this.safeString(this.options,"api","api"),h={hostname:this.hostname},c=this.implodeParams(this.urls.api.ws[d].public,h),l=this.requestId(),u={id:l,messageHash:n,symbol:a,limit:o,params:i,method:this.handleOrderBookSubscription};return(await this.watch(c,n,this.extend({sub:n,id:l},i),n,u)).limit()}handleOrderBookSnapshot(e,t,i){let s=this.safeString(i,"symbol"),r=this.safeString(i,"messageHash"),a=this.safeInteger(t,"ts"),o=this.orderbooks[s],n=this.safeDict(t,"data"),d=this.parseOrderBook(n,s);d.nonce=this.safeInteger(n,"seqNum"),d.timestamp=a,d.datetime=this.iso8601(a),o.reset(d);let h=o.cache;for(let t=0;t<h.length;t++)this.handleOrderBookMessage(e,h[t],o);this.orderbooks[s]=o,e.resolve(o,r)}async watchOrderBookSnapshot(e,t,i){let s=this.safeString(i,"messageHash");try{let e=this.safeString(i,"symbol"),t=this.safeInteger(i,"limit"),r=this.safeDict(i,"params"),a=this.safeString(this.options,"api","api"),o={hostname:this.hostname},n=this.implodeParams(this.urls.api.ws[a].public,o),d=this.requestId(),h={id:d,messageHash:s,symbol:e,limit:t,params:r,method:this.handleOrderBookSnapshot};return(await this.watch(n,d,{req:s,id:d},d,h)).limit()}catch(t){delete e.subscriptions[s],e.reject(t,s)}}handleDelta(e,t){let i=this.safeFloat(t,0),s=this.safeFloat(t,1);e.store(i,s)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}handleOrderBookMessage(e,t,i){let s=this.safeDict(t,"tick",{}),r=this.safeInteger(s,"seqNum"),a=this.safeInteger(s,"prevSeqNum");if(void 0===a||void 0===r)return i;if(a<=i.nonce&&r>i.nonce){let e=this.safeList(s,"asks",[]),a=this.safeList(s,"bids",[]);this.handleDeltas(i.asks,e),this.handleDeltas(i.bids,a),i.nonce=r;let o=this.safeInteger(t,"ts");i.timestamp=o,i.datetime=this.iso8601(o)}return i}handleOrderBook(e,t){let i=this.safeString(t,"ch"),s=this.safeValue(t,"ch").split("."),r=this.safeString(s,1),a=this.safeSymbol(r),o=this.orderbooks[a];void 0===o.nonce?o.cache.push(t):(this.handleOrderBookMessage(e,t,o),e.resolve(o,i))}handleOrderBookSubscription(e,t,i){let s=this.safeString(i,"symbol");if(void 0===s)return;let r=this.safeInteger(i,"limit");s in this.orderbooks&&delete this.orderbooks[s],this.orderbooks[s]=this.orderBook({},r),this.spawn(this.watchOrderBookSnapshot,e,t,i)}handleSubscriptionStatus(e,t){let i=this.safeString(t,"id");if(void 0===i)return t;let s=this.indexBy(e.subscriptions,"id"),r=this.safeDict(s,i);if(void 0!==r){let s=this.safeValue(r,"method");if(void 0!==s)return s.call(this,e,t,r);i in e.subscriptions&&delete e.subscriptions[i]}return t}handleSystemStatus(e,t){return t}handleSubject(e,t){let i=this.safeValue(t,"ch").split(".");if("market"===this.safeString(i,0)){let s=this.safeString(i,2),r={mbp:this.handleOrderBook,detail:this.handleTicker,trade:this.handleTrades,kline:this.handleOHLCV},a=this.safeValue(r,s);void 0!==a&&a.call(this,e,t)}}async pong(e,t){await e.send({pong:this.safeInteger(t,"ping")})}handlePing(e,t){this.spawn(this.pong,e,t)}handleErrorMessage(e,t){if("error"===this.safeString(t,"status")){let i=this.safeString(t,"id");if(void 0===i)return!1;let s=this.indexBy(e.subscriptions,"id"),r=this.safeDict(s,i);if(void 0!==r){let s=this.safeString(t,"err-code");try{this.throwExactlyMatchedException(this.exceptions.exact,s,this.json(t))}catch(s){let t=this.safeString(r,"messageHash");e.reject(s,t),e.reject(s,i),i in e.subscriptions&&delete e.subscriptions[i]}}return!1}return!0}handleMessage(e,t){!0===this.handleErrorMessage(e,t)&&(void 0!==this.safeString(t,"id")?this.handleSubscriptionStatus(e,t):void 0!==this.safeString(t,"ch")?this.handleSubject(e,t):void 0!==this.safeString(t,"ping")&&this.handlePing(e,t))}}i.d(t,{A:()=>o})},6385(e,t,i){"use strict";var s=i(4721),r=i(1117),a=i(1453),o=i(1697);class n extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,cancelOrdersWs:!1,fetchTradesWs:!1,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchTrades:!0,watchTradesForSymbols:!0,watchTicker:!0,watchTickers:!0,watchBidsAsks:!0,watchOHLCV:!0,watchOHLCVForSymbols:!0,watchOrders:!0,watchMyTrades:!0,unWatchOrderBook:!0,unWatchOrderBookForSymbols:!0,unWatchTrades:!0,unWatchTradesForSymbols:!0,unWatchOHLCV:!0,unWatchOHLCVForSymbols:!0,cancelAllOrdersWs:!0,cancelOrderWs:!0,createOrderWs:!0,createStopLimitOrderWs:!0,createStopMarketOrderWs:!0,createStopOrderWs:!0,editOrderWs:!0,fetchBalanceWs:!0,fetchCurrenciesWS:!0,fetchDepositAddressWs:!1,fetchDepositsWs:!0,fetchDepositWithdrawFeesWs:!1,fetchMyTradesWs:!0,fetchOHLCVWs:!0,fetchOpenOrdersWs:!0,fetchOrderWs:!0,fetchOrderBookWs:!1,fetchOrdersWs:!0,fetchTickerWs:!1,fetchTickersWs:!1,fetchTimeWs:!1,fetchTradingFeesWs:!0,fetchWithdrawalsWs:!0,withdrawWs:!0},urls:{api:{ws:"wss://ws.bitvavo.com/v2"}},options:{supressMultipleWsRequestsError:!1,tradesLimit:1e3,ordersLimit:1e3,OHLCVLimit:1e3}})}async watchPublic(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(t),r=e+"@"+s.id,a=this.urls.api.ws,o={action:"subscribe",channels:[{name:e,markets:[s.id]}]},n=this.extend(o,i);return await this.watch(a,r,n,r)}async watchPublicMultiple(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(i),a=[e],o=[];for(let e=0;e<r.length;e++){let t=this.market(r[e]);o.push(t.id)}let n=this.urls.api.ws,d=this.extend({action:"subscribe",channels:[{name:t,markets:o}]},s);return await this.watchMultiple(n,a,d,a)}watchTicker(e,t={}){return this.watchPublic("ticker24h",e,t)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s="ticker24h",r=await this.watchPublicMultiple(s,s,i,t);return this.filterByArray(r,"symbol",i)}handleTicker(e,t){this.handleBidAsk(e,t);let i=this.safeString(t,"event"),s=this.safeList(t,"data",[]),r=[];for(let t=0;t<s.length;t++){let a=s[t],o=this.safeString(a,"market"),n=this.safeMarket(o,void 0,"-"),d=this.parseTicker(a,n),h=d.symbol;if(this.tickers[h]=d,r.push(d),void 0!==i){let t=i+"@"+o;e.resolve(d,t)}}e.resolve(r,i)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=await this.watchPublicMultiple("bidask","ticker24h",i,t);return this.filterByArray(s,"symbol",i)}handleBidAsk(e,t){let i="bidask",s=this.safeList(t,"data",[]),r=[];for(let t=0;t<s.length;t++){let a=s[t],o=this.parseWsBidAsk(a),n=o.symbol;this.bidsasks[n]=o,r.push(o);let d=i+":"+n;e.resolve(o,d)}e.resolve(r,i)}parseWsBidAsk(e,t){let i=this.safeString(e,"market"),s=this.safeMarket(i,void 0,"-"),r=this.safeString(s,"symbol"),a=this.safeInteger(e,"timestamp");return this.safeTicker({symbol:r,timestamp:a,datetime:this.iso8601(a),ask:this.safeNumber(e,"ask"),askVolume:this.safeNumber(e,"askSize"),bid:this.safeNumber(e,"bid"),bidVolume:this.safeNumber(e,"bidSize"),info:e},s)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.symbol(e),a=await this.watchPublic("trades",r,s),o=i;return this.newUpdates&&(o=a.getLimit(r,i)),this.filterBySinceLimit(a,t,o,"timestamp",!0)}handleTrade(e,t){let i=this.safeString(t,"market"),s=this.safeMarket(i,void 0,"-"),r=s.symbol,a=this.parseTrade(t,s),n=this.safeValue(this.trades,r);if(void 0===n){let e=this.safeInteger(this.options,"tradesLimit",1e3);n=new o.I3(e)}n.append(a),this.trades[r]=n,e.resolve(n,"trades@"+i)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!1),a="trades",o=[],n=[];for(let e=0;e<r.length;e++){let t=this.market(r[e]);o.push(t.id),n.push(a+"@"+t.id)}let d=this.urls.api.ws,h=this.extend({action:"subscribe",channels:[{name:a,markets:o}]},s),c=await this.watchMultiple(d,n,h,n),l=this.safeDict(c,0),u=this.safeString(l,"symbol"),f=i;return this.newUpdates&&(f=c.getLimit(u,i)),this.filterBySinceLimit(c,t,f,"timestamp",!0)}async unWatchTrades(e,t={}){return await this.unWatchTradesForSymbols([e],t)}async unWatchTradesForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s="trades",r=[],a=[];for(let e=0;e<i.length;e++){let t=this.market(i[e]);r.push(t.id),a.push(s+"@"+t.id)}let o=[{name:s,markets:r}];return await this.unWatchChannels("trades",o,a,{symbols:i},t)}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n=a.id,d=this.safeString(this.timeframes,t,t),h="candles@"+n+"_"+d,c=this.urls.api.ws,l=this.extend({action:"subscribe",channels:[{name:"candles",interval:[d],markets:[n]}]},r),u=await this.watch(c,h,l,h),f=s;return this.newUpdates&&(f=u.getLimit(o,s)),this.filterBySinceLimit(u,i,f,0,!0)}handleFetchOHLCV(e,t){let i=this.safeList(t,"response"),s=this.parseOHLCVs(i,void 0,void 0,void 0),r=this.safeString(t,"requestId");e.resolve(s,r)}handleOHLCV(e,t){let i=this.safeString(t,"market"),s=this.safeMarket(i,void 0,"-"),r=s.symbol,a=this.safeString(t,"interval"),n=this.findTimeframe(a),d="candles@"+i+"_"+a,h=this.safeList(t,"candle",[]);this.ohlcvs[r]=this.safeValue(this.ohlcvs,r,{});let c=this.safeValue(this.ohlcvs[r],n);if(void 0===c){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);c=new o.TG(e),this.ohlcvs[r][n]=c}for(let e=0;e<h.length;e++){let t=h[e],i=this.parseOHLCV(t,s);c.append(i)}e.resolve(c,d),e.resolve([r,n,c],"multi:"+d)}async watchOHLCVForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r="candles",a=[],o={};for(let t=0;t<e.length;t++){let i=e[t],s=this.market(i[0]),n=i[1],d=this.safeString(this.timeframes,n,n);d in o||(o[d]=[]),o[d].push(s.id),a.push("multi:"+r+"@"+s.id+"_"+d)}let n=[],d=Object.keys(o);for(let e=0;e<d.length;e++){let t=d[e];n.push({name:r,interval:[t],markets:o[t]})}let h=this.urls.api.ws,c=this.extend({action:"subscribe",channels:n},s),[l,u,f]=await this.watchMultiple(h,a,c,a),p=i;this.newUpdates&&(p=f.getLimit(l,i));let m=this.filterBySinceLimit(f,t,p,0,!0);return this.createOHLCVObject(l,u,m)}async unWatchOHLCV(e,t="1m",i={}){return await this.unWatchOHLCVForSymbols([[e,t]],i)}async unWatchOHLCVForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i="candles",s=[],r={};for(let t=0;t<e.length;t++){let a=e[t],o=this.market(a[0]),n=a[1],d=this.safeString(this.timeframes,n,n);d in r||(r[d]=[]),r[d].push(o.id),s.push(i+"@"+o.id+"_"+d),s.push("multi:"+i+"@"+o.id+"_"+d)}let a=[],o=Object.keys(r);for(let e=0;e<o.length;e++){let t=o[e];a.push({name:i,interval:[t],markets:r[t]})}return await this.unWatchChannels("ohlcv",a,s,{symbolsAndTimeframes:e},t)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=s.symbol,a="book",o=a+"@"+s.id,n=this.urls.api.ws,d={action:"subscribe",channels:[{name:a,markets:[s.id]}]},h={messageHash:o,name:a,symbol:r,marketId:s.id,method:this.handleOrderBookSubscription,limit:t,params:i},c=this.extend(d,i);return(await this.watch(n,o,c,o,h)).limit()}async watchOrderBookForSymbols(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!1),r="book",a=[],o=[];for(let e=0;e<s.length;e++){let t=this.market(s[e]);a.push(t.id),o.push(r+"@"+t.id)}let n=this.urls.api.ws,d=this.extend({action:"subscribe",channels:[{name:r,markets:a}]},i);return(await this.watchMultiple(n,o,d,o,{name:r,symbols:s,limit:t,params:i})).limit()}async unWatchOrderBook(e,t={}){return await this.unWatchOrderBookForSymbols([e],t)}async unWatchOrderBookForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s="book",r=[],a=[];for(let e=0;e<i.length;e++){let t=this.market(i[e]);r.push(t.id),a.push(s+"@"+t.id)}let o=[{name:s,markets:r}];return await this.unWatchChannels("orderbook",o,a,{symbols:i},t)}handleDelta(e,t){let i=this.safeFloat(t,0),s=this.safeFloat(t,1);e.store(i,s)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}handleOrderBookMessage(e,t,i){let s=this.safeInteger(t,"nonce");return s>i.nonce&&(this.handleDeltas(i.asks,this.safeList(t,"asks",[])),this.handleDeltas(i.bids,this.safeList(t,"bids",[])),i.nonce=s),i}handleOrderBook(e,t){let i=this.safeString(t,"event"),s=this.safeString(t,"market"),r=this.safeMarket(s,void 0,"-"),a=r.symbol,o=i+"@"+r.id,n=this.safeValue(this.orderbooks,a);if(void 0!==n)if(void 0===n.nonce){let i=this.safeValue(e.subscriptions,o,{}),r="watchingOrderBookSnapshot@"+s;if(void 0===this.safeBool(i,r)){i[r]=!0,e.subscriptions[o]=i;let s=this.safeDict(this.options,"watchOrderBookSnapshot",{}),a=this.safeInteger(s,"delay",this.rateLimit);this.delay(a,this.watchOrderBookSnapshot,e,t,i)}n.cache.push(t)}else this.handleOrderBookMessage(e,t,n),e.resolve(n,o)}async watchOrderBookSnapshot(e,t,i){let s=this.safeDict(i,"params"),r=this.safeString2(i,"marketId","market",this.safeString(t,"market"));if(!(this.safeSymbol(r,void 0,"-")in this.orderbooks))return;let a="getBook",o=a+"@"+r,n=this.urls.api.ws;return(await this.watch(n,o,this.extend({action:a,market:r},s),o,i)).limit()}handleOrderBookSnapshot(e,t){let i=this.safeDict(t,"response");if(void 0===i)return;let s=this.safeString(i,"market"),r=this.safeSymbol(s,void 0,"-"),a="book@"+s,o=this.safeValue(this.orderbooks,r);if(void 0===o)return;let n=this.parseOrderBook(i,r);n.nonce=this.safeInteger(i,"nonce"),o.reset(n);let d=o.cache;for(let t=0;t<d.length;t++){let i=d[t];this.handleOrderBookMessage(e,i,o)}this.orderbooks[r]=o,e.resolve(o,a);let h="getBook@"+s;h in e.subscriptions&&delete e.subscriptions[h]}handleOrderBookSubscription(e,t,i){let s=this.safeString(i,"symbol"),r=this.safeInteger(i,"limit");s in this.orderbooks&&delete this.orderbooks[s],this.orderbooks[s]=this.orderBook({},r)}handleOrderBookSubscriptions(e,t,i){for(let s=0;s<i.length;s++){let r=this.safeString(i,s),a=this.safeSymbol(r,void 0,"-"),o="book@"+r;if(!(a in this.orderbooks)){let i=this.safeValue(e.subscriptions,o),s=this.safeValue(i,"method");if(void 0!==s)s.call(this,e,t,i);else if(void 0!==i){let e=this.safeInteger(i,"limit");this.orderbooks[a]=this.orderBook({},e)}}}}async unWatchChannels(e,t,i,s,r={}){let a=this.urls.api.ws,o=[];for(let e=0;e<i.length;e++)o.push("unsubscribe:"+i[e]);let n=this.extend({topic:e,subMessageHashes:i,unsubHashes:o},s),d=this.extend({action:"unsubscribe",channels:t},r);return await this.watchMultiple(a,o,d,o,n)}handleUnsubscriptionStatus(e,t){let i=Object.keys(e.subscriptions);for(let t=0;t<i.length;t++){let s=i[t];if(!(s in e.subscriptions)||!s.startsWith("unsubscribe:"))continue;let r=e.subscriptions[s],a=s.replace("unsubscribe:","");this.cleanCache(r),this.cleanUnsubscription(e,a,s),a in e.rejections&&delete e.rejections[a]}return t}async watchOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" watchOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.market(e),o=r.symbol,n=r.id,d=this.urls.api.ws,h="order:"+o,c=await this.watch(d,h,{action:"subscribe",channels:[{name:"account",markets:[n]}]},h),l=i;return this.newUpdates&&(l=c.getLimit(o,i)),this.filterBySymbolSinceLimit(c,o,t,l,!0)}async watchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" watchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.market(e),o=r.symbol,n=r.id,d=this.urls.api.ws,h="myTrades:"+o,c=await this.watch(d,h,{action:"subscribe",channels:[{name:"account",markets:[n]}]},h),l=i;return this.newUpdates&&(l=c.getLimit(o,i)),this.filterBySymbolSinceLimit(c,o,t,l,!0)}async createOrderWs(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let o=this.createOrderRequest(e,t,i,s,r,a);return await this.watchRequest("privateCreateOrder",o)}async editOrderWs(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let n=this.editOrderRequest(e,t,i,s,r,a,o);return await this.watchRequest("privateUpdateOrder",n)}async cancelOrderWs(e,t,i={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let s=this.cancelOrderRequest(e,t,i);return await this.watchRequest("privateCancelOrder",s)}async cancelAllOrdersWs(e,t={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let i={},[s,r]=this.handleOptionAndParams(t,"cancelAllOrdersWs","operatorId");if(void 0!==s)i.operatorId=this.parseToInt(s);else throw new a.ArgumentsRequired(this.id+" canceAllOrdersWs() requires an operatorId in params or options, eg: exchange.options['operatorId'] = 1234567890");return void 0!==e&&(i.market=this.market(e).id),await this.watchRequest("privateCancelOrders",this.extend(i,r))}handleMultipleOrders(e,t){let i=this.safeList(t,"response"),s=this.parseOrders(i),r=this.safeString(t,"requestId");e.resolve(s,r)}async fetchOrderWs(e,t,i={}){if(void 0===t)throw new a.ArgumentsRequired(this.id+" fetchOrder() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let s={orderId:e,market:this.market(t).id};return await this.watchRequest("privateGetOrder",this.extend(s,i))}async fetchOrdersWs(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOrdersWs() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.fetchOrdersRequest(e,t,i,s),o=await this.watchRequest("privateGetOrders",r);return this.filterBySymbolSinceLimit(o,e,t,i)}requestId(){return parseInt(this.milliseconds().toString()+this.randNumber(4).toString())}async watchRequest(e,t){let i=this.requestId(),s=i.toString();t.action=e,t.requestId=i;let r=this.urls.api.ws;return await this.watch(r,s,t,s)}async fetchOpenOrdersWs(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r={};void 0!==e&&(r.market=this.market(e).id);let a=await this.watchRequest("privateGetOrdersOpen",this.extend(r,s));return this.filterBySymbolSinceLimit(a,e,t,i)}async fetchMyTradesWs(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTradesWs() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.fetchMyTradesRequest(e,t,i,s),o=await this.watchRequest("privateGetTrades",r);return this.filterBySymbolSinceLimit(o,e,t,i)}handleMyTrades(e,t){let i=this.safeList(t,"response"),s=this.parseTrades(i,void 0,void 0,void 0),r=this.safeString(t,"requestId");e.resolve(s,r)}async withdrawWs(e,t,i,s,r={}){let[a,o]=this.handleWithdrawTagAndParams(s,r);this.checkAddress(i),void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let n=this.withdrawRequest(e,t,i,a,o);return await this.watchRequest("privateWithdrawAssets",n)}handleWithdraw(e,t){let i=this.safeString(t,"requestId"),s=this.safeDict(t,"response",{}),r=this.parseTransaction(s);e.resolve(r,i)}async fetchWithdrawalsWs(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.fetchWithdrawalsRequest(e,t,i,s),a=await this.watchRequest("privateGetWithdrawalHistory",r);return this.filterByCurrencySinceLimit(a,e,t,i)}handleWithdraws(e,t){let i=this.safeList(t,"response"),s=this.safeString(t,"requestId"),r=this.parseTransactions(i,void 0,void 0,void 0,{type:"withdrawal"});e.resolve(r,s)}async fetchOHLCVWs(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.fetchOHLCVRequest(e,t,i,s,r),o=await this.watchRequest("getCandles",a);return this.filterBySinceLimit(o,i,s,0,!0)}async fetchDepositsWs(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.fetchDepositsRequest(e,t,i,s),a=await this.watchRequest("privateGetDepositHistory",r);return this.filterByCurrencySinceLimit(a,e,t,i)}handleDeposits(e,t){let i=this.safeList(t,"response",[]),s=this.parseTransactions(i,void 0,void 0,void 0,{type:"deposit"}),r=this.safeString(t,"requestId");e.resolve(s,r)}async fetchTradingFeesWs(e={}){return void 0===this.markets&&await this.loadMarkets(),await this.authenticate(),await this.watchRequest("privateGetAccount",e)}fetchMarketsWs(e={}){return this.watchRequest("getMarkets",e)}async fetchCurrenciesWs(e={}){return void 0===this.markets&&await this.loadMarkets(),await this.watchRequest("getAssets",e)}handleFetchCurrencies(e,t){let i=this.safeString(t,"requestId"),s=this.safeList(t,"response"),r=this.parseCurrencies(s);e.resolve(r,i)}handleTradingFees(e,t){let i=this.safeString(t,"requestId"),s=this.safeDict(t,"response"),r=this.parseTradingFees(s);e.resolve(r,i)}async fetchBalanceWs(e={}){return void 0===this.markets&&await this.loadMarkets(),await this.authenticate(),await this.watchRequest("privateGetBalance",e)}handleFetchBalance(e,t){let i=this.safeString(t,"requestId"),s=this.safeList(t,"response",[]),r=this.parseBalance(s);e.resolve(r,i)}handleSingleOrder(e,t){let i=this.safeDict(t,"response",{}),s=this.parseOrder(i),r=this.safeString(t,"requestId");e.resolve(s,r)}handleMarkets(e,t){let i=this.safeList(t,"response",[]),s=this.parseMarkets(i),r=this.safeString(t,"requestId");e.resolve(s,r)}buildMessageHash(e,t={}){let i={privateCreateOrder:this.actionAndMarketMessageHash,privateUpdateOrder:this.actionAndOrderIdMessageHash,privateCancelOrder:this.actionAndOrderIdMessageHash,privateGetOrder:this.actionAndOrderIdMessageHash,privateGetTrades:this.actionAndMarketMessageHash},s=this.safeValue(i,e),r=e;return void 0!==s&&(r=s.call(this,e,t)),r}actionAndMarketMessageHash(e,t={}){return e+this.safeString(t,"market","")}actionAndOrderIdMessageHash(e,t={}){let i=this.safeString(t,"orderId");if(void 0===i)throw new a.ExchangeError(this.id+" privateUpdateOrderMessageHash requires a orderId parameter");return e+i}handleOrder(e,t){let i=this.safeString(t,"market"),s=this.safeMarket(i,void 0,"-"),r=s.symbol,a=this.parseOrder(t,s);if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}this.orders.append(a),e.resolve(this.orders,"order:"+r)}handleMyTrade(e,t){let i=this.safeString(t,"market"),s=this.safeMarket(i,void 0,"-"),r=s.symbol,a=this.parseTrade(t,s);if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new o.I3(e)}let n=this.myTrades;n.append(a),e.resolve(n,"myTrades:"+r)}handleSubscriptionStatus(e,t){let i=this.safeDict(t,"subscriptions",{}),s={book:this.handleOrderBookSubscriptions},r=Object.keys(i);for(let a=0;a<r.length;a++){let o=r[a],n=this.safeValue(s,o);if(void 0!==n){let s=this.safeValue(i,o);n.call(this,e,t,s)}}return t}async authenticate(e={}){let t=this.urls.api.ws,i=this.client(t),r="authenticated",a=this.safeValue(i.subscriptions,r);if(void 0===a){let o=this.milliseconds(),n=o.toString()+"GET/"+this.version+"/websocket",d=this.hmac(this.encode(n),this.encode(this.secret),s.sc),h={action:"authenticate",key:this.apiKey,signature:d,timestamp:o},c=this.extend(h,e);a=await this.watch(t,r,c,r),i.subscriptions[r]=a}return a}handleAuthenticationMessage(e,t){let i="authenticated";if(!0===this.safeBool(t,"authenticated",!1))e.resolve(t,i);else{let s=new a.AuthenticationError(this.json(t));e.reject(s,i),i in e.subscriptions&&delete e.subscriptions[i]}}handleErrorMessage(e,t){let i=this.safeString(t,"error");if(void 0===i)return;let s=this.safeInteger(i,"errorCode"),r=this.safeString(t,"action"),o=this.buildMessageHash(r,t),n=this.safeString(t,"requestId",o),d=!1;try{this.handleErrors(s,i,e.url,"",{},i,t,{},{})}catch(t){d=!0,e.reject(t,n)}if(!d){let i=new a.ExchangeError(this.id+" "+this.json(t));return e.reject(i,n),!0}}handleMessage(e,t){void 0!==this.safeString(t,"error")&&this.handleErrorMessage(e,t);let i={subscribed:this.handleSubscriptionStatus,unsubscribed:this.handleUnsubscriptionStatus,book:this.handleOrderBook,getBook:this.handleOrderBookSnapshot,trade:this.handleTrade,candle:this.handleOHLCV,ticker24h:this.handleTicker,authenticate:this.handleAuthenticationMessage,order:this.handleOrder,fill:this.handleMyTrade,privateCreateOrder:this.handleSingleOrder,privateUpdateOrder:this.handleSingleOrder,privateGetBalance:this.handleFetchBalance,privateCancelOrders:this.handleMultipleOrders,privateGetOrders:this.handleMultipleOrders,privateGetOrder:this.handleSingleOrder,privateCancelOrder:this.handleSingleOrder,privateGetOrdersOpen:this.handleMultipleOrders,privateGetAccount:this.handleTradingFees,privateGetDepositHistory:this.handleDeposits,privateGetWithdrawalHistory:this.handleWithdraws,privateWithdrawAssets:this.handleWithdraw,privateGetTrades:this.handleMyTrades,getAssets:this.handleFetchCurrencies,getCandles:this.handleFetchOHLCV,getMarkets:this.handleMarkets},s=this.safeString(t,"event"),r=this.safeValue(i,s);if(void 0===r){let s=this.safeString(t,"action");void 0!==(r=this.safeValue(i,s))&&r.call(this,e,t)}else r.call(this,e,t)}}i.d(t,{A:()=>n})},9343(e,t,i){"use strict";var s=i(3427),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchTicker:!0,watchTickers:!1,watchTrades:!0,watchTradesForSymbols:!1,watchMyTrades:!1,watchOrders:!0,watchOrderBook:!0,watchOHLCV:!0},urls:{api:{ws:"wss://ws.blockchain.info/mercury-gateway/v1/ws"}},options:{ws:{options:{headers:{Origin:"https://exchange.blockchain.com"}},noOriginHeader:!1}},streaming:{},exceptions:{},timeframes:{"1m":"60","5m":"300","15m":"900","1h":"3600","6h":"21600","1d":"86400"}})}async watchBalance(e={}){await this.authenticate(e);let t="balance",i=this.urls.api.ws,s=this.deepExtend({action:"subscribe",channel:"balances"},e);return await this.watch(i,t,s,t,s)}handleBalance(e,t){if("subscribed"===this.safeString(t,"event"))return;let i={info:t},s=this.safeList(t,"balances",[]);for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),r=this.safeString(t,"currency"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(t,"available"),o.total=this.safeString(t,"balance"),void 0!==a&&(i[a]=o)}this.balance=this.safeBalance(i),e.resolve(this.balance,"balance")}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n=this.safeString(this.timeframes,t,t),d="ohlcv:"+o,h={action:"subscribe",channel:"prices",symbol:a.id,granularity:this.parseNumber(n)};h=this.deepExtend(h,r);let c=this.urls.api.ws,l=await this.watch(c,d,h,d,h),u=s;return this.newUpdates&&(u=l.getLimit(o,s)),this.filterBySinceLimit(l,i,u,0,!0)}handleOHLCV(e,t){let i=this.safeString(t,"event");if("rejected"===i){let e=this.json(t);throw new r.ExchangeError(this.id+" "+e)}if("updated"===i){let i=this.safeString(t,"symbol"),s=this.safeSymbol(i,void 0,"-"),r="ohlcv:"+s,o=this.safeDict(e.subscriptions,r),n=this.safeString(o,"granularity"),d=this.findTimeframe(n),h=this.safeList(t,"price",[]);this.ohlcvs[s]=this.safeDict(this.ohlcvs,s,{});let c=this.safeValue(this.ohlcvs[s],d);if(void 0===c){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);c=new a.TG(e),this.ohlcvs[s][d]=c}c.append(h),e.resolve(c,r)}else if("subscribed"!==i)throw new r.NotSupported(this.id+" "+this.json(t))}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r=this.urls.api.ws,a="ticker:"+s,o={action:"subscribe",channel:"ticker",symbol:i.id};return o=this.deepExtend(o,t),await this.watch(r,a,o,a)}handleTicker(e,t){let i,s=this.safeString(t,"event"),r=this.safeString(t,"symbol"),a=this.safeMarket(r),o=a.symbol;if("subscribed"===s)return;if("snapshot"===s)i=this.parseTicker(t,a);else if("updated"===s){let e=this.safeDict(this.tickers,o);i=this.parseWsUpdatedTicker(t,e,a)}let n="ticker:"+o;this.tickers[o]=i,e.resolve(i,n)}parseWsUpdatedTicker(e,t,i){let s=this.safeString(e,"symbol"),r=this.safeSymbol(s,void 0,"-"),a=this.safeString(e,"mark_price");return this.safeTicker({symbol:r,timestamp:void 0,datetime:void 0,high:void 0,low:void 0,bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:this.safeString(t,"open"),close:void 0,last:a,previousClose:this.safeString(t,"close"),change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(t,"baseVolume"),quoteVolume:void 0,info:this.extend(this.safeDict(t,"info",{}),e)},i)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o=this.urls.api.ws,n="trades:"+a,d={action:"subscribe",channel:"trades",symbol:r.id};d=this.deepExtend(d,s);let h=await this.watch(o,n,d,n,d);return this.filterBySinceLimit(h,t,i,"timestamp",!0)}handleTrades(e,t){if("updated"!==this.safeString(t,"event"))return;let i=this.safeString(t,"symbol"),s=this.safeSymbol(i),r=this.safeMarket(i),o=this.safeValue(this.trades,s);if(void 0===o){let e=this.safeInteger(this.options,"tradesLimit",1e3);o=new a.I3(e),this.trades[s]=o}let n=this.parseWsTrade(t,r);o.append(n),this.trades[s]=o,e.resolve(this.trades[s],"trades:"+s)}parseWsTrade(e,t){let i=this.safeString(e,"symbol"),s=this.safeString(e,"timestamp");return this.safeTrade({id:this.safeString(e,"trade_id"),timestamp:this.parse8601(s),datetime:s,symbol:this.safeSymbol(i,t,"-"),order:void 0,type:void 0,side:this.safeString(e,"side"),takerOrMaker:void 0,price:this.safeString(e,"price"),amount:this.safeString(e,"qty"),cost:void 0,fee:void 0,info:e},t)}async watchOrders(e,t,i,s={}){let r;if(void 0===this.markets&&await this.loadMarkets(),await this.authenticate(),void 0!==e){let t=this.market(e);r=this.safeString(t,"symbol")}let a=this.urls.api.ws,o="orders",n=this.deepExtend({action:"subscribe",channel:"trading"},s),d=await this.watch(a,o,n,o),h=i;return this.newUpdates&&(h=d.getLimit(r,i)),this.filterBySymbolSinceLimit(d,r,t,h,!0)}handleOrders(e,t){let i=this.safeString(t,"event"),s=this.orders;if(void 0===s){let e=this.safeInteger(this.options,"ordersLimit",1e3);s=new a.Pt(e),this.orders=s}if("subscribed"!==i){if("rejected"===i)throw new r.ExchangeError(this.id+" "+this.json(t));if("snapshot"===i){let e=this.safeList(t,"orders",[]);for(let t=0;t<e.length;t++){let i=e[t],r=this.parseWsOrder(i);s.append(r)}}else if("updated"===i){let e=this.parseWsOrder(t);s.append(e)}this.orders=s,e.resolve(this.orders,"orders")}}parseWsOrder(e,t){let i=this.safeString(e,"transactTime"),s=this.safeString(e,"ordStatus"),r=this.safeString(e,"symbol"),a=this.safeMarket(r,t),o=this.safeString(e,"tradeId"),n=[];return"0"!==o&&n.push({id:o}),this.safeOrder({id:this.safeString(e,"orderID"),clientOrderId:this.safeString(e,"clOrdID"),datetime:i,timestamp:this.parse8601(i),status:this.parseWsOrderStatus(s),symbol:this.safeSymbol(r,a),type:this.safeString(e,"ordType"),timeInForce:this.safeString(e,"timeInForce"),postOnly:"ALO"===this.safeString(e,"execInst"),side:this.safeString(e,"side"),price:this.safeString(e,"price"),stopPrice:this.safeString(e,"stopPx"),cost:void 0,amount:this.safeString(e,"orderQty"),filled:this.safeString(e,"cumQty"),remaining:this.safeString(e,"leavesQty"),trades:n,fee:{rate:void 0,cost:this.safeNumber(e,"fee"),currency:this.safeString(a,"quote")},info:e,lastTradeTimestamp:void 0,average:this.safeString(e,"avgPx")},a)}parseWsOrderStatus(e){return this.safeString({pending:"open",open:"open",rejected:"rejected",cancelled:"canceled",filled:"closed",partial:"open",expired:"expired"},e,e)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=this.urls.api.ws,a=this.safeString(i,"type","l2"),o=this.omit(i,"type"),n="orderbook:"+e+":"+a,d={action:"subscribe",channel:a,symbol:s.id},h=this.deepExtend(d,o);return(await this.watch(r,n,h,n)).limit()}handleOrderBook(e,t){let i=this.safeString(t,"event");if("subscribed"===i)return;let s=this.safeString(t,"channel"),a=this.safeString(t,"symbol"),o=this.safeSymbol(a),n="orderbook:"+o+":"+s,d=this.safeString(t,"timestamp"),h=this.parse8601(d);void 0===this.safeValue(this.orderbooks,o)&&(this.orderbooks[o]=this.countedOrderBook());let c=this.orderbooks[o];if("snapshot"===i){let e=this.parseOrderBook(t,o,h,"bids","asks","px","qty","num");c.reset(e)}else if("updated"===i){let e=this.safeList(t,"asks",[]),i=this.safeList(t,"bids",[]);this.handleDeltas(c.asks,e),this.handleDeltas(c.bids,i),c.timestamp=h,c.datetime=d}else throw new r.NotSupported(this.id+" watchOrderBook() does not support "+i+" yet");e.resolve(c,n)}handleDelta(e,t){let i=this.parseOrderBookBidAsk(t,"px","qty","num");e.storeArray(i)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}handleMessage(e,t){let i=this.safeString(t,"channel"),s={ticker:this.handleTicker,trades:this.handleTrades,prices:this.handleOHLCV,l2:this.handleOrderBook,l3:this.handleOrderBook,auth:this.handleAuthenticationMessage,balances:this.handleBalance,trading:this.handleOrders},a=this.safeValue(s,i);if(void 0!==a)return void a.call(this,e,t);throw new r.NotSupported(this.id+" received an unsupported message: "+this.json(t))}handleAuthenticationMessage(e,t){if("subscribed"!==this.safeString(t,"event"))throw new r.AuthenticationError(this.id+" received an authentication error: "+this.json(t));let i=this.safeValue(e.futures,"authenticated");void 0!==i&&i.resolve(!0)}async authenticate(e={}){let t=this.urls.api.ws,i=this.client(t),s="authenticated",r=i.reusableFuture(s);if(void 0===this.safeValue(i.subscriptions,s)){this.checkRequiredCredentials();let i={action:"subscribe",channel:"auth",token:this.secret};return this.watch(t,s,this.extend(i,e),s)}return await r}}i.d(t,{A:()=>o})},270(e,t,i){"use strict";var s=i(4721),r=i(2114),a=i(1453),o=i(1697);class n extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchFundingRate:!0,watchFundingRates:!1,watchTrades:!0,watchTradesForSymbols:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchTicker:!0,watchTickers:!0,watchBidsAsks:!0,watchOHLCV:!0,watchOHLCVForSymbols:!0,watchOrders:!0,watchOrdersForSymbols:!0,watchPositions:!0},urls:{api:{ws:{swap:{public:"wss://openapi.blofin.com/ws/public",private:"wss://openapi.blofin.com/ws/private"}}},test:{ws:{swap:{public:"wss://demo-trading-openapi.blofin.com/ws/public",private:"wss://demo-trading-openapi.blofin.com/ws/private"}}}},options:{defaultType:"swap",tradesLimit:1e3,watchOrderBook:{channel:"books"},watchOrderBookForSymbols:{channel:"books"}},streaming:{ping:this.ping,keepAlive:25e3}})}ping(e){return"ping"}handlePong(e,t){e.lastPong=this.milliseconds()}async watchTrades(e,t,i,s={}){return s.callerMethodName="watchTrades",await this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.watchMultipleWrapper(!0,"trades","watchTradesForSymbols",e,s),a=this.safeDict(r,0),o=this.safeString(a,"symbol"),n=i;this.newUpdates&&(n=r.getLimit(o,i));let d=this.filterBySinceLimit(r,t,n,"timestamp",!0);return this.sortBy(d,"timestamp")}handleTrades(e,t){let i=this.safeDict(t,"arg"),s=this.safeString(i,"channel"),r=this.safeList(t,"data");if(void 0!==r)for(let t=0;t<r.length;t++){let i=r[t],a=this.parseWsTrade(i),n=a.symbol,d=this.safeValue(this.trades,n);if(void 0===d){let e=this.safeInteger(this.options,"tradesLimit",1e3);d=new o.I3(e),this.trades[n]=d}if(d.append(a),void 0!==s){let t=s+":"+n;e.resolve(d,t)}}}parseWsTrade(e,t){return this.parseTrade(e,t)}async watchOrderBook(e,t,i={}){return i.callerMethodName="watchOrderBook",await this.watchOrderBookForSymbols([e],t,i)}async watchOrderBookForSymbols(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleParamString(i,"callerMethodName","watchOrderBookForSymbols"),[o,n]=this.handleOptionStringAndParams(r,s,"channel","books");if("books"!==o)throw new a.NotSupported(this.id+" "+s+"() at this moment "+o+" is not supported, coming soon");return(await this.watchMultipleWrapper(!0,o,s,e,n)).limit()}handleOrderBook(e,t){let i=this.safeDict(t,"arg"),s=this.safeString(i,"channel"),r=this.safeDict(t,"data"),a=this.safeString(i,"instId"),o=this.safeMarket(a).symbol;o in this.orderbooks||(this.orderbooks[o]=this.orderBook());let n=this.orderbooks[o],d=this.safeInteger(r,"ts");if("snapshot"===this.safeString(t,"action")){let e=this.parseOrderBook(r,o,d);e.nonce=this.safeInteger(r,"seqId"),n.reset(e)}else{let e=this.safeList(r,"asks",[]),t=this.safeList(r,"bids",[]);this.handleDeltasWithKeys(n.asks,e),this.handleDeltasWithKeys(n.bids,t),n.timestamp=d,n.datetime=this.iso8601(d)}if(this.orderbooks[o]=n,void 0!==s){let t=s+":"+o;e.resolve(n,t)}}async watchTicker(e,t={}){t.callerMethodName="watchTicker";let i=this.market(e).symbol;return(await this.watchTickers([i],t))[i]}async watchTickers(e,t={}){if(void 0===e)throw new a.NotSupported(this.id+" watchTickers() requires a list of symbols");let i=await this.watchMultipleWrapper(!0,"tickers","watchTickers",e,t);if(this.newUpdates){let e={},t=this.safeString(i,"symbol");return void 0!==t&&(e[t]=i),e}return this.filterByArray(this.tickers,"symbol",e)}handleTicker(e,t){this.handleBidAsk(e,t);let i=this.safeDict(t,"arg"),s=this.safeString(i,"channel"),r=this.safeList(t,"data");for(let t=0;t<r.length;t++){let i=this.parseWsTicker(r[t]),a=i.symbol;if(this.tickers[a]=i,void 0!==s){let t=s+":"+a;e.resolve(this.tickers[a],t)}}}parseWsTicker(e,t){return this.parseTicker(e,t)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=this.market(i[0]),[r,a]=this.handleMarketTypeAndParams("watchBidsAsks",s,t),o=this.urls.api.ws[r].public,n=[],d=[];for(let e=0;e<i.length;e++){let t=this.market(i[e]);n.push("bidask:"+t.symbol),d.push({channel:"tickers",instId:t.id})}let h=this.getSubscriptionRequest(d),c=await this.watchMultiple(o,n,this.deepExtend(h,a),n);if(this.newUpdates){let e={},t=this.safeString(c,"symbol");return void 0!==t&&(e[t]=c),e}return this.filterByArray(this.bidsasks,"symbol",i)}handleBidAsk(e,t){let i=this.safeList(t,"data");for(let t=0;t<i.length;t++){let s=this.parseWsBidAsk(i[t]),r=s.symbol,a="bidask:"+r;this.bidsasks[r]=s,e.resolve(s,a)}}parseWsBidAsk(e,t){let i=this.safeString(e,"instId"),s=this.safeMarket(i,t,"-"),r=this.safeString(s,"symbol"),a=this.safeInteger(e,"ts");return this.safeTicker({symbol:r,timestamp:a,datetime:this.iso8601(a),ask:this.safeString(e,"askPrice"),askVolume:this.safeString(e,"askSize"),bid:this.safeString(e,"bidPrice"),bidVolume:this.safeString(e,"bidSize"),info:e},s)}async watchOHLCV(e,t="1m",i,s,r={}){return r.callerMethodName="watchOHLCV",(await this.watchOHLCVForSymbols([[e,t]],i,s,r))[e][t]}async watchOHLCVForSymbols(e,t,i,s={}){if(0===e.length||!Array.isArray(e[0]))throw new a.ArgumentsRequired(this.id+" watchOHLCVForSymbols() requires a an array of symbols and timeframes, like  [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]");void 0===this.markets&&await this.loadMarkets();let[r,o,n]=await this.watchMultipleWrapper(!0,"candle","watchOHLCVForSymbols",e,s),d=i;this.newUpdates&&(d=n.getLimit(r,i));let h=this.filterBySinceLimit(n,t,d,0,!0);return this.createOHLCVObject(r,o,h)}handleOHLCV(e,t){let i=this.safeDict(t,"arg"),s=this.safeString(i,"channel"),r=this.safeList(t,"data"),a=this.safeString(i,"instId"),n=this.safeMarket(a),d=n.symbol,h=s.replace("candle",""),c=this.findTimeframe(h);this.ohlcvs[d]=this.safeDict(this.ohlcvs,d,{});let l=this.safeValue(this.ohlcvs[d],c);if(void 0===l){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);l=new o.TG(e),this.ohlcvs[d][c]=l}for(let e=0;e<r.length;e++){let t=r[e],i=this.parseOHLCV(t,n);l.append(i)}let u=[d,c,l],f="candle"+h+":"+d;e.resolve(u,f)}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let[t,i]=this.handleMarketTypeAndParams("watchBalance",void 0,e);if("spot"===t)throw new a.NotSupported(this.id+" watchBalance() is not supported for spot markets yet");let s=t+":balance",r=this.getSubscriptionRequest([{channel:"account"}]),o=this.urls.api.ws[t].private;return await this.watch(o,s,this.deepExtend(r,i),s)}handleBalance(e,t){let i="swap";i in this.balance||(this.balance[i]={}),this.balance[i]=this.parseWsBalance(t),e.resolve(this.balance[i],i+":balance")}parseWsBalance(e){return this.parseBalance(e)}async watchOrders(e,t,i,s={}){return s.callerMethodName="watchOrders",await this.watchOrdersForSymbols(void 0!==e?[e]:[],t,i,s)}async watchOrdersForSymbols(e,t,i,s={}){await this.authenticate(),void 0===this.markets&&await this.loadMarkets();let r=this.safeBool2(s,"stop","trigger"),a=this.omit(s,["stop","trigger"]),o="orders";!0===r&&(o="orders-algo");let n=await this.watchMultipleWrapper(!1,o,"watchOrdersForSymbols",e,a),d=this.safeDict(n,0),h=this.safeString(d,"symbol"),c=i;return this.newUpdates&&(c=n.getLimit(h,i)),this.filterBySinceLimit(n,t,c,"timestamp",!0)}handleOrders(e,t){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}let i=this.orders,s=this.safeDict(t,"arg"),r=this.safeString(s,"channel"),a=this.safeList(t,"data");for(let t=0;t<a.length;t++){let s=this.parseWsOrder(a[t]),o=s.symbol;if(i.append(s),void 0!==r){let t=r+":"+o;e.resolve(i,t)}e.resolve(i,r)}}parseWsOrder(e,t){return this.parseOrder(e,t)}async watchPositions(e,t,i,s={}){await this.authenticate(),void 0===this.markets&&await this.loadMarkets();let r=await this.watchMultipleWrapper(!1,"positions","watchPositions",e,s);return this.newUpdates?r:this.filterBySymbolsSinceLimit(this.positions,e,t,i)}handlePositions(e,t){void 0===this.positions&&(this.positions=new o.Hk);let i=this.positions,s=this.safeDict(t,"arg"),r=this.safeString(s,"channel"),a=this.safeList(t,"data"),n=[];for(let t=0;t<a.length;t++){let s=this.parseWsPosition(a[t]);if(n.push(s),i.append(s),void 0!==r){let t=r+":"+s.symbol;e.resolve(s,t)}}}parseWsPosition(e,t){return this.parsePosition(e,t)}async watchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),[s,r]=this.handleMarketTypeAndParams("watchFundingRate",i,t),a="fundingRate:"+i.symbol,o={channel:"funding-rate",instId:i.id},n=this.getSubscriptionRequest([o]),d=this.urls.api.ws[s].public;return await this.watch(d,a,this.deepExtend(n,r),a)}handleFundingRate(e,t){let i=this.safeList(t,"data",[]),s=this.safeDict(i,0,{}),r=this.parseFundingRate(s),a=r.symbol;this.fundingRates[a]=r,e.resolve(r,"fundingRate:"+a)}async watchMultipleWrapper(e,t,i,s,r={}){let o;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleParamString(r,"callerMethodName",i),h="candle"===t,c=h?this.getListFromObjectValues(s,0):s;c=this.marketSymbols(c,void 0,!0,!0);let l=this.safeString(c,0);void 0!==l&&(o=this.market(l));let[u,f]=this.handleMarketTypeAndParams(n,o,d);if("swap"!==u)throw new a.NotSupported(this.id+" "+n+"() does not support "+u+" markets yet");let p=[],m=[];if(void 0===c&&(c=[]),c.length>0)for(let e=0;e<c.length;e++){let i,r=c[e],a=t;if(h){i=this.market(r);let t=s[e][1];a+=this.safeString(this.timeframes,t,t)}else i=this.market(r);let o={channel:a,instId:i.id};p.push(o),m.push(a+":"+i.symbol)}else p.push({channel:t}),m.push(t);this.inArray(t,["orders","orders-algo","positions"])&&(p=[{channel:t}]);let g=this.getSubscriptionRequest(p),v="private";e&&(v="public");let y=this.urls.api.ws[u][v];return await this.watchMultiple(y,m,this.deepExtend(g,f),m)}getSubscriptionRequest(e){return{op:"subscribe",args:e}}handleMessage(e,t){let i,s={pong:this.handlePong,trades:this.handleTrades,books:this.handleOrderBook,tickers:this.handleTicker,candle:this.handleOHLCV,account:this.handleBalance,orders:this.handleOrders,"orders-algo":this.handleOrders,positions:this.handlePositions,"funding-rate":this.handleFundingRate};if("pong"===t)i=this.safeValue(s,"pong");else{let r=this.safeString(t,"event");if("subscribe"===r)return;if("login"===r)return void this.safeValue(e.futures,"authenticate_hash").resolve(!0);if("error"===r)throw new a.ExchangeError(this.id+" error: "+this.json(t));let o=this.safeDict(t,"arg"),n=this.safeString(o,"channel");void 0===(i=this.safeValue(s,n))&&n.indexOf("candle")>=0&&(i=s.candle)}void 0!==i&&i.call(this,e,t)}async authenticate(e={}){this.checkRequiredCredentials();let t=this.milliseconds(),i="authenticate_hash",r=t.toString(),a="n_"+r,o=this.stringToBase64(this.hmac(this.encode("/users/self/verifyGET"+r+a),this.encode(this.secret),s.sc)),n={op:"login",args:[{apiKey:this.apiKey,passphrase:this.password,timestamp:r,nonce:a,sign:o}]},d=this.urls.api.ws.swap.private;await this.watch(d,i,this.deepExtend(n,e),i)}}i.d(t,{A:()=>n})},7755(e,t,i){"use strict";var s=i(3935),r=i(1697),a=i(1453);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchTicker:!0,watchTickers:!1,watchOrderBook:!0,watchOrders:!0,watchTrades:!0,watchPositions:!0,watchMyTrades:!0,watchBalance:!0,watchOHLCV:!1},urls:{api:{ws:{public:"wss://api.exchange.bullish.com",private:"wss://api.exchange.bullish.com/trading-api/v1/private-data"}},test:{ws:{public:"wss://api.simnext.bullish-test.com",private:"wss://api.simnext.bullish-test.com/trading-api/v1/private-data"}}},options:{ws:{cookies:{}}},streaming:{ping:this.ping,keepAlive:99e3}})}requestId(){let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,e}ping(e){return{jsonrpc:"2.0",type:"command",method:"keepalivePing",params:{},id:this.requestId().toString()}}handlePong(e,t){return e.lastPong=this.milliseconds(),t}async watchPublic(e,t,i={},s={}){let r=this.requestId().toString(),o=this.safeString(this.urls.api.ws,"public");if(void 0===o)throw new a.ExchangeError(this.id+" watchPublic() has no public websocket url");return await this.watch(o+e,t,this.deepExtend({jsonrpc:"2.0",type:"command",method:"subscribe",params:i,id:r},s),t)}async watchPrivate(e,t,i={},s={}){let r=this.urls.api.ws.private,a=await this.handleToken();this.options.ws.cookies={JWT_COOKIE:a};let o=this.requestId().toString();return await this.watch(r,e,this.deepExtend({jsonrpc:"2.0",type:"command",method:"subscribe",params:i,id:o},s),t)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a="trades::"+r.symbol,o={topic:"anonymousTrades",symbol:r.id},n=await this.watchPublic("/trading-api/v1/market-data/trades",a,o,s),d=i;return this.newUpdates&&(d=n.getLimit(e,i)),this.filterBySinceLimit(n,t,d,"timestamp",!0)}handleTrades(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"symbol"),a=this.safeSymbol(s),o=this.market(a),n=this.safeList(i,"trades",[]),d=this.parseTrades(n,o);if(!(a in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3),t=new r.I3(e);this.trades[a]=t}let h=this.trades[a];for(let e=0;e<d.length;e++)h.append(d[e]);this.trades[a]=h;let c="trades::"+o.symbol;e.resolve(h,c)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r=this.safeString(this.urls.api.ws,"public");if(void 0===r)throw new a.ExchangeError(this.id+" watchTicker() has no public websocket url");let o=r+"/trading-api/v1/market-data/tick/"+i.id,n="ticker::"+s;return await this.watch(o,n,t,n)}handleTicker(e,t){let i=this.safeString(t,"type",""),s=this.safeDict(t,"data",{}),r=this.safeString(s,"symbol"),a=this.safeMarket(r),o=a.symbol,n=this.parseTicker(s,a);if("update"===i){let e=this.safeDict(this.tickers,o,{}),t=this.safeDict(e,"info",{}),i=this.extend(t,s);n=this.parseTicker(i,a)}this.tickers[o]=n;e.resolve(this.tickers[o],"ticker::"+o)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="orderbook::"+s.symbol,a={topic:"l2Orderbook",symbol:s.id};return(await this.watchPublic("/trading-api/v1/market-data/orderbook",r,a,i)).limit()}handleOrderBook(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"symbol"),r=this.safeSymbol(s),a="orderbook::"+r,o=this.safeInteger(i,"timestamp");r in this.orderbooks||(this.orderbooks[r]=this.orderBook());let n=this.orderbooks[r],d=this.separateBidsOrAsks(this.safeList(i,"bids",[])),h=this.separateBidsOrAsks(this.safeList(i,"asks",[])),c=this.parseOrderBook({bids:d,asks:h},r,o),l=this.safeList(i,"sequenceNumberRange",[]);if(l.length>0){let e=l.length-1;c.nonce=this.safeInteger(l,e)}n.reset(c),this.orderbooks[r]=n,e.resolve(n,a)}separateBidsOrAsks(e){let t=[];for(let i=0;i<e.length;i++){if(i%2!=0)continue;let s=this.safeString(e,i),r=this.safeString(e,i+1);t.push([s,r])}return t}async watchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a="orders",o=a;void 0!==e&&(o=o+"::"+(r=this.symbol(e)));let n={topic:"orders"},d=this.safeString(s,"tradingAccountId"),h=void 0!==d?this.omit(s,"tradingAccountId"):s;void 0!==d&&(n.tradingAccountId=d);let c=await this.watchPrivate(o,a,n,h),l=i;return this.newUpdates&&(l=c.getLimit(r,i)),this.filterBySymbolSinceLimit(c,r,t,l,!0)}handleOrders(e,t){let i=this.safeString(t,"type"),s=[];if("update"===i){let e=this.safeDict(t,"data",{});s.push(e)}else s=this.safeList(t,"data",[]);if(s.length>0){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new r.Pt(e)}let t=this.orders,i={};for(let e=0;e<s.length;e++){let r=s[e],a=this.parseOrder(r);t.append(a);let o=this.safeString(a,"symbol");void 0!==o&&(i[o]=!0)}let a="orders";e.resolve(t,a);let o=Object.keys(i);for(let t=0;t<o.length;t++){let i=a+"::"+o[t];e.resolve(this.orders,i)}}}async watchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a="myTrades",o=a;void 0!==e&&(o+="::"+(r=this.symbol(e)));let n={topic:"trades"},d=this.safeString(s,"tradingAccountId"),h=void 0!==d?this.omit(s,"tradingAccountId"):s;void 0!==d&&(n.tradingAccountId=d);let c=await this.watchPrivate(o,a,n,h),l=i;return this.newUpdates&&(l=c.getLimit(r,i)),this.filterBySinceLimit(c,t,l,"timestamp",!0)}handleMyTrades(e,t){let i=this.safeString(t,"type"),s=[];if("update"===i){let e=this.safeDict(t,"data",{});s.push(e)}else s=this.safeList(t,"data",[]);if(s.length>0){if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new r.Pt(e)}let t=this.myTrades,i={};for(let e=0;e<s.length;e++){let r=s[e],a=this.parseTrade(r);t.append(a);let o=this.safeString(a,"symbol");void 0!==o&&(i[o]=!0)}let a="myTrades";e.resolve(t,a);let o=Object.keys(i);for(let t=0;t<o.length;t++){let i=a+"::"+o[t];e.resolve(this.myTrades,i)}}}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t={topic:"assetAccounts"},i="balance",s=this.safeString(e,"tradingAccountId"),r=void 0!==s?this.omit(e,"tradingAccountId"):e;return void 0!==s&&(t.tradingAccountId=s,i+="::"+s),await this.watchPrivate(i,i,t,r)}handleBalance(e,t){let i=this.safeString(t,"tradingAccountId");if(void 0===i)return;if(i in this.balance||(this.balance[i]={}),"snapshot"===this.safeString(t,"type")){let e=this.safeList(t,"data",[]),s=this.parseBalance(e),r=Object.keys(s);for(let e=0;e<r.length;e++){let t=r[e];this.balance[i][t]=s[t]}this.balance[i]=this.safeBalance(this.balance[i])}else{let e=this.safeDict(t,"data",{}),s=this.safeString(e,"assetSymbol"),r=this.account();r.total=this.safeString(e,"availableQuantity"),r.used=this.safeString(e,"lockedQuantity");let a=this.safeCurrencyCode(s);void 0!==i&&void 0!==a&&(this.balance[i][a]=r),this.balance[i].info=t,this.balance[i]=this.safeBalance(this.balance[i])}let s="balance";e.resolve(this.balance[i],s),e.resolve(this.balance[i],s+"::"+i)}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r="positions",a=r,o=void 0!==e&&!this.isEmpty(e),n=e;o&&(n=this.marketSymbols(e)),o&&void 0!==n&&(a+="::"+n.join(","));let d=await this.watchPrivate(a,r,{topic:"derivativesPositionsV2"},s);return this.newUpdates?d:this.filterBySymbolsSinceLimit(d,n,t,i,!0)}handlePositions(e,t){let i=this.safeString(t,"type"),s=[];if("update"===i){let e=this.safeDict(t,"data",{});s.push(e)}else s=this.safeList(t,"data",[]);void 0===this.positions&&(this.positions=new r.Hk);let a=this.positions,o=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.parsePosition(t);a.append(i),o.push(i)}let n=this.findMessageHashes(e,"positions::");for(let t=0;t<n.length;t++){let i=n[t],s=i.split("::")[1].split(","),r=this.filterByArray(o,"symbol",s,!1);this.isEmpty(r)||e.resolve(r,i)}e.resolve(a,"positions")}handleErrorMessage(e,t){let i=this.safeDict(t,"data",{}),s=this.id+" "+this.json(i);try{let e=this.safeString(i,"errorCode"),t=this.safeString(i,"errorCodeName");throw this.throwExactlyMatchedException(this.exceptions.exact,e,s),this.throwBroadlyMatchedException(this.exceptions.broad,t,s),new a.ExchangeError(s)}catch(t){e.reject(t)}}handleMessage(e,t){let i=this.safeString(t,"dataType"),s=this.safeDict(t,"result");void 0!==s?"Keep alive pong"===this.safeString(s,"message")&&this.handlePong(e,t):void 0!==i&&("V1TAAnonymousTradeUpdate"===i&&this.handleTrades(e,t),"V1TATickerResponse"===i&&this.handleTicker(e,t),"V1TALevel2"===i&&this.handleOrderBook(e,t),"V1TAOrder"===i&&this.handleOrders(e,t),"V1TATrade"===i&&this.handleMyTrades(e,t),"V1TAAssetAccount"===i&&this.handleBalance(e,t),"V1TAErrorResponse"===i&&this.handleErrorMessage(e,t))}}i.d(t,{A:()=>o})},7832(e,t,i){"use strict";var s=i(4721),r=i(1484),a=i(1453),o=i(7749),n=i(1697);class d extends r.A{describe(){let e=super.describe();return this.deepExtend(e,this.describeData())}describeData(){return{has:{ws:!0,createOrderWs:!0,editOrderWs:!0,fetchOpenOrdersWs:!1,fetchOrderWs:!1,cancelOrderWs:!0,cancelOrdersWs:!1,cancelAllOrdersWs:!1,fetchTradesWs:!1,fetchBalanceWs:!1,watchBalance:!0,watchBidsAsks:!0,watchLiquidations:!0,watchLiquidationsForSymbols:!1,watchMyLiquidations:!1,watchMyLiquidationsForSymbols:!1,watchMyTrades:!0,watchOHLCV:!0,watchOHLCVForSymbols:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOrders:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchPositions:!0,watchTradesForSymbols:!0,unWatchTicker:!0,unWatchTickers:!0,unWatchOHLCV:!0,unWatchOHLCVForSymbols:!0,unWatchOrderBook:!0,unWatchOrderBookForSymbols:!0,unWatchTrades:!0,unWatchTradesForSymbols:!0,unWatchMyTrades:!0,unWatchOrders:!0,unWatchPositions:!0},urls:{api:{ws:{public:{spot:"wss://stream.{hostname}/v5/public/spot",inverse:"wss://stream.{hostname}/v5/public/inverse",option:"wss://stream.{hostname}/v5/public/option",linear:"wss://stream.{hostname}/v5/public/linear"},private:{spot:{unified:"wss://stream.{hostname}/v5/private",nonUnified:"wss://stream.{hostname}/spot/private/v3"},contract:"wss://stream.{hostname}/v5/private",usdc:"wss://stream.{hostname}/trade/option/usdc/private/v1",trade:"wss://stream.bybit.com/v5/trade"}}},test:{ws:{public:{spot:"wss://stream-testnet.{hostname}/v5/public/spot",inverse:"wss://stream-testnet.{hostname}/v5/public/inverse",linear:"wss://stream-testnet.{hostname}/v5/public/linear",option:"wss://stream-testnet.{hostname}/v5/public/option"},private:{spot:{unified:"wss://stream-testnet.{hostname}/v5/private",nonUnified:"wss://stream-testnet.{hostname}/spot/private/v3"},contract:"wss://stream-testnet.{hostname}/v5/private",usdc:"wss://stream-testnet.{hostname}/trade/option/usdc/private/v1",trade:"wss://stream-testnet.bybit.com/v5/trade"}}},demotrading:{ws:{public:{spot:"wss://stream.{hostname}/v5/public/spot",inverse:"wss://stream.{hostname}/v5/public/inverse",option:"wss://stream.{hostname}/v5/public/option",linear:"wss://stream.{hostname}/v5/public/linear"},private:{spot:{unified:"wss://stream-demo.{hostname}/v5/private",nonUnified:"wss://stream-demo.{hostname}/spot/private/v3"},contract:"wss://stream-demo.{hostname}/v5/private",usdc:"wss://stream-demo.{hostname}/trade/option/usdc/private/v1",trade:"wss://stream-demo.bybit.com/v5/trade"}}}},options:{watchTicker:{name:"tickers"},watchPositions:{fetchPositionsSnapshot:!0,awaitPositionsSnapshot:!0},watchMyTrades:{execType:["Trade","AdlTrade","BustTrade","Settle"]},spot:{timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","12h":"12h","1d":"1d","1w":"1w","1M":"1M"}},contract:{timeframes:{"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","1h":"60","2h":"120","4h":"240","6h":"360","12h":"720","1d":"D","1w":"W","1M":"M"}}},streaming:{ping:this.ping,keepAlive:18e3}}}requestId(){this.lockId();let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,this.unlockId(),e}async getUrlByMarketType(e,t=!1,i,s={}){let r,a,o,n,d="public";t&&(d="private");let h=void 0===i?"":i,c=this.urls.api.ws;if(void 0!==e)r="USDC"===(n=this.market(e)).settle,o=this.safeString(n,"type");else{let[e,t]=this.handleMarketTypeAndParams(h,void 0,s);o=e;let i=this.safeString(this.options,"defaultSettle");r="USDC"===(i=this.safeString2(t,"settle","defaultSettle",i))}if(a="spot"===o,t){let e=await this.isUnifiedEnabled(),t=this.safeBool(e,0,!1),i=this.safeBool(e,1,!1);c=r&&!0!==t&&!0!==i?c[d].usdc:c[d].contract}else if(a)c=c[d].spot;else if("swap"===o||"future"===o){let e=this.handleSubTypeAndParams(h,n,s,"linear")[0];c=c[d][e]}else c=c[d].option;return this.implodeHostname(c)}cleanParams(e){return this.omit(e,["type","subType","settle","defaultSettle","unifiedMargin"])}async createOrderWs(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.createOrderRequest(e,t,i,s,r,a,!0),n=this.implodeHostname(this.urls.api.ws.private.trade);await this.authenticate(n);let d=this.requestId().toString(),h={op:"order.create",reqId:d,args:[o],header:{"X-BAPI-TIMESTAMP":this.milliseconds().toString(),"X-BAPI-RECV-WINDOW":this.options.recvWindow.toString()}};return await this.watch(n,d,h,d,!0)}async editOrderWs(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.editOrderRequest(e,t,i,s,r,a,o),d=this.implodeHostname(this.urls.api.ws.private.trade);await this.authenticate(d);let h=this.requestId().toString(),c={op:"order.amend",reqId:h,args:[n],header:{"X-BAPI-TIMESTAMP":this.milliseconds().toString(),"X-BAPI-RECV-WINDOW":this.options.recvWindow.toString()}};return await this.watch(d,h,c,h,!0)}async cancelOrderWs(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===t)throw new a.ArgumentsRequired(this.id+" cancelOrderWs() requires a symbol argument");let s=this.cancelOrderRequest(e,t,i),r=this.implodeHostname(this.urls.api.ws.private.trade);await this.authenticate(r);let o=this.requestId().toString();"orderFilter"in s&&delete s.orderFilter;let n={op:"order.cancel",reqId:o,args:[s],header:{"X-BAPI-TIMESTAMP":this.milliseconds().toString(),"X-BAPI-RECV-WINDOW":this.options.recvWindow.toString()}};return await this.watch(r,o,n,o,!0)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r="ticker:"+s,o=await this.getUrlByMarketType(s,!1,"watchTicker",t),n=this.cleanParams(t),d=this.safeDict(this.options,"watchTicker",{}),h=this.safeString(d,"name","tickers");if(!0!==i.spot&&"tickers"!==h)throw new a.BadRequest(this.id+" watchTicker() only supports name tickers for contract markets");let c=[h+="."+i.id];return await this.watchTopics(o,[r],c,n)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=[],r=await this.getUrlByMarketType(i[0],!1,"watchTickers",t),a=this.cleanParams(t),o=this.safeDict(this.options,"watchTickers",{}),n=this.safeString(o,"name","tickers"),d=this.marketIds(i),h=[];for(let e=0;e<d.length;e++){let t=d[e];h.push(n+"."+t),s.push("ticker:"+i[e])}let c=await this.watchTopics(r,s,h,a);if(this.newUpdates){let e={},t=this.safeString(c,"symbol");return void 0!==t&&(e[t]=c),e}return this.filterByArray(this.tickers,"symbol",i)}async unWatchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=this.safeDict(this.options,"watchTickers",{}),r=this.safeString(s,"name","tickers"),a=[],o=[],n=this.marketIds(i),d=[];for(let e=0;e<n.length;e++){let t=n[e],s=i[e];d.push(r+"."+t),o.push("ticker:"+s),a.push("unsubscribe:ticker:"+s)}let h=await this.getUrlByMarketType(i[0],!1,"watchTickers",t);return await this.unWatchTopics(h,"ticker",i,a,o,d,t)}unWatchTicker(e,t={}){return this.unWatchTickers([e],t)}handleTicker(e,t){let i,s,r=this.safeString(t,"topic",""),a=this.safeString(t,"type",""),o=this.safeDict(t,"data",{}),n=void 0!==this.safeString(o,"usdIndexPrice"),d="contract";if(n&&(d="spot"),"snapshot"===a)s=this.parseTicker(o),i=this.safeString(s,"symbol");else if("delta"===a){let e=r.split("."),t=e.length,a=this.safeString(e,t-1),n=this.safeMarket(a,void 0,void 0,d);i=this.safeString(n,"symbol");let h=this.safeDict(this.tickers,i,{}),c=this.safeDict(h,"info",{}),l=this.extend(c,o);s=this.parseTicker(l)}if(void 0===s||void 0===i)return;let h=this.safeInteger(t,"ts");s.timestamp=h,s.datetime=this.iso8601(h),this.tickers[i]=s;let c="ticker:"+i;e.resolve(this.tickers[i],c)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=[],r=await this.getUrlByMarketType(i[0],!1,"watchBidsAsks",t),a=this.cleanParams(t),o=this.marketIds(i),n=[];for(let e=0;e<o.length;e++){let t="orderbook.1."+o[e];n.push(t),s.push("bidask:"+i[e])}let d=await this.watchTopics(r,s,n,a);return this.newUpdates?d:this.filterByArray(this.bidsasks,"symbol",i)}parseWsBidAsk(e,t){let i=this.safeInteger(e,"timestamp"),s=this.sortBy(this.aggregate(e.bids),0),r=this.sortBy(this.aggregate(e.asks),0),a=this.safeList(s,0,[]),o=this.safeList(r,0,[]);return this.safeTicker({symbol:this.safeString(t,"symbol"),timestamp:i,datetime:this.iso8601(i),ask:this.safeNumber(o,0),askVolume:this.safeNumber(o,1),bid:this.safeNumber(a,0),bidVolume:this.safeNumber(a,1),info:e},t)}async watchOHLCV(e,t="1m",i,s,r={}){return r.callerMethodName="watchOHLCV",(await this.watchOHLCVForSymbols([[e,t]],i,s,r))[e][t]}async watchOHLCVForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.getListFromObjectValues(e,0),a=this.marketSymbols(r,void 0,!1,!0,!0)[0],o=await this.getUrlByMarketType(a,!1,"watchOHLCVForSymbols",s),n=[],d=[];for(let t=0;t<e.length;t++){let i=e[t],s=this.market(i[0]),r=s.symbol,a=i[1],o=this.safeString(this.timeframes,a,a);n.push("kline."+o+"."+s.id),d.push("ohlcv::"+r+"::"+a)}let[h,c,l]=await this.watchTopics(o,d,n,s),u=i;this.newUpdates&&(u=l.getLimit(h,i));let f=this.filterBySinceLimit(l,t,u,0,!0);return this.createOHLCVObject(h,c,f)}async unWatchOHLCVForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.getListFromObjectValues(e,0),s=this.marketSymbols(i,void 0,!1,!0,!0)[0],r=await this.getUrlByMarketType(s,!1,"watchOHLCVForSymbols",t),a=[],o=[],n=[];for(let t=0;t<e.length;t++){let i=e[t],s=this.market(i[0]),r=s.symbol,d=i[1],h=this.safeString(this.timeframes,d,d);a.push("kline."+h+"."+s.id),o.push("ohlcv::"+r+"::"+d),n.push("unsubscribe::ohlcv::"+r+"::"+d)}return await this.unWatchTopics(r,"ohlcv",i,n,o,a,t,{symbolsAndTimeframes:e})}async unWatchOHLCV(e,t="1m",i={}){return i.callerMethodName="watchOHLCV",await this.unWatchOHLCVForSymbols([[e,t]],i)}handleOHLCV(e,t){let i=this.safeValue(t,"data",{}),s=this.safeString(t,"topic","").split("."),r=s.length,a=this.safeString(s,1),o=this.findTimeframe(a);if(void 0===o)return;let d=this.safeString(s,r-1),h=e.url.indexOf("spot")>-1,c="contract";h&&(c="spot");let l=this.safeMarket(d,void 0,void 0,c),u=l.symbol,f=this.safeDict(this.ohlcvs,u);if(void 0===f&&(this.ohlcvs[u]={}),void 0===this.safeValue(f,o)){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);this.ohlcvs[u][o]=new n.TG(e)}let p=this.ohlcvs[u][o];for(let e=0;e<i.length;e++){let t=this.parseWsOHLCV(i[e],l);p.append(t)}let m="ohlcv::"+u+"::"+o,g=[u,o,p];e.resolve(g,m)}parseWsOHLCV(e,t){let i=this.safeBool(t,"inverse",!1),s="volume";return i&&(s="turnover"),[this.safeInteger(e,"start"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,s)]}watchOrderBook(e,t,i={}){return this.watchOrderBookForSymbols([e],t,i)}async watchOrderBookForSymbols(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),0===e.length)throw new a.ArgumentsRequired(this.id+" watchOrderBookForSymbols() requires a non-empty array of symbols");let s=this.marketSymbols(e),r=await this.getUrlByMarketType(s[0],!1,"watchOrderBook",i),o=this.cleanParams(i),n=this.market(s[0]),d=!0===n.option?100:50,h=void 0===t?d:t;if(void 0!==t){let e=this.safeList2({spot:[1,50,200,1e3],option:[25,100],default:[1,50,200,1e3]},n.type,"default",[]);if(!this.inArray(t,e))throw new a.BadRequest(this.id+" watchOrderBookForSymbols(): for "+n.type+" markets limit can be one of: "+this.json(e))}let c=[],l=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.marketId(t),r="orderbook."+h.toString()+"."+i;c.push(r);let a="orderbook:"+t;l.push(a)}return(await this.watchTopics(r,l,c,o)).limit()}async unWatchOrderBookForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s="orderbook.",r=this.safeInteger(t,"limit"),a=void 0!==r?this.omit(t,"limit"):t;void 0===r&&(r=!0===this.market(i[0]).spot?50:500),s+=r.toString();let o=[],n=[],d=[];for(let e=0;e<i.length;e++){let t=i[e],r=s+"."+this.market(t).id;n.push("unsubscribe:orderbook:"+t),o.push("orderbook:"+t),d.push(r)}let h=await this.getUrlByMarketType(i[0],!1,"watchOrderBook",a);return await this.unWatchTopics(h,"orderbook",i,n,o,d,a)}unWatchOrderBook(e,t={}){return this.unWatchOrderBookForSymbols([e],t)}handleOrderBook(e,t){let i=this.safeString(t,"topic","").split(".")[1],s=e.url.indexOf("spot")>=0,r=this.safeString(t,"type"),a=this.safeDict(t,"data",{}),o=this.safeString(a,"s"),n="contract";s&&(n="spot");let d=this.safeMarket(o,void 0,void 0,n),h=d.symbol,c=this.safeInteger(t,"ts");h in this.orderbooks||(this.orderbooks[h]=this.orderBook());let l=this.orderbooks[h];if(l.symbol=h,"snapshot"===r){let e=this.parseOrderBook(a,h,c,"b","a");l.reset(e)}else{let e=this.safeList(a,"a",[]),t=this.safeList(a,"b",[]);this.handleDeltas(l.asks,e),this.handleDeltas(l.bids,t),l.timestamp=c,l.datetime=this.iso8601(c)}let u="orderbook:"+h;if(this.orderbooks[h]=l,e.resolve(l,u),"1"===i){let t=this.parseWsBidAsk(this.orderbooks[h],d),i={};i[h]=t,this.bidsasks[h]=t,e.resolve(i,"bidask:"+h)}}handleDelta(e,t){let i=this.parseOrderBookBidAsk(t,0,1);e.storeArray(i)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e);if(0===r.length)throw new a.ArgumentsRequired(this.id+" watchTradesForSymbols() requires a non-empty array of symbols");let o=this.cleanParams(s),n=await this.getUrlByMarketType(r[0],!1,"watchTrades",o),d=[],h=[];for(let e=0;e<r.length;e++){let t=r[e],i="publicTrade."+this.market(t).id;d.push(i);let s="trade:"+t;h.push(s)}let c=await this.watchTopics(n,h,d,o),l=this.safeDict(c,0),u=this.safeString(l,"symbol"),f=i;return this.newUpdates&&(f=c.getLimit(u,i)),this.filterBySinceLimit(c,t,f,"timestamp",!0)}async unWatchTradesForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1,!0),s=await this.getUrlByMarketType(i[0],!1,"unWatchTradesForSymbols",t),r=[],a=[],o=[];for(let e=0;e<i.length;e++){let t=i[e],s="publicTrade."+this.market(t).id;a.push(s);let n="unsubscribe:trade:"+t;r.push(n),o.push("trade:"+t)}return await this.unWatchTopics(s,"trades",i,r,o,a,t)}unWatchTrades(e,t={}){return this.unWatchTradesForSymbols([e],t)}handleTrades(e,t){let i=this.safeValue(t,"data",{}),s=this.safeString(t,"topic","").split("."),r=e.url.indexOf("spot")>=0,a="contract";r&&(a="spot");let o=this.safeString(s,1),d=this.safeMarket(o,void 0,void 0,a),h=d.symbol,c=this.safeValue(this.trades,h);if(void 0===c){let e=this.safeInteger(this.options,"tradesLimit",1e3);c=new n.I3(e),this.trades[h]=c}for(let e=0;e<i.length;e++){let t=this.parseWsTrade(i[e],d);c.append(t)}let l="trade:"+h;e.resolve(c,l)}parseWsTrade(e,t){let i,s=this.safeStringN(e,["i","T","v"]),r="spot";"BT"in e&&(r="contract"),void 0!==t&&(r=this.safeString(t,"type"));let a=this.safeString(e,"s"),o=this.safeMarket(a,t,void 0,r),n=o.symbol,d=this.safeInteger2(e,"t","T"),h=this.safeStringLower(e,"S"),c=this.safeValue(e,"m");void 0===h?h=!0===c?"buy":"sell":i=c;let l=this.safeString(e,"p"),u=this.safeString2(e,"q","v"),f=this.safeString(e,"o");return this.safeTrade({id:s,info:e,timestamp:d,datetime:this.iso8601(d),symbol:n,order:f,type:void 0,side:h,takerOrMaker:i,price:l,amount:u,cost:void 0,fee:void 0},o)}getPrivateType(e){return e.indexOf("spot")>=0?"spot":e.indexOf("v5/private")>=0?"unified":"usdc"}async watchMyTrades(e,t,i,s={}){let r="myTrades";void 0===this.markets&&await this.loadMarkets();let a=void 0!==e?this.symbol(e):e;void 0!==e&&(r+=":"+a);let o=await this.getUrlByMarketType(a,!0,"watchMyTrades",s);await this.authenticate(o);let n=this.safeString({spot:"ticketInfo",unified:"execution",usdc:"user.openapi.perp.trade"},this.getPrivateType(o)),[d,h]=this.handleOptionBoolAndParams(s,"watchMyTrades","executionFast",!1);d&&(n="execution.fast");let c=await this.watchTopics(o,[r],[n],h),l=i;return this.newUpdates&&(l=c.getLimit(a,i)),this.filterBySymbolSinceLimit(c,a,t,l,!0)}async unWatchMyTrades(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0!==e)throw new a.NotSupported(this.id+" unWatchMyTrades() does not support a symbol parameter, you must unwatch all my trades");let i=await this.getUrlByMarketType(e,!0,"watchMyTrades",t);await this.authenticate(i);let s=this.safeString({spot:"ticketInfo",unified:"execution",usdc:"user.openapi.perp.trade"},this.getPrivateType(i)),[r,o]=this.handleOptionBoolAndParams(t,"watchMyTrades","executionFast",!1);return r&&(s="execution.fast"),await this.unWatchTopics(i,"myTrades",[],["unsubscribe:myTrades"],["myTrades"],[s],o)}handleMyTrades(e,t){let i,s=this.safeString(t,"topic",""),r="ticketInfo"===s,a="execution.fast"===s,o=this.safeList(t,"data",[]);if(Array.isArray(o)||(o=this.safeList(o,"result",[])),void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new n.Pt(e)}let d=this.myTrades,h={},c=this.handleOption("watchMyTrades","execType");void 0===c&&(c=this.handleOption("watchMyTrades","filterExecTypes")),i="string"==typeof c?[c]:c;for(let e=0;e<o.length;e++){let t,s=o[e];if(r&&!a)t=this.parseWsTrade(s);else{let e=this.safeString(s,"execType","");if(a&&(e="Trade"),void 0!==i&&!this.inArray(e,i))continue;t=this.parseTrade(s)}let n=t.symbol;void 0!==n&&(h[n]=!0,d.append(t))}let l=Object.keys(h);for(let t=0;t<l.length;t++){let i="myTrades:"+l[t];e.resolve(d,i)}e.resolve(d,"myTrades")}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r="",a=e;void 0===e||this.isEmpty(e)||(a=this.marketSymbols(e)),void 0===a||this.isEmpty(a)||(r="::"+a.join(","));let o=this.safeString(a,0),n=await this.getUrlByMarketType(o,!0,"watchPositions",s);r="positions"+r;let d=this.client(n);await this.authenticate(n),this.setPositionsCache(d,a);let h=this.positions,c=this.handleOption("watchPositions","fetchPositionsSnapshot",!0),l=this.handleOption("watchPositions","awaitPositionsSnapshot",!0);if(!0===c&&!0===l&&void 0===h){let e=await d.future("fetchPositionsSnapshot");return this.filterBySymbolsSinceLimit(e,a,t,i,!0)}let u=await this.watchTopics(n,[r],["position"],s);return this.newUpdates?u:this.filterBySymbolsSinceLimit(h,a,t,i,!0)}setPositionsCache(e,t){if(void 0===this.positions)if(!0===this.handleOption("watchPositions","fetchPositionsSnapshot",!0)){let t="fetchPositionsSnapshot";t in e.futures||(e.future(t),this.spawn(this.loadPositionsSnapshot,e,t))}else this.positions=new n.Hk}async loadPositionsSnapshot(e,t){let i=[this.fetchPositions(void 0,{type:"swap",subType:"linear"}),this.fetchPositions(void 0,{type:"swap",subType:"inverse"})],s=await Promise.all(i);this.positions=new n.Hk;let r=this.positions;for(let e=0;e<s.length;e++){let t=s[e];for(let e=0;e<t.length;e++){let i=t[e];r.append(i)}}t in e.futures&&(e.futures[t].resolve(r),e.resolve(r,"position"))}handlePositions(e,t){void 0===this.positions&&(this.positions=new n.Hk);let i=this.positions,s=[],r=this.safeList(t,"data",[]);for(let e=0;e<r.length;e++){let t=r[e],a=this.parsePosition(t),o=this.safeString(a,"side");s.push(a),void 0===o||""===o?(a.side="long",i.append(a),a.side="short",i.append(a),a.side=void 0):i.append(a)}let a=this.findMessageHashes(e,"positions::");for(let t=0;t<a.length;t++){let i=a[t],r=i.split("::")[1].split(","),o=this.filterByArray(s,"symbol",r,!1);this.isEmpty(o)||e.resolve(o,i)}e.resolve(s,"positions")}async unWatchPositions(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0!==e&&!this.isEmpty(e))throw new a.NotSupported(this.id+" unWatchPositions() does not support a symbol parameter, you must unwatch all orders");let i=await this.getUrlByMarketType(void 0,!0,"watchPositions",t);return await this.authenticate(i),await this.unWatchTopics(i,"positions",e,["unsubscribe:positions"],["positions"],["position"],t)}async watchLiquidations(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o=await this.getUrlByMarketType(a,!1,"watchLiquidations",s),[n,d]=this.handleOptionStringAndParams(this.cleanParams(s),"watchLiquidations","method","allLiquidation"),h="liquidations::"+a,c=n+"."+r.id,l=await this.watchTopics(o,[h],[c],d);return this.newUpdates?l:this.filterBySymbolsSinceLimit(this.liquidations,[a],t,i,!0)}handleLiquidation(e,t){if(Array.isArray(t.data)){let i=this.safeList(t,"data",[]);for(let t=0;t<i.length;t++){let s=this.safeDict(i,t),r=this.safeString(s,"s"),a=this.safeMarket(r,void 0,"","contract"),o=a.symbol,d=this.parseWsLiquidation(s,a);if(void 0===this.liquidations){let e=this.safeInteger(this.options,"liquidationsLimit",1e3);this.liquidations=new n.I3(e)}this.liquidations.append(d),e.resolve([d],"liquidations"),e.resolve([d],"liquidations::"+o)}}else{let i=this.safeDict(t,"data",{}),s=this.safeString(i,"symbol"),r=this.safeMarket(s,void 0,"","contract"),a=r.symbol,o=this.parseWsLiquidation(i,r);if(void 0===this.liquidations){let e=this.safeInteger(this.options,"liquidationsLimit",1e3);this.liquidations=new n.I3(e)}this.liquidations.append(o),e.resolve([o],"liquidations"),e.resolve([o],"liquidations::"+a)}}parseWsLiquidation(e,t){let i=this.safeString2(e,"symbol","s"),s=this.safeMarket(i,t,"","contract"),r=this.safeInteger2(e,"updatedTime","T");return this.safeLiquidation({info:e,symbol:s.symbol,contracts:this.safeNumber2(e,"size","v"),contractSize:this.safeNumber(s,"contractSize"),price:this.safeNumber2(e,"price","p"),side:this.safeStringLower2(e,"side","S"),baseValue:void 0,quoteValue:void 0,timestamp:r,datetime:this.iso8601(r)})}async watchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r="orders",a=void 0!==e?this.symbol(e):e;void 0!==e&&(r+=":"+a);let o=await this.getUrlByMarketType(a,!0,"watchOrders",s);await this.authenticate(o);let n=this.safeList({spot:["order","stopOrder"],unified:["order"],usdc:["user.openapi.perp.order"]},this.getPrivateType(o)),d=await this.watchTopics(o,[r],n,s),h=i;return this.newUpdates&&(h=d.getLimit(a,i)),this.filterBySymbolSinceLimit(d,a,t,h,!0)}async unWatchOrders(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0!==e)throw new a.NotSupported(this.id+" unWatchOrders() does not support a symbol parameter, you must unwatch all orders");let i=await this.getUrlByMarketType(e,!0,"watchOrders",t);await this.authenticate(i);let s=this.safeList({spot:["order","stopOrder"],unified:["order"],usdc:["user.openapi.perp.order"]},this.getPrivateType(i));return await this.unWatchTopics(i,"orders",[],["unsubscribe:orders"],["orders"],s,t)}handleOrderWs(e,t){let i=this.safeString(t,"reqId"),s=this.safeDict(t,"data",{}),r=this.parseOrder(s);e.resolve(r,i)}handleOrder(e,t){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new n.Pt(e)}let i=this.orders,s=this.safeList(t,"data",[]),r=this.safeDict(s,0,{});"spot"!==this.safeString(r,"category")&&(s=this.safeValue(s,"result",s));let a={};for(let e=0;e<s.length;e++){let t=this.parseOrder(s[e]),r=t.symbol;void 0!==r&&(a[r]=!0,i.append(t))}let o=Object.keys(a);for(let t=0;t<o.length;t++){let s="orders:"+o[t];e.resolve(i,s)}e.resolve(i,"orders")}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t="balances",[i,s]=this.handleMarketTypeAndParams("watchBalance",void 0,e),[r,a]=this.handleSubTypeAndParams("watchBalance",void 0,s),o=await this.isUnifiedEnabled(),n=this.safeBool(o,0,!1),d=this.safeBool(o,1,!1),h=await this.getUrlByMarketType(void 0,!0,"watchBalance",a);await this.authenticate(h),!0===d&&("inverse"===r?t+=":contract":t+=":unified"),!0!==n&&!0!==d&&("spot"===i?t+=":spot":t+=":contract"),!0===n&&("spot"===i?t+=":spot":"linear"===r?t+=":unified":t+=":contract");let c=[this.safeString({spot:"outboundAccountInfo",unified:"wallet"},this.getPrivateType(h))];return await this.watchTopics(h,[t],c,a)}handleBalance(e,t){let i,s;void 0===this.balance&&(this.balance={});let r="balance",a=this.safeString(t,"topic"),o=[];if("outboundAccountInfo"===a){s="spot";let e=this.safeList(t,"data",[]);for(let t=0;t<e.length;t++){let i=this.safeList(e[t],"B",[]);o=this.arrayConcat(o,i)}i=o}if("wallet"===a){let e=this.safeValue(t,"data",{});for(let t=0;t<e.length;t++){let t=this.safeDict(e,0,{});s=this.safeStringLower(t,"accountType"),o=this.arrayConcat(o,this.safeList(t,"coin",[]))}i=e}for(let e=0;e<o.length;e++)this.parseWsBalance(o[e],s);if(void 0!==s){void 0===this.safeDict(this.balance,s)&&(this.balance[s]={}),this.balance[s].info=i;let a=this.safeInteger(t,"ts");this.balance[s].timestamp=a,this.balance[s].datetime=this.iso8601(a),this.balance[s]=this.safeBalance(this.balance[s]),r="balances:"+s,e.resolve(this.balance[s],r)}else{this.balance.info=i;let s=this.safeInteger(t,"ts");this.balance.timestamp=s,this.balance.datetime=this.iso8601(s),this.balance=this.safeBalance(this.balance),r="balances",e.resolve(this.balance,r)}}parseWsBalance(e,t){let i=this.account(),s=this.safeString2(e,"a","coin"),r=this.safeCurrencyCode(s);i.free=this.safeStringN(e,["availableToWithdraw","f","free"]);let a=this.safeString2(e,"l","locked");if(void 0!==a)i.used=a;else{let t=this.safeString(e,"totalPositionIM","0"),s=this.safeString(e,"totalOrderIM","0");i.used=o.Y.stringAdd(t,s)}i.total=this.safeString2(e,"equity","walletBalance"),void 0!==t?(void 0===this.safeDict(this.balance,t)&&(this.balance[t]={}),void 0!==t&&void 0!==r&&(this.balance[t][r]=i)):void 0!==r&&(this.balance[r]=i)}async watchTopics(e,t,i,s={}){let r,a,o=this.client(e),n=[],d=i.length;if(d===t.length)for(let e=0;e<d;e++)t[e]in o.subscriptions||n.push(i[e]);else{let e={},t=Object.keys(o.subscriptions);for(let i=0;i<t.length;i++){let s=this.safeDict(o.subscriptions,t[i],{}),r=this.safeList(s,"topics",[]),a=r.length;for(let t=0;t<a;t++)e[r[t]]=!0}for(let t=0;t<d;t++){let s=i[t];s in e||n.push(s)}}if(n.length>0){let e=this.requestId();r=this.extend({op:"subscribe",req_id:e,args:n},s),a={id:e,topics:n}}return await this.watchMultiple(e,t,r,t,a)}async unWatchTopics(e,t,i,s,r,a,o={},n={}){let d=this.requestId(),h=this.extend({op:"unsubscribe",req_id:d,args:a},o);return await this.watchMultiple(e,s,h,s,this.extend({id:d,topic:t,messageHashes:s,subMessageHashes:r,symbols:i},n))}async authenticate(e,t={}){this.checkRequiredCredentials();let i="authenticated",r=this.client(e),a=r.reusableFuture(i);if(void 0===this.safeValue(r.subscriptions,i)){let r=this.milliseconds()+1e4,a=this.numberToString(r),o=this.hmac(this.encode("GET/realtime"+a),this.encode(this.secret),s.sc,"hex"),n={op:"auth",args:[this.apiKey,a,o]},d=this.extend(n,t);this.watch(e,i,d,i)}return await a}handleErrorMessage(e,t){let i=this.safeStringN(t,["code","ret_code","retCode"]);try{if(void 0!==i&&"0"!==i){let e=this.id+" "+this.json(t);this.throwExactlyMatchedException(this.exceptions.exact,i,e);let s=this.safeString2(t,"retMsg","ret_msg");throw this.throwBroadlyMatchedException(this.exceptions.broad,s,e),new a.ExchangeError(e)}let e=this.safeBool(t,"success");if(void 0!==e&&!0!==e){let e=this.safeString(t,"ret_msg"),i=this.safeDict(t,"request",{}),s=this.safeString(i,"op");if("auth"===s)throw new a.AuthenticationError("Authentication failed: "+e);throw new a.ExchangeError(this.id+" "+e)}return!1}catch(r){let i=this.safeString2(t,"req_id","reqId"),s=!1;if(void 0!==i){let t=Object.keys(e.subscriptions);for(let a=0;a<t.length;a++){let o=t[a];if(!(o in e.subscriptions))continue;let n=this.safeDict(e.subscriptions,o);i===this.safeString(n,"id")&&(s=!0,delete e.subscriptions[o],e.reject(r,o))}}if(!s)if(void 0!==i)e.reject(r,i);else if(r instanceof a.AuthenticationError){let i="authenticated";e.reject(r,i),i in e.subscriptions&&delete e.subscriptions[i];let s=this.safeString(t,"op");void 0!==s&&"auth"!==s&&e.reject(r)}else e.reject(r,i);return!0}}handleMessage(e,t){let i=this.safeString2(t,"topic","op","");if(!0===this.handleErrorMessage(e,t))return;if("pong"===this.safeString(t,"ret_msg")||"pong"===i||void 0!==this.safeInteger(t,"pong"))return void this.handlePong(e,t);if("sub"===this.safeString(t,"event")||"subscribe"===i)return void this.handleSubscriptionStatus(e,t);let s={orderbook:this.handleOrderBook,kline:this.handleOHLCV,order:this.handleOrder,stopOrder:this.handleOrder,ticker:this.handleTicker,trade:this.handleTrades,publicTrade:this.handleTrades,depth:this.handleOrderBook,wallet:this.handleBalance,outboundAccountInfo:this.handleBalance,execution:this.handleMyTrades,"execution.fast":this.handleMyTrades,ticketInfo:this.handleMyTrades,"user.openapi.perp.trade":this.handleMyTrades,position:this.handlePositions,liquidation:this.handleLiquidation,allLiquidation:this.handleLiquidation,pong:this.handlePong,"order.create":this.handleOrderWs,"order.amend":this.handleOrderWs,"order.cancel":this.handleOrderWs,auth:this.handleAuthenticate,unsubscribe:this.handleUnSubscribe},r=this.safeValue(s,i);if(void 0!==r)return void r.call(this,e,t);if(i.indexOf("orderbook")>=0)return void this.handleOrderBook(e,t);let a=Object.keys(s);for(let r=0;r<a.length;r++){let o=a[r];if(i.indexOf(o)>=0)return void s[o].call(this,e,t)}"AUTH_RESP"===this.safeString(t,"type")&&this.handleAuthenticate(e,t)}ping(e){return{req_id:this.requestId(),op:"ping"}}handlePong(e,t){return e.lastPong=this.safeInteger(t,"pong",this.milliseconds()),t}handleAuthenticate(e,t){let i=this.safeBool(t,"success"),s=this.safeInteger(t,"retCode"),r="authenticated";if(!0===i||0===s)this.safeValue(e.futures,r).resolve(!0);else{let i=new a.AuthenticationError(this.id+" "+this.json(t));e.reject(i,r),r in e.subscriptions&&delete e.subscriptions[r]}return t}handleSubscriptionStatus(e,t){return t}handleUnSubscribe(e,t){let i=this.safeString(t,"req_id"),s=Object.keys(e.subscriptions);for(let t=0;t<s.length;t++){let r=s[t];if(r in e.subscriptions&&r.startsWith("unsubscribe")){let t=e.subscriptions[r];if(i!==this.safeString(t,"id"))continue;let s=this.safeList(t,"messageHashes",[]),a=this.safeList(t,"subMessageHashes",[]);for(let t=0;t<s.length;t++){let i=s[t],r=this.safeString(a,t),o="orders"===r||"myTrades"===r||"positions"===r;this.cleanUnsubscription(e,r,i,o)}this.cleanCache(t)}}return t}}i.d(t,{A:()=>d})},5538(e,t,i){"use strict";var s=i(7832),r=i(3574);class a extends s.A{describe(){let e=new r.A().describe(),t=super.describeData(),i=this.deepExtend(e,t);return this.deepExtend(i,{id:"bybiteu",name:"Bybit EU",countries:["EU"],hostname:"bybit.eu",certified:!1,urls:{api:{ws:{public:{spot:"wss://stream.{hostname}/v5/public/spot",inverse:"wss://stream.{hostname}/v5/public/inverse",option:"wss://stream.{hostname}/v5/public/option",linear:"wss://stream.{hostname}/v5/public/linear"},private:{spot:{unified:"wss://stream.{hostname}/v5/private",nonUnified:"wss://stream.{hostname}/spot/private/v3"},contract:"wss://stream.{hostname}/v5/private",usdc:"wss://stream.{hostname}/trade/option/usdc/private/v1",trade:"wss://stream.bybit.eu/v5/trade"}}},test:{ws:{public:{spot:"wss://stream-testnet.{hostname}/v5/public/spot",inverse:"wss://stream-testnet.{hostname}/v5/public/inverse",linear:"wss://stream-testnet.{hostname}/v5/public/linear",option:"wss://stream-testnet.{hostname}/v5/public/option"},private:{spot:{unified:"wss://stream-testnet.{hostname}/v5/private",nonUnified:"wss://stream-testnet.{hostname}/spot/private/v3"},contract:"wss://stream-testnet.{hostname}/v5/private",usdc:"wss://stream-testnet.{hostname}/trade/option/usdc/private/v1",trade:"wss://stream-testnet.bybit.eu/v5/trade"}}},demotrading:{ws:{public:{spot:"wss://stream.{hostname}/v5/public/spot",inverse:"wss://stream.{hostname}/v5/public/inverse",option:"wss://stream.{hostname}/v5/public/option",linear:"wss://stream.{hostname}/v5/public/linear"},private:{spot:{unified:"wss://stream-demo.{hostname}/v5/private",nonUnified:"wss://stream-demo.{hostname}/spot/private/v3"},contract:"wss://stream-demo.{hostname}/v5/private",usdc:"wss://stream-demo.{hostname}/trade/option/usdc/private/v1",trade:"wss://stream-demo.bybit.eu/v5/trade"}}}}})}}i.d(t,{A:()=>a})},9301(e,t,i){"use strict";var s=i(7832),r=i(3825);class a extends s.A{describe(){let e=new r.A().describe(),t=super.describeData(),i=this.deepExtend(e,t);return this.deepExtend(i,{id:"bybitid",name:"Bybit Indonesia",countries:["ID"],hostname:"bybit.id",certified:!1,urls:{api:{ws:{public:{spot:"wss://stream.{hostname}/v5/public/spot",inverse:"wss://stream.{hostname}/v5/public/inverse",option:"wss://stream.{hostname}/v5/public/option",linear:"wss://stream.{hostname}/v5/public/linear"},private:{spot:{unified:"wss://stream.{hostname}/v5/private",nonUnified:"wss://stream.{hostname}/spot/private/v3"},contract:"wss://stream.{hostname}/v5/private",usdc:"wss://stream.{hostname}/trade/option/usdc/private/v1",trade:"wss://stream.{hostname}/v5/trade"}}},test:{ws:{public:{spot:"wss://stream-testnet.{hostname}/v5/public/spot",inverse:"wss://stream-testnet.{hostname}/v5/public/inverse",linear:"wss://stream-testnet.{hostname}/v5/public/linear",option:"wss://stream-testnet.{hostname}/v5/public/option"},private:{spot:{unified:"wss://stream-testnet.{hostname}/v5/private",nonUnified:"wss://stream-testnet.{hostname}/spot/private/v3"},contract:"wss://stream-testnet.{hostname}/v5/private",usdc:"wss://stream-testnet.{hostname}/trade/option/usdc/private/v1",trade:"wss://stream-testnet.{hostname}/v5/trade"}}},demotrading:{ws:{public:{spot:"wss://stream.{hostname}/v5/public/spot",inverse:"wss://stream.{hostname}/v5/public/inverse",option:"wss://stream.{hostname}/v5/public/option",linear:"wss://stream.{hostname}/v5/public/linear"},private:{spot:{unified:"wss://stream-demo.{hostname}/v5/private",nonUnified:"wss://stream-demo.{hostname}/spot/private/v3"},contract:"wss://stream-demo.{hostname}/v5/private",usdc:"wss://stream-demo.{hostname}/trade/option/usdc/private/v1",trade:"wss://stream-demo.{hostname}/v5/trade"}}}}})}}i.d(t,{A:()=>a})},338(e,t,i){"use strict";var s=i(4721),r=i(6094),a=i(7749),o=i(1453),n=i(1697);class d extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchBidsAsks:!1,watchMyTrades:!1,watchOHLCV:!0,watchOHLCVForSymbols:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOrders:!0,watchOrdersForSymbols:!0,watchPositions:!0,watchTicker:!0,watchTickers:!0,watchTrades:!1,watchTradesForSymbols:!1,unwatchBidsAsks:!1,unwatchOHLCV:!0,unwatchOHLCVForSymbols:!0,unwatchOrderBook:!0,unwatchOrderBookForSymbols:!0,unwatchTicker:!0,unwatchTickers:!0,unWatchTrades:!1,unWatchTradesForSymbols:!1,unWatchOrders:!1,unWatchOrdersForSymbols:!1,unWatchPositions:!1},urls:{api:{ws:"wss://stream.bydfi.com/v1/public/fapi"}},options:{watchOrderBookForSymbols:{depth:"100",frequency:"1000ms"},watchBalance:{fetchBalanceSnapshot:!1,awaitBalanceSnapshot:!0},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","8h":"8h","12h":"12h","1d":"1d","1w":"1w","1M":"1M"}},streaming:{ping:this.ping,keepAlive:119e3}})}ping(e){return{id:this.requestId(),method:"ping"}}requestId(){this.lockId();let e=this.sum(this.safeInteger(this.options,"reqid",0),1);return this.options.reqid=e,this.unlockId(),e}async watchPublic(e,t,i={},s={}){let r=this.urls.api.ws,a=this.requestId(),o={id:a},n=this.safeBool(i,"unsubscribe",!1),d="SUBSCRIBE",h=!0===n?this.omit(i,"unsubscribe"):i;!0===n&&(d="UNSUBSCRIBE",o.unsubscribe=!0,o.messageHashes=e);let c={id:a,method:d,params:t};return await this.watchMultiple(r,e,this.deepExtend(c,h),e,this.extend(o,s))}async watchPrivate(e,t={}){let i;this.checkRequiredCredentials();let r=this.urls.api.ws,a=this.client(r),o=this.safeValue(a.subscriptions,"private"),n={};if(void 0===o){let e=this.requestId(),r=this.milliseconds().toString(),a=this.apiKey+r,o=this.hmac(this.encode(a),this.encode(this.secret),s.sc,"hex"),d={id:e,method:"LOGIN",params:{apiKey:this.apiKey,timestamp:r,sign:o}};i=this.deepExtend(d,t),n.id=e}let d=void 0!==i?i:t;return await this.watchMultiple(r,e,d,["private"],n)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e).id;return await this.watchPublic(["ticker::"+e],[i+"@ticker"],t)}unWatchTicker(e,t={}){return this.unWatchTickers([e],t)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0),s=[],r="ticker::",a=[];if(void 0===i)s.push(r+"all"),a.push("!ticker@arr");else for(let e=0;e<i.length;e++){let t=i[e],o=this.marketId(t);s.push(r+t),a.push(o+"@ticker")}return await this.watchPublic(s,a,t),this.filterByArray(this.tickers,"symbol",i)}async unWatchTickers(e,t={}){let i=this.marketSymbols(e,void 0,!0),s=[],r="unsubscribe::ticker::",a=[],o="@ticker",n={topic:"ticker"};if(void 0===i){let e=this.getMessageHashesForTickersUnsubscription();n.subHashIsPrefix=!0;for(let t=0;t<e.length;t++){let i=this.safeString(e,t);if(void 0!==i){let e=i.split("::"),t=this.safeString(e,1);if("all"===t)continue;let s=this.marketId(t);a.push(s+o)}}s.push(r),a.push("!ticker@arr")}else{for(let e=0;e<i.length;e++){let t=i[e],n=this.marketId(t);s.push(r+t),a.push(n+o)}n.symbols=i}let d=this.extend(t,{unsubscribe:!0});return await this.watchPublic(s,a,d,n)}getMessageHashesForTickersUnsubscription(){let e=this.urls.api.ws.public,t=this.client(e).subscriptions,i=[],s=Object.keys(t);for(let e=0;e<s.length;e++){let t=s[e];0===t.indexOf("ticker::")&&i.push(t)}return i}handleTicker(e,t){let i=this.parseTicker(t),s=i.symbol;this.tickers[s]=i,e.resolve(this.tickers[s],"ticker::"+s),e.resolve(this.tickers,"ticker::all")}async watchOHLCV(e,t="1m",i,s,r={}){return(await this.watchOHLCVForSymbols([[e,t]],i,s,r))[e][t]}unWatchOHLCV(e,t="1m",i={}){return this.unWatchOHLCVForSymbols([[e,t]],i)}async watchOHLCVForSymbols(e,t,i,s={}){if(0===e.length||!Array.isArray(e[0]))throw new o.ArgumentsRequired(this.id+" watchOHLCVForSymbols() requires a an array of symbols and timeframes, like  ['ETH/USDC', '1m']");await this.loadMarkets();let r=[],a=[];for(let t=0;t<e.length;t++){let i=this.safeList(e,t),s=this.safeString(i,0),o=this.market(s),n=this.safeString(i,1),d=this.safeDict(this.options,"timeframes",{}),h=this.safeString(d,n,n);r.push(o.id+"@kline_"+h),a.push("ohlcv::"+o.symbol+"::"+h)}let[n,d,h]=await this.watchPublic(a,r,s),c=i;this.newUpdates&&(c=h.getLimit(n,i));let l=this.filterBySinceLimit(h,t,c,0,!0);return this.createOHLCVObject(n,d,l)}async unWatchOHLCVForSymbols(e,t={}){if(0===e.length||!Array.isArray(e[0]))throw new o.ArgumentsRequired(this.id+" unWatchOHLCVForSymbols() requires a an array of symbols and timeframes, like  ['ETH/USDC', '1m']");await this.loadMarkets();let i=[],s=[];for(let t=0;t<e.length;t++){let r=this.safeList(e,t),a=this.safeString(r,0),o=this.market(a),n=this.safeString(r,1),d=this.safeString(this.timeframes,n,n);i.push(o.id+"@kline_"+d),s.push("unsubscribe::ohlcv::"+o.symbol+"::"+d)}let r=this.extend(t,{unsubscribe:!0});return await this.watchPublic(s,i,r,{topic:"ohlcv",symbolsAndTimeframes:e})}handleOHLCV(e,t){let i=this.safeString(t,"s"),s=this.safeMarket(i).symbol,r=this.safeString(t,"i"),a=this.safeDict(this.options,"timeframes",{}),o=this.findTimeframe(r,a);if(s in this.ohlcvs||(this.ohlcvs[s]={}),!(o in this.ohlcvs[s])){let e=this.safeInteger(this.options,"OHLCVLimit",1e3),t=new n.TG(e);this.ohlcvs[s][o]=t}let d=this.ohlcvs[s][o],h=this.parseWsOHLCV(t);d.append(h),e.resolve([s,o,d],"ohlcv::"+s+"::"+o)}watchOrderBook(e,t,i={}){return this.watchOrderBookForSymbols([e],t,i)}unWatchOrderBook(e,t={}){return this.unWatchOrderBookForSymbols([e],t)}async watchOrderBookForSymbols(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!1),[r,a]=this.handleOptionStringAndParams(i,"watchOrderBookForSymbols","depth","100"),[o,n]=this.handleOptionStringAndParams(a,"watchOrderBookForSymbols","frequency","100ms"),d="";"100ms"===o&&(d="@100ms");let h=[],c=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t);h.push(i.id+"@depth"+r+d),c.push("orderbook::"+t)}return(await this.watchPublic(c,h,n)).limit()}async unWatchOrderBookForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),[s,r]=this.handleOptionStringAndParams(t,"watchOrderBookForSymbols","depth","100"),[a,o]=this.handleOptionStringAndParams(r,"watchOrderBookForSymbols","frequency","100ms"),n="";"100ms"===a&&(n="@100ms");let d=[],h=[];for(let e=0;e<i.length;e++){let t=i[e],r=this.market(t);d.push(r.id+"@depth"+s+n),h.push("unsubscribe::orderbook::"+t)}let c=this.extend(o,{unsubscribe:!0});return await this.watchPublic(h,d,c,{topic:"orderbook",symbols:i})}handleOrderBook(e,t){let i=this.safeString(t,"s"),s=this.safeSymbol(i),r=this.safeInteger(t,"E");s in this.orderbooks||(this.orderbooks[s]=this.orderBook());let a=this.orderbooks[s],o=this.parseOrderBook(t,s,r,"b","a");a.reset(o);let n="orderbook::"+s;this.orderbooks[s]=a,e.resolve(a,n)}async watchOrders(e,t,i,s={}){let r;return void 0!==e&&(r=[e]),await this.watchOrdersForSymbols(r,t,i,s)}async watchOrdersForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!0),a=[];if(void 0===r)a.push("orders");else for(let e=0;e<r.length;e++){let t=r[e];a.push("orders::"+t)}let o=await this.watchPrivate(a,s),n=this.safeDict(o,0),d=this.safeString(n,"symbol"),h=i;return this.newUpdates&&(h=o.getLimit(d,i)),this.filterBySinceLimit(o,t,h,"timestamp",!0)}handleOrder(e,t){let i=this.safeDict(t,"o",{}),s=this.safeString(i,"s"),r=this.safeMarket(s),a=r.symbol,o="orders";if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new n.Pt(e)}let d=this.orders,h=this.parseWsOrder(i,r);h.lastUpdateTimestamp=this.safeInteger(t,"T"),d.append(h),e.resolve(d,o),e.resolve(d,o+"::"+a)}parseWsOrder(e,t){let i,s=this.safeString(e,"s"),r=this.safeMarket(s,t),o=this.safeString(e,"st"),n=this.safeString(e,"t"),d=this.safeString(e,"fee");return void 0!==d&&(i={cost:a.Y.stringAbs(d),currency:r.quote}),this.safeOrder({info:e,id:this.safeString(e,"o"),clientOrderId:this.safeString(e,"cid"),timestamp:void 0,datetime:void 0,lastTradeTimestamp:void 0,lastUpdateTimestamp:void 0,status:this.parseOrderStatus(o),symbol:r.symbol,type:this.parseOrderType(n),timeInForce:void 0,postOnly:void 0,reduceOnly:this.safeBool(e,"ro"),side:this.safeStringLower(e,"S"),price:this.safeString(e,"p"),triggerPrice:void 0,stopLossPrice:void 0,takeProfitPrice:void 0,amount:this.safeString(e,"v"),filled:this.safeString(e,"ev"),remaining:this.safeString(e,"qty"),cost:void 0,trades:void 0,fee:i,average:this.omitZero(this.safeString(e,"ap"))},r)}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!0),a=[],o="positions";if(void 0===r)a.push(o);else for(let e=0;e<r.length;e++){let t=r[e];a.push(o+"::"+t)}let n=await this.watchPrivate(a,s);return this.newUpdates?n:this.filterBySymbolsSinceLimit(this.positions,r,t,i,!0)}handlePositions(e,t){let i=this.safeDict(t,"a",{}),s=this.safeList(i,"p",[]),r=this.safeDict(s,0,{}),a=this.safeString(r,"s"),o=this.safeMarket(a),d=o.symbol,h="positions";void 0===this.positions&&(this.positions=new n.Hk);let c=this.positions,l=this.parseWsPosition(r,o),u=this.safeInteger(t,"T");l.timestamp=u,l.datetime=this.iso8601(u),c.append(l),e.resolve([l],h),e.resolve([l],h+"::"+d)}parseWsPosition(e,t){let i=this.safeString(e,"s"),s=this.safeMarket(i,t),r=this.safeString(e,"S"),a=this.safeString(e,"pt");return this.safePosition({info:e,id:this.safeString(e,"id"),symbol:s.symbol,entryPrice:this.parseNumber(this.safeString(e,"ap")),markPrice:void 0,lastPrice:void 0,notional:void 0,collateral:void 0,unrealizedPnl:void 0,realizedPnl:this.parseNumber(this.safeString(e,"rp")),side:this.parseWsPositionSide(r),contracts:this.parseNumber(this.safeString(e,"v")),contractSize:this.parseNumber(this.safeString(e,"uq")),timestamp:void 0,datetime:void 0,lastUpdateTimestamp:void 0,hedged:"ONEWAY"!==a,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,initialMargin:this.parseNumber(this.safeString(e,"pm")),initialMarginPercentage:void 0,leverage:this.safeInteger(e,"l"),liquidationPrice:this.parseNumber(this.safeString(e,"lq")),marginRatio:void 0,marginMode:this.safeStringLower(e,"mt"),percentage:void 0})}parseWsPositionSide(e){return this.safeString({1:"long",2:"short"},e,e)}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=this.urls.api.ws,i=this.client(t);this.fetchBalanceSnapshot(i);let s=this.safeDict(this.options,"watchBalance"),r=this.safeBool(s,"fetchBalanceSnapshot",!1),a=this.safeBool(s,"awaitBalanceSnapshot",!0);return!0===r&&!0===a&&await i.future("fetchBalanceSnapshot"),await this.watchPrivate(["balance"],e)}fetchBalanceSnapshot(e){let t=this.safeDict(this.options,"watchBalance");if(!0===this.safeBool(t,"fetchBalanceSnapshot",!1)){let t="fetchBalanceSnapshot";t in e.futures||(e.future(t),this.spawn(this.loadBalanceSnapshot,e,t))}}async loadBalanceSnapshot(e,t){let i=await this.fetchBalance({type:"swap"});this.balance=this.extend(i,this.balance),e.futures[t].resolve(),e.resolve(this.balance,"balance")}handleBalance(e,t){let i="balance";if(i in e.futures){let s=this.safeDict(t,"a",{}),r=this.safeList(s,"B",[]),a=this.safeInteger(t,"T"),o={info:t,timestamp:a,datetime:this.iso8601(a)};for(let e=0;e<r.length;e++){let t=this.safeDict(r,e),i=this.safeString(t,"a"),s=this.safeCurrencyCode(i),a=this.account();a.total=this.safeString(t,"wb"),a.used=this.safeString(t,"tfm"),void 0!==s&&(o[s]=a)}let n=this.safeBalance(o);this.balance=this.extend(this.balance,n),e.resolve(this.balance,i)}}handleSubscriptionStatus(e,t){let i=this.safeString(t,"id"),s=this.indexBy(e.subscriptions,"id"),r=this.safeDict(s,i,{});return!0===this.safeBool(r,"unsubscribe",!1)&&this.handleUnSubscription(e,r),t}handleUnSubscription(e,t){let i=this.safeList(t,"messageHashes",[]),s=this.safeBool(t,"subHashIsPrefix",!1);for(let t=0;t<i.length;t++){let r=i[t],a=r.replace("unsubscribe::","");this.cleanUnsubscription(e,a,r,s)}this.cleanCache(t)}handlePong(e,t){return e.lastPong=this.milliseconds(),t}handleErrorMessage(e,t){let i=this.safeString(t,"code"),s=this.safeString(t,"msg"),r=this.id+" "+this.json(t);throw this.throwExactlyMatchedException(this.exceptions.exact,s,r),this.throwBroadlyMatchedException(this.exceptions.broad,s,r),this.throwExactlyMatchedException(this.exceptions.exact,i,r),new o.ExchangeError(r)}handleMessage(e,t){let i=this.safeString(t,"code");void 0!==i&&"0"!==i&&this.handleErrorMessage(e,t);let s=this.safeString(t,"result");if("pong"===s)this.handlePong(e,t);else if(void 0!==s)this.handleSubscriptionStatus(e,t);else{let i=this.safeString(t,"e");if("24hrTicker"===i)this.handleTicker(e,t);else if("kline"===i)this.handleOHLCV(e,t);else if("depthUpdate"===i)this.handleOrderBook(e,t);else if("ORDER_TRADE_UPDATE"===i)this.handleOrder(e,t);else if("ACCOUNT_UPDATE"===i){let i=this.safeDict(t,"a",{});this.safeList(i,"B",[]).length>0&&this.handleBalance(e,t),this.safeList(i,"p",[]).length>0&&this.handlePositions(e,t)}}}}i.d(t,{A:()=>d})},6340(e,t,i){"use strict";var s=i(4721),r=i(5704),a=i(1453),o=i(7749),n=i(1697);class d extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!1,watchMyTrades:!0,watchOrders:!0,watchOrderBook:!0,watchOHLCV:!0,watchPosition:void 0,createOrderWs:!0,editOrderWs:!0,cancelOrderWs:!0,cancelOrdersWs:!0,fetchOrderWs:!0,fetchOpenOrdersWs:!0,fetchTickerWs:!0,fetchBalanceWs:!0},urls:{api:{ws:"wss://ws.cex.io/ws"}},options:{orderbook:{},watchTrades:{symbol:void 0}},streaming:{},exceptions:{}})}requestId(){this.lockId();let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,this.unlockId(),e.toString()}async watchBalance(e={}){await this.authenticate(e);let t=this.requestId(),i=this.urls.api.ws,s={e:"get-balance",data:{},oid:this.requestId()},r=this.deepExtend(s,e);return await this.watch(i,t,r,t,r)}handleBalance(e,t){let i=this.safeDict(t,"data",{}),s=this.safeDict(i,"balance",{}),r=this.safeDict(i,"obalance",{}),a={info:i},o=Object.keys(s);for(let e=0;e<o.length;e++){let t=o[e],i=this.account();i.free=this.safeString(s,t),i.used=this.safeString(r,t);let n=this.safeCurrencyCode(t);void 0!==n&&(a[n]=i)}this.balance=this.safeBalance(a);let n=this.safeString(t,"oid");e.resolve(this.balance,n)}async watchTrades(e,t,i,s={}){let r=this.safeString(this.options.watchTrades,"symbol");if(void 0!==r&&r!==e)throw new a.ArgumentsRequired(this.id+' : this exchange only supports watching trades for one symbol per instance. You should either set .options["watchTrades"]["symbol"] to new symbol, or create a new instance');this.options.watchTrades.symbol=e,void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=o.symbol,d=this.urls.api.ws,h="old:"+n,c=this.safeValue(this.clients,d);if(void 0!==c){let e=Object.keys(c.subscriptions);for(let t=0;t<e.length;t++){let i=e[t];if(i!==h&&"old"===(i=i.slice(0,3)))throw new a.ExchangeError(this.id+" watchTrades() only supports watching one symbol at a time.")}}let l={e:"subscribe",rooms:["pair-"+o.base+"-"+o.quote]},u=this.deepExtend(l,s),f=await this.watch(d,"trades",u,h);return this.filterBySinceLimit(f,t,i,"timestamp",!0)}handleTradesSnapshot(e,t){this.handleTradesInner(e,t)}parseWsOldTrade(e,t){let i=e;Array.isArray(e)||(i=e.split(":"));let s=this.safeString(i,0),r=this.safeInteger(i,1),a=this.safeString(i,2),o=this.safeString(i,3),n=this.safeString(i,4);return this.safeTrade({info:i,id:n,timestamp:r,datetime:this.iso8601(r),symbol:this.safeString(t,"symbol"),type:void 0,side:s,order:void 0,takerOrMaker:void 0,price:o,amount:a,cost:void 0,fee:void 0},t)}handleTrade(e,t){this.handleTradesInner(e,t)}handleTradesInner(e,t){let i=this.safeList(t,"data",[]),s=this.safeString(this.options.watchTrades,"symbol");if(void 0===s)return;if(!(s in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.trades[s]=new n.I3(e)}let r=this.trades[s],a=this.market(s),o=i.length;for(let e=0;e<o;e++){let t=i[o-1-e],s=this.parseWsOldTrade(t,a);r.append(s)}this.trades[s]=r,e.resolve(this.trades[s],"trades")}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r=this.urls.api.ws,a=this.safeString(t,"method","private"),o={e:"subscribe",rooms:["tickers"]},n="tickers";"private"===a&&(await this.authenticate(),o={e:"ticker",data:[i.baseId,i.quoteId],oid:this.requestId()},n="ticker:"+s);let d=this.deepExtend(o,t);return await this.watch(r,"ticker:"+s,d,n)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=this.urls.api.ws,r="tickers",a=this.deepExtend({e:"subscribe",rooms:["tickers"]},t),o=await this.watch(s,r,a,r),n=o.symbol;if(void 0!==i&&!this.inArray(n,i))return await this.watchTickers(i,t);if(this.newUpdates){let e={};return e[n]=o,e}return this.filterByArray(this.tickers,"symbol",i)}async fetchTickerWs(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.urls.api.ws,r=this.requestId(),a=this.extend({e:"ticker",oid:r,data:[i.base,i.quote]},t);return await this.watch(s,r,a,r)}handleTicker(e,t){let i=this.safeDict(t,"data",{}),s=this.parseWsTicker(i),r=s.symbol;if(void 0===r)return;this.tickers[r]=s;let a="ticker:"+r;e.resolve(s,a),e.resolve(s,"tickers"),void 0!==(a=this.safeString(t,"oid"))&&e.resolve(s,a)}parseWsTicker(e,t){let i,s=this.safeList(e,"pair",[]),r=this.safeString(e,"symbol1");void 0===r&&(r=this.safeString(s,0));let a=this.safeString(e,"symbol2");void 0===a&&(a=this.safeString(s,1));let o=this.safeCurrencyCode(r),n=this.safeCurrencyCode(a);void 0!==o&&void 0!==n&&(i=o+"/"+n);let d=this.safeInteger(e,"timestamp");return void 0!==d&&(d*=1e3),this.safeTicker({symbol:i,timestamp:d,datetime:this.iso8601(d),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeString(e,"bid"),bidVolume:void 0,ask:this.safeString(e,"ask"),askVolume:void 0,vwap:void 0,open:this.safeString(e,"open24"),close:void 0,last:this.safeString2(e,"price","last"),previousClose:void 0,change:this.safeString(e,"priceChange"),percentage:this.safeString(e,"priceChangePercentage"),average:void 0,baseVolume:void 0,quoteVolume:this.safeString(e,"volume"),info:e},t)}async fetchBalanceWs(e={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let t=this.urls.api.ws,i=this.requestId(),s=this.extend({e:"get-balance",oid:i},e);return await this.watch(t,i,s,i)}async watchOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" watchOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),await this.authenticate(s);let r=this.urls.api.ws,o=this.market(e),n=o.symbol,d="orders:"+n,h={e:"open-orders",data:{pair:[o.baseId,o.quoteId]},oid:n},c=this.deepExtend(h,s),l=await this.watch(r,d,c,d,c),u=i;return this.newUpdates&&(u=l.getLimit(n,i)),this.filterBySymbolSinceLimit(l,n,t,u,!0)}async watchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" watchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),await this.authenticate(s);let r=this.urls.api.ws,o=this.market(e),n="myTrades:"+o.symbol,d="orders:"+o.symbol,h={e:"open-orders",data:{pair:[o.baseId,o.quoteId]},oid:o.symbol},c=this.deepExtend(h,s),l=await this.watch(r,n,c,d,c);return this.filterBySymbolSinceLimit(l,this.safeString(o,"symbol"),t,i)}handleTransaction(e,t){let i=this.safeDict(t,"data");void 0!==this.safeString(i,"symbol2")&&(this.handleOrderUpdate(e,t),this.handleMyTrades(e,t))}handleMyTrades(e,t){let i=this.safeDict(t,"data",{}),s=this.myTrades;if(void 0===s){let e=this.safeInteger(this.options,"tradesLimit",1e3);s=new n.Pt(e),this.myTrades=s}let r=this.parseWsTrade(i);s.append(r);let a="myTrades:"+r.symbol;e.resolve(s,a)}parseWsTrade(e,t){let i,s=this.safeString(e,"type"),r=this.safeString(e,"price"),a=this.safeString(e,"time"),n=this.safeString(e,"symbol"),d=this.safeString(e,"symbol2"),h=this.safeCurrencyCode(n),c=this.safeCurrencyCode(d);void 0!==h&&void 0!==c&&(i=h+"/"+c,"sell"===s&&(i=c+"/"+h));let l=this.safeString(e,"amount");"sell"===s&&(l=o.Y.stringDiv(l,r));let u={id:this.safeString(e,"id"),order:this.safeString(e,"order"),info:e,timestamp:this.parse8601(a),datetime:a,symbol:i,type:void 0,side:s,takerOrMaker:void 0,price:r,cost:void 0,amount:l,fee:void 0},f=this.safeString(e,"fee_amount");return void 0!==f&&(u.fee={cost:f,currency:c,rate:void 0}),this.safeTrade(u,t)}handleOrderUpdate(e,t){let i=this.safeDict(t,"data",{}),s="tx"===this.safeString(t,"e"),r=this.safeString2(i,"id","order"),a=this.safeString(i,"remains"),o=this.safeString(i,"symbol"),d=this.safeString(i,"symbol2"),h=this.safeDict(i,"pair");void 0!==h&&(o=this.safeString(h,"symbol1"),d=this.safeString(h,"symbol2"));let c=this.safeCurrencyCode(o),l=this.safeCurrencyCode(d);if(void 0===c||void 0===l)return;let u=c+"/"+l,f=this.safeMarket(u);if(a=this.currencyFromPrecision(c,a),void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new n.Pt(e)}let p=this.orders,m=this.safeDict(p.hashmap,u,{}),g=this.safeValue(m,r);void 0===g&&(g=this.parseWsOrderUpdate(i,f)),g.remaining=a,!0===this.safeBool(i,"cancel",!1)&&(g.status="canceled"),s&&(g.status="closed");let v=this.safeNumber(i,"fee");void 0!==v&&(g.fee={cost:v,currency:l,rate:void 0});let y=this.safeInteger(i,"time");g.timestamp=y,g.datetime=this.iso8601(y),g=this.safeOrder(g),p.append(g);let b="orders:"+u;e.resolve(p,b)}parseWsOrderUpdate(e,t){let i,s,r=void 0!==this.safeString(e,"d"),a=this.safeString(e,"remains");if(void 0!==a){if(void 0===t)return;i=this.currencyFromPrecision(t.base,a)}let o=this.safeString(e,"amount");if(!r){if(void 0===t)return;this.currencyFromPrecision(t.base,o)}let n=this.safeString(e,"symbol"),d=this.safeString(e,"symbol2");void 0!==this.safeDict(e,"pair")&&(n=this.safeString(e,"symbol1"),d=this.safeString(e,"symbol2"));let h=this.safeCurrencyCode(n),c=this.safeCurrencyCode(d);void 0!==h&&void 0!==c&&(s=h+"/"+c);let l=this.safeMarket(s,t),u=this.safeInteger(e,"time"),f=u;r&&(f=this.parse8601(u));let p=this.safeBool(e,"cancel",!1),m="open";!0===p?m="canceled":r&&(m="closed");let g={id:this.safeString2(e,"id","order"),clientOrderId:void 0,info:e,timestamp:f,datetime:this.iso8601(f),lastTradeTimestamp:void 0,status:m,symbol:s,type:void 0,timeInForce:void 0,postOnly:void 0,side:this.safeString(e,"type"),price:this.safeNumber(e,"price"),stopPrice:void 0,triggerPrice:void 0,average:void 0,cost:void 0,amount:o,filled:void 0,remaining:i,fee:{cost:this.safeNumber2(e,"fee","fee_amount"),currency:c,rate:void 0},trades:void 0};return r&&(g.trades=this.parseWsTrade(e,l)),this.safeOrder(g,l)}fromPrecision(e,t){if(void 0===e)return;let i=new o.Y(e);return i.decimals=this.sum(i.decimals,t),i.reduce(),i.toString()}currencyFromPrecision(e,t){let i=this.safeInteger(this.currencies[e],"precision",0);return this.fromPrecision(t,i)}handleOrdersSnapshot(e,t){let i=this.safeString(t,"oid"),s=this.safeList(t,"data",[]),r=this.orders;if(void 0===r){let e=this.safeInteger(this.options,"ordersLimit",1e3);r=new n.Pt(e)}for(let e=0;e<s.length;e++){let t=s[e],a=this.safeMarket(i),o=this.parseOrder(t,a);o.status="open",r.append(o)}this.orders=r;r.length>0&&e.resolve(r,"orders:"+i)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let s=this.market(e),r=s.symbol,a=this.urls.api.ws,o="orderbook:"+r,n={e:"order-book-subscribe",data:{pair:[s.baseId,s.quoteId],subscribe:!0,depth:void 0===t?0:t},oid:this.requestId()},d=this.deepExtend(n,i);return(await this.watch(a,o,d,o)).limit()}handleOrderBookSnapshot(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"pair"),r=this.pairToSymbol(s);if(void 0===r)return;let a="orderbook:"+r,o=this.safeInteger2(i,"timestamp_ms","timestamp"),n=this.safeInteger(i,"id"),d=this.orderBook({}),h=this.parseOrderBook(i,r,o,"bids","asks");h.nonce=n,d.reset(h),this.options.orderbook[r]={incrementalId:n},this.orderbooks[r]=d,e.resolve(d,a)}pairToSymbol(e){let t=e.split(":"),i=this.safeString(t,0),s=this.safeString(t,1),r=this.safeCurrencyCode(i),a=this.safeCurrencyCode(s);if(void 0!==r&&void 0!==a)return r+"/"+a}handleOrderBookUpdate(e,t){let i=this.safeDict(t,"data",{}),s=this.safeInteger(i,"id"),r=this.safeString(i,"pair",""),o=this.pairToSymbol(r);if(void 0===o)return;let n=this.safeValue(this.orderbooks,o),d="orderbook:"+o,h=this.safeInteger(n,"nonce");if(void 0===h||s!==h+1){delete e.subscriptions[d];let t=new a.InvalidNonce(this.id+" watchOrderBook() skipped a message");e.reject(t,d);return}let c=this.safeInteger(i,"time"),l=this.safeList(i,"asks",[]),u=this.safeList(i,"bids",[]);this.handleDeltas(n.asks,l),this.handleDeltas(n.bids,u),n.timestamp=c,n.datetime=this.iso8601(c),n.nonce=s,e.resolve(n,d)}handleDelta(e,t){let i=this.parseOrderBookBidAsk(t,0,1);e.storeArray(i)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n="ohlcv:"+o,d=this.urls.api.ws,h={e:"init-ohlcv",i:t,rooms:["pair-"+a.baseId+"-"+a.quoteId]},c=await this.watch(d,n,this.extend(h,r),n),l=s;return this.newUpdates&&(l=c.getLimit(o,s)),this.filterBySinceLimit(c,i,l,0,!0)}handleInitOHLCV(e,t){let i=this.safeString(t,"pair");if(void 0===i)return;let s=i.split(":"),r=this.safeString(s,0),a=this.safeString(s,1),o=this.safeCurrencyCode(r),d=this.safeCurrencyCode(a);if(void 0===o||void 0===d)return;let h=o+"/"+d,c=this.safeMarket(h),l="ohlcv:"+h,u=this.safeList(t,"data",[]),f=this.safeInteger(this.options,"OHLCVLimit",1e3),p=new n.TG(f),m=this.sortBy(u,0);for(let e=0;e<m.length;e++)p.append(this.parseOHLCV(m[e],c));h in this.ohlcvs||(this.ohlcvs[h]={}),this.ohlcvs[h].unknown=p,e.resolve(p,l)}handleOHLCV24(e,t){return t}handleOHLCV1m(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"pair"),r=this.pairToSymbol(s);if(void 0===r)return;let a="ohlcv:"+r,o=[this.safeTimestamp(i,"time"),this.safeNumber(i,"o"),this.safeNumber(i,"h"),this.safeNumber(i,"l"),this.safeNumber(i,"c"),this.safeNumber(i,"v")],n=this.safeValue(this.ohlcvs,r);n.append(o),e.resolve(n,a)}handleOHLCV(e,t){let i=this.safeList(t,"data",[]),s=this.safeString(t,"pair"),r=this.pairToSymbol(s);if(void 0===r)return;let a=this.ohlcvs[r].unknown;for(let e=0;e<i.length;e++){let t=[this.safeTimestamp(i[e],0),this.safeNumber(i[e],1),this.safeNumber(i[e],2),this.safeNumber(i[e],3),this.safeNumber(i[e],4),this.safeNumber(i[e],5)];a.append(t)}i.length>0&&e.resolve(a,"ohlcv:"+r)}async fetchOrderWs(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),await this.authenticate(),void 0!==t&&(s=this.market(t));let r=this.extend({order_id:e.toString()},i),a=this.urls.api.ws,o=this.requestId(),n=await this.watch(a,o,{e:"get-order",oid:o,data:r},o);return this.parseOrder(n,s)}async fetchOpenOrdersWs(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" fetchOpenOrdersWs requires a symbol.");void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.market(e),o=this.urls.api.ws,n=this.requestId(),d=this.extend({pair:[r.baseId,r.quoteId]},s),h=await this.watch(o,n,{e:"open-orders",oid:n,data:d},n);return this.parseOrders(h,r,t,i,s)}async createOrderWs(e,t,i,s,r,o={}){if(void 0===r)throw new a.BadRequest(this.id+" createOrderWs requires a price argument");void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let n=this.market(e),d=this.urls.api.ws,h=this.requestId(),c=this.extend({pair:[n.baseId,n.quoteId],amount:s,price:r,type:i},o),l=await this.watch(d,h,{e:"place-order",oid:h,data:c},h);return this.parseOrder(l,n)}async editOrderWs(e,t,i,s,r,o,n={}){if(void 0===r)throw new a.ArgumentsRequired(this.id+" editOrder() requires a amount argument");if(void 0===o)throw new a.ArgumentsRequired(this.id+" editOrder() requires a price argument");void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let d=this.market(t),h=this.extend({pair:[d.baseId,d.quoteId],type:s,amount:r,price:o,order_id:e},n),c=this.requestId(),l=this.urls.api.ws,u=await this.watch(l,c,{e:"cancel-replace-order",oid:c,data:h},c,c);return this.parseOrder(u,d)}async cancelOrderWs(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),await this.authenticate(),void 0!==t&&(s=this.market(t));let r=this.extend({order_id:e},i),a=this.requestId(),o=this.urls.api.ws,n=await this.watch(o,a,{e:"cancel-order",oid:a,data:r},a,a);return this.parseOrder(n,s)}async cancelOrdersWs(e,t,i={}){if(void 0!==t)throw new a.BadRequest(this.id+" cancelOrderWs does not allow filtering by symbol");void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let s=this.requestId(),r=this.extend({"cancel-orders":e},i),o=this.urls.api.ws,n=await this.watch(o,s,{e:"mass-cancel-place-orders",oid:s,data:r},s,s),d=this.safeList(n,"cancel-orders");return this.parseOrders(d,void 0,void 0,void 0,i)}resolveData(e,t){let i=this.safeList(t,"data"),s=this.safeString(t,"oid");e.resolve(i,s)}handleConnected(e,t){return t}handleErrorMessage(e,t){try{let e=this.safeDict(t,"data",{}),i=this.safeString(e,"error"),s=this.safeString(t,"e",""),r=this.id+" "+s+" "+i;throw this.throwExactlyMatchedException(this.exceptions.exact,i,r),this.throwBroadlyMatchedException(this.exceptions.broad,i,r),new a.ExchangeError(r)}catch(s){let i=this.safeString(t,"oid");if(void 0!==this.safeValue(e.futures,i))return e.reject(s,i),!0;throw s}}handleMessage(e,t){if("error"===this.safeString(t,"ok"))return void this.handleErrorMessage(e,t);let i=this.safeString(t,"e"),s={auth:this.handleAuthenticationMessage,connected:this.handleConnected,tick:this.handleTicker,ticker:this.handleTicker,"init-ohlcv-data":this.handleInitOHLCV,ohlcv24:this.handleOHLCV24,ohlcv1m:this.handleOHLCV1m,ohlcv:this.handleOHLCV,"get-balance":this.handleBalance,"order-book-subscribe":this.handleOrderBookSnapshot,md_update:this.handleOrderBookUpdate,"open-orders":this.resolveData,order:this.handleOrderUpdate,"history-update":this.handleTrade,history:this.handleTradesSnapshot,tx:this.handleTransaction,"place-order":this.resolveData,"cancel-replace-order":this.resolveData,"cancel-order":this.resolveData,"mass-cancel-place-orders":this.resolveData,"get-order":this.resolveData},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}handleAuthenticationMessage(e,t){let i=this.safeValue(e.futures,"authenticated");void 0!==i&&i.resolve(!0)}async authenticate(e={}){let t=this.urls.api.ws,i=this.client(t),r="authenticated",a=i.reusableFuture("authenticated");if(void 0===this.safeValue(i.subscriptions,r)){this.checkRequiredCredentials();let i=this.seconds().toString(),a=i+this.apiKey,o=this.hmac(this.encode(a),this.encode(this.secret),s.sc),n={e:"auth",auth:{key:this.apiKey,signature:o.toUpperCase(),timestamp:i}};this.watch(t,r,this.extend(n,e),r)}return await a}}i.d(t,{A:()=>d})},3434(e,t,i){"use strict";var s=i(4721),r=i(4038),a=i(1453),o=i(1697);class n extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,cancelAllOrdersWs:!1,cancelOrdersWs:!1,cancelOrderWs:!1,createOrderWs:!1,editOrderWs:!1,fetchBalanceWs:!1,fetchOpenOrdersWs:!1,fetchOrderWs:!1,fetchTradesWs:!1,watchBalance:!1,watchMyTrades:!1,watchOHLCV:!1,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOrders:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!0,unWatchTicker:!0,unWatchTickers:!0,unWatchTrades:!0,unWatchOrders:!0,unWatchTradesForSymbols:!0},urls:{api:{ws:"wss://advanced-trade-ws.coinbase.com"}},options:{tradesLimit:1e3,ordersLimit:1e3,myTradesLimit:1e3,sides:{bid:"bids",offer:"asks"}}})}async subscribe(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=e,o=[];if(Array.isArray(i)){let e=this.marketSymbols(i),t=this.marketIds(e);o=void 0===t?[]:t,a=a+"::"+e.join(",")}else void 0!==i&&(r=this.market(i),a=e+"::"+i,o=[this.safeString(r,"id")]);let n=this.urls.api.ws,d={type:"subscribe",product_ids:o,channel:e};return t&&(d=this.extend(d,this.createWSAuth(e,o))),await this.watch(n,a,d,a)}async unSubscribe(e,t,i,s){let r;if(void 0===this.markets&&await this.loadMarkets(),this.safeBool(this.options,"unSubscriptionPending",!1))throw new a.ExchangeError(this.id+" another unSubscription is pending, coinbase does not support concurrent unSubscriptions");this.options.unSubscriptionPending=!0;let o=t,n="unsubscribe:"+t,d=[];if(Array.isArray(s)){let e=this.marketSymbols(s),t=this.marketIds(e);d=void 0===t?[]:t,o=o+"::"+e.join(","),n=n+"::"+e.join(",")}else void 0!==s&&(r=this.market(s),o=t+"::"+s,n=n+"::"+s,d=[this.safeString(r,"id")]);let h=this.urls.api.ws,c={type:"unsubscribe",product_ids:d,channel:t},l={messageHashes:[n],subMessageHashes:[o],topic:e,unsubscribe:!0,symbols:[s]};i&&(c=this.extend(c,this.createWSAuth(t,d))),this.options.unSubscription=l;let u=await this.watch(h,n,c,n,l);return this.options.unSubscriptionPending=!1,this.options.unSubscription=void 0,u}async subscribeMultiple(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=[],a=[],o=this.marketSymbols(i,void 0,!1);for(let t=0;t<o.length;t++){let i=o[t],s=this.market(i).id;r.push(s),a.push(e+"::"+i)}let n=this.urls.api.ws,d={type:"subscribe",product_ids:r,channel:e};return t&&(d=this.extend(d,this.createWSAuth(e,r))),await this.watchMultiple(n,a,d,a)}async unSubscribeMultiple(e,t,i,s,r={}){if(this.safeBool(this.options,"unSubscriptionPending",!1))throw new a.ExchangeError(this.id+" another unSubscription is pending, coinbase does not support concurrent unSubscriptions");this.options.unSubscriptionPending=!0,void 0===this.markets&&await this.loadMarkets();let o=[],n=[],d=[],h=this.marketSymbols(s,void 0,!1);for(let e=0;e<h.length;e++){let i=h[e],s=this.market(i).id;o.push(s),n.push(t+"::"+i),d.push("unsubscribe:"+t+"::"+i)}let c=this.urls.api.ws,l={type:"unsubscribe",product_ids:o,channel:t};i&&(l=this.extend(l,this.createWSAuth(t,o)));let u={messageHashes:d,subMessageHashes:n,topic:e,unsubscribe:!0,symbols:h};this.options.unSubscription=u;let f=await this.watchMultiple(c,d,l,d,u);return this.options.unSubscriptionPending=!1,this.options.unSubscription=void 0,f}createWSAuth(e,t){let i={},r=this.numberToString(this.seconds());this.checkRequiredCredentials();let o=this.apiKey.indexOf("organizations/")>=0||this.secret.startsWith("-----BEGIN"),n=r+e+t.join(",");if(o){if(this.apiKey.startsWith("-----BEGIN"))throw new a.ArgumentsRequired(this.id+" apiKey should contain the name (eg: organizations/3b910e93....) and not the public key");let e=this.safeString(this.options,"wsToken"),t=this.safeInteger(this.options,"wsTokenTimestamp",0),s=this.seconds();if(void 0===e||t+120<s){let e=this.createAuthToken(s);this.options.wsToken=e,this.options.wsTokenTimestamp=s}i.jwt=this.safeString(this.options,"wsToken")}else i.api_key=this.apiKey,i.timestamp=r,i.signature=this.hmac(this.encode(n),this.encode(this.secret),s.sc);return i}async watchTicker(e,t={}){return void 0===this.markets&&await this.loadMarkets(),await this.subscribe("ticker",!1,e,t)}async unWatchTicker(e,t={}){return void 0===this.markets&&await this.loadMarkets(),await this.unSubscribe("ticker","ticker",!1,e)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=e;void 0===e&&(i=this.symbols);let s=await this.subscribeMultiple("ticker_batch",!1,i,t);if(this.newUpdates){let e={};return e[s.symbol]=s,e}return this.tickers}async unWatchTickers(e,t={}){return(void 0===this.markets&&await this.loadMarkets(),void 0===e)?await this.unSubscribeMultiple("ticker","ticker_batch",!1,this.symbols):await this.unSubscribeMultiple("ticker","ticker_batch",!1,e)}handleTickers(e,t){let i=this.safeString(t,"channel"),s=this.safeList(t,"events",[]),r=this.safeString(t,"timestamp"),a=this.parse8601(r),o=[];for(let t=0;t<s.length;t++){let n=this.safeDict(s,t),d=this.safeList(n,"tickers",[]);for(let t=0;t<d.length;t++){let s=d[t];if(void 0===this.safeString(s,"product_id"))continue;let n=this.parseWsTicker(s);n.timestamp=a,n.datetime=r;let h=n.symbol;if(void 0!==h&&(this.tickers[h]=n),o.push(n),void 0!==i){let t=i+"::"+h;e.resolve(n,t),this.tryResolveUsdc(e,t,n)}}}}parseWsTicker(e,t){let i=this.safeString(e,"product_id"),s,r=this.safeNumber(e,"price");return this.safeTicker({info:e,symbol:this.safeSymbol(i,t,"-"),timestamp:s,datetime:this.iso8601(s),high:this.safeString(e,"high_24_h"),low:this.safeString(e,"low_24_h"),bid:this.safeString(e,"best_bid"),bidVolume:this.safeString(e,"best_bid_quantity"),ask:this.safeString(e,"best_ask"),askVolume:this.safeString(e,"best_ask_quantity"),vwap:void 0,open:void 0,close:r,last:r,previousClose:void 0,change:void 0,percentage:this.safeString(e,"price_percent_chg_24_h"),average:void 0,baseVolume:this.safeString(e,"volume_24_h"),quoteVolume:void 0})}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.symbol(e),a=await this.subscribe("market_trades",!1,r,s),o=i;return this.newUpdates&&(o=a.getLimit(r,i)),this.filterBySinceLimit(a,t,o,"timestamp",!0)}async unWatchTrades(e,t={}){return void 0===this.markets&&await this.loadMarkets(),await this.unSubscribe("trades","market_trades",!1,e)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.subscribeMultiple("market_trades",!1,e,s),a=this.safeDict(r,0),o=this.safeString(a,"symbol"),n=i;return this.newUpdates&&(n=r.getLimit(o,i)),this.filterBySinceLimit(r,t,n,"timestamp",!0)}async unWatchTradesForSymbols(e,t={}){return void 0===this.markets&&await this.loadMarkets(),await this.unSubscribeMultiple("trades","market_trades",!1,e,t)}async watchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.subscribe("user",!0,e,s),a=i;return this.newUpdates&&(a=r.getLimit(e,i)),this.filterBySinceLimit(r,t,a,"timestamp",!0)}async unWatchOrders(e,t={}){return void 0===this.markets&&await this.loadMarkets(),await this.unSubscribe("orders","user",!0,this.symbol(e))}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e).symbol;return(await this.subscribe("level2",!1,s,i)).limit()}async unWatchOrderBook(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.symbol(e);return await this.unSubscribe("orderbook","level2",!1,i)}async watchOrderBookForSymbols(e,t,i={}){return void 0===this.markets&&await this.loadMarkets(),(await this.subscribeMultiple("level2",!1,e,i)).limit()}handleTrade(e,t){let i=this.safeList(t,"events");if(void 0===i)return;let s=this.safeDict(i,0),r=this.safeList(s,"trades"),a=this.safeDict(r,0),n=this.safeString(a,"product_id"),d=this.safeSymbol(n),h="market_trades::"+d,c=this.safeValue(this.trades,d);if(void 0===c){let e=this.safeInteger(this.options,"tradesLimit",1e3);c=new o.Pt(e),this.trades[d]=c}for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),s=this.safeList(t,"trades");if(void 0===s)continue;let r=s.length;for(let e=0;e<r;e++){let t=s[r-e-1];c.append(this.parseTrade(t))}}e.resolve(c,h),this.tryResolveUsdc(e,h,c)}handleOrder(e,t){let i=this.safeList(t,"events");if(void 0===i)return;let s=[];if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),r=this.safeList(t,"orders");if(void 0!==r)for(let e=0;e<r.length;e++){let t=r[e],i=this.parseWsOrder(t),a=this.orders,o=this.safeString(t,"product_id");void 0===o||o in s||s.push(o),a.append(i)}}for(let t=0;t<s.length;t++){let i=s[t],r="user::"+this.safeSymbol(i);e.resolve(this.orders,r),this.tryResolveUsdc(e,r,this.orders)}e.resolve(this.orders,"user")}parseWsOrder(e,t){let i=this.safeString(e,"order_id"),s=this.safeString(e,"client_order_id"),r=this.safeString(e,"product_id"),a=this.safeString2(e,"time","creation_time"),o=this.safeMarket(r,t),n=this.safeString(e,"stop_price");return this.safeOrder({info:e,symbol:this.safeString(o,"symbol"),id:i,clientOrderId:s,timestamp:this.parse8601(a),datetime:a,lastTradeTimestamp:void 0,type:this.safeString(e,"order_type"),timeInForce:void 0,postOnly:void 0,side:this.safeStringLower2(e,"side","order_side"),price:this.safeString(e,"limit_price"),stopPrice:n,triggerPrice:n,amount:this.safeString(e,"cumulative_quantity"),cost:this.omitZero(this.safeString(e,"filled_value")),average:this.safeString(e,"avg_price"),filled:this.safeString(e,"cumulative_quantity"),remaining:this.safeString(e,"leaves_quantity"),status:this.parseOrderStatus(this.safeString(e,"status")),fee:{amount:this.safeString(e,"total_fees"),currency:this.safeString(o,"quote")},trades:void 0})}handleOrderBookHelper(e,t){for(let i=0;i<t.length;i++){let s=this.safeDict(t,i),r=this.safeString(s,"side"),a=this.safeString(this.options.sides,r),o=this.safeNumber(s,"price_level"),n=this.safeNumber(s,"new_quantity");this.safeValue(e,a).store(o,n)}}handleOrderBook(e,t){let i=this.safeList(t,"events");if(void 0===i)return;let s=this.safeString(t,"timestamp");for(let t=0;t<i.length;t++){let r=this.safeDict(i,t),a=this.safeList(r,"updates",[]),o=this.safeString(r,"product_id"),n=this.safeMarket(o).symbol,d="level2::"+n,h=this.safeDict(e.subscriptions,d,{}),c=this.safeInteger(h,"limit");if("snapshot"===this.safeString(r,"type")&&(this.orderbooks[n]=this.orderBook({},c)),!(n in this.orderbooks)&&void 0===this.orderbooks[n])continue;let l=this.orderbooks[n];this.handleOrderBookHelper(l,a),l.timestamp=this.parse8601(s),l.datetime=s,l.symbol=n,e.resolve(l,d),this.tryResolveUsdc(e,d,l)}}tryResolveUsdc(e,t,i){(t.endsWith("/USD")||t.endsWith("-USD"))&&e.resolve(i,t+"C")}handleSubscriptionStatus(e,t){let i=this.safeList(t,"events",[]),s=this.safeDict(i,0,{}),r="subscriptions"in s,a=Object.keys(s.subscriptions).length;if(r&&0===a){let t=this.safeDict(this.options,"unSubscription",{}),i=this.safeList(t,"messageHashes",[]),s=this.safeList(t,"subMessageHashes",[]);for(let t=0;t<i.length;t++){let r=i[t],a=s[t];this.cleanUnsubscription(e,a,r)}this.cleanCache(t)}return t}handleHeartbeats(e,t){return t}handleMessage(e,t){let i=this.safeString(t,"channel"),s={subscriptions:this.handleSubscriptionStatus,ticker:this.handleTickers,ticker_batch:this.handleTickers,market_trades:this.handleTrade,user:this.handleOrder,l2_data:this.handleOrderBook,heartbeats:this.handleHeartbeats};if("error"===this.safeString(t,"type")){let e=this.safeString(t,"message"),i="unknown error";throw void 0!==e&&(i=e),new a.ExchangeError(i)}let r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}}i.d(t,{A:()=>n})},4867(e,t,i){"use strict";var s=i(4721),r=i(7455),a=i(1453),o=i(1697),n=i(7749);class d extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchOHLCV:!1,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!0,watchMyTradesForSymbols:!0,watchBalance:!1,watchStatus:!1,watchOrders:!0,watchOrdersForSymbols:!0,watchMyTrades:!0},urls:{api:{ws:"wss://ws-feed.exchange.coinbase.com"},test:{ws:"wss://ws-feed-public.sandbox.exchange.coinbase.com"}},options:{tradesLimit:1e3,ordersLimit:1e3,myTradesLimit:1e3}})}authenticate(){this.checkRequiredCredentials();let e=this.nonce(),t=e.toString()+"GET/users/self/verify",i=this.hmac(this.encode(t),this.base64ToBinary(this.secret),s.sc,"base64");return{timestamp:e,key:this.apiKey,signature:i,passphrase:this.password}}async subscribe(e,t,i,s={}){let r;if(void 0===i)throw new a.ArgumentsRequired(this.id+" "+e+" subscription requires a messageHashStart argument");void 0===this.markets&&await this.loadMarkets();let o=i,n=[];void 0!==t&&(o+=":"+(r=this.market(t)).id,n.push(r.id));let d=this.safeString(this.urls.api,"ws");if(void 0===d)throw new a.ExchangeError(this.id+" urls.api.ws is not set");"signature"in s&&(d+="?");let h=this.extend({type:"subscribe",product_ids:n,channels:[e]},s);return await this.watch(d,o,h,o)}async subscribeMultiple(e,t=[],i,s={}){let r;if(void 0===i)throw new a.ArgumentsRequired(this.id+" "+e+" subscription requires a messageHashStart argument");void 0===this.markets&&await this.loadMarkets();let o=this.marketSymbols(t),n=[],d=[];for(let e=0;e<o.length;e++){let t=o[e];r=this.market(t),d.push(r.id),n.push(i+":"+r.symbol)}let h=this.safeString(this.urls.api,"ws");if(void 0===h)throw new a.ExchangeError(this.id+" urls.api.ws is not set");"signature"in s&&(h+="?");let c=this.extend({type:"subscribe",product_ids:d,channels:[e]},s);return await this.watchMultiple(h,n,c,n)}async watchTicker(e,t={}){let i="ticker";return await this.subscribe(i,e,i,t)}async watchTickers(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ArgumentsRequired(this.id+" watchTickers() symbols is required");if(0===e.length)throw new a.BadSymbol(this.id+" watchTickers requires a non-empty symbols array");let i=await this.subscribeMultiple("ticker",e,"ticker",t);if(this.newUpdates){let e={},t=this.safeString(i,"symbol");return void 0!==t&&(e[t]=i),e}return this.filterByArray(this.tickers,"symbol",e)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.symbol(e),a="matches",o=await this.subscribe(a,r,a,s),n=i;return this.newUpdates&&(n=o.getLimit(r,i)),this.filterBySinceLimit(o,t,n,"timestamp",!0)}async watchTradesForSymbols(e,t,i,s={}){if(0===e.length)throw new a.BadRequest(this.id+" watchTradesForSymbols() requires a non-empty array of symbols");void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e),o="matches",n=await this.subscribeMultiple(o,r,o,s),d=this.safeDict(n,0),h=this.safeString(d,"symbol"),c=i;return this.newUpdates&&(c=n.getLimit(h,i)),this.filterBySinceLimit(n,t,c,"timestamp",!0)}async watchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" watchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let r=this.symbol(e),o=this.authenticate(),n=await this.subscribe("user",r,"myTrades",this.extend(s,o)),d=i;return this.newUpdates&&(d=n.getLimit(r,i)),this.filterBySinceLimit(n,t,d,"timestamp",!0)}async watchMyTradesForSymbols(e,t,i,s={}){let r=this.marketSymbols(e,void 0,!1);void 0===this.markets&&await this.loadMarkets();let a=this.authenticate(),o=await this.subscribeMultiple("user",r,"myTrades",this.extend(s,a)),n=this.safeDict(o,0),d=this.safeString(n,"symbol"),h=i;return this.newUpdates&&(h=o.getLimit(d,i)),this.filterBySinceLimit(o,t,h,"timestamp",!0)}async watchOrdersForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!1),a=this.authenticate(),o=await this.subscribeMultiple("user",r,"orders",this.extend(s,a)),n=this.safeDict(o,0),d=this.safeString(n,"symbol"),h=i;return this.newUpdates&&(h=o.getLimit(d,i)),this.filterBySinceLimit(o,t,h,"timestamp",!0)}async watchOrders(e,t,i,s={}){if(void 0===e)throw new a.BadSymbol(this.id+" watchMyTrades requires a symbol");void 0===this.markets&&await this.loadMarkets();let r=this.symbol(e),o=this.authenticate(),n=await this.subscribe("user",r,"orders",this.extend(s,o)),d=i;return this.newUpdates&&(d=n.getLimit(r,i)),this.filterBySinceLimit(n,t,d,"timestamp",!0)}async watchOrderBookForSymbols(e,t,i={}){let s=e.length;if(0===s)throw new a.BadRequest(this.id+" watchOrderBookForSymbols() requires a non-empty array of symbols");let r="level2";void 0===this.markets&&await this.loadMarkets();let o=this.marketSymbols(e),n=this.marketIds(o),d=[];for(let e=0;e<s;e++){let t=n[e];d.push(r+":"+t)}let h=this.urls.api.ws,c=this.extend({type:"subscribe",product_ids:n,channels:[r]},i),l=this.authenticate();return(await this.watchMultiple(h,d,this.extend(c,l),d,{messageHash:r,symbols:o,marketIds:n,limit:t})).limit()}async watchOrderBook(e,t,i={}){let s="level2";void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o=s+":"+r.id,n=this.urls.api.ws,d={type:"subscribe",product_ids:[r.id],channels:[s]},h=this.extend(d,i),c={messageHash:o,symbol:a,marketId:r.id,limit:t},l=this.authenticate();return(await this.watch(n,o,this.extend(h,l),o,c)).limit()}handleTrade(e,t){let i=this.safeString(t,"product_id");if(void 0!==i){let s=this.parseWsTrade(t),r=s.symbol,a=this.safeValue(this.trades,r);if(void 0===a){let e=this.safeInteger(this.options,"tradesLimit",1e3);a=new o.I3(e),void 0!==r&&(this.trades[r]=a)}a.append(s),e.resolve(a,"matches:"+i)}return t}handleMyTrade(e,t){let i=this.safeString(t,"product_id");if(void 0!==i){let s=this.parseWsTrade(t),r=this.myTrades;if(void 0===r){let e=this.safeInteger(this.options,"myTradesLimit",1e3);r=new o.Pt(e),this.myTrades=r}r.append(s),e.resolve(r,"myTrades:"+i)}return t}parseWsTrade(e,t){let i,s,r=super.parseTrade(e),a=!1;if("maker_fee_rate"in e)a=!0,r.takerOrMaker="maker",i=this.safeString(e,"maker_fee_rate");else{r.takerOrMaker="taker",i=this.safeString(e,"taker_fee_rate");let t=r.side;r.side=this.safeString({buy:"sell",sell:"buy"},t,t)}let o="taker_order_id";a&&(o="maker_order_id"),r.order=this.safeString(e,o);let d=this.market(r.symbol).quote;if(void 0!==r.cost&&void 0!==i){let e=this.safeString(r,"cost");s=n.A.stringMul(e,i)}return r.fee={rate:this.parseNumber(i),cost:this.parseNumber(s),currency:d},r}parseWsOrderStatus(e){return this.safeString({filled:"closed",canceled:"canceled"},e,"open")}handleOrder(e,t){let i=this.orders;if(void 0===i){let e=this.safeInteger(this.options,"ordersLimit",1e3);i=new o.Pt(e),this.orders=i}let s=this.safeString(t,"type"),r=this.safeString(t,"product_id");if(void 0!==r){let i="orders:"+r,a=this.safeSymbol(r),o=this.safeString(t,"order_id"),d=this.safeString(t,"maker_order_id"),h=this.safeString(t,"taker_order_id"),c=this.orders;if(void 0===c)return;let l=this.safeDict(c.hashmap,a,{}),u=this.safeDict(l,o);if(void 0===u&&(u=this.safeDictN(l,[d,h])),void 0===u){let s=this.parseWsOrder(t);c.append(s),e.resolve(c,i)}else{let r=this.safeInteger(t,"sequence");if(void 0===r)return;let a=this.safeDict(u,"info",{}),o=this.safeInteger(a,"sequence");if(void 0===o||r>o){if("match"===s){let s=this.parseWsTrade(t);void 0===u.trades&&(u.trades=[]),u.trades.push(s),u.lastTradeTimestamp=s.timestamp;let r="0",a="0",o=u.trades;for(let e=0;e<o.length;e++){let t=this.safeDict(o,e);r=this.safeString(t,"cost","0"),a=this.safeString(t,"amount","0")}n.A.stringEq(a,"0")||(u.average=this.parseNumber(n.A.stringDiv(r,a))),u.cost=this.parseNumber(r);let d=this.safeString(u,"filled");if(void 0!==d&&(u.filled=this.parseNumber(n.A.stringAdd(d,this.safeString(s,"amount"))),void 0!==u.amount&&(u.remaining=this.parseNumber(n.A.stringSub(this.safeString(u,"amount"),this.safeString(u,"filled"))))),void 0===u.fee&&(u.fee={cost:0,currency:this.safeString(s.fee,"currency")}),void 0!==u.fee.cost&&void 0!==this.safeNumber(s.fee,"cost")){u.fee.cost=this.sum(u.fee.cost,this.safeNumber(s.fee,"cost"));let e=this.safeDict(u,"fee"),t=this.safeDict(s,"fee");u.fee.cost=this.parseNumber(n.A.stringAdd(this.safeString(e,"cost"),this.safeString(t,"cost")))}c.append(u),e.resolve(c,i)}else if("received"===s||"done"===s){let s=this.extend(u.info,t),r=this.parseWsOrder(s),a=Object.keys(r);for(let e=0;e<a.length;e++){let t=a[e];void 0!==r[t]&&(u[t]=r[t])}if(void 0===c)return;c.append(u),e.resolve(c,i)}}}}}parseWsOrder(e,t){let i,s=this.safeString(e,"order_id"),r=this.safeString(e,"client_oid"),a=this.safeString(e,"product_id"),o=this.safeSymbol(a),d=this.safeString(e,"side"),h=this.safeNumber(e,"price"),c=this.safeString2(e,"size","funds"),l=this.safeString(e,"time"),u=this.parse8601(l),f=this.safeString(e,"reason"),p=this.parseWsOrderStatus(f),m=this.safeString(e,"order_type"),g=this.safeString(e,"remaining_size"),v=this.safeString(e,"type");return void 0!==c&&void 0!==g?i=n.A.stringSub(c,g):"received"===v&&(i="0",void 0!==c&&(g=n.A.stringSub(c,i))),this.safeOrder({info:e,symbol:o,id:s,clientOrderId:r,timestamp:u,datetime:this.iso8601(u),lastTradeTimestamp:void 0,type:m,timeInForce:void 0,postOnly:void 0,side:d,price:h,stopPrice:void 0,triggerPrice:void 0,amount:this.parseNumber(c),cost:void 0,average:void 0,filled:this.parseNumber(i),remaining:this.parseNumber(g),status:p,fee:void 0,trades:void 0})}handleTicker(e,t){let i=this.safeString(t,"product_id");if(void 0!==i){let s=this.parseTicker(t),r=s.symbol;void 0!==r&&(this.tickers[r]=s),e.resolve(s,"ticker:"+r),e.resolve(s,"ticker:"+i)}return t}parseTicker(e,t){if(void 0===this.safeString(e,"type"))return super.parseTicker(e,t);let i=this.safeString(e,"product_id"),s=this.safeSymbol(i,t,"-"),r=this.parse8601(this.safeString(e,"time")),a=this.safeString(e,"price");return this.safeTicker({symbol:s,timestamp:r,datetime:this.iso8601(r),high:this.safeString(e,"high_24h"),low:this.safeString(e,"low_24h"),bid:this.safeString(e,"best_bid"),bidVolume:this.safeString(e,"best_bid_size"),ask:this.safeString(e,"best_ask"),askVolume:this.safeString(e,"best_ask_size"),vwap:void 0,open:this.safeString(e,"open_24h"),close:a,last:a,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"volume_24h"),quoteVolume:void 0,info:e})}handleDelta(e,t){let i=this.safeNumber(t,0),s=this.safeNumber(t,1);e.store(i,s)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}handleOrderBook(e,t){let i=this.safeString(t,"type"),s=this.safeString(t,"product_id"),r=this.safeMarket(s,void 0,"-").symbol,a="level2:"+s,o=this.safeDict(e.subscriptions,a,{}),n=this.safeInteger(o,"limit");if("snapshot"===i){this.orderbooks[r]=this.orderBook({},n);let i=this.orderbooks[r];this.handleDeltas(i.asks,this.safeList(t,"asks",[])),this.handleDeltas(i.bids,this.safeList(t,"bids",[])),i.timestamp=void 0,i.datetime=void 0,i.symbol=r,e.resolve(i,a)}else if("l2update"===i){let i=this.orderbooks[r],s=this.parse8601(this.safeString(t,"time")),o=this.safeList(t,"changes",[]),n={sell:"asks",buy:"bids"};for(let e=0;e<o.length;e++){let t=this.safeList(o,e),s=this.safeString(t,0),r=this.safeString(n,s),a=this.safeNumber(t,1),d=this.safeNumber(t,2);this.safeValue(i,r).store(a,d)}i.timestamp=s,i.datetime=this.iso8601(s),e.resolve(i,a)}}handleSubscriptionStatus(e,t){return t}handleErrorMessage(e,t){let i=this.safeString(t,"message"),s=this.safeString(t,"reason");try{if("Authentication Failed"===i)throw new a.AuthenticationError("Authentication failed: "+s);throw new a.ExchangeError(this.id+" "+s)}catch(t){return e.reject(t),!0}}handleMessage(e,t){let i=this.safeString(t,"type"),s={snapshot:this.handleOrderBook,l2update:this.handleOrderBook,subscribe:this.handleSubscriptionStatus,ticker:this.handleTicker,received:this.handleOrder,open:this.handleOrder,change:this.handleOrder,done:this.handleOrder,error:this.handleErrorMessage},r=e.url.length-0,a="?"===e.url[r-1],o=this.safeValue(s,i);void 0===o?"match"===i&&(a?(this.handleMyTrade(e,t),this.handleOrder(e,t)):this.handleTrade(e,t)):o.call(this,e,t)}}i.d(t,{A:()=>d})},2896(e,t,i){"use strict";var s=i(4721),r=i(5700),a=i(1453),o=i(1697);class n extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchTrades:!0,watchTradesForSymbols:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchTicker:!0,watchBalance:!1,watchMyTrades:!1,watchOHLCV:!0,watchOHLCVForSymbols:!1,watchOrders:!1,watchOrdersForSymbols:!1,watchPositions:!1,watchTickers:!0,createOrderWs:!1,editOrderWs:!1,cancelOrderWs:!1,cancelOrdersWs:!1,cancelAllOrdersWs:!1,fetchOrderWs:!1,fetchOrdersWs:!1,fetchBalanceWs:!1,fetchMyTradesWs:!1},urls:{api:{ws:"wss://ws-md.international.coinbase.com"},test:{ws:"wss://ws-md.n5e2.coinbase.com"}},options:{watchTicker:{channel:"LEVEL1"},tradesLimit:1e3,ordersLimit:1e3,myTradesLimit:1e3,timeframes:{"1m":"CANDLES_ONE_MINUTE","5m":"CANDLES_FIVE_MINUTES","30m":"CANDLES_THIRTY_MINUTES","1h":"CANDLES_ONE_HOUR","2h":"CANDLES_TWO_HOURS","1d":"CANDLES_ONE_DAY"}},exceptions:{exact:{"Unable to authenticate":a.AuthenticationError}}})}async subscribe(e,t,i={}){let r,o;void 0===this.markets&&await this.loadMarkets(),this.checkRequiredCredentials();let n=e,d=void 0===t?this.getActiveSymbols():t,h=d.length,c=[];if(h>1){let t=this.marketSymbols(d);o=this.marketIds(t);for(let i=0;i<t.length;i++)c.push(e+"::"+t[i])}else 1===h&&(n=e+"::"+(r=this.market(d[0])).symbol,o=[r.id]);let l=this.safeString(this.urls.api,"ws");if(void 0===l)throw new a.NotSupported(this.id+" is not supported in sandbox environment");let u=this.nonce().toString(),f=u+this.apiKey+"CBINTLMD"+this.password,p=this.hmac(this.encode(f),this.base64ToBinary(this.secret),s.sc,"base64"),m={type:"SUBSCRIBE",channels:[e],time:u,key:this.apiKey,passphrase:this.password,signature:p};return(void 0!==o&&(m.product_ids=o),h>1)?await this.watchMultiple(l,c,this.extend(m,i),c):await this.watch(l,n,this.extend(m,i),n)}async subscribeMultiple(e,t,i={}){let r;void 0===this.markets&&await this.loadMarkets(),this.checkRequiredCredentials(),r=this.isEmpty(t)?this.symbols:this.marketSymbols(t);let o=[],n=[];for(let t=0;t<r.length;t++){let i=this.marketId(r[t]),s=this.symbol(i);n.push(i),o.push(e+"::"+s)}let d=this.safeString(this.urls.api,"ws");if(void 0===d)throw new a.NotSupported(this.id+" is not supported in sandbox environment");let h=this.numberToString(this.seconds()),c=h+this.apiKey+"CBINTLMD"+this.password,l=this.hmac(this.encode(c),this.base64ToBinary(this.secret),s.sc,"base64"),u={type:"SUBSCRIBE",time:h,product_ids:n,channels:[e],key:this.apiKey,passphrase:this.password,signature:l};return await this.watchMultiple(d,o,this.extend(u,i),o)}watchFundingRate(e,t={}){return this.subscribe("RISK",[e],t)}async watchFundingRates(e,t={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" watchFundingRates() requires an array of symbols");void 0===this.markets&&await this.loadMarkets();let i=await this.subscribeMultiple("RISK",e,t),s=this.safeString(i,"symbol");if(this.newUpdates){let e={};return e[s]=i,e}return this.filterByArray(this.fundingRates,"symbol",e)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionStringAndParams(t,"watchTicker","channel","LEVEL1");return await this.subscribe(i,[e],s)}getActiveSymbols(){let e=this.symbols,t=[];for(let i=0;i<e.length;i++){let s=e[i];!0===this.market(s).active&&t.push(s)}return t}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionStringAndParams(t,"watchTickers","channel","LEVEL1"),r=await this.subscribe(i,e,s);if(this.newUpdates){let e={},t=this.safeString(r,"symbol");return void 0!==t&&(e[t]=r),e}return this.filterByArray(this.tickers,"symbol",e)}handleInstrument(e,t){let i=this.parseWsInstrument(t),s=this.safeString(t,"channel");e.resolve(i,s),void 0!==s&&e.resolve(i,s+"::"+i.symbol)}parseWsInstrument(e,t){let i=this.safeString(e,"product_id"),s=this.safeString(e,"time");return this.safeTicker({info:e,symbol:this.safeSymbol(i,t,"-"),timestamp:this.parse8601(s),datetime:s,high:void 0,low:void 0,bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:void 0,close:void 0,last:void 0,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString2(e,"total_24_hour_quantity","total24_hour_quantity"),quoteVolume:this.safeString2(e,"total_24_hour_volume","total24_hour_volume")})}handleTicker(e,t){let i=this.parseWsTicker(t),s=this.safeString(t,"channel");e.resolve(i,s),void 0!==s&&e.resolve(i,s+"::"+i.symbol)}parseWsTicker(e,t){let i=this.safeString(e,"time"),s=this.safeString(e,"product_id");return this.safeTicker({info:e,symbol:this.safeSymbol(s,t),timestamp:this.parse8601(i),datetime:i,bid:this.safeNumber(e,"bid_price"),bidVolume:this.safeNumber(e,"bid_qty"),ask:this.safeNumber(e,"ask_price"),askVolume:this.safeNumber(e,"ask_qty"),high:void 0,low:void 0,open:void 0,close:void 0,last:void 0,change:void 0,percentage:void 0,average:void 0,vwap:void 0,baseVolume:void 0,quoteVolume:void 0,previousClose:void 0})}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e).symbol,o=this.safeDict(this.options,"timeframes",{}),n=this.safeString(o,t,t),d=await this.subscribe(n,[a],r),h=s;return this.newUpdates&&(h=d.getLimit(a,s)),this.filterBySinceLimit(d,i,h,0,!0)}handleOHLCV(e,t){let i=this.safeString(t,"channel"),s=this.safeString(t,"product_id"),r=this.safeMarket(s),a=r.symbol,n=this.findTimeframe(i);if(this.ohlcvs[a]=this.safeDict(this.ohlcvs,a,{}),void 0===this.safeDict(this.ohlcvs[a],n)){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);this.ohlcvs[a][n]=new o.TG(e)}let d=this.ohlcvs[a][n],h=this.safeList(t,"candles",[]);for(let e=0;e<h.length;e++){let t=this.safeDict(h,e),i=this.parseOHLCV(t,r);d.append(i)}void 0!==i&&e.resolve(d,i+"::"+a)}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!1,!0,!0),a=await this.subscribeMultiple("MATCH",r,s),o=i;if(this.newUpdates){let e=this.safeDict(a,0),t=this.safeString(e,"symbol");o=a.getLimit(t,i)}return this.filterBySinceLimit(a,t,o,"timestamp",!0)}handleTrade(e,t){let i=this.parseWsTrade(t),s=i.symbol,r=this.safeString(t,"channel");if(!(s in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3),t=new o.I3(e);this.trades[s]=t}let a=this.trades[s];return a.append(i),this.trades[s]=a,e.resolve(a,r),void 0!==r&&e.resolve(a,r+"::"+i.symbol),t}parseWsTrade(e,t){let i=this.safeString2(e,"symbol","product_id"),s=this.safeString(e,"time");return this.safeTrade({info:e,id:this.safeString(e,"match_id"),order:void 0,timestamp:this.parse8601(s),datetime:s,symbol:this.safeSymbol(i,t),type:void 0,side:this.safeStringLower(e,"agressor_side"),takerOrMaker:void 0,price:this.safeString(e,"trade_price"),amount:this.safeString(e,"trade_qty"),cost:void 0,fee:void 0})}watchOrderBook(e,t,i={}){return this.watchOrderBookForSymbols([e],t,i)}watchOrderBookForSymbols(e,t,i={}){return this.subscribeMultiple("LEVEL2",e,i)}handleOrderBook(e,t){let i=this.safeString(t,"type"),s=this.safeString(t,"product_id"),r=this.safeSymbol(s),a=this.safeString(t,"time"),o=this.safeString(t,"channel");if(!(r in this.orderbooks)){let e=this.safeInteger(this.options,"watchOrderBookLimit",1e3);this.orderbooks[r]=this.orderBook({},e)}let n=this.orderbooks[r];if("SNAPSHOT"===i){let e=this.parseOrderBook(t,r,void 0,"bids","asks");n.reset(e),n.symbol=r}else{let e=this.safeList(t,"changes",[]);this.handleBookDeltas(n,e)}n.nonce=this.safeInteger(t,"sequence"),n.datetime=a,n.timestamp=this.parse8601(a),this.orderbooks[r]=n,void 0!==o&&e.resolve(n,o+"::"+r)}handleBookDelta(e,t){let i=this.safeStringLower(t,0),s="asks";"buy"===i&&(s="bids");let r=this.safeFloat(t,1),a=this.safeFloat(t,2);e[s].store(r,a)}handleBookDeltas(e,t){for(let i=0;i<t.length;i++)this.handleBookDelta(e,t[i])}handleSubscriptionStatus(e,t){return t}handleFundingRate(e,t){let i=this.safeString(t,"channel"),s=this.parseFundingRate(t);this.fundingRates[s.symbol]=s,void 0!==i&&e.resolve(s,i+"::"+s.symbol)}handleErrorMessage(e,t){if("REJECT"!==this.safeString(t,"type"))return!1;let i=this.safeString(t,"reason"),s=this.safeString(t,"message");try{let e=this.id+" "+s+i;throw this.throwExactlyMatchedException(this.exceptions.exact,i,e),this.throwBroadlyMatchedException(this.exceptions.broad,i,e),new a.ExchangeError(e)}catch(t){e.reject(t)}return!0}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;let i=this.safeString(t,"channel",""),s={SUBSCRIPTIONS:this.handleSubscriptionStatus,INSTRUMENTS:this.handleInstrument,LEVEL1:this.handleTicker,MATCH:this.handleTrade,LEVEL2:this.handleOrderBook,FUNDING:this.handleFundingRate,RISK:this.handleTicker};if("error"===this.safeString(t,"type")){let e=this.safeString(t,"message");throw new a.ExchangeError(e)}i.indexOf("CANDLES")>-1&&this.handleOHLCV(e,t);let r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}}i.d(t,{A:()=>n})},8951(e,t,i){"use strict";var s=i(2603),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchOrderBook:!0,watchOrders:!1,watchTrades:!0,watchTradesForSymbols:!1,watchOHLCV:!1,watchTicker:!1,watchTickers:!1},urls:{api:{ws:"wss://ws-api.coincheck.com/"}},options:{expiresIn:"",userId:"",wsSessionToken:"",watchOrderBook:{snapshotDelay:6,snapshotMaxRetries:3},tradesLimit:1e3,OHLCVLimit:1e3},exceptions:{exact:{4009:r.AuthenticationError}}})}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="orderbook:"+s.symbol,a=this.urls.api.ws,o={type:"subscribe",channel:s.id+"-orderbook"},n=this.extend(o,i);return(await this.watch(a,r,n,r)).limit()}handleOrderBook(e,t){let i=this.symbol(this.safeString(t,0)),s=this.safeDict(t,1,{}),r=this.safeTimestamp(s,"last_update_at"),a=this.parseOrderBook(s,i,r),o=this.safeValue(this.orderbooks,i);void 0===o?(o=this.orderBook(a),this.orderbooks[i]=o):(o=this.orderbooks[i]).reset(a);let n="orderbook:"+i;e.resolve(o,n)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o="trade:"+r.symbol,n=this.urls.api.ws,d={type:"subscribe",channel:r.id+"-trades"},h=this.extend(d,s),c=await this.watch(n,o,h,o),l=i;return this.newUpdates&&(l=c.getLimit(a,i)),this.filterBySinceLimit(c,t,l,"timestamp",!0)}handleTrades(e,t){let i=this.safeList(t,0,[]),s=this.symbol(this.safeString(i,2)),r=this.safeValue(this.trades,s);if(void 0===r){let e=this.safeInteger(this.options,"tradesLimit",1e3);r=new a.I3(e),this.trades[s]=r}for(let e=0;e<t.length;e++){let i=this.safeValue(t,e),s=this.parseWsTrade(i);r.append(s)}let o="trade:"+s;e.resolve(r,o)}parseWsTrade(e,t){let i=this.symbol(this.safeString(e,2)),s=this.safeTimestamp(e,0),r=this.safeString(e,5),a=this.safeString(e,3),o=this.safeString(e,4);return this.safeTrade({id:this.safeString(e,1),info:e,timestamp:s,datetime:this.iso8601(s),order:void 0,symbol:i,type:void 0,side:r,takerOrMaker:void 0,price:a,amount:o,cost:void 0,fee:void 0},t)}handleMessage(e,t){Array.isArray(this.safeValue(t,0))?this.handleTrades(e,t):this.handleOrderBook(e,t)}}i.d(t,{A:()=>o})},7778(e,t,i){"use strict";var s=i(4721),r=i(6494),a=i(1453),o=i(1697);class n extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchBidsAsks:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!0,watchMyTrades:!0,watchOrders:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOHLCV:!1,fetchOHLCVWs:!1},urls:{api:{ws:{spot:"wss://socket.coinex.com/v2/spot/",swap:"wss://socket.coinex.com/v2/futures/"}}},options:{ws:{gunzip:!0},timeframes:{"1m":60,"3m":180,"5m":300,"15m":900,"30m":1800,"1h":3600,"2h":7200,"4h":14400,"6h":21600,"12h":43200,"1d":86400,"3d":259200,"1w":604800},account:"spot",watchOrderBook:{limits:[5,10,20,50],defaultLimit:50,aggregations:["1000","100","10","1","0","0.1","0.01","0.001","0.0001","0.00001","0.000001","0.0000001","0.00000001","0.000000001","0.0000000001","0.00000000001"],defaultAggregation:"0"}},streaming:{},exceptions:{exact:{20001:a.BadRequest,20002:a.NotSupported,21001:a.AuthenticationError,21002:a.AuthenticationError,23001:a.RequestTimeout,23002:a.RateLimitExceeded,24001:a.ExchangeError,24002:a.ExchangeNotAvailable,30001:a.BadRequest,30002:a.NotSupported,31001:a.AuthenticationError,31002:a.AuthenticationError,33001:a.RequestTimeout,33002:a.RateLimitExceeded,34001:a.ExchangeError,34002:a.ExchangeNotAvailable},broad:{}}})}requestId(){this.lockId();let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,this.unlockId(),e}handleTicker(e,t){let i=this.safeString(this.options,"defaultType"),s=this.safeDict(t,"data",{}),r=this.safeList(s,"state_list",[]),a={};for(let e=0;e<r.length;e++){let t=r[e],s=this.safeString(t,"market"),o=this.safeSymbol(s,void 0,void 0,i),n=this.safeMarket(s,void 0,void 0,i),d=this.parseWSTicker(t,n);this.tickers[o]=d,a[o]=d}let o=this.findMessageHashes(e,"tickers::");for(let t=0;t<o.length;t++){let i=o[t],s=i.split("::")[1].split(","),r=this.filterByArray(a,"symbol",s);Object.keys(r).length>0&&e.resolve(r,i)}e.resolve(a,"tickers")}parseWSTicker(e,t){let i=this.safeString(this.options,"defaultType"),s=this.safeString(e,"market");return this.safeTicker({symbol:this.safeSymbol(s,t,void 0,i),timestamp:void 0,datetime:void 0,high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:void 0,bidVolume:this.safeString(e,"volume_buy"),ask:void 0,askVolume:this.safeString(e,"volume_sell"),vwap:void 0,open:this.safeString(e,"open"),close:this.safeString(e,"close"),last:this.safeString(e,"last"),previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"volume"),quoteVolume:this.safeString(e,"value"),info:e},t)}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleMarketTypeAndParams("watchBalance",void 0,e,"spot");await this.authenticate(t);let s=this.safeString(this.urls.api.ws,t);if(void 0===s)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let r=this.filterBy(this.currencies_by_id,"active",!0),o=Object.keys(this.indexBy(r,"id"));void 0===o&&(o=[]);let n="balances";"spot"===t?n+=":spot":n+=":swap";let d={method:"balance.subscribe",params:{ccy_list:o},id:this.requestId()},h=this.deepExtend(d,i);return await this.watch(s,n,h,n)}handleBalance(e,t){let i,s,r;void 0===this.balance&&(this.balance={});let a=this.safeDict(t,"data",{}),o=this.safeList(a,"balance_list",[]),n=this.safeDict(o,0),d=this.safeInteger(n,"updated_at"),h=this.safeString(n,"unrealized_pnl"),c=[];if(void 0!==d){s="spot";for(let e=0;e<o.length;e++)c=this.arrayConcat(c,o);i=c}if(void 0!==h){s="swap";for(let e=0;e<o.length;e++)c=this.arrayConcat(c,o);i=c}for(let e=0;e<c.length;e++){let t=c[e];this.parseWsBalance(t,s)}void 0!==s&&(void 0===this.safeDict(this.balance,s)&&(this.balance[s]={}),this.balance[s].info=i,this.balance[s]=this.safeBalance(this.balance[s]),r="balances:"+s,e.resolve(this.balance[s],r))}parseWsBalance(e,t){let i=this.account(),s=this.safeString(e,"ccy"),r=this.safeCurrencyCode(s);i.free=this.safeString(e,"available"),i.used=this.safeString(e,"frozen"),void 0!==t?(void 0===this.safeDict(this.balance,t)&&(this.balance[t]={}),void 0!==t&&void 0!==r&&(this.balance[t][r]=i)):void 0!==r&&(this.balance[r]=i)}async watchMyTrades(e,t,i,s={}){let r,o;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e),o=this.safeString(r,"symbol"));let[n,d]=this.handleMarketTypeAndParams("watchMyTrades",r,s,"spot");await this.authenticate(n);let h=this.safeString(this.urls.api.ws,n);if(void 0===h)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let c=[],l="myTrades";void 0!==r?(l+=":"+o,c.push(r.id)):"spot"===n?l+=":spot":l+=":swap";let u={method:"user_deals.subscribe",params:{market_list:c},id:this.requestId()},f=this.deepExtend(u,d),p=await this.watch(h,l,f,l),m=i;return this.newUpdates&&(m=p.getLimit(o,i)),this.filterBySymbolSinceLimit(p,o,t,m,!0)}handleMyTrades(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"market"),r=e.url.indexOf("spot")>-1,a="swap";r&&(a="spot");let n=this.safeMarket(s,void 0,void 0,a),d=n.symbol,h="myTrades:"+n.type,c=this.safeValue(this.trades,d);if(void 0===c){let e=this.safeInteger(this.options,"tradesLimit",1e3);c=new o.I3(e),this.trades[d]=c}let l=this.parseWsTrade(i,n);c.append(l),this.trades[d]=c,e.resolve(this.trades[d],h),e.resolve(this.trades[d],"myTrades:"+d)}handleTrades(e,t){let i=this.safeDict(t,"data",{}),s=this.safeList(i,"deal_list",[]),r=this.safeString(i,"market"),a=e.url.indexOf("spot")>-1,n="swap";a&&(n="spot");let d=this.safeMarket(r,void 0,void 0,n),h=d.symbol,c=this.safeValue(this.trades,h);if(void 0===c){let e=this.safeInteger(this.options,"tradesLimit",1e3);c=new o.I3(e),this.trades[h]=c}for(let e=0;e<s.length;e++){let t=s[e],i=this.parseWsTrade(t,d);c.append(i)}this.trades[h]=c,e.resolve(this.trades[h],"trades:"+h)}parseWsTrade(e,t){let i=this.safeInteger(e,"created_at"),s="swap";"margin_market"in e&&(s="spot");let r=this.safeString(e,"market"),a=this.safeMarket(r,t,void 0,s),o={},n=this.omitZero(this.safeString(e,"fee"));if(void 0!==n){let t=this.safeString(e,"fee_ccy",a.quote);o={currency:this.safeCurrencyCode(t),cost:n}}return this.safeTrade({id:this.safeString(e,"deal_id"),info:e,timestamp:i,datetime:this.iso8601(i),symbol:this.safeSymbol(r,a,void 0,s),order:this.safeString(e,"order_id"),type:void 0,side:this.safeString(e,"side"),takerOrMaker:this.safeString(e,"role"),price:this.safeString(e,"price"),amount:this.safeString(e,"amount"),cost:void 0,fee:o},a)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);return(await this.watchTickers([e],t))[i.symbol]}async watchTickers(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketIds(e),r=[];if(void 0!==e)for(let t=0;t<e.length;t++){let s=e[t];i=this.market(s),r.push("tickers::"+i.symbol)}else s=[],r.push("tickers");let[o,n]=this.handleMarketTypeAndParams("watchTickers",i,t),d=this.safeString(this.urls.api.ws,o);if(void 0===d)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let h={method:"state.subscribe",params:{market_list:s},id:this.requestId()},c=await this.watchMultiple(d,r,this.deepExtend(h,n),["all@ticker"]);return this.newUpdates?c:this.filterByArray(this.tickers,"symbol",e)}async watchTrades(e,t,i,s={}){return s.callerMethodName="watchTrades",await this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let o=[],n=[],[d,h]=this.handleParamString(s,"callerMethodName","watchTradesForSymbols");if(void 0!==e)for(let t=0;t<e.length;t++){let i=e[t];r=this.market(i),o.push(r.id),n.push("trades:"+r.symbol)}else n.push("trades");let[c,l]=this.handleMarketTypeAndParams(d,r,h),u=this.safeString(this.urls.api.ws,c);if(void 0===u)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let f={method:"deals.subscribe",params:{market_list:o},id:this.requestId()},p=await this.watchMultiple(u,n,this.deepExtend(f,l),n);return this.newUpdates?p:this.filterBySinceLimit(p,t,i,"timestamp",!0)}async watchOrderBookForSymbols(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r={},o=[],[n,d]=this.handleParamString(i,"callerMethodName","watchOrderBookForSymbols"),h=this.safeDict(this.options,"watchOrderBook",{}),c=this.safeList(h,"limits",[]),l=void 0===t?this.safeInteger(h,"defaultLimit",50):t;if(!this.inArray(l,c))throw new a.NotSupported(this.id+" watchOrderBookForSymbols() limit must be one of "+c.join(", "));let u=this.safeString(h,"defaultAggregation","0"),f=this.safeList(h,"aggregations",[]),p=this.safeString(d,"aggregation",u);if(!this.inArray(p,f))throw new a.NotSupported(this.id+" watchOrderBookForSymbols() aggregation must be one of "+f.join(", "));let m=this.omit(d,"aggregation");if(void 0===e)throw new a.ArgumentsRequired(this.id+" watchOrderBookForSymbols() requires a symbol argument");for(let t=0;t<e.length;t++){let i=e[t];s=this.market(i),o.push("orderbook:"+s.symbol),r[i]=[s.id,l,p,!0]}let[g,v]=this.handleMarketTypeAndParams(n,s,m),y={method:"depth.subscribe",params:{market_list:Object.values(r)},id:this.requestId()},b=this.safeString(this.urls.api.ws,g);if(void 0===b)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let w=await this.watchMultiple(b,o,this.deepExtend(y,v),o);return this.newUpdates?w:w.limit()}async watchOrderBook(e,t,i={}){return i.callerMethodName="watchOrderBook",await this.watchOrderBookForSymbols([e],t,i)}handleDelta(e,t){let i=this.parseOrderBookBidAsk(t,0,1);e.storeArray(i)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}handleOrderBook(e,t){let i=e.url.indexOf("spot")>-1,s="swap";i&&(s="spot");let r=this.safeDict(t,"data",{}),a=this.safeDict(r,"depth",{}),o=this.safeString(r,"market"),n=this.safeMarket(o,void 0,void 0,s).symbol,d="orderbook:"+n,h=this.safeInteger(a,"updated_at"),c=this.safeValue(this.orderbooks,n);if(!0===this.safeBool(r,"is_full",!1)){let e=this.parseOrderBook(a,n,h);void 0===c?this.orderbooks[n]=this.orderBook(e):this.orderbooks[n].reset(e)}else{let e=this.safeList(a,"asks",[]),t=this.safeList(a,"bids",[]);this.handleDeltas(c.asks,e),this.handleDeltas(c.bids,t),c.nonce=h,c.timestamp=h,c.datetime=this.iso8601(h),this.orderbooks[n]=c}e.resolve(this.orderbooks[n],d)}async watchOrders(e,t,i,s={}){let r,o,n;void 0===this.markets&&await this.loadMarkets();let d=this.safeBool2(s,"trigger","stop"),h=this.omit(s,["trigger","stop"]),c="orders";void 0!==e&&(r=this.market(e),n=this.safeString(r,"symbol"));let[l,u]=this.handleMarketTypeAndParams("watchOrders",r,h,"spot");await this.authenticate(l),void 0!==n?(o=[r.id],c+=":"+n):(o=[],"spot"===l?c+=":spot":c+=":swap");let f={method:!0===d?"stop.subscribe":"order.subscribe",params:{market_list:o},id:this.requestId()},p=this.safeString(this.urls.api.ws,l);if(void 0===p)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let m=this.deepExtend(f,u),g=await this.watch(p,c,m,c,m),v=i;return this.newUpdates&&(v=g.getLimit(n,i)),this.filterBySymbolSinceLimit(g,n,t,v,!0)}handleOrders(e,t){let i=this.safeDict(t,"data",{}),s=this.extend({status:this.safeString(i,"event")},this.safeDict2(i,"order","stop",{})),r=this.parseWsOrder(s),a=r.symbol,n=this.market(a);if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}this.orders.append(r);let d="orders",h=d+":"+n.type;e.resolve(this.orders,h),d+=":"+a,e.resolve(this.orders,d)}parseWsOrder(e,t){let i,s=this.safeInteger(e,"created_at"),r=this.safeString(e,"market"),a=this.safeString(e,"status"),o="swap";"margin_market"in e&&(o="spot");let n=this.safeMarket(r,t,void 0,o),d=this.omitZero(this.safeString2(e,"fee","quote_ccy_fee"));if(void 0!==d){let t=this.safeString(e,"fee_ccy",n.quote);i={currency:this.safeCurrencyCode(t),cost:d}}return this.safeOrder({info:e,id:this.safeString2(e,"order_id","stop_id"),clientOrderId:this.safeString(e,"client_id"),datetime:this.iso8601(s),timestamp:s,lastTradeTimestamp:this.safeInteger(e,"updated_at"),symbol:n.symbol,type:this.safeString(e,"type"),timeInForce:void 0,postOnly:void 0,side:this.safeString(e,"side"),price:this.safeString(e,"price"),stopPrice:this.safeString(e,"trigger_price"),triggerPrice:this.safeString(e,"trigger_price"),amount:this.safeString(e,"amount"),filled:this.safeString2(e,"filled_amount","fill_value"),remaining:this.safeString2(e,"unfilled_amount","unfill_amount"),cost:void 0,average:void 0,status:this.parseWsOrderStatus(a),fee:i,trades:void 0},n)}parseWsOrderStatus(e){return this.safeString({active_success:"open",active_fail:"canceled",cancel:"canceled",put:"open",update:"open",modify:"open",finish:"closed"},e,e)}async watchBidsAsks(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketIds(e),r=[];if(void 0!==e)for(let t=0;t<e.length;t++){let s=e[t];i=this.market(s),r.push("bidsasks:"+i.symbol)}else r.push("bidsasks");let[o,n]=this.handleMarketTypeAndParams("watchBidsAsks",i,t),d=this.safeString(this.urls.api.ws,o);if(void 0===d)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let h={method:"bbo.subscribe",params:{market_list:s},id:this.requestId()},c=await this.watchMultiple(d,r,this.deepExtend(h,n),["all@bidsasks"]);return this.newUpdates?c:this.filterByArray(this.bidsasks,"symbol",e)}handleBidAsk(e,t){let i=this.safeDict(t,"data",{}),s=this.parseWsBidAsk(i),r=s.symbol;this.bidsasks[r]=s,e.resolve(s,"bidsasks:"+r)}parseWsBidAsk(e,t){let i=this.safeString(this.options,"defaultType"),s=this.safeString(e,"market"),r=this.safeMarket(s,t,void 0,i),a=this.safeInteger(e,"updated_at");return this.safeTicker({symbol:this.safeSymbol(s,r,void 0,i),timestamp:a,datetime:this.iso8601(a),ask:this.safeNumber(e,"best_ask_price"),askVolume:this.safeNumber(e,"best_ask_size"),bid:this.safeNumber(e,"best_bid_price"),bidVolume:this.safeNumber(e,"best_bid_size"),info:e},r)}handleMessage(e,t){let i=this.safeString(t,"method"),s=this.safeString(t,"message");void 0!==s&&this.handleErrors(1,"",e.url,i,{},this.json(s),t,{},{});let r={"state.update":this.handleTicker,"balance.update":this.handleBalance,"deals.update":this.handleTrades,"user_deals.update":this.handleMyTrades,"depth.update":this.handleOrderBook,"order.update":this.handleOrders,"stop.update":this.handleOrders,"bbo.update":this.handleBidAsk},a=this.safeValue(r,i);void 0!==a?a.call(this,e,t):this.handleSubscriptionStatus(e,t)}handleErrors(e,t,i,s,r,o,n,d,h){if(void 0===n)return;let c=this.safeStringLower(n,"message"),l=void 0!==c&&"ok"!==c,u=this.safeString(n,"code");if(void 0!==u&&"0"!==u||l){let e=this.id+" "+o;throw this.throwExactlyMatchedException(this.exceptions.exact,u,e),this.throwBroadlyMatchedException(this.exceptions.broad,c,e),new a.ExchangeError(e)}}handleAuthenticationMessage(e,t){let i=this.safeStringLower(t,"message"),s=this.safeString(t,"code"),r="authenticated";if("ok"===i||"0"===s)this.safeValue(e.futures,r).resolve(!0);else{let i=new a.AuthenticationError(this.json(t));e.reject(i,r),r in e.subscriptions&&delete e.subscriptions[r]}}handleSubscriptionStatus(e,t){let i=this.safeInteger(t,"id"),s=this.safeDict(e.subscriptions,i);if(void 0!==s){let t=this.safeString(s,"future"),r=this.safeValue(e.futures,t);void 0!==r&&r.resolve(!0),delete e.subscriptions[i]}}async authenticate(e){let t=this.safeString(this.urls.api.ws,e);if(void 0===t)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let i=this.client(t),r=this.milliseconds(),o=r.toString(),n="authenticated",d=i.reusableFuture(n);if(void 0!==this.safeValue(i.subscriptions,n))return await d;let h=this.requestId(),c=this.hmac(this.encode(o),this.encode(this.secret),s.sc,"hex"),l={id:h,method:"server.sign",params:{access_id:this.apiKey,signed_str:c.toLowerCase(),timestamp:r}};return this.watch(t,n,l,h,{id:h,future:n}),i.subscriptions[n]=!0,await d}}i.d(t,{A:()=>n})},7087(e,t,i){"use strict";var s=i(6899),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchOrderBook:!0,watchOrders:!1,watchTrades:!0,watchTradesForSymbols:!1,watchOHLCV:!1,watchTicker:!0,watchTickers:!1},urls:{api:{ws:"wss://stream.coinone.co.kr"}},options:{expiresIn:"",userId:"",wsSessionToken:"",watchOrderBook:{snapshotDelay:6,snapshotMaxRetries:3},tradesLimit:1e3,OHLCVLimit:1e3},exceptions:{exact:{4009:r.AuthenticationError}},streaming:{ping:this.ping,keepAlive:2e4}})}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="orderbook:"+s.symbol,a=this.urls.api.ws,o={request_type:"SUBSCRIBE",channel:"ORDERBOOK",topic:{quote_currency:s.quote,target_currency:s.base}},n=this.extend(o,i);return(await this.watch(a,r,n,r)).limit()}handleOrderBook(e,t){let i=this.safeDict(t,"data",{}),s=this.safeStringUpper(i,"target_currency"),r=this.safeStringUpper(i,"quote_currency"),a=this.safeCurrencyCode(s),o=this.safeCurrencyCode(r);if(void 0===a||void 0===o)return;let n=this.symbol(a+"/"+o),d=this.safeInteger(i,"timestamp"),h=this.safeValue(this.orderbooks,n);void 0===h?h=this.orderBook():h.reset(),h.symbol=n;let c=this.safeList(i,"asks",[]),l=this.safeList(i,"bids",[]);this.handleDeltas(h.asks,c),this.handleDeltas(h.bids,l),h.timestamp=d,h.datetime=this.iso8601(d);let u="orderbook:"+n;this.orderbooks[n]=h,e.resolve(h,u)}handleDelta(e,t){let i=this.parseOrderBookBidAsk(t,"price","qty");e.storeArray(i)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="ticker:"+i.symbol,r=this.urls.api.ws,a={request_type:"SUBSCRIBE",channel:"TICKER",topic:{quote_currency:i.quote,target_currency:i.base}},o=this.extend(a,t);return await this.watch(r,s,o,s)}handleTicker(e,t){let i=this.safeDict(t,"data",{}),s=this.parseWsTicker(i),r=s.symbol;void 0!==r&&(this.tickers[r]=s,e.resolve(this.tickers[r],"ticker:"+r))}parseWsTicker(e,t){let i,s=this.safeInteger(e,"timestamp"),r=this.safeString(e,"last"),a=this.safeString(e,"target_currency"),o=this.safeString(e,"quote_currency"),n=this.safeCurrencyCode(a),d=this.safeCurrencyCode(o);return void 0!==n&&void 0!==d&&(i=this.symbol(n+"/"+d)),this.safeTicker({symbol:i,timestamp:s,datetime:this.iso8601(s),high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:this.safeNumber(e,"bid_best_price"),bidVolume:this.safeNumber(e,"bid_best_qty"),ask:this.safeNumber(e,"ask_best_price"),askVolume:this.safeNumber(e,"ask_best_qty"),vwap:void 0,open:this.safeString(e,"first"),close:r,last:r,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"target_volume"),quoteVolume:this.safeString(e,"quote_volume"),info:e},t)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a="trade:"+r.symbol,o=this.urls.api.ws,n={request_type:"SUBSCRIBE",channel:"TRADE",topic:{quote_currency:r.quote,target_currency:r.base}},d=this.extend(n,s),h=await this.watch(o,a,d,a),c=i;return this.newUpdates&&(c=h.getLimit(r.symbol,i)),this.filterBySinceLimit(h,t,c,"timestamp",!0)}handleTrades(e,t){let i=this.safeDict(t,"data",{}),s=this.parseWsTrade(i),r=s.symbol,o=this.safeValue(this.trades,r);if(void 0===o){let e=this.safeInteger(this.options,"tradesLimit",1e3);o=new a.I3(e),this.trades[r]=o}o.append(s);let n="trade:"+r;e.resolve(o,n)}parseWsTrade(e,t){let i,s,r=this.safeStringUpper(e,"target_currency"),a=this.safeStringUpper(e,"quote_currency"),o=this.safeCurrencyCode(r),n=this.safeCurrencyCode(a);void 0!==o&&void 0!==n&&(i=o+"/"+n);let d=this.safeInteger(e,"timestamp"),h=this.safeMarket(i,t),c=this.safeBool(e,"is_seller_maker");void 0!==c&&(s=!0===c?"sell":"buy");let l=this.safeString(e,"price"),u=this.safeString(e,"qty");return this.safeTrade({id:this.safeString(e,"id"),info:e,timestamp:d,datetime:this.iso8601(d),order:void 0,symbol:h.symbol,type:void 0,side:s,takerOrMaker:void 0,price:l,amount:u,cost:void 0,fee:void 0},h)}handleErrorMessage(e,t){return"ERROR"===this.safeString(t,"response_type","")}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;let i=this.safeString(t,"response_type");if("PONG"===i)return void this.handlePong(e,t);if("DATA"===i){let i=this.safeString(t,"channel",""),s={ORDERBOOK:this.handleOrderBook,TICKER:this.handleTicker,TRADE:this.handleTrades},r=this.safeValue(s,i);if(void 0!==r)return void r.call(this,e,t);let a=Object.keys(s);for(let r=0;r<a.length;r++){let o=a[r];if(i.indexOf(a[r])>=0)return void s[o].call(this,e,t)}}}ping(e){return{request_type:"PING"}}handlePong(e,t){return e.lastPong=this.milliseconds(),t}}i.d(t,{A:()=>o})},8202(e,t,i){"use strict";var s=i(4721),r=i(6214),a=i(1453),o=i(1697);class n extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchTicker:!0,watchTickers:!0,watchBidsAsks:!0,watchMyTrades:!0,watchTrades:!0,watchTradesForSymbols:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOrders:!0,watchOHLCV:!0,watchPositions:!0,createOrderWs:!0,cancelOrderWs:!0,cancelAllOrders:!0,editOrderWs:!0},urls:{api:{ws:{public:"wss://stream.crypto.com/exchange/v1/market",private:"wss://stream.crypto.com/exchange/v1/user"}},test:{public:"wss://uat-stream.3ona.co/exchange/v1/market",private:"wss://uat-stream.3ona.co/exchange/v1/user"}},options:{watchPositions:{fetchPositionsSnapshot:!0,awaitPositionsSnapshot:!0},watchOrderBook:{checksum:!0}},streaming:{}})}async pong(e,t){try{await e.send({id:this.safeInteger(t,"id"),method:"public/respond-heartbeat"})}catch(i){let t=new a.NetworkError(this.id+" pong failed with error "+this.exceptionMessage(i));e.reset(t)}}watchOrderBook(e,t,i={}){return this.watchOrderBookForSymbols([e],t,i)}unWatchOrderBook(e,t={}){return this.unWatchOrderBookForSymbols([e],t)}async watchOrderBookForSymbols(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e),r=[],a=[],o=50;void 0!==t&&0!==t&&(o=t),void 0===this.safeValue(i,"params")&&(i.params={});let[n,d]=this.handleOptionStringAndParams(i,"watchOrderBook","bookSubscriptionType","SNAPSHOT_AND_UPDATE"),[h,c]=this.handleOptionStringAndParams(d,"watchOrderBookForSymbols","bookSubscriptionType",n);c.params.bookSubscriptionType=h;let[l,u]=this.handleOptionStringAndParams(c,"watchOrderBook","bookUpdateFrequency"),[f,p]=this.handleOptionStringAndParams(u,"watchOrderBookForSymbols","bookUpdateFrequency",l);void 0!==f&&(p.params.bookSubscriptionType=f);for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t),n="book."+i.id+"."+o.toString(),d="orderbook:"+i.symbol;a.push(d),r.push(n)}return(await this.watchPublicMultiple(a,r,p)).limit()}async unWatchOrderBookForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=[],r=[],a=[],o=this.safeInteger(t,"limit",50);void 0===this.safeValue(t,"params")&&(t.params={});let[n,d]=this.handleOptionStringAndParams(t,"watchOrderBook","bookSubscriptionType","SNAPSHOT_AND_UPDATE"),[h,c]=this.handleOptionStringAndParams(d,"watchOrderBookForSymbols","bookSubscriptionType",n);c.params.bookSubscriptionType=h;let[l,u]=this.handleOptionStringAndParams(c,"watchOrderBook","bookUpdateFrequency"),[f,p]=this.handleOptionStringAndParams(u,"watchOrderBookForSymbols","bookUpdateFrequency",l);void 0!==f&&(p.params.bookSubscriptionType=f);for(let e=0;e<i.length;e++){let t=i[e],n=this.market(t),d="book."+n.id+"."+o.toString(),h="orderbook:"+n.symbol;r.push(h),a.push("unsubscribe:"+h),s.push(d)}return await this.unWatchPublicMultiple("orderbook",i,a,r,s,p)}handleDelta(e,t){let i=this.safeFloat(t,0),s=this.safeFloat(t,1),r=this.safeInteger(t,2);e.storeArray([i,s,r])}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}handleOrderBook(e,t){let i=this.safeString(t,"instrument_name"),s=this.safeMarket(i).symbol,r=this.safeValue(t,"data");r=this.safeDict(r,0);let o=this.safeInteger(r,"t");if(!(s in this.orderbooks)){let e=this.safeInteger(t,"depth");this.orderbooks[s]=this.countedOrderBook({},e)}let n=this.orderbooks[s],d=this.safeString(t,"channel"),h=this.safeInteger2(r,"u","s"),c=r;if("book"===d)n.reset({}),n.symbol=s,n.timestamp=o,n.datetime=this.iso8601(o),n.nonce=h;else{c=this.safeDict(r,"update",{});let e=this.safeInteger(r,"pu");if(n.nonce!==e&&!0===this.handleOption("watchOrderBook","checksum",!0))throw new a.ChecksumError(this.id+" "+this.orderbookChecksumMessage(s))}this.handleDeltas(n.asks,this.safeList(c,"asks",[])),this.handleDeltas(n.bids,this.safeList(c,"bids",[])),n.nonce=h,this.orderbooks[s]=n;let l="orderbook:"+s;e.resolve(n,l)}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}unWatchTrades(e,t={}){return this.unWatchTradesForSymbols([e],t)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e),a=[];for(let e=0;e<r.length;e++){let t=r[e],i="trade."+this.market(t).id;a.push(i)}let o=await this.watchPublicMultiple(a,a,s),n=this.safeDict(o,0),d=this.safeString(n,"symbol"),h=i;return this.newUpdates&&(h=o.getLimit(d,i)),this.filterBySinceLimit(o,t,h,"timestamp",!0)}async unWatchTradesForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=[],r=[];for(let e=0;e<i.length;e++){let t=i[e],a=this.market(t),o="trade."+a.id;r.push("unsubscribe:trades:"+a.symbol),s.push(o)}return await this.unWatchPublicMultiple("trades",i,r,s,s,t)}handleTrades(e,t){let i=this.safeString(t,"channel");if(void 0===i)return;let s=this.safeString(t,"instrument_name"),r=this.safeString(t,"subscription"),a=this.safeMarket(s),n=a.symbol,d=this.safeValue(this.trades,n);if(void 0===d){let e=this.safeInteger(this.options,"tradesLimit",1e3);d=new o.I3(e),this.trades[n]=d}let h=this.safeList(t,"data",[]);if(0===h.length)return;let c=this.parseTrades(h,a);for(let e=0;e<c.length;e++)d.append(c[e]);let l=i.replace("."+s,"");e.resolve(d,r),e.resolve(d,l)}async watchMyTrades(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e),a=this.safeString(r,"symbol"));let o="user.trade";o=void 0!==r?o+"."+r.id:o;let n=await this.watchPrivateSubscribe(o,s),d=i;return this.newUpdates&&(d=n.getLimit(a,i)),this.filterBySymbolSinceLimit(n,a,t,d,!0)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i="ticker."+this.market(e).id;return await this.watchPublic(i,t)}async unWatchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="ticker."+i.id,r="unsubscribe:ticker:"+i.symbol;return await this.unWatchPublicMultiple("ticker",[i.symbol],[r],[s],[s],t)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=[],r=this.marketIds(i);for(let e=0;e<r.length;e++){let t=r[e];s.push("ticker."+t)}let a=this.urls.api.ws.public,o=this.incrementingNonce(),n=await this.watchMultiple(a,s,this.extend({method:"subscribe",params:{channels:s},nonce:o},t),s);if(this.newUpdates){let e={},t=this.safeString(n,"symbol");return void 0!==t&&(e[t]=n),e}return this.filterByArray(this.tickers,"symbol",i)}async unWatchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=[],r=[],a=this.marketIds(i);for(let e=0;e<a.length;e++){let t=a[e],o=i[e];r.push("ticker."+t),s.push("unsubscribe:ticker:"+o)}return await this.unWatchPublicMultiple("ticker",i,s,r,r,t)}handleTicker(e,t){this.handleBidAsk(e,t);let i=this.safeString(t,"subscription"),s=this.safeString(t,"instrument_name"),r=this.safeMarket(s),a=this.safeList(t,"data",[]);for(let t=0;t<a.length;t++){let s=a[t],o=this.parseWsTicker(s,r),n=o.symbol;void 0!==n&&(this.tickers[n]=o),e.resolve(o,i)}}parseWsTicker(e,t){let i=this.safeInteger(e,"t"),s=this.safeString(e,"i"),r=this.safeMarket(s,t,"_"),a=this.safeString(r,"quote"),o=this.safeString(e,"a");return this.safeTicker({symbol:r.symbol,timestamp:i,datetime:this.iso8601(i),high:this.safeNumber(e,"h"),low:this.safeNumber(e,"l"),bid:this.safeNumber(e,"b"),bidVolume:this.safeNumber(e,"bs"),ask:this.safeNumber(e,"k"),askVolume:this.safeNumber(e,"ks"),vwap:void 0,open:void 0,close:o,last:o,previousClose:void 0,change:void 0,percentage:this.safeString(e,"c"),average:void 0,baseVolume:this.safeString(e,"v"),quoteVolume:"USD"===a?this.safeString(e,"vv"):void 0,info:e},r)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=[],r=[],a=this.marketIds(i);for(let e=0;e<a.length;e++){let t=a[e];s.push("bidask."+i[e]),r.push("ticker."+t)}let o=this.urls.api.ws.public,n=this.incrementingNonce(),d=await this.watchMultiple(o,s,this.extend({method:"subscribe",params:{channels:r},nonce:n},t),s);if(this.newUpdates){let e={},t=this.safeString(d,"symbol");return void 0!==t&&(e[t]=d),e}return this.filterByArray(this.bidsasks,"symbol",i)}handleBidAsk(e,t){let i=this.safeList(t,"data",[]),s=this.safeDict(i,0,{}),r=this.parseWsBidAsk(s),a=r.symbol;void 0!==a&&(this.bidsasks[a]=r),e.resolve(r,"bidask."+a)}parseWsBidAsk(e,t){let i=this.safeString(e,"i"),s=this.safeMarket(i,t),r=this.safeString(s,"symbol"),a=this.safeInteger(e,"t");return this.safeTicker({symbol:r,timestamp:a,datetime:this.iso8601(a),ask:this.safeString(e,"k"),askVolume:this.safeString(e,"ks"),bid:this.safeString(e,"b"),bidVolume:this.safeString(e,"bs"),info:e},s)}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n="candlestick."+this.safeString(this.timeframes,t,t)+"."+a.id,d=await this.watchPublic(n,r),h=s;return this.newUpdates&&(h=d.getLimit(o,s)),this.filterBySinceLimit(d,i,h,0,!0)}async unWatchOHLCV(e,t="1m",i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="candlestick."+this.safeString(this.timeframes,t,t)+"."+s.id,a="unsubscribe:ohlcv:"+s.symbol+":"+t,o={symbolsAndTimeframes:[[s.symbol,t]]};return await this.unWatchPublicMultiple("ohlcv",[s.symbol],[a],[r],[r],i,o)}handleOHLCV(e,t){let i=this.safeString(t,"subscription"),s=this.safeString(t,"instrument_name"),r=this.safeMarket(s),a=r.symbol,n=this.safeString(t,"interval"),d=this.findTimeframe(n);this.ohlcvs[a]=this.safeDict(this.ohlcvs,a,{});let h=this.safeValue(this.safeDict(this.ohlcvs,a),d);if(void 0===h){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);h=new o.TG(e),void 0!==a&&void 0!==d&&(this.ohlcvs[a][d]=h)}let c=this.safeValue(t,"data");for(let e=0;e<c.length;e++){let t=this.safeDict(c,e),i=this.parseOHLCV(t,r);h.append(i)}e.resolve(h,i)}async watchOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e),a=this.safeString(r,"symbol"));let o="user.order";o=void 0!==r?o+"."+r.id:o;let n=await this.watchPrivateSubscribe(o,s),d=i;return this.newUpdates&&(d=n.getLimit(a,i)),this.filterBySymbolSinceLimit(n,a,t,d,!0)}handleOrders(e,t,i){let s=this.safeString(t,"channel"),r=this.safeString(t,"subscription"),a=this.safeList(t,"data",[]);if(a.length>0){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}let t=this.orders,i=this.parseOrders(a);for(let e=0;e<i.length;e++)t.append(i[e]);e.resolve(t,r),e.resolve(t,s),e.resolve(t,"user.order")}}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.urls.api.ws.private,o=this.incrementingNonce(),n="positions",d=this.marketSymbols(e);if(!this.isEmpty(d)){if(void 0===d)throw new a.ArgumentsRequired(this.id+" watchPositions() symbols is required");n="positions::"+d.join(",")}let h=this.client(r);this.setPositionsCache(h,d);let c=this.handleOption("watchPositions","fetchPositionsSnapshot",!0),l=this.handleOption("watchPositions","awaitPositionsSnapshot",!0);if(!0===c&&!0===l&&void 0===this.positions){let e=await h.future("fetchPositionsSnapshot");return this.filterBySymbolsSinceLimit(e,d,t,i,!0)}let u=await this.watch(r,n,this.extend({method:"subscribe",params:{channels:["user.position_balance"]},nonce:o},s));return this.newUpdates?u:this.filterBySymbolsSinceLimit(this.positions,d,t,i,!0)}setPositionsCache(e,t,i){if(!0===this.handleOption("watchPositions","fetchPositionsSnapshot",!1)){let t="fetchPositionsSnapshot";t in e.futures||(e.future(t),this.spawn(this.loadPositionsSnapshot,e,t))}else this.positions=new o.Hk}async loadPositionsSnapshot(e,t){let i=await this.fetchPositions();this.positions=new o.Hk;let s=this.positions;for(let e=0;e<i.length;e++){let t=i[e],r=this.safeNumber(t,"contracts",0);void 0!==r&&r>0&&s.append(t)}t in e.futures&&(e.futures[t].resolve(s),e.resolve(s,"positions"))}handlePositions(e,t){let i=this.safeList(t,"data",[]),s=this.safeDict(i,0,{}),r=this.safeList(s,"positions",[]);void 0===this.positions&&(this.positions=new o.Hk);let a=this.positions,n=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.parsePosition(t);n.push(i),a.append(i)}let d=this.findMessageHashes(e,"positions::");for(let t=0;t<d.length;t++){let i=d[t],s=i.split("::")[1].split(","),r=this.filterByArray(n,"symbol",s,!1);this.isEmpty(r)||e.resolve(r,i)}e.resolve(n,"positions")}async watchBalance(e={}){return await this.watchPrivateSubscribe("user.balance",e)}handleBalance(e,t){let i=this.safeString(t,"subscription"),s=this.safeList(t,"data",[]),r=this.safeList(s[0],"position_balances",[]);this.balance.info=s;for(let e=0;e<r.length;e++){let t=this.safeDict(r,e),i=this.safeString(t,"instrument_name"),s=this.safeCurrencyCode(i),a=this.account();a.total=this.safeString(t,"quantity"),a.used=this.safeString(t,"reserved_qty"),void 0!==s&&(this.balance[s]=a),this.balance=this.safeBalance(this.balance)}e.resolve(this.balance,i);let a=this.safeString(t,"id");void 0!==a&&e.resolve(this.balance,a)}async createOrderWs(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.createOrderRequest(e,t,i,s,r,a),n=this.incrementingNonce();return await this.watchPrivateRequest(n,{method:"private/create-order",params:o})}async editOrderWs(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.editOrderRequest(e,t,r,a,o),d=this.incrementingNonce();return await this.watchPrivateRequest(d,{method:"private/amend-order",params:n})}handleOrder(e,t){let i=this.safeString(t,"id"),s=this.safeDict(t,"result",{}),r=this.parseOrder(s);e.resolve(r,i)}async cancelOrderWs(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.extend({order_id:e},i),r=this.incrementingNonce();return await this.watchPrivateRequest(r,{method:"private/cancel-order",params:s})}async cancelAllOrdersWs(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s={method:"private/cancel-all-orders",params:this.extend({},t)};void 0!==e&&(i=this.market(e),s.params.instrument_name=i.id);let r=this.incrementingNonce();return await this.watchPrivateRequest(r,s)}handleCancelAllOrders(e,t){let i=this.safeString(t,"id");e.resolve(t,i)}async watchPublic(e,t={}){let i=this.urls.api.ws.public,s=this.incrementingNonce(),r=this.extend({method:"subscribe",params:{channels:[e]},nonce:s},t);return await this.watch(i,e,r,e)}async watchPublicMultiple(e,t,i={}){let s=this.urls.api.ws.public,r=this.incrementingNonce(),a=this.deepExtend({method:"subscribe",params:{channels:t},nonce:r},i);return await this.watchMultiple(s,e,a,e)}async unWatchPublicMultiple(e,t,i,s,r,a={},o={}){let n=this.urls.api.ws.public,d=this.incrementingNonce(),h={method:"unsubscribe",params:{channels:r},nonce:d,id:d.toString()},c={id:d.toString(),topic:e,symbols:t,subMessageHashes:s,messageHashes:i},l=this.deepExtend(h,a);return await this.watchMultiple(n,i,l,i,this.extend(c,o))}async watchPrivateRequest(e,t={}){await this.authenticate();let i=this.urls.api.ws.private,s=this.extend({id:e,nonce:e},t);return await this.watch(i,e.toString(),s,!0)}async watchPrivateSubscribe(e,t={}){await this.authenticate();let i=this.urls.api.ws.private,s=this.incrementingNonce(),r=this.extend({method:"subscribe",params:{channels:[e]},nonce:s},t);return await this.watch(i,e,r,e)}handleErrorMessage(e,t){let i=this.safeString(t,"id"),s=this.safeString(t,"code");try{if(void 0!==s&&""!==s&&"0"!==s){let e=this.id+" "+this.json(t);this.throwExactlyMatchedException(this.exceptions.exact,s,e);let i=this.safeString(t,"message");throw void 0!==i&&this.throwBroadlyMatchedException(this.exceptions.broad,i,e),new a.ExchangeError(e)}return!1}catch(t){if(t instanceof a.AuthenticationError){let i="authenticated";e.reject(t,i),i in e.subscriptions&&delete e.subscriptions[i]}else e.reject(t,i);return!0}}handleSubscribe(e,t){let i={candlestick:this.handleOHLCV,ticker:this.handleTicker,trade:this.handleTrades,book:this.handleOrderBook,"book.update":this.handleOrderBook,"user.order":this.handleOrders,"user.trade":this.handleTrades,"user.balance":this.handleBalance,"user.position_balance":this.handlePositions},s=this.safeValue2(t,"result","info"),r=this.safeString(s,"channel");void 0!==r&&r.indexOf("user.trade")>-1&&this.handleTrades(e,s),void 0!==r&&r.startsWith("user.order")&&this.handleOrders(e,s);let a=this.safeValue(i,r);void 0!==a&&a.call(this,e,s)}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;let i=this.safeString(t,"method"),s={"":this.handlePing,"public/heartbeat":this.handlePing,"public/auth":this.handleAuthenticate,"private/create-order":this.handleOrder,"private/amend-order":this.handleOrder,"private/cancel-order":this.handleOrder,"private/cancel-all-orders":this.handleCancelAllOrders,"private/close-position":this.handleOrder,subscribe:this.handleSubscribe,unsubscribe:this.handleUnsubscribe},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}async authenticate(e={}){this.checkRequiredCredentials();let t=this.urls.api.ws.private,i=this.client(t),r="authenticated",a=i.reusableFuture(r);if(void 0===this.safeValue(i.subscriptions,r)){let i="public/auth",a=this.incrementingNonce().toString(),o=i+a+this.apiKey+a,n=this.hmac(this.encode(o),this.encode(this.secret),s.sc),d={id:a,nonce:a,method:i,api_key:this.apiKey,sig:n},h=this.extend(d,e);this.watch(t,r,h,r)}return await a}handlePing(e,t){this.spawn(this.pong,e,t)}handleAuthenticate(e,t){this.safeValue(e.futures,"authenticated").resolve(!0)}handleUnsubscribe(e,t){let i=this.safeString(t,"id"),s=Object.keys(e.subscriptions);for(let t=0;t<s.length;t++){let r=s[t];if(r in e.subscriptions&&r.startsWith("unsubscribe")){let t=e.subscriptions[r];if(i!==this.safeString(t,"id"))continue;let s=this.safeList(t,"messageHashes",[]),a=this.safeList(t,"subMessageHashes",[]);for(let t=0;t<s.length;t++){let i=s[t],r=a[t];this.cleanUnsubscription(e,r,i)}this.cleanCache(t)}}}}i.d(t,{A:()=>n})},1837(e,t,i){"use strict";var s=i(7929),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchTicker:!0,watchMarkPrice:!1,watchMarkPrices:!1,watchTickers:!1,watchBidsAsks:!1,watchOrderBook:!0,watchTrades:!0,watchTradesForSymbols:!1,watchOrderBookForSymbols:!1,watchBalance:!1,watchLiquidations:!1,watchLiquidationsForSymbols:!1,watchMyLiquidations:!1,watchMyLiquidationsForSymbols:!1,watchOHLCV:!0,watchOHLCVForSymbols:!1,watchOrders:!0,watchMyTrades:!0,watchPositions:!0,watchFundingRate:!1,watchFundingRates:!1,createOrderWs:!1,editOrderWs:!1,cancelOrderWs:!1,cancelOrdersWs:!1,cancelAllOrdersWs:!1,unWatchTicker:!0,unWatchTrades:!0,unWatchOHLCV:!0,unWatchOrderBook:!0},urls:{api:{ws:{public:{spot:"wss://stream.deepcoin.com/streamlet/trade/public/spot?platform=api",swap:"wss://stream.deepcoin.com/streamlet/trade/public/swap?platform=api"},private:"wss://stream.deepcoin.com/v1/private"}}},options:{lastRequestId:void 0,listenKey:void 0,listenKeyExpiryTimestamp:void 0,authenticate:{method:"privateGetDeepcoinListenkeyExtend"},timeframes:{"1m":"1m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","4h":"4h","12h":"12h","1d":"1d","1w":"1w","1M":"1o","1y":"1y"}},streaming:{ping:this.ping,keepAlive:15e3}})}ping(e){return e.url.indexOf("private")>=0&&(e.lastPong=this.milliseconds()),"ping"}handlePong(e,t){return e.lastPong=this.milliseconds(),t}requestId(){this.lockId();let e=this.safeInteger(this.options,"lastRequestId",0),t=this.sum(e,1);return this.options.lastRequestId=t,this.unlockId(),t}createPublicRequest(e,t,i,s="",r=!1){let a=this.safeString(e,"symbol");"swap"===this.safeString(e,"type")&&(a=this.safeString(e,"baseId","")+this.safeString(e,"quoteId",""));let o="1";return r&&(o="0"),{sendTopicAction:{Action:o,FilterValue:"DeepCoin_"+a+s,LocalNo:t,ResumeNo:-1,TopicID:i}}}async watchPublic(e,t,i,s={},r=""){let a=this.urls.api.ws.public[e.type],o=this.requestId(),n=this.createPublicRequest(e,o,i,r);return await this.watch(a,t,this.deepExtend(n,s),t,{subHash:t,id:o})}async unWatchPublic(e,t,i,s={},a={},o=""){let n=this.urls.api.ws.public[e.type],d=this.requestId(),h=this.client(n),c=this.safeDict(h.subscriptions,t);if(void 0===c)throw new r.BadRequest(this.id+" no subscription for "+t);let l=this.safeInteger(c,"id"),u=this.createPublicRequest(e,l,i,o,!0),f="unsubscribe::"+t,p=this.extend(a,{subHash:t,unsubHash:f,symbols:[e.symbol],id:d});return await this.watch(n,f,this.deepExtend(u,s),f,p)}async watchPrivate(e,t={}){let i=await this.authenticate(),s=this.safeString(this.urls.api.ws,"private")+"?listenKey="+i;return await this.watch(s,e,void 0,"private",t)}async authenticate(e={}){let t;this.checkRequiredCredentials();let i=this.milliseconds(),s="authenticate",a=this.client("authenticationFlights");if(s in a.futures)return await a.future(s),this.safeString(this.options,"listenKey");let o=a.reusableFuture(s);try{let o,n=this.safeInteger(this.options,"listenKeyExpiryTimestamp",i),d=i-n>6e4;if(t=this.safeString(this.options,"listenKey"),void 0===t)o=await this.privateGetDeepcoinListenkeyAcquire(e);else if(d){let i=this.safeString(this.options,"method","privateGetDeepcoinListenkeyExtend");if("privateGetDeepcoinListenkeyAcquire"===i)o=await this.privateGetDeepcoinListenkeyAcquire(e);else{let i={listenkey:t};o=await this.privateGetDeepcoinListenkeyExtend(this.extend(i,e))}}if(void 0!==o){let e=this.safeDict(o,"data",{});if(t=this.safeString(e,"listenkey"),void 0===t)throw new r.AuthenticationError(this.id+" authenticate() received an empty listenKey");n=this.safeTimestamp(e,"expire_time"),this.options.listenKey=t,this.options.listenKeyExpiryTimestamp=n}a.resolve(t,s)}catch(e){a.reject(e,s)}return await o,t}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="ticker::"+i.symbol;return await this.watchPublic(i,s,"7",t)}async unWatchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="ticker::"+i.symbol;return await this.unWatchPublic(i,s,"7",t,{topic:"ticker"})}handleTicker(e,t){let i=this.safeList(t,"r",[]),s=this.safeDict(i,0,{}),r=this.safeDict(s,"d",{}),a=this.safeString(r,"I"),o=this.safeMarket(a,void 0,"/"),n=this.safeSymbol(a,o),d=this.parseWsTicker(r,o);this.tickers[n]=d,e.resolve(d,"ticker::"+n)}parseWsTicker(e,t){let i=this.safeInteger(e,"U"),s=this.safeNumber(e,"H"),r=this.safeNumber(e,"L"),a=this.safeNumber(e,"O"),o=this.safeNumber(e,"N"),n=this.safeNumber(e,"BP1"),d=this.safeNumber(e,"AP1"),h=this.safeNumber(e,"V"),c=this.safeNumber(e,"T");if(this.safeBool(t,"inverse",!1)){let e=h;h=c,c=e}return this.safeTicker({symbol:this.safeString(t,"symbol"),timestamp:i,datetime:this.iso8601(i),high:s,low:r,bid:n,bidVolume:void 0,ask:d,askVolume:void 0,vwap:void 0,open:a,close:o,last:o,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:h,quoteVolume:c,info:e},t)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a="trades::"+r.symbol,o=await this.watchPublic(r,a,"2",s),n=i;return this.newUpdates&&(n=o.getLimit(e,i)),this.filterBySinceLimit(o,t,n,"timestamp",!0)}async unWatchTrades(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="trades::"+i.symbol;return await this.unWatchPublic(i,s,"2",t,{topic:"trades"})}handleTrades(e,t){let i=this.safeList(t,"r",[]),s=this.safeDict(i,0,{}),r=this.safeDict(s,"d",{}),o=this.safeString(r,"I"),n=this.safeMarket(o,void 0,"/"),d=this.safeSymbol(o,n);if(!(d in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.trades[d]=new a.I3(e)}let h=this.trades[d];if(void 0!==r){let e=this.parseWsTrade(r,n);h.append(e)}e.resolve(h,"trades::"+d)}parseWsTrade(e,t){let i,s=this.safeString(e,"D"),r=this.safeTimestamp2(e,"TT","T"),a=this.safeString(e,"m"),o=this.safeString(e,"F");return void 0!==o&&(i={cost:o,currency:this.safeCurrencyCode(this.safeString(e,"f"))}),this.safeTrade({info:e,timestamp:r,datetime:this.iso8601(r),symbol:this.safeString(t,"symbol"),id:this.safeString2(e,"TradeID","TI"),order:this.safeString(e,"OS"),type:void 0,takerOrMaker:this.handleTakerOrMaker(a),side:this.parseTradeSide(s),price:this.safeString(e,"P"),amount:this.safeString(e,"V"),cost:this.safeString(e,"T"),fee:i},t)}parseTradeSide(e){return this.safeString({0:"buy",1:"sell"},e,e)}handleTakerOrMaker(e){return this.safeString({0:"maker",1:"taker"},e,e)}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n=this.safeDict(this.options,"timeframes",{}),d=this.safeString(n,t,t),h=await this.watchPublic(a,"ohlcv::"+o+"::"+t,"11",r,"_"+d),c=s;return this.newUpdates&&(c=h.getLimit(o,s)),this.filterBySinceLimit(h,i,c,0,!0)}async unWatchOHLCV(e,t="1m",i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=s.symbol,a=this.safeDict(this.options,"timeframes",{}),o=this.safeString(a,t,t),n="ohlcv::"+r+"::"+t;return await this.unWatchPublic(s,n,"11",i,{topic:"ohlcv",symbolsAndTimeframes:[[r,t]]},"_"+o)}handleOHLCV(e,t){let i=this.safeList(t,"r",[]),s=this.safeDict(i,0,{}),r=this.safeDict(s,"d",{}),o=this.safeString(r,"I"),n=this.safeMarket(o,void 0,"/"),d=this.safeSymbol(o,n),h=this.safeString(r,"P"),c=this.findTimeframe(h);if(d in this.ohlcvs||(this.ohlcvs[d]={}),!(c in this.ohlcvs[d])){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);this.ohlcvs[d][c]=new a.TG(e)}let l=this.ohlcvs[d][c];if(void 0!==r){let e=this.parseWsOHLCV(r,n);l.append(e)}e.resolve(l,"ohlcv::"+d+"::"+c)}parseWsOHLCV(e,t){return[this.safeTimestamp(e,"B"),this.safeNumber(e,"O"),this.safeNumber(e,"H"),this.safeNumber(e,"L"),this.safeNumber(e,"C"),this.safeNumber(e,"V")]}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="orderbook::"+s.symbol,[a,o]=this.orderBookSuffix(s,"watchOrderBook",i);return(await this.watchPublic(s,r,"25",o,a)).limit()}async unWatchOrderBook(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="orderbook::"+i.symbol,[r,a]=this.orderBookSuffix(i,"unWatchOrderBook",t);return await this.unWatchPublic(i,s,"25",a,{topic:"orderbook"},r)}orderBookSuffix(e,t,i={}){let s,a,o=this.safeString(e,"symbol");if([s,a]=this.handleOptionStringAndParams(i,t,"aggregation"),void 0===s){let i=this.safeDict(e,"precision",{}),a=this.safeNumber(i,"price");if(void 0===a)throw new r.BadRequest(this.id+" "+t+'() requires a params["aggregation"] price level for '+o+" because the market has no price precision");s=this.numberToString(a)}return["_"+s,a]}handleOrderBook(e,t){let i=this.safeList(t,"r",[]),s=this.safeDict(i,0,{}),r=this.safeDict(s,"d",{}),a=this.safeString(r,"I"),o=this.safeMarket(a,void 0,"/"),n=this.safeSymbol(a,o);n in this.orderbooks||(this.orderbooks[n]=this.orderBook());let d=this.orderbooks[n],h=this.safeString(t,"t");void 0===d.timestamp?"f"===h?this.handleOrderBookSnapshot(e,t):d.cache.push(t):(this.handleOrderBookMessage(e,t,d),e.resolve(d,"orderbook::"+n))}handleOrderBookSnapshot(e,t){let i=this.safeList(t,"r",[]),s=this.safeDict(i,0,{}),r=this.safeDict(s,"d",{}),a=this.safeString(r,"I"),o=this.safeMarket(a,void 0,"/"),n=this.safeSymbol(a,o),d=this.orderbooks[n],h={bids:[],asks:[]};for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),s=this.safeDict(t,"d",{}),r=this.safeString(s,"D"),a=this.safeNumber(s,"P"),o=this.safeNumber(s,"V");"0"===r?h.bids.push([a,o]):"1"===r&&h.asks.push([a,o])}let c=this.safeInteger(t,"mt",0),l=this.parseOrderBook(h,n,c);d.reset(l);let u=d.cache;for(let t=0;t<u.length;t++){let i=u[t];this.handleOrderBookMessage(e,i,d)}d.cache=[];let f="orderbook::"+n;e.resolve(d,f)}handleOrderBookMessage(e,t,i){let s=this.safeInteger(t,"mt",0),r=this.safeInteger(i,"timestamp");if(void 0!==r&&s>r){let e=this.safeList(t,"r",[]);this.handleBookDeltas(i,e),i.timestamp=s,i.datetime=this.iso8601(s)}}handleBookDelta(e,t){let i=this.safeDict(t,"d",{}),s=e.bids,r=e.asks,a=this.safeString(i,"D"),o=this.safeNumber(i,"P"),n=this.safeNumber(i,"V");"0"===a?s.store(o,n):"1"===a&&r.store(o,n)}async watchMyTrades(e,t,i,s={}){let r="myTrades";void 0===this.markets&&await this.loadMarkets();let a=void 0!==e?this.symbol(e):void 0;void 0!==a&&(r+="::"+a);let o=await this.watchPrivate(r,s),n=i;return this.newUpdates&&(n=o.getLimit(a,i)),this.filterBySymbolSinceLimit(o,a,t,n,!0)}handleMyTrade(e,t){let i=this.safeList(t,"result",[]),s=this.safeDict(i,0,{}),r=this.safeDict(s,"data",{}),o=this.safeString(r,"I"),n=this.safeMarket(o,void 0,"/"),d=this.safeSymbol(o,n),h="myTrades",c=h+"::"+d;if(h in e.futures||c in e.futures){if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new a.Pt(e)}let t=this.myTrades,i=this.parseWsTrade(r,n);t.append(i),e.resolve(t,h),e.resolve(t,c)}}async watchOrders(e,t,i,s={}){let r="orders";void 0===this.markets&&await this.loadMarkets();let a=void 0!==e?this.symbol(e):void 0;void 0!==a&&(r+="::"+a);let o=await this.watchPrivate(r,s),n=i;return this.newUpdates&&(n=o.getLimit(a,i)),this.filterBySymbolSinceLimit(o,a,t,n,!0)}handleOrder(e,t){let i=this.safeList(t,"result",[]),s=this.safeDict(i,0,{}),r=this.safeDict(s,"data",{}),o=this.safeString(r,"I"),n=this.safeMarket(o,void 0,"/"),d=this.safeSymbol(o,n),h="orders",c=h+"::"+d;if(h in e.futures||c in e.futures){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}let t=this.parseWsOrder(r,n);this.orders.append(t),e.resolve(this.orders,h),e.resolve(this.orders,c)}}parseWsOrder(e,t){let i=this.safeString(e,"Or"),s=this.safeTimestamp(e,"IT"),r=this.safeString(e,"D");return this.safeOrder({id:this.safeString(e,"OS"),clientOrderId:void 0,datetime:this.iso8601(s),timestamp:s,lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeTimestamp(e,"U"),status:this.parseWsOrderStatus(i),symbol:this.safeString(t,"symbol"),type:void 0,timeInForce:void 0,side:this.parseTradeSide(r),price:this.safeString(e,"P"),average:this.safeString(e,"t"),amount:this.safeString(e,"V"),filled:this.safeString(e,"VT"),remaining:void 0,triggerPrice:void 0,takeProfitPrice:this.safeString(e,"TPT"),stopLossPrice:this.safeString(e,"SLT"),cost:this.safeString(e,"T"),trades:void 0,fee:void 0,reduceOnly:void 0,postOnly:void 0,info:e},t)}parseWsOrderStatus(e){return this.safeString({1:"closed",4:"open",6:"canceled"},e,e)}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.authenticate(),a=this.marketSymbols(e),o="positions",n=[];if(void 0!==a)for(let e=0;e<a.length;e++){let t=o+"::"+a[e];n.push(t)}else n.push(o);let d=this.safeString(this.urls.api.ws,"private")+"?listenKey="+r,h=await this.watchMultiple(d,n,s,["private"]);return this.newUpdates?h:this.filterBySymbolsSinceLimit(this.positions,a,t,i,!0)}handlePosition(e,t){let i=this.safeList(t,"result",[]),s=this.safeDict(i,0,{}),r=this.safeDict(s,"data",{}),o=this.safeString(r,"I"),n=this.safeMarket(o,void 0,"/"),d=this.safeSymbol(o,n),h="positions",c=h+"::"+d;if(h in e.futures||c in e.futures){void 0===this.positions&&(this.positions=new a.Hk);let t=this.parseWsPosition(r,n);this.positions.append(t),e.resolve(this.positions,h),e.resolve(this.positions,c)}}parseWsPosition(e,t){let i=this.safeInteger(e,"U"),s=this.safeString(e,"p"),r=this.safeString(e,"i");return this.safePosition({symbol:this.safeString(t,"symbol"),id:void 0,timestamp:i,datetime:this.iso8601(i),contracts:this.safeString(e,"Po"),contractSize:void 0,side:this.parsePositionSide(s),notional:void 0,leverage:this.omitZero(this.safeString(e,"l")),unrealizedPnl:void 0,realizedPnl:void 0,collateral:void 0,entryPrice:this.safeString(e,"OP"),markPrice:void 0,liquidationPrice:void 0,marginMode:this.parseWsMarginMode(r),hedged:!0,maintenanceMargin:this.safeString(e,"u"),maintenanceMarginPercentage:void 0,initialMargin:void 0,initialMarginPercentage:void 0,marginRatio:void 0,lastUpdateTimestamp:void 0,lastPrice:void 0,stopLossPrice:void 0,takeProfitPrice:void 0,percentage:void 0,info:e})}parsePositionSide(e){return void 0===e?e:this.safeString({0:"long",1:"short"},e,e)}parseWsMarginMode(e){return void 0===e?e:this.safeString({0:"isolated",1:"cross"},e,e)}handleMessage(e,t){if("string"==typeof t)"pong"===t&&this.handlePong(e,t);else{let i=this.safeString(t,"m");void 0!==i&&"Success"!==i&&this.handleErrorMessage(e,t);let s=this.safeString2(t,"a","action");"RecvTopicAction"===s?this.handleSubscriptionStatus(e,t):"PO"===s?this.handleTicker(e,t):"PMT"===s?this.handleTrades(e,t):"PK"===s?this.handleOHLCV(e,t):"PMO"===s?this.handleOrderBook(e,t):"PushTrade"===s?this.handleMyTrade(e,t):"PushOrder"===s?this.handleOrder(e,t):"PushPosition"===s&&this.handlePosition(e,t)}}handleSubscriptionStatus(e,t){let i=this.safeList(t,"r",[]),s=this.safeDict(i,0,{}),r=this.safeDict(s,"d",{});if("0"===this.safeString(r,"A")){let t=this.indexBy(e.subscriptions,"id"),i=this.safeInteger(r,"L"),s=this.safeDict(t,i,{}),a=this.safeString(s,"subHash"),o=this.safeDict(e.subscriptions,"unsubscribe::"+a,{});this.handleUnSubscription(e,o)}}handleUnSubscription(e,t){let i=this.safeString(t,"subHash"),s=this.safeString(t,"unsubHash");this.cleanUnsubscription(e,i,s),this.cleanCache(t)}handleErrorMessage(e,t){let i=this.safeString(t,"m",""),s=this.safeList(t,"r",[]),a=this.safeDict(s,0,{}),o=this.safeDict(a,"d",{}),n=this.safeInteger(o,"L"),d=this.indexBy(e.subscriptions,"id"),h=this.safeDict(d,n,{}),c=this.safeString(h,"subHash"),l=this.id+" "+this.json(t);try{throw this.throwExactlyMatchedException(this.exceptions.exact,i,l),this.throwBroadlyMatchedException(this.exceptions.broad,i,l),new r.ExchangeError(l)}catch(t){e.reject(t,c)}}}i.d(t,{A:()=>o})},673(e,t,i){"use strict";var s=i(4721),r=i(3045),a=i(1453),o=i(1697);class n extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchTicker:!0,watchTickers:!0,watchBidsAsks:!0,watchTrades:!0,watchTradesForSymbols:!0,watchMyTrades:!0,watchOrders:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOHLCV:!0,watchOHLCVForSymbols:!0},urls:{test:{ws:"wss://test.deribit.com/ws/api/v2"},api:{ws:"wss://www.deribit.com/ws/api/v2"}},options:{ws:{timeframes:{"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","1h":"60","2h":"120","4h":"180","6h":"360","12h":"720","1d":"1D"},watchTradesForSymbols:{interval:"100ms"},watchOrderBookForSymbols:{interval:"100ms",useDepthEndpoint:!1,depth:"20",group:"none"}},currencies:["BTC","ETH","SOL","USDC"]},streaming:{},exceptions:{}})}requestId(){let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,e}async watchBalance(e={}){await this.authenticate(e);let t="balance",i=this.urls.api.ws,s=this.safeList(this.options,"currencies",[]),r=[];for(let e=0;e<s.length;e++){let t=this.safeString(s,e);r.push("user.portfolio."+t)}let a={jsonrpc:"2.0",method:"private/subscribe",params:{channels:r},id:this.requestId()},o=this.deepExtend(a,e);return await this.watch(i,t,o,t,o)}handleBalance(e,t){let i=this.safeDict(t,"params",{}),s=this.safeDict(i,"data",{});this.balance.info=s;let r=this.safeString(s,"currency"),a=this.safeCurrencyCode(r),o=this.parseBalance(s);void 0!==a&&(this.balance[a]=o),e.resolve(this.balance,"balance")}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.urls.api.ws,r=this.safeString(t,"interval","100ms"),a=this.omit(t,"interval");void 0===this.markets&&await this.loadMarkets(),"raw"===r&&await this.authenticate();let o="ticker."+i.id+"."+r,n={jsonrpc:"2.0",method:"public/subscribe",params:{channels:["ticker."+i.id+"."+r]},id:this.requestId()},d=this.deepExtend(n,a);return await this.watch(s,o,d,o,d)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=this.urls.api.ws,r=this.safeString(t,"interval","100ms"),a=this.omit(t,"interval");void 0===this.markets&&await this.loadMarkets(),"raw"===r&&await this.authenticate();let o=[];for(let e=0;e<i.length;e++){let t=this.market(i[e]);o.push("ticker."+t.id+"."+r)}let n={jsonrpc:"2.0",method:"public/subscribe",params:{channels:o},id:this.requestId()},d=this.deepExtend(n,a),h=await this.watchMultiple(s,o,d,o,d);if(this.newUpdates){let e={},t=this.safeString(h,"symbol");return void 0!==t&&(e[t]=h),e}return this.filterByArray(this.tickers,"symbol",i)}handleTicker(e,t){let i=this.safeDict(t,"params",{}),s=this.safeDict(i,"data",{}),r=this.safeString(s,"instrument_name"),a=this.safeSymbol(r),o=this.parseTicker(s),n=this.safeString(i,"channel");this.tickers[a]=o,e.resolve(o,n)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=this.urls.api.ws,r=[];for(let e=0;e<i.length;e++){let t=this.market(i[e]);r.push("quote."+t.id)}let a={jsonrpc:"2.0",method:"public/subscribe",params:{channels:r},id:this.requestId()},o=this.deepExtend(a,t),n=await this.watchMultiple(s,r,o,r,o);if(this.newUpdates){let e={},t=this.safeString(n,"symbol");return void 0!==t&&(e[t]=n),e}return this.filterByArray(this.bidsasks,"symbol",i)}handleBidAsk(e,t){let i=this.safeDict(t,"params",{}),s=this.safeDict(i,"data",{}),r=this.parseWsBidAsk(s),a=r.symbol;this.bidsasks[a]=r;let o=this.safeString(i,"channel");e.resolve(r,o)}parseWsBidAsk(e,t){let i=this.safeString(e,"instrument_name"),s=this.safeMarket(i,t),r=this.safeString(s,"symbol"),a=this.safeInteger(e,"timestamp");return this.safeTicker({symbol:r,timestamp:a,datetime:this.iso8601(a),ask:this.safeString(e,"best_ask_price"),askVolume:this.safeString(e,"best_ask_amount"),bid:this.safeString(e,"best_bid_price"),bidVolume:this.safeString(e,"best_bid_amount"),info:e},s)}async watchTrades(e,t,i,s={}){return s.callerMethodName="watchTrades",await this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){let[r,a]=this.handleOptionStringAndParams(s,"watchTradesForSymbols","interval","100ms");"raw"===r&&await this.authenticate();let o=await this.watchMultipleWrapper("trades",r,e,a),n=this.safeDict(o,0),d=this.safeString(n,"symbol"),h=i;return this.newUpdates&&(h=o.getLimit(d,i)),this.filterBySinceLimit(o,t,h,"timestamp",!0)}handleTrades(e,t){let i=this.safeDict(t,"params",{}),s=this.safeString(i,"channel","").split("."),r=this.safeString(s,1),a=this.safeString(s,2),n=this.safeSymbol(r),d=this.safeMarket(r),h=this.safeList(i,"data",[]);if(void 0===this.safeDict(this.trades,n)){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.trades[n]=new o.I3(e)}let c=this.trades[n];for(let e=0;e<h.length;e++){let t=h[e],i=this.parseTrade(t,d);c.append(i)}this.trades[n]=c,e.resolve(this.trades[n],"trades|"+n+"|"+a)}async watchMyTrades(e,t,i,s={}){await this.authenticate(s),void 0!==e&&await this.loadMarkets();let r=void 0!==e?this.symbol(e):void 0,a=this.urls.api.ws,o=this.safeString(s,"interval","raw"),n=this.omit(s,"interval"),d="user.trades.any.any."+o,h={jsonrpc:"2.0",method:"private/subscribe",params:{channels:[d]},id:this.requestId()},c=this.deepExtend(h,n),l=await this.watch(a,d,c,d,c);return this.filterBySymbolSinceLimit(l,r,t,i,!0)}handleMyTrades(e,t){let i=this.safeDict(t,"params",{}),s=this.safeString(i,"channel",""),r=this.safeList(i,"data",[]),a=this.myTrades;if(void 0===a){let e=this.safeInteger(this.options,"tradesLimit",1e3);a=new o.Pt(e)}let n=this.parseTrades(r),d={};for(let e=0;e<n.length;e++){let t=n[e];a.append(t),d[t.symbol]=!0}e.resolve(a,s)}async watchOrderBook(e,t,i={}){return i.callerMethodName="watchOrderBook",await this.watchOrderBookForSymbols([e],t,i)}async watchOrderBookForSymbols(e,t,i={}){let[s,r]=this.handleOptionStringAndParams(i,"watchOrderBookForSymbols","interval","100ms");"raw"===s&&await this.authenticate();let[a,o]=this.handleOptionBoolAndParams(r,"watchOrderBookForSymbols","useDepthEndpoint",!1),[n,d]=this.handleOptionStringAndParams(o,"watchOrderBookForSymbols","depth","20"),[h,c]=this.handleOptionStringAndParams(d,"watchOrderBookForSymbols","group","none"),l=s;a&&(l=h+"."+n+"."+s);let u=o;return a&&(u=c),(await this.watchMultipleWrapper("book",l,e,u)).limit()}handleOrderBook(e,t){let i=this.safeDict(t,"params",{}),s=this.safeDict(i,"data",{}),r=this.safeString(i,"channel").split("."),a="";a=5===r.length?this.safeString(r,2)+"."+this.safeString(r,3)+"."+this.safeString(r,4):this.safeString(r,2);let o=this.safeString(s,"instrument_name"),n=this.safeSymbol(o),d=this.safeInteger(s,"timestamp");n in this.orderbooks||(this.orderbooks[n]=this.countedOrderBook());let h=this.orderbooks[n],c=this.safeList(s,"asks",[]),l=this.safeList(s,"bids",[]);this.handleDeltas(h.asks,c),this.handleDeltas(h.bids,l),h.nonce=d,h.timestamp=d,h.datetime=this.iso8601(d),h.symbol=n,this.orderbooks[n]=h;let u="book|"+n+"|"+a;e.resolve(h,u)}cleanOrderBook(e){let t=this.safeList(e,"bids",[]),i=this.safeList(e,"asks",[]),s=[];for(let e=0;e<t.length;e++)s.push([t[e][1],t[e][2]]);let r=[];for(let e=0;e<i.length;e++)r.push([i[e][1],i[e][2]]);return e.bids=s,e.asks=r,e}handleDelta(e,t){let i=t[1],s=t[2],r=this.safeString(t,0);"new"===r||"change"===r?e.storeArray([i,s,1]):"delete"===r&&e.storeArray([i,s,0])}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}async watchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate(s);let r=void 0!==e?this.symbol(e):void 0,a=this.urls.api.ws,o=this.safeString(s,"currency","any"),n=this.safeString(s,"interval","raw"),d=this.safeString(s,"kind","any"),h=this.omit(s,"interval","currency","kind"),c="user.orders."+d+"."+o+"."+n,l={jsonrpc:"2.0",method:"private/subscribe",params:{channels:[c]},id:this.requestId()},u=this.deepExtend(l,h),f=await this.watch(a,c,u,c,u),p=i;return this.newUpdates&&(p=f.getLimit(r,i)),this.filterBySymbolSinceLimit(f,r,t,p,!0)}handleOrders(e,t){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}let i=this.safeDict(t,"params",{}),s=this.safeString(i,"channel",""),r=this.safeValue(i,"data",{}),a=[];a=Array.isArray(r)?this.parseOrders(r):[this.parseOrder(r)];let n=this.orders;for(let e=0;e<a.length;e++)n.append(a[e]);e.resolve(this.orders,s)}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.symbol(e);return(await this.watchOHLCVForSymbols([[a,t]],i,s,r))[a][t]}async watchOHLCVForSymbols(e,t,i,s={}){if(0===e.length||!Array.isArray(e[0]))throw new a.ArgumentsRequired(this.id+" watchOHLCVForSymbols() requires a an array of symbols and timeframes, like  [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]");let[r,o,n]=await this.watchMultipleWrapper("chart.trades",void 0,e,s),d=i;this.newUpdates&&(d=n.getLimit(r,i));let h=this.filterBySinceLimit(n,t,d,0,!0);return this.createOHLCVObject(r,o,h)}handleOHLCV(e,t){let i=this.safeDict(t,"params",{}),s=this.safeString(i,"channel","").split("."),r=this.safeString(s,2),a=this.safeString(s,3),n=this.safeMarket(r),d=n.symbol,h=this.safeDict(this.options,"ws",{}),c=this.safeDict(h,"timeframes",{}),l=this.findTimeframe(a,c);if(this.ohlcvs[d]=this.safeDict(this.ohlcvs,d,{}),void 0===this.safeDict(this.ohlcvs[d],l)){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);this.ohlcvs[d][l]=new o.TG(e)}let u=this.ohlcvs[d][l],f=this.safeDict(i,"data",{}),p=this.parseWsOHLCV(f,n);u.append(p),this.ohlcvs[d][l]=u;let m=[d,l,u],g="chart.trades|"+d+"|"+a;e.resolve(m,g)}parseWsOHLCV(e,t){return[this.safeInteger(e,"tick"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async watchMultipleWrapper(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.urls.api.ws,o=[],n=[],d="chart.trades"===e,h=d?this.getListFromObjectValues(i,0):i;if(this.marketSymbols(h,void 0,!1),void 0===i)throw new a.ArgumentsRequired(this.id+" watchMultipleWrapper() symbolsArray is required");for(let s=0;s<i.length;s++){let r,h;if(void 0===i)throw new a.ArgumentsRequired(this.id+" watchMultipleWrapper() symbolsArray is required");let c=i[s];if(d){r=this.market(c[0]);let e=c[1];h=this.safeString(this.timeframes,e,e)}else r=this.market(c),h=t;let l=e+"."+r.id+"."+h;o.push(l),n.push(e+"|"+r.symbol+"|"+h)}let c={jsonrpc:"2.0",method:"public/subscribe",params:{channels:o},id:this.requestId()},l=this.deepExtend(c,s);if(this.json(l).length>=32767)throw new a.ExchangeError(this.id+" requested subscription length over limit, try to reduce symbols amount");return await this.watchMultiple(r,n,l,o)}handleMessage(e,t){let i=this.safeValue(t,"error");if(void 0!==i)throw new a.ExchangeError(this.id+" "+this.json(i));let s=this.safeDict(t,"params"),r=this.safeString(s,"channel");if(void 0!==r){let i=r.split("."),s=this.safeString(i,0),o={trades:this.handleMyTrades,portfolio:this.handleBalance,orders:this.handleOrders},n={ticker:this.handleTicker,quote:this.handleBidAsk,book:this.handleOrderBook,trades:this.handleTrades,chart:this.handleOHLCV,user:this.safeValue(o,this.safeString(i,1))},d=this.safeValue(n,s);if(void 0!==d)return void d.call(this,e,t);throw new a.NotSupported(this.id+" no handler found for this message "+this.json(t))}let o=this.safeDict(t,"result",{});void 0!==this.safeString(o,"access_token")&&this.handleAuthenticationMessage(e,t)}handleAuthenticationMessage(e,t){return e.resolve(t,"authenticated"),t}async authenticate(e={}){let t=this.urls.api.ws,i=this.client(t),r=this.milliseconds(),a=this.numberToString(r),o="authenticated",n=this.safeValue(i.subscriptions,o);if(void 0===n){this.checkRequiredCredentials();let d=this.requestId(),h=this.hmac(this.encode(a+"\n"+a+"\n"),this.encode(this.secret),s.sc),c={jsonrpc:"2.0",id:d,method:"public/auth",params:{grant_type:"client_signature",client_id:this.apiKey,timestamp:r,signature:h,nonce:a,data:""}};n=await this.watch(t,o,this.extend(c,e),o),i.subscriptions[o]=n}return n}}i.d(t,{A:()=>n})},3253(e,t,i){"use strict";var s=i(8025),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!1,watchBalance:!1,watchMyTrades:!0,watchOHLCV:!1,watchOrderBook:!0,watchOrders:!0,watchTicker:!0,watchTickers:!1,watchBidsAsks:!1,watchTrades:!0,watchTradesForSymbols:!1,watchPositions:!1},urls:{api:{ws:"wss://api.lyra.finance/ws"},test:{ws:"wss://api-demo.lyra.finance/ws"}},options:{tradesLimit:1e3,ordersLimit:1e3,requestId:{}},streaming:{keepAlive:9e3},exceptions:{ws:{exact:{}}}})}requestId(e){let t=this.safeDict(this.options,"requestId",{}),i=this.safeInteger(t,e,0),s=this.sum(i,1);return this.options.requestId[e]=s,s}async watchPublic(e,t,i){let s=this.urls.api.ws,r=this.requestId(s),a=this.extend(t,{id:r}),o=this.extend(i,{id:r,method:"subscribe"});return await this.watch(s,e,a,e,o)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=void 0===t?10:t,r="orderbook."+this.market(e).id+".10."+this.numberToString(s);return(await this.watchPublic(r,{method:"subscribe",params:{channels:[r]}},{name:r,symbol:e,limit:s,params:i})).limit()}handleOrderBook(e,t){let i=this.safeDict(t,"params"),s=this.safeDict(i,"data",{}),r=this.safeString(s,"instrument_name"),a=this.safeMarket(r).symbol,o=this.safeString(i,"channel");if(!(a in this.orderbooks)){let t=this.safeInteger(this.options,"watchOrderBookLimit",1e3),i=void 0===o?void 0:e.subscriptions[o],s=this.safeInteger(i,"limit",t);this.orderbooks[a]=this.orderBook({},s)}let n=this.orderbooks[a],d=this.safeInteger(s,"timestamp"),h=this.parseOrderBook(s,a,d,"bids","asks");n.reset(h),e.resolve(n,o)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i="ticker_slim."+this.market(e).id+".100";return await this.watchPublic(i,{method:"subscribe",params:{channels:[i]}},{name:i,symbol:e,params:t})}handleTicker(e,t){let i,s=this.safeDict(t,"params"),r=this.safeDict(s,"data"),a=this.safeDict(r,"instrument_ticker",{}),o=this.safeString(s,"channel");if(void 0!==o&&o.startsWith("ticker_slim")){let e=o.split("."),t=this.safeString(e,1),s=this.safeMarket(t),n=this.safeDict(a,"stats",{});i=this.safeTicker({symbol:s.symbol,timestamp:this.safeInteger(a,"t"),datetime:this.iso8601(this.safeInteger(a,"t")),bid:this.safeString(a,"b"),bidVolume:this.safeString(a,"B"),ask:this.safeString(a,"a"),askVolume:this.safeString(a,"A"),high:this.safeString(n,"h"),low:this.safeString(n,"l"),baseVolume:this.safeString(n,"c"),quoteVolume:this.safeString(n,"v"),percentage:this.safeString(n,"p"),markPrice:this.safeString(a,"M"),indexPrice:this.safeString(a,"I"),info:r},s)}else i=this.parseTicker(a);let n=i.symbol;return void 0!==n&&(this.tickers[n]=i),e.resolve(i,o),t}async unWatchOrderBook(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeInteger(t,"limit");void 0===i&&(i=10);let s="orderbook."+this.market(e).id+".10."+this.numberToString(i),r="unwatch"+s;return await this.unWatchPublic(r,{method:"unsubscribe",params:{channels:[s]}},{name:s})}async unWatchTrades(e,t={}){void 0===this.markets&&await this.loadMarkets();let i="trades."+this.market(e).id,s="unwatch"+i;return await this.unWatchPublic(s,{method:"unsubscribe",params:{channels:[i]}},{name:i})}async unWatchPublic(e,t,i){let s=this.urls.api.ws,r=this.requestId(s),a=this.extend(t,{id:r}),o=this.extend(i,{id:r,method:"unsubscribe"});return await this.watch(s,e,a,e,o)}handleOrderBookUnSubscription(e,t){let i=t.split("."),s=this.safeString(i,1),a=this.safeMarket(s).symbol;a in this.orderbooks&&delete this.orderbooks[a],t in e.subscriptions&&delete e.subscriptions[t];let o=new r.UnsubscribeError(this.id+" orderbook "+a);e.reject(o,t),e.resolve(o,"unwatch"+t)}handleTradesUnSubscription(e,t){let i=t.split("."),s=this.safeString(i,1),a=this.safeMarket(s).symbol;a in this.orderbooks&&delete this.trades[a],t in e.subscriptions&&delete e.subscriptions[t];let o=new r.UnsubscribeError(this.id+" trades "+a);e.reject(o,t),e.resolve(o,"unwatch"+t)}handleUnSubscribe(e,t){let i=this.safeDict(t,"result"),s=this.safeDict(i,"status");if(void 0!==s){let t=Object.keys(s);for(let i=0;i<t.length;i++){let s=t[i];s.indexOf("orderbook")>=0?this.handleOrderBookUnSubscription(e,s):s.indexOf("trades")>=0&&this.handleTradesUnSubscription(e,s)}}return t}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a="trades."+r.id,o=await this.watchPublic(a,{method:"subscribe",params:{channels:[a]}},{name:a,symbol:e,params:s}),n=i;return this.newUpdates&&(n=o.getLimit(r.symbol,i)),this.filterBySymbolSinceLimit(o,e,t,n,!0)}handleTrade(e,t){let i=this.safeDict(t,"params"),s=this.safeDict(i,"data",{}),r=this.safeValue(i,"channel"),o=r.split("."),n=this.safeString(o,1),d=this.safeMarket(n).symbol,h=this.safeValue(this.trades,d);if(void 0===h){let e=this.safeInteger(this.options,"tradesLimit",1e3);h=new a.I3(e)}for(let e=0;e<s.length;e++){let t=this.parseTrade(s[e]);h.append(t)}this.trades[d]=h,e.resolve(h,r)}async authenticate(e={}){this.checkRequiredCredentials();let t=this.urls.api.ws,i=this.client(t),s="authenticated",r=i.reusableFuture(s);if(void 0===this.safeValue(i.subscriptions,s)){let i=this.requestId(t),r=this.milliseconds().toString(),a=this.signMessage(r,this.privateKey),o=this.safeString(this.options,"deriveWalletAddress"),n=this.extend({id:i,method:"public/login",params:{wallet:o,timestamp:r,signature:a}},e);this.watch(t,s,n,s,n)}return await r}async watchPrivate(e,t,i){await this.authenticate();let s=this.urls.api.ws,r=this.requestId(s),a=this.extend(t,{id:r}),o=this.extend(i,{id:r,method:"subscribe"});return await this.watch(s,e,a,e,o)}async watchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleDeriveSubaccountId("watchOrders",s),o=this.numberToString(r)+".orders",n=o,d=void 0!==e?this.symbol(e):e;void 0!==d&&(n+=":"+d);let h=this.extend({method:"subscribe",params:{channels:[o]}},a),c=await this.watchPrivate(n,h,{name:o,params:a}),l=i;return this.newUpdates&&(l=c.getLimit(d,i)),this.filterBySymbolSinceLimit(c,d,t,l,!0)}handleOrder(e,t){let i=this.safeDict(t,"params"),s=this.safeString(i,"channel"),r=this.safeList(i,"data",[]);for(let t=0;t<r.length;t++){let i=r[t],o=this.parseOrder(i),n=this.safeString(o,"symbol"),d=this.safeString(o,"id");if(void 0!==n){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}let t=this.orders,i=this.safeDict(t.hashmap,n,{}),r=void 0===d?void 0:this.safeDict(i,d);if(void 0!==r){let e=this.safeValue(r,"fee");void 0!==e&&(o.fee=e);let t=this.safeList(r,"fees");void 0!==t&&(o.fees=t),o.trades=this.safeValue(r,"trades"),o.timestamp=this.safeInteger(r,"timestamp"),o.datetime=this.safeString(r,"datetime")}if(t.append(o),void 0!==s){let t=s+":"+n;e.resolve(this.orders,t)}}}e.resolve(this.orders,s)}async watchMyTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleDeriveSubaccountId("watchMyTrades",s),o=this.numberToString(r)+".trades",n=o,d=void 0!==e?this.symbol(e):e;void 0!==d&&(n+=":"+d);let h=this.extend({method:"subscribe",params:{channels:[o]}},a),c=await this.watchPrivate(n,h,{name:o,params:a}),l=i;return this.newUpdates&&(l=c.getLimit(d,i)),this.filterBySymbolSinceLimit(c,d,t,l,!0)}handleMyTrade(e,t){let i=this.myTrades;if(void 0===i){let e=this.safeInteger(this.options,"tradesLimit",1e3);i=new a.Pt(e)}let s=this.safeDict(t,"params"),r=this.safeString(s,"channel"),o=this.safeList(s,"data",[]);for(let s=0;s<o.length;s++){let s=this.parseTrade(t);if(i.append(s),e.resolve(i,r),void 0!==r){let t=r+this.safeString(s,"symbol","");e.resolve(i,t)}}}handleErrorMessage(e,t){if(!("error"in t))return!1;let i=this.safeDict(t,"error"),s=this.safeString(i,"code");try{if(void 0!==s){let e=this.id+" "+this.json(t);throw this.throwExactlyMatchedException(this.exceptions.exact,s,e),new r.ExchangeError(e)}return!1}catch(t){if(t instanceof r.AuthenticationError){let i="authenticated";e.reject(t,i),i in e.subscriptions&&delete e.subscriptions[i]}else e.reject(t);return!0}}handleMessage(e,t){let i;if(!0===this.handleErrorMessage(e,t))return;let s={orderbook:this.handleOrderBook,ticker:this.handleTicker,ticker_slim:this.handleTicker,trades:this.handleTrade,orders:this.handleOrder,mytrades:this.handleMyTrade},r=this.safeDict(t,"params");if(void 0!==r){let e=this.safeString(r,"channel");if(void 0!==e){let t=e.split(".");e.indexOf("orders")>=0||e.indexOf("trades")>0?"trades"===(i=this.safeString(t,1))&&(i="mytrades"):i=this.safeString(t,0)}}let a=void 0===i?void 0:this.safeValue(s,i);if(void 0!==a)return void a.call(this,e,t);if("id"in t){let i=this.safeString(t,"id"),s=this.indexBy(e.subscriptions,"id"),r=void 0===i?{}:this.safeDict(s,i,{});"method"in r&&("public/login"===this.safeString(r,"method")?this.handleAuth(e,t):"unsubscribe"===this.safeString(r,"method")&&this.handleUnSubscribe(e,t))}}handleAuth(e,t){let i="authenticated";if(this.safeList(t,"result",[]).length>0)this.safeValue(e.futures,"authenticated").resolve(!0);else{let s=new r.AuthenticationError(this.json(t));e.reject(s,i),i in e.subscriptions&&delete e.subscriptions.authenticated}}}i.d(t,{A:()=>o})},9601(e,t,i){"use strict";var s=i(3397),r=i(1697),a=i(1453);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!1,watchTicker:!1,watchTickers:!1,watchTrades:!0,watchOrderBook:!0,watchOHLCV:!0},urls:{test:{ws:"wss://indexer.v4testnet.dydx.exchange/v4/ws"},api:{ws:"wss://indexer.dydx.trade/v4/ws"}},options:{},streaming:{},exceptions:{}})}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.urls.api.ws,a=this.market(e),o="trade:"+a.symbol,n={type:"subscribe",channel:"v4_trades",id:a.id},d=await this.watch(r,o,this.extend(n,s),o),h=i;return this.newUpdates&&(h=d.getLimit(e,i)),this.filterBySinceLimit(d,t,h,"timestamp",!0)}async unWatchTrades(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.urls.api.ws,s=this.market(e),r="trade:"+s.symbol,a={type:"unsubscribe",channel:"v4_trades",id:s.id};return await this.watch(i,r,this.extend(a,t),r)}handleTrades(e,t){let i=this.safeString(t,"id"),s=this.safeMarket(i),a=s.symbol,o=this.safeDict(t,"contents"),n=this.safeList(o,"trades",[]),d=this.safeValue(this.trades,a);if(void 0===d){let e=this.safeInteger(this.options,"tradesLimit",1e3);d=new r.I3(e),this.trades[a]=d}let h=this.parseTrades(n,s);for(let e=0;e<h.length;e++){let t=h[e];d.append(t)}let c="trade:"+a;e.resolve(d,c)}parseWsTrade(e,t){let i=this.parse8601(this.safeString(e,"createdAt"));return this.safeTrade({id:this.safeString(e,"id"),info:e,timestamp:i,datetime:this.iso8601(i),symbol:this.safeString(t,"symbol"),order:void 0,type:this.safeStringLower(e,"type"),side:this.safeStringLower(e,"side"),takerOrMaker:void 0,price:this.safeString(e,"price"),amount:this.safeString(e,"size"),cost:void 0,fee:void 0},t)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.urls.api.ws,r=this.market(e),a="orderbook:"+r.symbol,o={type:"subscribe",channel:"v4_orderbook",id:r.id};return(await this.watch(s,a,this.extend(o,i),a)).limit()}async unWatchOrderBook(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.urls.api.ws,s=this.market(e),r="orderbook:"+s.symbol,a={type:"unsubscribe",channel:"v4_orderbook",id:s.id};return await this.watch(i,r,this.extend(a,t),r)}handleOrderBook(e,t){let i=this.safeString(t,"id"),s=this.safeMarket(i).symbol,r=this.safeDict(t,"contents"),a=this.safeValue(this.orderbooks,s);void 0===a&&(a=this.orderBook()),a.symbol=s;let o=this.safeList(r,"asks",[]),n=this.safeList(r,"bids",[]);this.handleDeltas(a.asks,o),this.handleDeltas(a.bids,n),a.nonce=this.safeInteger(t,"message_id");let d="orderbook:"+s;this.orderbooks[s]=a,e.resolve(a,d)}handleDelta(e,t){if(Array.isArray(t)){let i=this.safeFloat(t,0),s=this.safeFloat(t,1);e.store(i,s)}else{let i=this.parseOrderBookBidAsk(t,"price","size");e.storeArray(i)}}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.urls.api.ws,o=this.market(e),n="ohlcv:"+o.symbol,d=this.safeString(this.timeframes,t,t),h={type:"subscribe",channel:"v4_candles",id:o.id+"/"+d},c=await this.watch(a,n,this.extend(h,r),n),l=s;return this.newUpdates&&(l=c.getLimit(e,s)),this.filterBySinceLimit(c,i,l,0,!0)}async unWatchOHLCV(e,t="1m",i={}){void 0===this.markets&&await this.loadMarkets();let s=this.urls.api.ws,r=this.market(e),a="ohlcv:"+r.symbol,o=this.safeString(this.timeframes,t,t),n={type:"unsubscribe",channel:"v4_candles",id:r.id+"/"+o};return await this.watch(s,a,this.extend(n,i),a)}handleOHLCV(e,t){let i=this.safeString(t,"id","").split("/"),s=this.safeString(i,1),a=this.findTimeframe(s),o=this.safeString(i,0),n=this.safeMarket(o),d=n.symbol,h=this.safeDict(t,"contents"),c=this.safeList(h,"candles"),l=this.safeDict(c,0,h),u=this.parseOHLCV(l,n);this.ohlcvs[d]=this.safeDict(this.ohlcvs,d,{});let f=this.safeValue(this.ohlcvs[d],a);if(void 0===f){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);f=new r.TG(e),this.ohlcvs[d][a]=f}f.append(u),e.resolve(f,"ohlcv:"+d)}handleErrorMessage(e,t){try{let e=this.safeString(t,"message");throw new a.ExchangeError(this.id+" "+e)}catch(t){e.reject(t)}return!0}handleMessage(e,t){let i=this.safeString(t,"type");if("error"===i)return void this.handleErrorMessage(e,t);if(void 0!==i){let i=this.safeString(t,"channel"),s={v4_trades:this.handleTrades,v4_orderbook:this.handleOrderBook,v4_candles:this.handleOHLCV},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}}}i.d(t,{A:()=>o})},9195(e,t,i){"use strict";var s=i(1223),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchFundingRate:!0,watchOHLCV:!0,watchOrderBook:!0,watchIndexPrice:!0,watchMarkPrice:!0,watchTrades:!0,watchBalance:!0,watchMyTrades:!0,watchOrders:!0,watchPositions:!0},urls:{api:{ws:"wss://api.starknet.extended.exchange/stream.extended.exchange/v1"},test:{ws:"wss://api.starknet.sepolia.extended.exchange/stream.extended.exchange/v1"}},options:{ws:{options:{headers:{"User-Agent":this.userAgents.chrome}}}}})}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=s.symbol,a="orderbook:"+r,o=this.urlencode(i),n=this.safeString(this.urls.api,"ws")+"/orderbooks/"+s.id;return o.length>0&&(n+="?"+o),(await this.watch(n,a,void 0,a,{symbol:r,limit:t})).limit()}handleOrderBook(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"m"),a=this.safeMarket(s).symbol,o="orderbook:"+a,n=this.safeInteger(t,"ts"),d=this.safeInteger(t,"seq"),h=this.safeString(t,"type",this.safeString(i,"t"));if(!(a in this.orderbooks)){let t=this.safeInteger(this.options,"watchOrderBookLimit",1e3),i=this.safeDict(e.subscriptions,o,{}),s=this.safeInteger(i,"limit",t);this.orderbooks[a]=this.orderBook({},s)}let c=this.orderbooks[a];if("SNAPSHOT"===h){let t=this.parseOrderBook(i,a,n,"b","a","p","q");t.nonce=d,c.reset(t),e.resolve(c,o);return}let l=this.safeInteger(c,"nonce");if(void 0!==l&&d!==l+1){delete e.subscriptions[o],delete this.orderbooks[a];let t=new r.InvalidNonce(this.id+" watchOrderBook received invalid nonce");e.reject(t,o);return}this.handleDeltas(c.bids,this.safeList(i,"b",[])),this.handleDeltas(c.asks,this.safeList(i,"a",[])),c.timestamp=n,c.datetime=this.iso8601(n),c.nonce=d,e.resolve(c,o)}handleDelta(e,t){let i=this.safeFloat(t,"p"),s=this.safeFloat2(t,"c","q");e.store(i,s)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}async watchPrivate(e,t){this.checkRequiredCredentials();let i=this.safeString(this.urls.api,"ws")+"/account";if(void 0===this.clients||!(i in this.clients)){this.extendExchangeOptions({ws:{options:{headers:{}}}});let e=this.options.ws.options,t=this.safeDict(e,"headers",{});this.options.ws.options=this.extend(this.extend({},e),{headers:this.extend(this.extend({"User-Agent":this.userAgents.chrome},t),{"X-Api-Key":this.apiKey})}),this.client(i),this.options.ws.options=e}return await this.watch(i,e,void 0,e,t)}async watchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a="orders";if(void 0!==e){let t=this.market(e);a+=":"+(r=this.safeString(t,"symbol"))}let o=await this.watchPrivate(a,{symbol:r,limit:i}),n=i;return this.newUpdates&&(n=o.getLimit(r,i)),this.filterBySymbolSinceLimit(o,r,t,n,!0)}async watchBalance(e={}){return void 0===this.markets&&await this.loadMarkets(),await this.watchPrivate("balance",e)}handleBalance(e,t){void 0===this.balance&&(this.balance={});let i=this.safeDict(t,"data",{});this.balance.info=i;let s=this.safeDict(i,"balance");if(void 0!==s){let e=this.safeString(s,"collateralName"),t=this.safeCurrencyCode(e);if(void 0!==t){let e=this.account();e.free=this.safeString(s,"availableForWithdrawal"),e.total=this.safeString(s,"balance"),this.balance[t]=e}}let r=this.safeList(i,"spotBalances",[]);for(let e=0;e<r.length;e++){let t=this.safeDict(r,e,{}),i=this.safeString(t,"asset"),s=this.safeCurrencyCode(i);if(void 0!==s){let e=this.account();e.free=this.safeString(t,"availableToWithdraw"),e.total=this.safeString(t,"balance"),this.balance[s]=e}}let a=this.safeInteger(t,"ts");this.balance.timestamp=a,this.balance.datetime=this.iso8601(a),this.balance=this.safeBalance(this.balance),e.resolve(this.balance,"balance")}async watchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a="myTrades";if(void 0!==e){let t=this.market(e);a+=":"+(r=this.safeString(t,"symbol"))}let o=await this.watchPrivate(a,{symbol:r,limit:i}),n=i;return this.newUpdates&&(n=o.getLimit(r,i)),this.filterBySymbolSinceLimit(o,r,t,n,!0)}handleMyTrades(e,t){if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new a.Pt(e)}let i=this.myTrades,s=this.safeDict(t,"data",{}),r=this.safeList(s,"trades",[]),o={};if(void 0===this.safeDict(r,0))return;for(let e=0;e<r.length;e++){let t=this.parseTrade(r[e]);o[this.safeString(t,"symbol")]=!0,i.append(t)}let n=Object.keys(o);for(let t=0;t<n.length;t++){let s="myTrades:"+n[t];e.resolve(i,s)}e.resolve(i,"myTrades");let d=Object.keys(e.subscriptions);for(let t=0;t<d.length;t++){let s=d[t];0===s.indexOf("myTrades:")&&e.resolve(i,s)}}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e),a="positions";void 0!==r&&(a+="::"+r.join(","));let o=await this.watchPrivate(a,{symbols:r,limit:i});return this.newUpdates?o:this.filterBySymbolsSinceLimit(this.positions,r,t,i,!0)}handlePositions(e,t){void 0===this.positions&&(this.positions=new a.Hk);let i=this.positions,s=this.safeDict(t,"data",{}),r=this.safeList(s,"positions",[]),o=[];if(void 0===this.safeDict(r,0))return;for(let e=0;e<r.length;e++){let t=r[e];if(void 0===this.safeString(t,"market"))continue;let s=this.parsePosition(t);o.push(s),i.append(s)}let n=this.findMessageHashes(e,"positions::");for(let t=0;t<n.length;t++){let i=n[t],s=i.split("::")[1].split(","),r=this.filterByArray(o,"symbol",s,!1);this.isEmpty(r)||e.resolve(r,i)}e.resolve(o,"positions")}handleOrders(e,t){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}let i=this.orders,s=this.safeDict(t,"data",{}),r=this.safeList(s,"orders"),o={};if(void 0===this.safeDict(r,0))return;for(let e=0;e<r.length;e++){let t=this.parseOrder(r[e]);o[this.safeString(t,"symbol")]=!0,i.append(t)}let n=Object.keys(o);for(let t=0;t<n.length;t++){let s="orders:"+n[t];e.resolve(i,s)}e.resolve(i,"orders");let d=Object.keys(e.subscriptions);for(let t=0;t<d.length;t++){let s=d[t];0===s.indexOf("orders:")&&e.resolve(i,s)}}async watchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r="fundingRate:"+s,a=this.urlencode(t),o=this.safeString(this.urls.api,"ws")+"/funding/"+i.id;return a.length>0&&(o+="?"+a),await this.watch(o,r,void 0,r,{symbol:s,messageHash:r})}handleFundingRate(e,t){let i=this.safeDict(t,"data",{}),s=this.parseWsFundingRate(i,void 0,t),r=this.safeString(s,"symbol");this.fundingRates[r]=s,e.resolve(s,"fundingRate:"+r)}parseWsFundingRate(e,t,i){let s=this.safeString(e,"m"),r=this.safeMarket(s,t),a=this.safeInteger(i,"ts"),o=this.safeInteger(e,"T");return{info:e,symbol:r.symbol,markPrice:void 0,indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:a,datetime:this.iso8601(a),fundingRate:this.safeNumber(e,"f"),fundingTimestamp:o,fundingDatetime:this.iso8601(o),nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:void 0}}async watchMarkPrice(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r="markPrice:"+s,a=this.urlencode(t),o=this.safeString(this.urls.api,"ws")+"/prices/mark/"+i.id;return a.length>0&&(o+="?"+a),await this.watch(o,r,void 0,r,{name:"markPrice",symbol:s,messageHash:r})}handleMarkPrice(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"m"),r=this.safeMarket(s),a=r.symbol,o=this.safeInteger(i,"ts");(void 0===o||0===o)&&(o=this.safeInteger(t,"ts"));let n=this.safeTicker({symbol:a,timestamp:o,datetime:this.iso8601(o),markPrice:this.safeString(i,"p"),info:t},r);this.tickers[a]=n;let d="markPrice:"+a;e.resolve(n,d)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o="trades:"+a,n=this.urlencode(s),d=this.safeString(this.urls.api,"ws")+"/publicTrades/"+r.id;n.length>0&&(d+="?"+n);let h=await this.watch(d,o,void 0,o,{symbol:a,limit:i}),c=i;return this.newUpdates&&(c=h.getLimit(a,i)),this.filterBySinceLimit(h,t,c,"timestamp",!0)}handleTrades(e,t){let i=this.safeList(t,"data",[]),s=this.safeDict(i,0);if(void 0===s)return;let r=this.safeString(s,"m"),o=this.safeMarket(r),n=o.symbol,d="trades:"+n,h=this.safeDict(e.subscriptions,d,{}),c=this.safeValue(this.trades,n);if(void 0===c){let e=this.safeInteger(this.options,"tradesLimit",1e3),t=this.safeInteger(h,"limit",e);c=new a.I3(t),this.trades[n]=c}let l=this.safeInteger(h,"nonce"),u=this.safeInteger(t,"seq");if(void 0===l||void 0===u||!(u<=l)){h.nonce=u;for(let e=0;e<i.length;e++){let t=this.parseTrade(i[e],o);c.append(t)}e.resolve(c,d)}}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n=this.safeString(r,"price"),d=this.safeString(r,"candleType");void 0===d&&(d="mark"===n?"mark-prices":"index"===n?"index-prices":"trades");let h=this.omit(r,["candleType","price"]),c=this.safeString(this.timeframes,t,t),l="ohlcv:"+o+":"+t+":"+d,u=this.urlencode(this.extend({interval:c},h)),f=this.safeString(this.urls.api,"ws")+"/candles/"+a.id+"/"+d+"?"+u,p=await this.watch(f,l,void 0,l,{name:"ohlcv",symbol:o,timeframe:t,candleType:d,limit:s,messageHash:l}),m=s;return this.newUpdates&&(m=p.getLimit(o,s)),this.filterBySinceLimit(p,i,m,0,!0)}handleOHLCV(e,t){let i,s=this.findSubscription(e,"ohlcv");if(void 0===s)return;let r=this.safeString(s,"symbol"),o=this.safeString(s,"timeframe"),n=this.safeString(s,"candleType");i="trades"===n?o:o+":"+n;let d=this.safeString(s,"messageHash");this.ohlcvs[r]=this.safeDict(this.ohlcvs,r,{});let h=this.safeValue(this.ohlcvs[r],i);if(void 0===h){let e=this.safeInteger(this.options,"OHLCVLimit",1e3),t=this.safeInteger(s,"limit",e);h=new a.TG(t),this.ohlcvs[r][i]=h}let c=this.safeInteger(s,"nonce"),l=this.safeInteger(t,"seq");if(void 0!==c&&void 0!==l&&l<=c)return;s.nonce=l;let u=this.safeList(t,"data",[]);for(let e=0;e<u.length;e++){let t=this.parseOHLCV(u[e]);h.append(t)}e.resolve(h,d)}findSubscription(e,t){let i=Object.keys(e.subscriptions);for(let s=0;s<i.length;s++){let r=i[s],a=this.safeDict(e.subscriptions,r);if(this.safeString(a,"name")===t)return a}}handleErrorMessage(e,t){let i=this.safeDict(t,"error");if(void 0===i)return!1;let s=this.id+" "+this.json(t),a=this.safeString(i,"code");this.throwExactlyMatchedException(this.exceptions.exact,a,s);let o=this.safeString(i,"message");throw this.throwBroadlyMatchedException(this.exceptions.broad,o,s),new r.ExchangeError(s)}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;let i=this.safeString(t,"type"),s=this.safeValue(t,"data");if(Array.isArray(s)){let i=this.safeDict(s,0,{});void 0!==this.safeString(i,"S")?this.handleTrades(e,t):this.handleOHLCV(e,t)}else if(void 0!==s){let r=!1;("ORDER"===i||"orders"in s)&&(this.handleOrders(e,t),r=!0),("TRADE"===i||"trades"in s)&&(this.handleMyTrades(e,t),r=!0),("POSITION"===i||"positions"in s)&&(this.handlePositions(e,t),r=!0),("BALANCE"===i||"balance"in s||"spotBalances"in s)&&(this.handleBalance(e,t),r=!0),"MP"===i?this.handleMarkPrice(e,t):"f"in s?this.handleFundingRate(e,t):r||this.handleOrderBook(e,t)}}}i.d(t,{A:()=>o})},2541(e,t,i){"use strict";var s=i(4721),r=i(1305),a=i(1453),o=i(1697),n=i(7749);class d extends r.A{describe(){let e=super.describe();return this.deepExtend(e,this.describeData())}describeData(){return{has:{ws:!0,cancelAllOrdersWs:!0,cancelOrderWs:!0,createMarketBuyOrderWithCostWs:!0,createMarketOrderWs:!0,createMarketOrderWithCostWs:!1,createMarketSellOrderWithCostWs:!1,createOrderWs:!0,createOrdersWs:!0,createPostOnlyOrderWs:!0,createReduceOnlyOrderWs:!0,createStopLimitOrderWs:!0,createStopLossOrderWs:!0,createStopMarketOrderWs:!1,createStopOrderWs:!0,createTakeProfitOrderWs:!0,createTriggerOrderWs:!0,editOrderWs:!0,fetchOrderWs:!0,fetchOrdersWs:!1,fetchOpenOrdersWs:!0,fetchClosedOrdersWs:!0,watchOrderBook:!0,watchBidsAsks:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!0,watchMyTrades:!0,watchOHLCV:!0,watchBalance:!0,watchOrders:!0,watchLiquidations:!1,watchLiquidationsForSymbols:!1,watchMyLiquidations:!0,watchMyLiquidationsForSymbols:!0,watchPositions:!0,unWatchTicker:!1,unWatchTickers:!1,unWatchOHLCV:!1,unWatchOHLCVForSymbols:!1,unWatchOrderBook:!0,unWatchOrderBookForSymbols:!1,unWatchTrades:!0,unWatchTradesForSymbols:!0,unWatchMyTrades:!1,unWatchOrders:!1,unWatchPositions:!1,unWatchMarkPrices:!1,unWatchMarkPrice:!1},urls:{api:{ws:"wss://ws.gate.io/v4",spot:"wss://api.gateio.ws/ws/v4/",swap:{usdt:"wss://fx-ws.gateio.ws/v4/ws/usdt",btc:"wss://fx-ws.gateio.ws/v4/ws/btc"},future:{usdt:"wss://fx-ws.gateio.ws/v4/ws/delivery/usdt",btc:"wss://fx-ws.gateio.ws/v4/ws/delivery/btc"},option:{usdt:"wss://op-ws.gateio.live/v4/ws/usdt",btc:"wss://op-ws.gateio.live/v4/ws/btc"}},test:{swap:{usdt:"wss://ws-testnet.gate.com/v4/ws/futures/usdt",btc:"wss://fx-ws-testnet.gateio.ws/v4/ws/btc"},future:{usdt:"wss://fx-ws-testnet.gateio.ws/v4/ws/delivery/usdt",btc:"wss://fx-ws-testnet.gateio.ws/v4/ws/delivery/btc"},option:{usdt:"wss://ws-testnet.gate.com/v4/ws/options/usdt",btc:"wss://ws-testnet.gate.com/v4/ws/options/btc"}}},options:{tradesLimit:1e3,OHLCVLimit:1e3,watchTradesSubscriptions:{},watchTickerSubscriptions:{},watchOrderBookSubscriptions:{},watchTicker:{name:"tickers"},watchOrderBook:{snapshotDelay:10,snapshotMaxRetries:3,checksum:!0},watchBalance:{settle:"usdt",spot:"spot.balances"},watchPositions:{fetchPositionsSnapshot:!0,awaitPositionsSnapshot:!0}},exceptions:{ws:{exact:{1:a.BadRequest,2:a.BadRequest,4:a.AuthenticationError,6:a.AuthenticationError,11:a.AuthenticationError},broad:{}}}}}async createOrderWs(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=o.symbol,d=this.getTypeByMarket(o),h=this.getUrlByMarket(o);a.textIsRequired=!0;let c=this.createOrderRequest(n,t,i,s,r,a);await this.authenticate(h,d);let l=await this.requestPrivate(h,c,d+".order_place");return this.parseOrder(l,o)}async createOrdersWs(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.createOrdersRequest(e,t),s=e[0],r=this.market(s.symbol);if(!0!==r.swap)throw new a.NotSupported(this.id+" createOrdersWs is not supported for swap markets");let o=this.getTypeByMarket(r),n=this.getUrlByMarket(r);await this.authenticate(n,o);let d=await this.requestPrivate(n,i,o+".order_batch_place");return this.parseOrders(d,r)}async cancelAllOrdersWs(e,t={}){let i;if(void 0===e)throw new a.ArgumentsRequired(this.id+" cancelAllOrdersWs() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),i=void 0===e?void 0:this.market(e);let s=this.safeBool2(t,"stop","trigger"),r=this.getTypeByMarket(i),[o,n]=this.handleOptionStringAndParams(t,"cancelAllOrdersWs","channel",r+".order_cancel_cp"),d=this.getUrlByMarket(i),h=this.omit(n,["stop","trigger"]),[c,l]=this.handleMarketTypeAndParams("cancelAllOrders",i,h),[u,f]="spot"===c?this.multiOrderSpotPrepareRequest(i,s,l):this.prepareRequest(i,c,l);await this.authenticate(d,r);let p=await this.requestPrivate(d,this.extend(u,f),o);return this.parseOrders(p,i)}async cancelOrderWs(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),s=void 0===t?void 0:this.market(t);let r=this.safeBoolN(i,["is_stop_order","stop","trigger"],!1),a=this.omit(i,["is_stop_order","stop","trigger"]),[o,n]=this.handleMarketTypeAndParams("cancelOrder",s,a),[d,h]="spot"===o||"margin"===o?this.spotOrderPrepareRequest(s,r,n):this.prepareRequest(s,o,n),c=this.getTypeByMarket(s),l=this.getUrlByMarket(s);await this.authenticate(l,c),d.order_id=e.toString();let u=await this.requestPrivate(l,this.extend(d,h),c+".order_cancel");return this.parseOrder(u,s)}async editOrderWs(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(t),d=this.editOrderRequest(e,t,i,s,r,a,o),h=this.getTypeByMarket(n),c=this.getUrlByMarket(n);await this.authenticate(c,h);let l=await this.requestPrivate(c,d,h+".order_amend");return this.parseOrder(l,n)}async fetchOrderWs(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets(),s=void 0===t?void 0:this.market(t);let[r,a]=this.fetchOrderRequest(e,t,i),o=this.getTypeByMarket(s),n=this.getUrlByMarket(s);await this.authenticate(n,o);let d=await this.requestPrivate(n,this.extend(r,a),o+".order_status");return this.parseOrder(d,s)}fetchOpenOrdersWs(e,t,i,s={}){return this.fetchOrdersByStatusWs("open",e,t,i,s)}fetchClosedOrdersWs(e,t,i,s={}){return this.fetchOrdersByStatusWs("finished",e,t,i,s)}async fetchOrdersByStatusWs(e,t,i,s,r={}){let o,n;if(void 0===this.markets&&await this.loadMarkets(),void 0!==t&&(o=this.market(t),n=this.safeString(o,"symbol"),!0!==o.swap))throw new a.NotSupported(this.id+" fetchOrdersByStatusWs is only supported by swap markets. Use rest API for other markets");let[d,h]=this.prepareOrdersByStatusRequest(e,n,i,s,r),c=this.omit(d,["settle"]),l=this.getTypeByMarket(o),u=this.getUrlByMarket(o);await this.authenticate(u,l);let f=await this.requestPrivate(u,this.extend(c,h),l+".order_list"),p=this.parseOrders(f,o);return this.filterBySymbolSinceLimit(p,n,i,s)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=s.symbol,a=s.id,o=this.getUrlByMarket(s),n=o.indexOf("gateeu")>=0,d=!0===s.spot&&!n,h="100ms";d&&(h="50");let[c,l]=this.handleOptionStringAndParams(i,"watchOrderBook","interval",h),u=this.getTypeByMarket(s),f=100;(!0===s.spot||"options"===u)&&(f=50);let p=void 0===t?f:t;!0===s.spot&&(p=Math.min(p,this.handleOption("fetchOrderBook","maxSpotLimit",1e3)));let m=[],g="";if(n)g="spot.order_book_update",m=[a,c];else if(!0===s.spot){g="spot.obu";let e=c;400===p&&(e="400"),m=["ob."+s.id+"."+e]}else{g=u+".order_book_update",m=[a,c];let e=p.toString();m.push(e)}let v={symbol:r,limit:p};return(await this.subscribePublic(o,"orderbook:"+r,m,g,l,v)).limit()}async unWatchOrderBook(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.getUrlByMarket(i),r=i.symbol,a=i.id,o=s.indexOf("gateeu")>=0,n=!0===i.spot&&!o,d="100ms";n&&(d="50");let h=d,[c,l]=this.handleOptionStringAndParams(t,"watchOrderBook","interval",h),u=this.getTypeByMarket(i),f=this.safeInteger(l,"limit");void 0===f&&(f=!0===i.spot?50:100,"options"===u&&(f=50));let p=[],m="";if(o)m="spot.order_book_update",p=[a,c];else if(!0===i.spot){m="spot.obu";let e=c;400===f&&(e="400"),p=["ob."+i.id+"."+e]}else{m=u+".order_book_update",p=[a,c];let e=f.toString();p.push(e)}return await this.unSubscribePublicMultiple(s,"orderbook",[r],["unsubscribe:orderbook:"+r],["orderbook:"+r],p,m,l)}handleOrderBookSubscription(e,t,i){let s=this.safeString(i,"symbol"),r=this.safeInteger(i,"limit");void 0!==s&&(this.orderbooks[s]=this.orderBook({},r))}handleNewSpotOrderBook(e,t){let i=this.safeDict(t,"result",{}),s=this.safeBool(i,"full",!1),r=this.safeString(i,"s");if(void 0===r)return;let a=r.split("."),o=this.safeString(a,1),n=this.safeSymbol(o,void 0,"_","spot"),d="orderbook:"+n;void 0===this.safeValue(this.orderbooks,n)&&(this.orderbooks[n]=this.orderBook({},1e3));let h=this.orderbooks[n];if(!0===s){let e=this.parseOrderBook(i,n,void 0,"b","a");e.nonce=this.safeInteger(i,"u"),e.timestamp=this.safeInteger(i,"t"),h.reset(e)}else{let e=this.safeInteger(h,"nonce"),t=this.safeInteger(i,"u");if(void 0===e||void 0!==t&&e>=t)return;this.handleBookDelta(h,i)}e.resolve(h,d)}handleOrderBook(e,t){let i=this.safeString(t,"channel");if("spot.obu"===i)return void this.handleNewSpotOrderBook(e,t);let s=i.split("."),r="spot"===this.safeString(s,0),o="contract";r&&(o="spot");let n=this.safeDict(t,"result"),d=this.safeInteger(n,"U"),h=this.safeInteger(n,"u"),c=this.safeString(n,"s"),l=this.safeSymbol(c,void 0,"_",o),u="orderbook:"+l,f=this.safeValue(this.orderbooks,l,this.orderBook({})),p=this.safeInteger(f,"nonce");if(void 0===p){let t=0;void 0!==f&&(t=f.cache.length);let i=this.handleOption("watchOrderBook","snapshotDelay",10),s=0;if(r&&(s=i),t===s){let t=this.safeDict(e.subscriptions,u),i=this.safeInteger(t,"limit");this.spawn(this.loadOrderBook,e,u,l,i,{})}f.cache.push(n);return}if(void 0===h||!(p>=h)){if(void 0!==d&&p>=d-1)this.handleBookDelta(f,n);else if(delete e.subscriptions[u],delete this.orderbooks[l],!0===this.handleOption("watchOrderBook","checksum",!0)){let t=new a.ChecksumError(this.id+" "+this.orderbookChecksumMessage(l));e.reject(t,u)}e.resolve(f,u)}}getCacheIndex(e,t){let i=this.safeInteger(e,"nonce"),s=this.safeDict(t,0),r=this.safeInteger(s,"U");if(void 0!==i&&void 0!==r&&i<r)return -1;for(let e=0;e<t.length;e++){let s=this.safeDict(t,e),r=this.safeInteger(s,"U"),a=this.safeInteger(s,"u");if(void 0!==i&&void 0!==r&&void 0!==a&&i>=r-1&&i<a)return e}return t.length}handleBidAsks(e,t){for(let i=0;i<t.length;i++){let s=t[i];if(Array.isArray(s))e.storeArray(this.parseOrderBookBidAsk(s));else{let t=this.safeFloat(s,"p"),i=this.safeFloat(s,"s");e.store(t,i)}}}handleBookDelta(e,t){let i=this.safeInteger(t,"t");e.timestamp=i,e.datetime=this.iso8601(i),e.nonce=this.safeInteger(t,"u");let s=this.safeList(t,"b",[]),r=this.safeList(t,"a",[]),a=e.bids,o=e.asks;this.handleBidAsks(a,s),this.handleBidAsks(o,r)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e).symbol;t.callerMethodName="watchTicker";let s=await this.watchTickers([i],t);return this.safeValue(s,i)}watchTickers(e,t={}){return this.subscribeWatchTickersAndBidsAsks(e,"watchTickers",this.extend({method:"tickers"},t))}handleTicker(e,t){this.handleTickerAndBidAsk("ticker",e,t)}watchBidsAsks(e,t={}){return this.subscribeWatchTickersAndBidsAsks(e,"watchBidsAsks",this.extend({method:"book_ticker"},t))}handleBidAsk(e,t){this.handleTickerAndBidAsk("bidask",e,t)}async subscribeWatchTickersAndBidsAsks(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleParamString(i,"callerMethodName",t),o=this.marketSymbols(e,void 0,!1),n=this.market(o[0]),d=this.getTypeByMarket(n),h=this.marketIds(o),[c,l]=this.handleOptionStringAndParams(r,s,"method"),u=this.getUrlByMarket(n);if(void 0===s)throw new a.ArgumentsRequired(this.id+" requires a callerMethodName argument");let f=s.indexOf("watchTicker")>=0,p="bidask";f&&(p="ticker");let m=[];for(let e=0;e<o.length;e++){let t=o[e];m.push(p+":"+t)}let g=await this.subscribePublicMultiple(u,m,h,d+"."+c,l);if(this.newUpdates){let e={},t=this.safeString(g,"symbol");return void 0!==t&&(e[t]=g),e}let v=f?this.tickers:this.bidsasks;return this.filterByArray(v,"symbol",o,!0)}handleTickerAndBidAsk(e,t,i){let s=this.safeString(i,"channel").split("."),r=this.safeString(s,0),a="spot";"futures"===r&&(a="contract");let o=this.safeValue(i,"result"),n=[];n=Array.isArray(o)?this.safeList(i,"result",[]):[this.safeDict(i,"result",{})];let d="ticker"===e;for(let i=0;i<n.length;i++){let s=n[i],r=this.safeString(s,"s"),o=this.safeMarket(r,void 0,"_",a),h=this.parseTicker(s,o),c=h.symbol;d?void 0!==c&&(this.tickers[c]=h):void 0!==c&&(this.bidsasks[c]=h);let l=e+":"+c;t.resolve(h,l)}}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e),a=this.marketIds(r),o=this.market(r[0]),n=this.getTypeByMarket(o),d=[];for(let e=0;e<r.length;e++){let t=r[e];d.push("trades:"+t)}let h=this.getUrlByMarket(o),c=await this.subscribePublicMultiple(h,d,a,n+".trades",s),l=this.safeDict(c,0),u=this.safeString(l,"symbol"),f=i;return this.newUpdates&&(f=c.getLimit(u,i)),this.filterBySinceLimit(c,t,f,"timestamp",!0)}async unWatchTradesForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=this.marketIds(i),r=this.market(i[0]),a=this.getTypeByMarket(r),o=[],n=[];for(let e=0;e<i.length;e++){let t=i[e];o.push("trades:"+t),n.push("unsubscribe:trades:"+t)}let d=this.getUrlByMarket(r);return await this.unSubscribePublicMultiple(d,"trades",i,n,o,s,a+".trades",t)}unWatchTrades(e,t={}){return this.unWatchTradesForSymbols([e],t)}handleTrades(e,t){let i=this.safeValue(t,"result");Array.isArray(i)||(i=[i]);let s=this.parseTrades(i);for(let t=0;t<s.length;t++){let i=s[t],r=i.symbol,a=this.safeValue(this.trades,r);if(void 0===a){let e=this.safeInteger(this.options,"tradesLimit",1e3);a=new o.I3(e),void 0!==r&&(this.trades[r]=a)}a.append(i);let n="trades:"+r;e.resolve(a,n)}}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n=a.id,d=this.safeString(this.timeframes,t,t),h=this.getTypeByMarket(a),c="candles:"+d+":"+a.symbol,l=this.getUrlByMarket(a),u=await this.subscribePublic(l,c,[d,n],h+".candlesticks",r),f=s;return this.newUpdates&&(f=u.getLimit(o,s)),this.filterBySinceLimit(u,i,f,0,!0)}handleOHLCV(e,t){let i=this.safeString(t,"channel").split("."),s=this.safeString(i,0),r="contract";"spot"===s&&(r="spot");let a=this.safeValue(t,"result");Array.isArray(a)||(a=[a]);let n={};for(let e=0;e<a.length;e++){let t=a[e],i=this.safeString(t,"n",""),s=i.split("_"),d=this.safeString(s,0),h=this.findTimeframe(d),c=h+"_",l=i.replace(c,""),u=this.safeSymbol(l,void 0,"_",r),f=this.parseOHLCV(t);this.ohlcvs[u]=this.safeValue(this.ohlcvs,u,{});let p=this.safeValue(this.safeDict(this.ohlcvs,u),h);if(void 0===p){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);p=new o.TG(e),void 0!==u&&void 0!==h&&(this.ohlcvs[u][h]=p)}p.append(f),n[u]=h}let d=Object.keys(n);for(let t=0;t<d.length;t++){let i=d[t],s=n[i],r=this.findTimeframe(s),a="candles:"+r+":"+i,o=this.safeValue(this.ohlcvs[i],r);e.resolve(o,a)}}async watchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a="!all";void 0!==e&&(a=(r=this.market(e)).id);let[o,n]=this.handleMarketTypeAndParams("watchMyTrades",r,s),[d,h]=this.handleSubTypeAndParams("watchMyTrades",r,n),c=this.getSupportedMapping(o,{spot:"spot",margin:"spot",future:"futures",swap:"futures",option:"options"}),l="myTrades";void 0!==e&&(l+=":"+e);let u=this.getUrlByMarketType(o,"inverse"===d),f=[a],p=await this.subscribePrivate(u,l,f,c+".usertrades",h,"spot"!==o),m=i;return this.newUpdates&&(m=p.getLimit(e,i)),this.filterBySymbolSinceLimit(p,e,t,m,!0)}handleMyTrades(e,t){let i=this.safeList(t,"result",[]);if(0===i.length)return;let s=this.myTrades;if(void 0===s){let e=this.safeInteger(this.options,"tradesLimit",1e3);s=new o.Pt(e),this.myTrades=s}let r=this.parseTrades(i),a={};for(let e=0;e<r.length;e++){let t=r[e];s.append(t);let i=t.symbol;void 0!==i&&(a[i]=!0)}let n=Object.keys(a);for(let t=0;t<n.length;t++){let i="myTrades:"+n[t];e.resolve(s,i)}e.resolve(s,"myTrades")}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleMarketTypeAndParams("watchBalance",void 0,e),[s,r]=this.handleSubTypeAndParams("watchBalance",void 0,i),a=this.getUrlByMarketType(t,"inverse"===s),o="spot"!==t,n=this.getSupportedMapping(t,{spot:"spot",margin:"spot",future:"futures",swap:"futures",option:"options"}),d=t+".balance";return await this.subscribePrivate(a,d,void 0,n+".balances",r,o)}handleBalance(e,t){let i=this.safeList(t,"result",[]);this.balance.info=i;for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),s=this.account(),r=this.safeString(t,"currency","USDT"),a=this.safeCurrencyCode(r),o=this.safeInteger2(t,"time_ms","timestamp_ms");this.balance.timestamp=o,this.balance.datetime=this.iso8601(o),s.used=this.safeString(t,"freeze"),s.free=this.safeString(t,"available"),s.total=this.safeString2(t,"total","balance"),void 0!==a&&(this.balance[a]=s)}let s=this.safeString(t,"channel").split("."),r=this.safeString(s,0),a=this.getSupportedMapping(r,{spot:"spot",futures:"swap",options:"option"});this.balance=this.safeBalance(this.balance),e.resolve(this.balance,a+".balance")}async watchPositions(e,t,i,s={}){let r,o,n,d;void 0===this.markets&&await this.loadMarkets();let h=this.marketSymbols(e);this.isEmpty(h)||(r=this.getMarketFromSymbols(h)),[o,n]=this.handleMarketTypeAndParams("watchPositions",r,s),"spot"===o&&(o="swap");let c=this.getSupportedMapping(o,{future:"futures",swap:"futures",option:"options"}),l=o+":positions";if(!this.isEmpty(h)){if(void 0===h)throw new a.ArgumentsRequired(this.id+" watchPositions() symbols is required");l+="::"+h.join(",")}[d,n]=this.handleSubTypeAndParams("watchPositions",r,n);let u=this.getUrlByMarketType(o,"inverse"===d),f=this.client(u);this.setPositionsCache(f,o,h);let p=this.handleOption("watchPositions","fetchPositionsSnapshot",!0),m=this.handleOption("watchPositions","awaitPositionsSnapshot",!0),g=this.safeValue(this.positions,o);if(!0===p&&!0===m&&void 0===g)return await f.future(o+":fetchPositionsSnapshot");let v=await this.subscribePrivate(u,l,["!all"],c+".positions",n,!0);return this.newUpdates?v:this.filterBySymbolsSinceLimit(this.safeValue(this.positions,o),h,t,i,!0)}setPositionsCache(e,t,i){if(void 0===this.positions&&(this.positions={}),!(t in this.positions))if(!0===this.handleOption("watchPositions","fetchPositionsSnapshot",!1)){let i=t+":fetchPositionsSnapshot";i in e.futures||(e.future(i),this.spawn(this.loadPositionsSnapshot,e,i,t))}else this.positions[t]=new o.Hk}async loadPositionsSnapshot(e,t,i){let s=await this.fetchPositions(void 0,{type:i});this.positions[i]=new o.Hk;let r=this.positions[i];for(let e=0;e<s.length;e++){let t=s[e],i=this.safeNumber(t,"contracts",0);void 0!==i&&i>0&&r.append(t)}t in e.futures&&(e.futures[t].resolve(r),e.resolve(r,i+":position"))}handlePositions(e,t){let i=this.getMarketTypeByUrl(e.url),s=this.safeList(t,"result",[]),r=this.positions[i],a=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.parsePosition(t),o=this.safeString(i,"symbol");if(void 0===this.safeString(i,"side")){if(void 0===o)continue;let e=this.safeDict(r,o+"long");void 0!==e&&(i.side=e.side,a.push(i),r.append(i));let t=this.safeDict(r,o+"short");void 0!==t&&(i.side=t.side,a.push(i),r.append(i)),void 0===e&&void 0===t&&(i.side="long",a.push(i),r.append(i))}else a.push(i),r.append(i)}let o=this.findMessageHashes(e,i+":positions::");for(let t=0;t<o.length;t++){let i=o[t],s=i.split("::")[1].split(","),r=this.filterByArray(a,"symbol",s,!1);this.isEmpty(r)||e.resolve(r,i)}e.resolve(a,i+":positions")}async watchOrders(e,t,i,s={}){let r,o,n,d,h;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(o=(r=this.market(e)).symbol),[n,d]=this.handleMarketTypeAndParams("watchOrders",r,s);let c=this.getSupportedMapping(n,{spot:"spot",margin:"spot",future:"futures",swap:"futures",option:"options"}),l=!1;if([l,d]=this.handleParamBool2(d,"trigger","stop",!1),!0===l&&"options"===c)throw new a.NotSupported(this.id+" watchOrders() does not support trigger orders for options, see https://github.com/ccxt/ccxt/issues/27202");let u=".orders";!0===l&&(u="spot"===c?".priceorders":".autoorders");let f=c+u,p="orders";!0===l&&(p="triggerOrders");let m=["!all"];if(void 0!==r){p+=":"+r.id;let e=r.id;void 0!==e&&(m=[e])}[h,d]=this.handleSubTypeAndParams("watchOrders",r,d);let g=this.getUrlByMarketType(n,"inverse"===h),v=await this.subscribePrivate(g,p,m,f,d,"spot"!==n),y=i;return this.newUpdates&&(y=v.getLimit(o,i)),this.filterBySinceLimit(v,t,y,"timestamp",!0)}handleOrder(e,t){let i=this.safeList(t,"result",[]),s=this.safeString(t,"channel",""),r=s.indexOf("autoorders")>=0||s.indexOf("priceorders")>=0,a="orders";r&&(a="triggerOrders");let n=this.safeInteger(this.options,"ordersLimit",1e3);void 0===this.orders&&(this.orders=new o.Pt(n),this.triggerOrders=new o.Pt(n));let d=r?this.triggerOrders:this.orders,h={},c=this.parseOrders(i);for(let e=0;e<c.length;e++){let t=c[e],i=this.safeDict(t,"info"),s=this.safeString(i,"event");"put"===s||"update"===s?t.status="open":"finish"===s&&void 0===this.safeString(t,"status")&&(t.status=0===this.safeInteger(i,"left")?"closed":"canceled"),d.append(t);let r=t.symbol,a=this.market(r);void 0!==a.id&&(h[a.id]=!0)}let l=Object.keys(h);for(let t=0;t<l.length;t++){let i=a+":"+l[t];e.resolve(d,i)}e.resolve(d,a)}watchMyLiquidations(e,t,i,s={}){return this.watchMyLiquidationsForSymbols([e],t,i,s)}async watchMyLiquidationsForSymbols(e,t,i,s={}){let r,o,n;void 0===this.markets&&await this.loadMarkets();let d=this.marketSymbols(e,void 0,!0,!0),h=this.getMarketFromSymbols(d);[r,o]=this.handleMarketTypeAndParams("watchMyLiquidationsForSymbols",h,s);let c=this.getSupportedMapping(r,{future:"futures",swap:"futures",option:"options"});[n,o]=this.handleSubTypeAndParams("watchMyLiquidationsForSymbols",h,o);let l="inverse"===n,u=this.getUrlByMarketType(r,l),f=[],p="";if(this.isEmpty(d)){if("futures"!==c&&!l)throw new a.BadRequest(this.id+" watchMyLiquidationsForSymbols() does not support listening to all symbols, you must call watchMyLiquidations() instead for each symbol you wish to watch.");p="myLiquidations",f.push("!all")}else{if(1!==d.length)throw new a.BadRequest(this.id+" watchMyLiquidationsForSymbols() only allows one symbol at a time. To listen to several symbols call watchMyLiquidationsForSymbols() several times.");p="myLiquidations::"+d[0],f.push(h.id)}let m=await this.subscribePrivate(u,p,f,c+".liquidates",o,!0);return this.newUpdates?m:this.filterBySymbolsSinceLimit(this.liquidations,d,t,i,!0)}handleLiquidation(e,t){let i=this.safeList(t,"result",[]);if(void 0===this.liquidations){let e=this.safeInteger(this.options,"liquidationsLimit",1e3);this.liquidations=new o.I3(e)}let s=this.liquidations;for(let t=0;t<i.length;t++){let r=i[t],a=this.parseWsLiquidation(r);s.append(a);let o=this.safeString(a,"symbol"),n=this.safeList(s,o,[]);e.resolve(n,"myLiquidations::"+o)}e.resolve([],"myLiquidations")}parseWsLiquidation(e,t){let i=this.safeString(e,"contract"),s=this.safeMarket(i,t),r=this.safeInteger(e,"time_ms"),a=this.safeString(e,"size"),o=this.safeString(e,"left"),d=n.Y.stringAbs(n.Y.stringSub(a,o));return this.safeLiquidation({info:e,symbol:this.safeSymbol(i,s),contracts:this.parseNumber(d),contractSize:this.safeNumber(s,"contractSize"),price:this.safeNumber(e,"fill_price"),baseValue:void 0,quoteValue:void 0,timestamp:r,datetime:this.iso8601(r)})}handleErrorMessage(e,t){let i=this.safeDict(t,"data"),s=this.safeDict(i,"errs"),r=this.safeDict(t,"error",s),o=this.safeString2(r,"code","label"),n=this.safeStringN(t,["id","requestId","request_id"]);if(void 0!==r){let i=this.safeString(e.subscriptions,n);try{this.throwExactlyMatchedException(this.exceptions.ws.exact,o,this.json(t)),this.throwExactlyMatchedException(this.exceptions.exact,o,this.json(s));let e=this.safeString(r,"message",this.safeString(s,"message"));throw this.throwBroadlyMatchedException(this.exceptions.ws.broad,e,this.json(t)),new a.ExchangeError(this.json(t))}catch(r){e.reject(r,i),void 0!==i&&i in e.subscriptions&&delete e.subscriptions[i];let s=this.safeString(t,"channel");if(void 0!==s&&s.indexOf(".")>0){let i=s.split("."),r=this.safeList(t,"payload",[]);for(let t=0;t<r.length;t++){let s;s="futures"===i[0]?"swap":i[0];let a=this.safeSymbol(r[t],void 0,"_",s),o=i[1]+":"+a;void 0!==o&&o in e.subscriptions&&delete e.subscriptions[o]}}}return void 0!==n&&n in e.subscriptions&&delete e.subscriptions[n],!0}return!1}handleBalanceSubscription(e,t,i){this.balance={}}handleSubscriptionStatus(e,t){let i=this.safeString(t,"channel"),s={balance:this.handleBalanceSubscription,"spot.order_book_update":this.handleOrderBookSubscription,"futures.order_book_update":this.handleOrderBookSubscription,"options.order_book_update":this.handleOrderBookSubscription},r=this.safeString(t,"id");if(void 0!==r){if(i in s){let a=this.safeString(e.subscriptions,r),o=this.safeValue(e.subscriptions,a);s[i].call(this,e,t,o)}r in e.subscriptions&&void 0!==r&&delete e.subscriptions[r]}}handleUnSubscribe(e,t){let i=this.safeString(t,"id"),s=Object.keys(e.subscriptions);for(let t=0;t<s.length;t++){let r=s[t];if(r in e.subscriptions&&r.startsWith("unsubscribe")){let t=e.subscriptions[r];if(i!==this.safeString(t,"id"))continue;let s=this.safeList(t,"messageHashes",[]),a=this.safeList(t,"subMessageHashes",[]);for(let t=0;t<s.length;t++){let i=s[t],r=a[t];this.cleanUnsubscription(e,r,i)}this.cleanCache(t)}}}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;let i=this.safeString(t,"event");if("subscribe"===i)return void this.handleSubscriptionStatus(e,t);if("unsubscribe"===i)return void this.handleUnSubscribe(e,t);let s=this.safeString(t,"channel","");if("spot.obu"===s)return void this.handleOrderBook(e,t);let r=s.split("."),a=this.safeString(r,1),o={usertrades:this.handleMyTrades,candlesticks:this.handleOHLCV,orders:this.handleOrder,autoorders:this.handleOrder,priceorders:this.handleOrder,positions:this.handlePositions,tickers:this.handleTicker,book_ticker:this.handleBidAsk,trades:this.handleTrades,order_book_update:this.handleOrderBook,balances:this.handleBalance,liquidates:this.handleLiquidation},n=this.safeValue(o,a);void 0!==n&&n.call(this,e,t);let d=this.safeString(t,"request_id");if("authenticated"===d)return void this.handleAuthenticationMessage(e,t);if(void 0!==d){let i=this.safeDict(t,"data"),s=this.safeValue(i,"result");!0!==this.safeBool(t,"ack")&&e.resolve(s,d)}}getUrlByMarket(e){let t=this.urls.api[e.type];return this.safeBool(e,"contract",!1)?this.safeBool(e,"linear",!1)?t.usdt:t.btc:t}getTypeByMarket(e){if(void 0!==e)if(!0===e.spot)return"spot";else if(!0===e.option)return"options";else return"futures"}getUrlByMarketType(e,t=!1){let i=this.urls.api,s=this.safeValue(i,e);return"swap"===e||"future"===e?t?s.btc:s.usdt:s}getMarketTypeByUrl(e){let t={"op-":"option",delivery:"future",fx:"swap"},i=Object.keys(t);for(let s=0;s<i.length;s++){let r=i[s],a=t[r];if(e.indexOf(r)>=0)return a}return"spot"}requestId(){this.lockId();let e=this.sum(this.safeInteger(this.options,"reqid",0),1);return this.options.reqid=e,this.unlockId(),e}async subscribePublic(e,t,i,s,r={},a){let o=this.requestId(),n=this.seconds();if(void 0!==a){let i=this.client(e);if(!(t in i.subscriptions)){let e=o.toString();i.subscriptions[e]=t}}let d=this.extend({id:o,time:n,channel:s,event:"subscribe",payload:i},r);return await this.watch(e,t,d,t,a)}async subscribePublicMultiple(e,t,i,s,r={}){let a=this.requestId(),o=this.seconds(),n=this.extend({id:a,time:o,channel:s,event:"subscribe",payload:i},r);return await this.watchMultiple(e,t,n,t)}async unSubscribePublicMultiple(e,t,i,s,r,a,o,n={}){let d=this.requestId(),h=this.seconds(),c={id:d.toString(),topic:t,unsubscribe:!0,messageHashes:s,subMessageHashes:r,symbols:i},l=this.extend({id:d,time:h,channel:o,event:"unsubscribe",payload:a},n);return await this.watchMultiple(e,s,l,s,c)}async authenticate(e,t){let i=this.client(e),s="authenticated",r=i.reusableFuture(s);return void 0===this.safeValue(i.subscriptions,s)?await this.requestPrivate(e,{},t+".login",s):r}handleAuthenticationMessage(e,t){this.safeValue(e.futures,"authenticated").resolve(!0)}async requestPrivate(e,t,i,r){this.checkRequiredCredentials();let a=void 0===r?this.requestId().toString():r,o=this.seconds(),n=["api",i,this.json(t),o.toString()].join("\n"),d=this.hmac(this.encode(n),this.encode(this.secret),s.Zf,"hex"),h={req_id:a,timestamp:o.toString(),api_key:this.apiKey,signature:d,req_param:t};return("spot.order_place"===i||"futures.order_place"===i)&&(h.req_header={"X-Gate-Channel-Id":"ccxt"}),await this.watch(e,a,{id:a,time:o,channel:i,event:"api",payload:h},a,a)}async subscribePrivate(e,t,i,r,o,n=!1){if(this.checkRequiredCredentials(),n&&(void 0===this.uid||0===this.uid.length))throw new a.ArgumentsRequired(this.id+" requires uid to subscribe");let d=[this.uid],h=void 0===i?d:this.arrayConcat(d,i),c=i;n&&(c=h);let l=this.seconds(),u="subscribe",f="channel="+r+"&event="+u+"&time="+l.toString(),p=this.hmac(this.encode(f),this.encode(this.secret),s.Zf,"hex"),m={method:"api_key",KEY:this.apiKey,SIGN:p},g=this.requestId(),v={id:g,time:l,channel:r,event:u,auth:m};void 0!==c&&(v.payload=c);let y=this.client(e);if(!(t in y.subscriptions)){let e=g.toString();y.subscriptions[e]=t}let b=this.extend(v,o);return await this.watch(e,t,b,t,t)}}i.d(t,{A:()=>d})},2227(e,t,i){"use strict";var s=i(2541),r=i(2943);class a extends s.A{describe(){let e=new r.A().describe(),t=super.describeData(),i=this.deepExtend(e,t);return this.deepExtend(i,{id:"gateeu",name:"Gate EU",countries:["EU"],certified:!1,urls:{api:{ws:"wss://ws.gateeu.com/v4",spot:"wss://api.gateeu.com/ws/v4/"}}})}}i.d(t,{A:()=>a})},4453(e,t,i){"use strict";var s=i(4721),r=i(841),a=i(1697),o=i(1453),n=i(7749);class d extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!1,watchTicker:!1,watchTickers:!1,watchBidsAsks:!0,watchTrades:!0,watchTradesForSymbols:!0,watchMyTrades:!1,watchOrders:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOHLCV:!0},urls:{api:{ws:"wss://api.gemini.com"},test:{ws:"wss://api.sandbox.gemini.com"}}})}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a="trades:"+r.symbol,n=r.id;if(void 0===n)throw new o.ArgumentsRequired(this.id+" watchTrades() marketId is required");let d={type:"subscribe",subscriptions:[{name:"l2",symbols:[n.toUpperCase()]}]},h="l2:"+r.symbol,c=this.safeString(this.urls.api,"ws");if(void 0===c)throw new o.ExchangeError(this.id+" watchTrades() has no websocket url");let l=await this.watch(c+"/v2/marketdata",a,d,h),u=i;return this.newUpdates&&(u=l.getLimit(r.symbol,i)),this.filterBySinceLimit(l,t,u,"timestamp",!0)}async watchTradesForSymbols(e,t,i,s={}){let r=await this.helperForWatchMultipleConstruct("trades",e,s),a=this.safeList(r,0),o=this.safeString(a,"symbol"),n=i;return this.newUpdates&&(n=r.getLimit(o,i)),this.filterBySinceLimit(r,t,n,"timestamp",!0)}parseWsTrade(e,t){let i=this.safeInteger(e,"timestamp"),s=this.safeString2(e,"event_id","tid"),r=this.safeString(e,"price"),a=this.safeString2(e,"quantity","amount"),o=this.safeStringLower(e,"side");if(void 0===o){let t=this.safeStringLower(e,"makerSide");"bid"===t?o="sell":"ask"===t&&(o="buy")}let n=this.safeStringLower(e,"symbol"),d=this.safeSymbol(n,t);return this.safeTrade({id:s,order:void 0,info:e,timestamp:i,datetime:this.iso8601(i),symbol:d,type:void 0,side:o,takerOrMaker:void 0,price:r,cost:void 0,amount:a,fee:void 0},t)}handleTrade(e,t){let i=this.parseWsTrade(t),s=i.symbol,r=this.safeInteger(this.options,"tradesLimit",1e3),o=this.safeValue(this.trades,s);void 0===o&&(o=new a.I3(r),void 0!==s&&(this.trades[s]=o)),o.append(i);let n="trades:"+s;e.resolve(o,n)}handleTrades(e,t){let i=this.safeStringLower(t,"symbol"),s=this.safeMarket(i),r=this.safeList(t,"trades");if(void 0!==r){let t=s.symbol,i=this.safeInteger(this.options,"tradesLimit",1e3),o=this.safeValue(this.trades,t);void 0===o&&(o=new a.I3(i),this.trades[t]=o);for(let e=0;e<r.length;e++){let t=this.parseWsTrade(r[e],s);o.append(t)}let n="trades:"+t;e.resolve(o,n)}}handleTradesForMultidata(e,t,i){if(void 0!==t){let s=this.safeInteger(this.options,"tradesLimit",1e3),r={};for(let e=0;e<t.length;e++){let o=t[e].symbol,n=this.safeMarket(o.toLowerCase()),d=n.symbol,h=this.parseWsTrade(t[e],n);h.timestamp=i,h.datetime=this.iso8601(i);let c=this.safeValue(this.trades,d);void 0===c&&(c=new a.I3(s),this.trades[d]=c),c.append(h),r[d]=c}let o=Object.keys(r);for(let t=0;t<o.length;t++){let i=o[t],s=r[i],a="trades:"+i;e.resolve(s,a)}}}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),n=this.safeString(this.timeframes,t,t),d={type:"subscribe",subscriptions:[{name:"candles_"+n,symbols:[this.safeStringUpper(a,"id")]}]},h="ohlcv:"+a.symbol+":"+n,c=this.safeString(this.urls.api,"ws");if(void 0===c)throw new o.ExchangeError(this.id+" watchOHLCV() has no websocket url");let l=await this.watch(c+"/v2/marketdata",h,d,h),u=s;return this.newUpdates&&(u=l.getLimit(e,s)),this.filterBySinceLimit(l,i,u,0,!0)}handleOHLCV(e,t){let i=this.safeString(t,"type","").slice(8),s=i.indexOf("_");i=i.slice(0,s);let r=this.safeString(t,"symbol","").toLowerCase(),o=this.safeMarket(r),n=this.safeSymbol(r,o),d=this.safeList(t,"changes",[]),h=this.findTimeframe(i);void 0===this.safeDict(this.ohlcvs,n)&&(this.ohlcvs[n]={});let c=this.safeValue(this.safeDict(this.ohlcvs,n),h);if(void 0===c){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);c=new a.TG(e),void 0!==n&&void 0!==h&&(this.ohlcvs[n][h]=c)}let l=d.length;for(let e=0;e<l;e++){let t=l-e-1,i=this.parseOHLCV(d[t],o);c.append(i)}let u="ohlcv:"+n+":"+i;return e.resolve(c,u),t}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="orderbook:"+s.symbol,a=s.id;if(void 0===a)throw new o.ArgumentsRequired(this.id+" watchOrderBook() marketId is required");let n={type:"subscribe",subscriptions:[{name:"l2",symbols:[a.toUpperCase()]}]},d="l2:"+s.symbol,h=this.safeString(this.urls.api,"ws");if(void 0===h)throw new o.ExchangeError(this.id+" watchOrderBook() has no websocket url");return(await this.watch(h+"/v2/marketdata",r,n,d)).limit()}handleOrderBook(e,t){let i="auction_events"in t&&"trades"in t&&"changes"in t,s=this.safeList(t,"changes",[]),r=this.safeStringLower(t,"symbol"),a=this.safeMarket(r).symbol;a in this.orderbooks?i&&(a in this.orderbooks&&delete this.orderbooks[a],this.orderbooks[a]=this.orderBook()):this.orderbooks[a]=this.orderBook();let o=this.orderbooks[a];for(let e=0;e<s.length;e++){let t=s[e],i=this.safeNumber(t,1),r=this.safeNumber(t,2),a="buy"===this.safeString(t,0)?"bids":"asks",n=o[a];n.store(i,r),o[a]=n}o.symbol=a,this.orderbooks[a]=o,e.resolve(o,"orderbook:"+a)}async watchOrderBookForSymbols(e,t,i={}){return(await this.helperForWatchMultipleConstruct("orderbook",e,i)).limit()}watchBidsAsks(e,t={}){return this.helperForWatchMultipleConstruct("bidsasks",e,t)}handleBidsAsksForMultidata(e,t,i,s){let r=t[0].symbol,a=this.safeMarket(r.toLowerCase()).symbol;a in this.bidsasks||(this.bidsasks[a]=this.parseTicker({}),this.bidsasks[a].symbol=a);let o=this.bidsasks[a];for(let e=0;e<t.length;e++){let i=this.safeDict(t,e),s=this.safeString(i,"side"),r=this.safeNumber(i,"price"),a=this.safeString(i,"remaining");if(n.Y.stringEq(a,"0"))continue;let d=this.parseNumber(a);"bid"===s?(o.bid=r,o.bidVolume=d):(o.ask=r,o.askVolume=d)}o.timestamp=i,o.datetime=this.iso8601(i),o.info=t;let d={};d[a]=o,this.bidsasks[a]=o,e.resolve(d,"bidsasks:"+a)}async helperForWatchMultipleConstruct(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===t)throw new o.NotSupported(this.id+" watchMultiple requires at least one symbol");let s=this.marketSymbols(t,void 0,!1,!0,!0),r=this.market(s[0]);if(!0!==r.spot&&!0!==r.linear)throw new o.NotSupported(this.id+" watchMultiple supports only spot or linear-swap symbols");let a=[],n=[];for(let t=0;t<s.length;t++){let i=s[t],r=e+":"+i;a.push(r);let o=this.market(i);n.push(o.id)}let d=n.join(","),h=this.safeString(this.urls.api,"ws");if(void 0===h)throw new o.ExchangeError(this.id+" helperForWatchMultipleConstruct() has no websocket url");let c=h+"/v1/multimarketdata?symbols="+d+"&heartbeat=true&";return"orderbook"===e?c+="trades=false&bids=true&offers=true":"bidsasks"===e?c+="trades=false&bids=true&offers=true&top_of_book=true":"trades"===e&&(c+="trades=true&bids=false&offers=false"),await this.watchMultiple(c,a,void 0)}handleOrderBookForMultidata(e,t,i,s){let r=t[0].symbol,a=this.safeMarket(r.toLowerCase()).symbol,o="orderbook:"+a;if(!(a in this.orderbooks)){let e=this.orderBook();this.orderbooks[a]=e}let n=this.orderbooks[a],d=n.bids,h=n.asks;for(let e=0;e<t.length;e++){let i=this.safeDict(t,e),s=this.safeNumber(i,"price"),r=this.safeNumber(i,"remaining");"bid"===this.safeString(i,"side")?d.store(s,r):h.store(s,r)}n.bids=d,n.asks=h,n.symbol=a,n.nonce=s,n.timestamp=i,n.datetime=this.iso8601(i),this.orderbooks[a]=n,e.resolve(n,o)}handleL2Updates(e,t){this.handleOrderBook(e,t),this.handleTrades(e,t)}async watchOrders(e,t,i,s={}){let r,a=this.safeString(this.urls.api,"ws");if(void 0===a)throw new o.ExchangeError(this.id+" watchOrders() has no websocket url");let n=a+"/v1/order/events?eventTypeFilter=initial&eventTypeFilter=accepted&eventTypeFilter=rejected&eventTypeFilter=fill&eventTypeFilter=cancelled&eventTypeFilter=booked";void 0===this.markets&&await this.loadMarkets(),await this.authenticate({url:n}),void 0!==e&&(r=this.market(e));let d=void 0!==r?this.safeString(r,"symbol"):void 0,h="orders",c=await this.watch(n,h,void 0,h),l=i;return this.newUpdates&&(l=c.getLimit(d,i)),this.filterBySymbolSinceLimit(c,d,t,l,!0)}handleHeartbeat(e,t){return e.lastPong=this.milliseconds(),t}handleSubscription(e,t){return t}handleOrder(e,t){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}let i=this.orders;for(let e=0;e<t.length;e++){let s=this.parseWsOrder(t[e]);i.append(s)}e.resolve(this.orders,"orders")}parseWsOrder(e,t){let i=this.safeInteger(e,"timestampms"),s=this.safeString(e,"type"),r=this.safeString(e,"symbol"),a=this.safeString(e,"order_type"),o=this.safeString(e,"behavior"),n="GTC",d=!1;return"immediate-or-cancel"===o?n="IOC":"fill-or-kill"===o?n="FOK":"maker-or-cancel"===o&&(n="PO",d=!0),this.safeOrder({id:this.safeString(e,"order_id"),clientOrderId:this.safeString(e,"client_order_id"),info:e,timestamp:i,datetime:this.iso8601(i),lastTradeTimestamp:void 0,status:this.parseWsOrderStatus(s),symbol:this.safeSymbol(r,t),type:this.parseWsOrderType(a),timeInForce:n,postOnly:d,side:this.safeString(e,"side"),price:this.safeNumber(e,"price"),stopPrice:void 0,average:this.safeNumber(e,"avg_execution_price"),cost:void 0,amount:this.safeNumber(e,"original_amount"),filled:this.safeNumber(e,"executed_amount"),remaining:this.safeNumber(e,"remaining_amount"),fee:void 0,trades:void 0},t)}parseWsOrderStatus(e){return this.safeString({accepted:"open",booked:"open",fill:"closed",cancelled:"canceled",cancel_rejected:"rejected",rejected:"rejected"},e,e)}parseWsOrderType(e){return this.safeString({"exchange limit":"limit","market buy":"market","market sell":"market"},e,e)}handleError(e,t){throw new o.ExchangeError(this.json(t))}handleMessage(e,t){if(Array.isArray(t))return void this.handleOrder(e,t);"error"===this.safeString(t,"reason")&&this.handleError(e,t);let i={l2_updates:this.handleL2Updates,trade:this.handleTrade,subscription_ack:this.handleSubscription,heartbeat:this.handleHeartbeat},s=this.safeString(t,"type","");if(s.indexOf("candles")>=0)return void this.handleOHLCV(e,t);let r=this.safeValue(i,s);if(void 0!==r&&r.call(this,e,t),"update"===s){let i=this.safeInteger(t,"timestampms",this.milliseconds()),s=this.safeInteger(t,"eventId"),r=this.safeList(t,"events");if(void 0===r)return;let a=[],o=[],n=[],d=r.length;for(let e=0;e<r.length;e++){let t=r[e],i=this.safeString(t,"type"),s="change"===i&&"side"in t&&this.inArray(t.side,["ask","bid"]),h=this.safeString(t,"reason");"top-of-book"===h||s&&"initial"===h&&2===d?o.push(t):s?a.push(t):"trade"===i&&n.push(r[e])}o.length>0&&this.handleBidsAsksForMultidata(e,o,i,s),a.length>0&&this.handleOrderBookForMultidata(e,a,i,s),n.length>0&&this.handleTradesForMultidata(e,n,i)}}async authenticate(e={}){let t=this.safeString(e,"url");if(void 0===t||void 0!==this.clients&&t in this.clients)return;this.checkRequiredCredentials();let i=this.urls.api.ws.length,r=t.indexOf("?"),a=t.length,o={request:t.slice(i,r>=0?r:a),nonce:this.incrementingNonce()},n=this.stringToBase64(this.json(o)),d=this.hmac(this.encode(n),this.encode(this.secret),s.qt,"hex");this.extendExchangeOptions({ws:{options:{headers:{}}}});let h=this.options.ws.options.headers,c={"X-GEMINI-APIKEY":this.apiKey,"X-GEMINI-PAYLOAD":n,"X-GEMINI-SIGNATURE":d};this.options.ws.options.headers=c,this.client(t),this.options.ws.options.headers=h}}i.d(t,{A:()=>d})},9193(e,t,i){"use strict";var s=i(5781),r=i(1697),a=i(1453);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!0,watchOHLCV:!0,watchOHLCVForSymbols:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchMyTrades:!0,watchPositions:!0,watchOrders:!0},urls:{api:{ws:{publicMarket:"wss://market-data.grvt.io/ws/full",privateTrading:"wss://trades.grvt.io/ws/full"}}},options:{watchOrderBookForSymbols:{depth:100,interval:500,channel:"v1.book.s"},watchTickers:{channel:"v1.ticker.s",interval:500}},streaming:{keepAlive:3e5}})}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;let i={"v1.ticker.s":this.handleTicker,"v1.ticker.d":this.handleTicker,"v1.mini.d":this.handleTicker,"v1.mini.s":this.handleTicker,"v1.trade":this.handleTrades,"v1.candle":this.handleOHLCV,"v1.book.s":this.handleOrderBook,"v1.book.d":this.handleOrderBook,"v1.fill":this.handleMyTrade,"v1.position":this.handlePosition,"v1.order":this.handleOrder};if("subscribe"===this.safeString(t,"method"))return;let s=this.safeString(t,"stream"),r=this.safeValue(i,s);void 0!==r&&r.call(this,e,t)}async subscribeMultiple(e,t,i,s=!0){let r={jsonrpc:"2.0",method:"subscribe",params:t,id:this.requestId()},a="privateTrading";return s&&(a="publicMarket"),await this.watchMultiple(this.urls.api.ws[a],e,r,i)}requestId(){this.lockId();let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,this.unlockId(),e}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.symbol(e);return(await this.watchTickers([i],this.extend(t,{callerMethodName:"watchTicker"})))[i]}async watchTickers(e,t={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" watchTickers requires a symbols argument");let[i,s]=this.handleOptionStringAndParams(t,"watchTickers","channel","v1.ticker.s"),[r,o]=this.handleOptionIntegerAndParams(s,"watchTickers","interval",500);void 0===this.markets&&await this.loadMarkets();let n=this.marketSymbols(e),d=[],h=[];for(let e=0;e<n.length;e++){let t=n[e],i=this.market(t),s=i.id;d.push(s+"@"+r.toString()),h.push("ticker::"+i.symbol)}let c=await this.subscribeMultiple(h,this.extend(o,{stream:i,selectors:d}),d);if(this.newUpdates){let e={},t=this.safeString(c,"symbol");return void 0!==t&&(e[t]=c),e}return this.filterByArray(this.tickers,"symbol",n)}handleTicker(e,t){let i=this.safeDict(t,"feed",{}),s=this.safeString(t,"selector","").split("@"),r=this.safeString(s,0),a=this.safeMarket(r),o=a.symbol,n=this.parseWsTicker(i,a);this.tickers[o]=n,e.resolve(n,"ticker::"+o)}parseWsTicker(e,t){return this.parseTicker(e,t)}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e),a=[],o=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.market(t),n=i.id,d=this.safeInteger(s,"limit",50);a.push(n+"@"+d.toString()),o.push("trade::"+i.symbol)}let n=await this.subscribeMultiple(o,this.extend(s,{stream:"v1.trade",selectors:a}),a),d=this.safeDict(n,0),h=this.safeString(d,"symbol"),c=i;return this.newUpdates&&(c=n.getLimit(h,i)),this.filterBySinceLimit(n,t,c,"timestamp",!0)}handleTrades(e,t){let i=this.safeDict(t,"feed",{}),s=this.safeString(t,"selector","").split("@"),a=this.safeString(s,0),o=this.safeMarket(a).symbol;if(!(o in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.trades[o]=new r.I3(e)}let n=this.parseWsTrade(i),d=this.trades[o];d.append(n),e.resolve(d,"trade::"+o)}parseWsTrade(e,t){return this.parseTrade(e,t)}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.symbol(e);return r.callerMethodName="watchOHLCV",(await this.watchOHLCVForSymbols([[a,t]],i,s,r))[a][t]}async watchOHLCVForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=[],a=[];for(let t=0;t<e.length;t++){let i=this.safeList(e,t),s=this.safeString(i,0),o=this.market(s),n=o.id,d=this.safeString(i,1,"1"),h=this.safeString(this.timeframes,d,d);r.push(n+"@"+h+"-TRADE"),a.push("ohlcv::"+o.symbol+"::"+d)}let[o,n,d]=await this.subscribeMultiple(a,this.extend(s,{stream:"v1.candle",selectors:r}),r),h=i;this.newUpdates&&(h=d.getLimit(o,i));let c=this.filterBySinceLimit(d,t,h,0,!0);return this.createOHLCVObject(o,n,c)}handleOHLCV(e,t){let i=this.safeDict(t,"feed",{}),s=this.safeString(t,"selector","").split("@"),a=this.safeString(s,0),o=this.safeMarket(a),n=o.symbol,d=this.safeString(s,1,"").replace("-TRADE",""),h=this.findTimeframe(d),c="ohlcv::"+n+"::"+h;if(this.ohlcvs[n]=this.safeDict(this.ohlcvs,n,{}),!(h in this.ohlcvs[n])){let e=this.handleOption("watchOHLCV","limit",1e3);this.ohlcvs[n][h]=new r.TG(e)}let l=this.ohlcvs[n][h],u=this.parseWsOHLCV(i,o);l.append(u);let f=[n,h,l];e.resolve(f,c)}parseWsOHLCV(e,t){return this.parseOHLCV(e,t)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.symbol(e);return await this.watchOrderBookForSymbols([s],t,i)}async watchOrderBookForSymbols(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let[r,o]=this.handleOptionStringAndParams(i,"watchOrderBook","channel","v1.book.d"),n="v1.book.s"===r;if(0===e.length)throw new a.ArgumentsRequired(this.id+" watchOrderBookForSymbols() requires a non-empty array of symbols");let[d,h]=this.handleOptionIntegerAndParams(o,"watchOrderBook","limit",100),c=d,l=h;void 0!==t&&(c=t,l=o);let[u,f]=this.handleOptionIntegerAndParams(l,"watchOrderBook","interval",500),p=this.marketSymbols(e);s=n?u.toString()+"-"+c.toString():u.toString();let m=[],g=[];for(let e=0;e<p.length;e++){let t=p[e],i=this.market(t),r=i.id;m.push(r+"@"+s),g.push("orderbook::"+i.symbol)}return(await this.subscribeMultiple(g,this.extend({stream:r,selectors:m},f),m)).limit()}handleOrderBook(e,t){let i=this.safeDict(t,"feed",{}),s=this.safeString(t,"selector","").split("@"),r=this.safeString(s,0),a=this.safeMarket(r).symbol,o=this.safeIntegerProduct(i,"event_time",1e-6);a in this.orderbooks||(this.orderbooks[a]=this.orderBook());let n=this.orderbooks[a],d=this.safeInteger(t,"sequence_number",0),h=this.safeString(t,"stream"),c=d<=0;if("v1.book.s"===h||c){let e=this.parseOrderBook(i,a,o,"bids","asks","price","size");n.reset(e)}else{let e=this.safeList(i,"asks",[]),t=this.safeList(i,"bids",[]);this.handleDeltasWithKeys(n.asks,e,"price","size"),this.handleDeltasWithKeys(n.bids,t,"price","size"),n.timestamp=o,n.datetime=this.iso8601(o)}n.symbol=a,n.nonce=d;let l="orderbook::"+a;this.orderbooks[a]=n,e.resolve(n,l)}async authenticate(e={}){this.checkRequiredCredentials(),await this.signIn();let t=this.safeDict(this.options,"ws",{});if(void 0===this.safeString(t,"token")){let e=this.safeString(this.options,"AuthAccountId"),t=this.safeString(this.options,"AuthCookieValue");if(void 0===t||void 0===e)throw new a.AuthenticationError(this.id+" : at first, you need to authenticate with exchange using signIn() method.");this.extendExchangeOptions({ws:{options:{headers:{Cookie:t,"X-Grvt-Account-Id":e}}}}),this.client(this.urls.api.ws.privateTrading)}}async watchMyTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.getSubAccountId(s),a=[],o=[];if(void 0!==e){let t=this.market(e);o.push(r+"-"+t.id),a.push("myTrades::"+t.symbol)}else a.push("myTrades"),o.push(r);let n=await this.subscribeMultiple(a,this.extend({stream:"v1.fill",selectors:o},s),a,!1),d=i;return this.newUpdates&&(d=n.getLimit(e,i)),this.filterBySinceLimit(n,t,d,"timestamp",!0)}handleMyTrade(e,t){let i=this.safeDict(t,"feed",{});if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new r.Pt(e)}let s=this.parseWsMyTrade(i);this.myTrades.append(s),e.resolve(this.myTrades,"myTrades::"+s.symbol),e.resolve(this.myTrades,"myTrades")}parseWsMyTrade(e,t){return this.parseTrade(e,t)}async watchPositions(e,t,i,s={}){await this.authenticate(),void 0===this.markets&&await this.loadMarkets();let r=this.getSubAccountId(s),a=this.marketSymbols(e),o=[],n=[];if(void 0!==a)for(let e=0;e<a.length;e++){let t=a[e],i=this.market(t);o.push(r+"-"+i.id),n.push("positions::"+i.symbol)}else n.push("positions"),o.push(r);let d=await this.subscribeMultiple(n,this.extend({stream:"v1.position",selectors:o},s),o,!1);return this.newUpdates?d:this.filterBySymbolsSinceLimit(this.positions,a,t,i,!0)}handlePosition(e,t){void 0===this.positions&&(this.positions=new r.Hk);let i=this.safeDict(t,"feed"),s=this.parseWsPosition(i),a=this.safeString(s,"symbol");this.positions.append(s);let o=[];o.push(s),e.resolve(o,"positions::"+a),e.resolve(o,"positions")}parseWsPosition(e,t){return this.parsePosition(e,t)}async watchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.getSubAccountId(s),a=[],o=[];if(void 0===e)a.push("orders"),o.push(r);else{let t=this.market(e);a.push("order::"+t.symbol),o.push(r+"-"+t.id)}let n=await this.subscribeMultiple(a,this.extend({stream:"v1.order",selectors:o},s),o,!1),d=i;return this.newUpdates&&(d=n.getLimit(e,i)),this.filterBySymbolSinceLimit(n,e,t,d,!0)}handleOrder(e,t){let i=this.safeDict(t,"feed");if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new r.Pt(e)}let s=this.parseWsOrder(i);this.orders.append(s),e.resolve(this.orders,"orders"),e.resolve(this.orders,"order::"+s.symbol)}parseWsOrder(e,t){return this.parseOrder(e,t)}handleErrorMessage(e,t){let i=this.safeDict(t,"error"),s=this.safeString(i,"code");if(void 0!==s){let e=this.json(t),r=this.id+" "+e,o=this.safeString(i,"message");throw this.throwExactlyMatchedException(this.exceptions.exact,s,r),this.throwExactlyMatchedException(this.exceptions.exact,o,r),this.throwBroadlyMatchedException(this.exceptions.broad,o,r),new a.ExchangeError(this.id+" "+e)}return!1}}i.d(t,{A:()=>o})},5915(e,t,i){"use strict";var s=i(6671),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchMyTrades:!0,watchOHLCV:!0,watchOrderBook:!0,watchOrders:!0,watchTicker:!0,watchTrades:!0,watchTradesForSymbols:!1,watchPositions:!1},urls:{api:{ws:{public:"wss://stream-glb.hashkey.com/quote/ws/v1",private:"wss://stream-glb.hashkey.com/api/v1/ws"},test:{ws:{public:"wss://stream-glb.sim.hashkeydev.com/quote/ws/v1",private:"wss://stream-glb.sim.hashkeydev.com/api/v1/ws"}}}},options:{listenKeyRefreshRate:36e5,listenKey:void 0,watchBalance:{fetchBalanceSnapshot:!0,awaitBalanceSnapshot:!1}},streaming:{keepAlive:1e4}})}async wathPublic(e,t,i,s={}){let r={symbol:e.id,topic:t,event:"sub"},a=this.urls.api.ws.public;return await this.watch(a,i,this.deepExtend(r,s),i)}async watchPrivate(e){let t=await this.authenticate(),i=this.getPrivateUrl(t);return await this.watch(i,e,void 0,e)}getPrivateUrl(e){let t=this.safeString(this.urls.api.ws,"private");if(void 0===t)throw new r.ExchangeError(this.id+" getPrivateUrl() has no private websocket url");return t+"/"+e}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n=this.safeString(this.timeframes,t,t),d=await this.wathPublic(a,"kline_"+n,"ohlcv:"+o+":"+t,r),h=s;return this.newUpdates&&(h=d.getLimit(o,s)),this.filterBySinceLimit(d,i,h,0,!0)}handleOHLCV(e,t){let i=this.safeString(t,"symbol"),s=this.safeMarket(i),r=this.safeSymbol(i,s);r in this.ohlcvs||(this.ohlcvs[r]={});let o=this.safeDict(t,"params"),n=this.safeString(o,"klineType"),d=this.findTimeframe(n);if(!(d in this.ohlcvs[r])){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);this.ohlcvs[r][d]=new a.TG(e)}let h=this.safeList(t,"data",[]),c=this.ohlcvs[r][d];for(let e=0;e<h.length;e++){let t=this.safeDict(h,e,{}),i=this.parseWsOHLCV(t,s);c.append(i)}e.resolve(c,"ohlcv:"+r+":"+d)}parseWsOHLCV(e,t){return[this.safeInteger(e,"t"),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol;return await this.wathPublic(i,"realtimes","ticker:"+s,t)}handleTicker(e,t){let i=this.safeList(t,"data",[]),s=this.parseTicker(this.safeDict(i,0,{})),r=s.symbol;this.tickers[r]=s,e.resolve(this.tickers[r],"ticker:"+r)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o=await this.wathPublic(r,"trade","trades:"+a,s),n=i;return this.newUpdates&&(n=o.getLimit(a,i)),this.filterBySinceLimit(o,t,n,"timestamp",!0)}handleTrades(e,t){let i=this.safeString(t,"symbol"),s=this.safeMarket(i),r=s.symbol;if(!(r in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.trades[r]=new a.I3(e)}let o=this.trades[r],n=this.safeList(t,"data");if(void 0!==n){n=this.sortBy(n,"t");for(let e=0;e<n.length;e++){let t=this.safeDict(n,e),i=this.parseWsTrade(t,s);o.append(i)}}e.resolve(o,"trades:"+r)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=s.symbol;return(await this.wathPublic(s,"depth","orderbook:"+r,i)).limit()}handleOrderBook(e,t){let i=this.safeString(t,"symbol"),s=this.safeSymbol(i),r="orderbook:"+s;s in this.orderbooks||(this.orderbooks[s]=this.orderBook({}));let a=this.orderbooks[s],o=this.safeList(t,"data",[]),n=this.safeDict(o,0),d=this.safeInteger(n,"t"),h=this.parseOrderBook(n,s,d,"b","a");a.reset(h),a.nonce=this.safeInteger(t,"id"),this.orderbooks[s]=a,e.resolve(a,r)}async watchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r="orders",a=void 0!==e?this.symbol(e):e;void 0!==e&&(r=r+":"+a);let o=await this.watchPrivate(r),n=i;return this.newUpdates&&(n=o.getLimit(a,i)),this.filterBySymbolSinceLimit(o,a,t,n,!0)}handleOrder(e,t){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}let i=this.parseWsOrder(t),s=this.orders;s.append(i);let r="orders";e.resolve(s,r);let o=i.symbol;e.resolve(s,r+":"+o)}parseWsOrder(e,t){let i,s,r=this.safeString(e,"s"),a=this.safeMarket(r,t),o=this.safeInteger(e,"O"),n=this.safeStringLower(e,"S");[n,i]=this.parseOrderSideAndReduceOnly(n);let d=this.parseOrderType(this.safeString(e,"o")),h=this.safeString(e,"f");return[d,h,s]=this.parseOrderTypeTimeInForceAndPostOnly(d,h),!0===a.contract&&(d=void 0),this.safeOrder({id:this.safeString(e,"i"),clientOrderId:this.safeString(e,"c"),datetime:this.iso8601(o),timestamp:o,lastTradeTimestamp:void 0,lastUpdateTimestamp:void 0,status:this.parseOrderStatus(this.safeString(e,"X")),symbol:a.symbol,type:d,timeInForce:h,side:n,price:this.safeString(e,"p"),average:this.safeString(e,"V"),amount:this.omitZero(this.safeString(e,"q")),filled:this.safeString(e,"z"),remaining:this.safeString(e,"r"),stopPrice:void 0,triggerPrice:void 0,takeProfitPrice:void 0,stopLossPrice:void 0,cost:this.omitZero(this.safeString(e,"Z")),trades:void 0,fee:{currency:this.safeCurrencyCode(this.safeString(e,"N")),amount:this.omitZero(this.safeString(e,"n"))},reduceOnly:i,postOnly:s,info:e},a)}async watchMyTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r="myTrades",a=void 0!==e?this.symbol(e):e;void 0!==e&&(r+=":"+a);let o=await this.watchPrivate(r),n=i;return this.newUpdates&&(n=o.getLimit(a,i)),this.filterBySinceLimit(o,t,n,"timestamp",!0)}handleMyTrade(e,t,i={}){if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new a.Pt(e)}let s=this.myTrades,r=this.parseWsTrade(t);s.append(r),this.myTrades=s;let o="myTrades";e.resolve(s,o);let n=r.symbol;e.resolve(s,o+":"+n)}parseWsTrade(e,t){let i,s,r=this.safeString(e,"s"),a=this.safeMarket(r,t),o=this.safeInteger(e,"t"),n=this.safeBool(e,"m"),d=void 0===this.safeString(e,"e");return void 0!==n&&(d?(s="taker",i=n?"sell":"buy"):(s=n?"maker":"taker",i=this.safeStringLower(e,"S"))),this.safeTrade({id:this.safeString2(e,"v","T"),timestamp:o,datetime:this.iso8601(o),symbol:a.symbol,side:i,price:this.safeString(e,"p"),amount:this.safeString(e,"q"),cost:void 0,takerOrMaker:s,type:void 0,order:this.safeString(e,"o"),fee:void 0,info:e},a)}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.authenticate(),a=this.marketSymbols(e),o="positions",n=[];if(void 0===a)n.push(o);else for(let e=0;e<a.length;e++){let t=a[e];n.push(o+":"+t)}let d=this.getPrivateUrl(r),h=await this.watchMultiple(d,n,void 0,n);return this.newUpdates?h:this.filterBySymbolsSinceLimit(this.positions,a,t,i,!0)}handlePosition(e,t){void 0===this.positions&&(this.positions=new a.Hk);let i=this.positions,s=this.parseWsPosition(t);i.append(s);let r="positions";e.resolve(s,r);let o=s.symbol;e.resolve(s,r+":"+o)}parseWsPosition(e,t){let i=this.safeString(e,"s"),s=this.safeMarket(i),r=this.safeInteger(e,"E");return this.safePosition({symbol:s.symbol,id:void 0,timestamp:r,datetime:this.iso8601(r),contracts:this.safeNumber(e,"P"),contractSize:void 0,side:this.safeStringLower(e,"S"),notional:this.safeNumber(e,"pv"),leverage:this.safeInteger(e,"v"),unrealizedPnl:this.safeNumber(e,"up"),realizedPnl:this.safeNumber(e,"r"),collateral:void 0,entryPrice:this.safeNumber(e,"p"),markPrice:void 0,liquidationPrice:this.safeNumber(e,"f"),marginMode:this.safeStringLower(e,"mt"),hedged:!0,maintenanceMargin:this.safeNumber(e,"mm"),maintenanceMarginPercentage:void 0,initialMargin:this.safeNumber(e,"m"),initialMarginPercentage:void 0,marginRatio:void 0,lastUpdateTimestamp:void 0,lastPrice:void 0,stopLossPrice:void 0,takeProfitPrice:void 0,percentage:void 0,info:e})}async watchBalance(e={}){let t=await this.authenticate();void 0===this.markets&&await this.loadMarkets();let i=this.handleMarketTypeAndParams("watchBalance",void 0,e,"spot")[0],s="balance:"+i,r=this.getPrivateUrl(t),a=this.client(r);this.setBalanceCache(a,i,s);let o=this.handleOptionBoolAndParams(this.options,"watchBalance","fetchBalanceSnapshot",!0)[0],n=this.handleOptionBoolAndParams(this.options,"watchBalance","awaitBalanceSnapshot",!1)[0];return o&&n&&await a.future(i+":fetchBalanceSnapshot"),await this.watch(r,s,void 0,s)}setBalanceCache(e,t,i){if(i in e.subscriptions)return;let s=this.safeDict(this.options,"watchBalance");if(!0===this.safeBool(s,"fetchBalanceSnapshot",!0)){let i=t+":fetchBalanceSnapshot";i in e.futures||(e.future(i),this.spawn(this.loadBalanceSnapshot,e,i,t))}this.balance[t]={}}async loadBalanceSnapshot(e,t,i){let s=await this.fetchBalance({type:i});this.balance[i]=this.extend(s,this.safeDict(this.balance,i,{})),t in e.futures&&(e.futures[t].resolve(),e.resolve(this.balance[i],"balance:"+i))}handleBalance(e,t){let i=this.safeString(t,"e"),s=this.safeList(t,"B",[]),r=this.safeDict(s,0),a="swap";"outboundAccountInfo"===i&&(a="spot"),a in this.balance||(this.balance[a]={}),this.balance[a].info=t;let o=this.safeString(r,"a"),n=this.safeCurrencyCode(o),d=this.account();d.free=this.safeString(r,"f"),d.used=this.safeString(r,"l"),void 0!==n&&(this.balance[a][n]=d),this.balance[a]=this.safeBalance(this.balance[a]);let h="balance:"+a;e.resolve(this.balance[a],h)}async authenticate(e={}){let t=this.safeString(this.options,"listenKey");if(void 0!==t)return t;let i="authenticateFlight",s=this.client("authenticationFlights");if(i in s.futures)return await s.future(i),this.safeString(this.options,"listenKey");let a=s.reusableFuture(i);try{let a=await this.privatePostApiV1UserDataStream(e);if(t=this.safeString(a,"listenKey"),void 0===t)throw new r.AuthenticationError(this.id+" authenticate() received an empty listenKey");this.options.listenKey=t;let o=this.safeInteger(this.options,"listenKeyRefreshRate",36e5);this.delay(o,this.keepAliveListenKey,t,e),s.resolve(t,i)}catch(e){s.reject(e,i)}return await a,t}async keepAliveListenKey(e,t={}){if(void 0!==e)try{await this.privatePutApiV1UserDataStream(this.extend({listenKey:e},t));let i=this.safeInteger(this.options,"listenKeyRefreshRate",12e5);this.delay(i,this.keepAliveListenKey,e,t)}catch(s){let t=this.getPrivateUrl(e),i=this.client(t);this.options.listenKey=void 0,i.reject(s),delete this.clients[t]}}handleMessage(e,t){let i=t;Array.isArray(t)&&(i=this.safeDict(t,0,{}));let s=this.safeString2(i,"topic","e");"kline"===s?this.handleOHLCV(e,i):"realtimes"===s?this.handleTicker(e,i):"trade"===s?this.handleTrades(e,i):"depth"===s?this.handleOrderBook(e,i):"contractExecutionReport"===s||"executionReport"===s?this.handleOrder(e,i):"ticketInfo"===s?this.handleMyTrade(e,i):"outboundContractPositionInfo"===s?this.handlePosition(e,i):("outboundAccountInfo"===s||"outboundContractAccountInfo"===s)&&this.handleBalance(e,i)}}i.d(t,{A:()=>o})},3906(e,t,i){"use strict";var s=i(4721),r=i(3030),a=i(1697),o=i(1453);class n extends r.A{describe(){return this.deepExtend(super.describe(),this.describeData())}describeData(){return{has:{ws:!0,watchTicker:!0,watchTickers:!0,watchBidsAsks:!0,watchTrades:!0,watchTradesForSymbols:!1,watchOrderBook:!0,watchBalance:!0,watchOrders:!0,watchOHLCV:!0,watchMyTrades:!1,createOrderWs:!0,cancelOrderWs:!0,fetchOpenOrdersWs:!0,cancelAllOrdersWs:!0},urls:{api:{ws:{public:"wss://api.hitbtc.com/api/3/ws/public",private:"wss://api.hitbtc.com/api/3/ws/trading"}},test:{ws:{public:"wss://api.demo.hitbtc.com/api/3/ws/public",private:"wss://api.demo.hitbtc.com/api/3/ws/trading"}}},options:{tradesLimit:1e3,watchTicker:{method:"ticker/{speed}"},watchTickers:{method:"ticker/{speed}"},watchBidsAsks:{method:"orderbook/top/{speed}"},watchOrderBook:{method:"orderbook/full"}},timeframes:{"1m":"M1","3m":"M3","5m":"M5","15m":"M15","30m":"M30","1h":"H1","4h":"H4","1d":"D1","1w":"D7","1M":"1M"},streaming:{keepAlive:4e3}}}async authenticate(){this.checkRequiredCredentials();let e=this.urls.api.ws.private,t="authenticated",i=this.client(e),r=i.reusableFuture(t);if(void 0===this.safeValue(i.subscriptions,t)){let i=this.milliseconds(),r=this.numberToString(i),a=r;void 0===r&&(a="");let o=this.hmac(this.encode(a),this.encode(this.secret),s.sc,"hex"),n={method:"login",params:{type:"HS256",api_key:this.apiKey,timestamp:i,signature:o}};this.watch(e,t,n,t)}return await r}async subscribePublic(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(i),a=!(e.indexOf("batch")>=0)||"orderbooks"===t,o=this.urls.api.ws.public,n=[];if(void 0!==r&&a)for(let e=0;e<r.length;e++)n.push(t+"::"+r[e]);else n.push(t);let d=this.incrementingNonce(),h=this.extend({method:"subscribe",id:d,ch:e},s);return await this.watchMultiple(o,n,h,n,{id:d})}async subscribePrivate(e,t,i={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let s=this.urls.api.ws.private,r=e.split("_subscribe"),a=this.safeString(r,0,"");void 0!==t&&(a=a+"::"+t);let o=this.incrementingNonce();return await this.watch(s,a,{method:e,params:i,id:o},a,{id:o})}async tradeRequest(e,t={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let i=this.urls.api.ws.private,s=this.incrementingNonce().toString();return await this.watch(i,s,{method:e,params:t,id:s},s)}async watchOrderBook(e,t,i={}){let s=this.safeDict(this.options,"watchOrderBook"),r=this.safeString(s,"method","orderbook/full"),a=this.safeString2(i,"method","defaultMethod",r),o=this.safeString(i,"depth","20"),n=this.safeString(i,"speed","100"),d=this.omit(i,["method","defaultMethod","depth","speed"]);"orderbook/{depth}/{speed}"===a?a="orderbook/D"+o+"/"+n+"ms":"orderbook/{depth}/{speed}/batch"===a&&(a="orderbook/D"+o+"/"+n+"ms/batch");let h={params:{symbols:[this.market(e).id]}};return(await this.subscribePublic(a,"orderbooks",[e],this.deepExtend(h,d))).limit()}handleOrderBook(e,t){let i=this.safeDict2(t,"snapshot","data"),s=this.safeDict(t,"update",{});void 0!==i&&(s=i);let r="update";null!=i&&(r="snapshot");let a=Object.keys(s);for(let t=0;t<a.length;t++){let i=a[t],o=this.safeMarket(i).symbol,n=s[i],d="orderbooks::"+o;if(!(o in this.orderbooks)){let t=this.safeDict(e.subscriptions,d,{}),i=this.safeInteger(t,"limit");this.orderbooks[o]=this.orderBook({},i)}let h=this.orderbooks[o],c=this.safeInteger(n,"t"),l=this.safeInteger(n,"s");if("snapshot"===r){let e=this.parseOrderBook(n,o,c,"b","a");h.reset(e)}else{let e=this.safeList(n,"a",[]),t=this.safeList(n,"b",[]);this.handleDeltas(h.asks,e),this.handleDeltas(h.bids,t)}h.timestamp=c,h.datetime=this.iso8601(c),h.nonce=l,h.symbol=o,this.orderbooks[o]=h,e.resolve(h,d)}}handleDelta(e,t){let i=this.safeNumber(t,0),s=this.safeNumber(t,1);e.store(i,s)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}async watchTicker(e,t={}){let i=await this.watchTickers([e],this.extend(t,{callerMethodName:"watchTicker"}));return this.safeValue(i,e)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),[s,r]=this.handleParamString(t,"callerMethodName","watchTickers"),a=this.safeDict(this.options,s),o=this.safeString(a,"method","ticker/{speed}/batch"),n=this.safeString2(r,"method","defaultMethod",o),d=this.safeString(r,"speed","1s"),h=this.implodeParams(n,{speed:d}),c=this.omit(r,["method","defaultMethod","speed"]),l=[];if(void 0===i)l.push("*");else for(let e=0;e<i.length;e++){let t=this.marketId(i[e]);void 0!==t&&l.push(t)}let u=await this.subscribePublic(h,"tickers",i,this.deepExtend({params:{symbols:l}},c));if(this.newUpdates&&!Array.isArray(u)){let e={},t=this.safeString(u,"symbol");return void 0!==t&&(e[t]=u),e}return this.filterByArray(u,"symbol",i)}handleTicker(e,t){let i=this.safeDict(t,"data",{}),s=Object.keys(i),r=[],a="tickers";for(let t=0;t<s.length;t++){let o=s[t],n=this.safeMarket(o),d=n.symbol,h=this.parseWsTicker(i[o],n);this.tickers[d]=h,r.push(h);let c=a+"::"+d;e.resolve(h,c)}e.resolve(r,a)}parseWsTicker(e,t){let i=this.safeInteger(e,"t"),s=this.safeSymbol(void 0,t),r=this.safeString(e,"c");return this.safeTicker({symbol:s,timestamp:i,datetime:this.iso8601(i),high:this.safeString(e,"h"),low:this.safeString(e,"l"),bid:this.safeString(e,"b"),bidVolume:this.safeString(e,"B"),ask:this.safeString(e,"a"),askVolume:this.safeString(e,"A"),vwap:void 0,open:this.safeString(e,"o"),close:r,last:r,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"v"),quoteVolume:this.safeString(e,"q"),info:e},t)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=this.safeDict(this.options,"watchBidsAsks"),r=this.safeString(s,"method","orderbook/top/{speed}/batch"),a=this.safeString2(t,"method","defaultMethod",r),o=this.safeString(t,"speed","100ms"),n=this.implodeParams(a,{speed:o}),d=this.omit(t,["method","defaultMethod","speed"]),h=this.marketIds(i),c=await this.subscribePublic(n,"bidask",i,this.deepExtend({params:{symbols:h}},d));if(this.newUpdates&&!Array.isArray(c)){let e={},t=this.safeString(c,"symbol");return void 0!==t&&(e[t]=c),e}return this.filterByArray(c,"symbol",i)}handleBidAsk(e,t){let i=this.safeDict(t,"data",{}),s=Object.keys(i),r=[],a="bidask";for(let t=0;t<s.length;t++){let o=s[t],n=this.safeMarket(o),d=n.symbol,h=this.parseWsBidAsk(i[o],n);this.bidsasks[d]=h,r.push(h);let c=a+"::"+d;e.resolve(h,c)}e.resolve(r,a)}parseWsBidAsk(e,t){let i,s=this.safeInteger(e,"t");return void 0!==t&&(i=t.symbol),this.safeTicker({symbol:i,timestamp:s,datetime:this.iso8601(s),ask:this.safeString(e,"a"),askVolume:this.safeString(e,"A"),bid:this.safeString(e,"b"),bidVolume:this.safeString(e,"B"),info:e},t)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={params:{symbols:[this.market(e).id]}};void 0!==i&&(r.limit=i);let a=await this.subscribePublic("trades","trades",[e],this.deepExtend(r,s)),o=i;return this.newUpdates&&(o=a.getLimit(e,i)),this.filterBySinceLimit(a,t,o,"timestamp")}handleTrades(e,t){let i=this.safeDict2(t,"snapshot","update",{}),s=Object.keys(i);for(let t=0;t<s.length;t++){let r=s[t],o=this.safeMarket(r),n=this.safeInteger(this.options,"tradesLimit",1e3),d=o.symbol,h=this.safeValue(this.trades,d);void 0===h&&(h=new a.I3(n),this.trades[d]=h);let c=this.parseWsTrades(i[r],o);for(let e=0;e<c.length;e++)h.append(c[e]);let l="trades::"+d;e.resolve(h,l)}return t}parseWsTrades(e,t,i,s,r={}){let a=this.toArray(e),o=[];for(let e=0;e<a.length;e++){let i=this.extend(this.parseWsTrade(a[e],t),r);o.push(i)}o=this.sortBy2(o,"timestamp","id");let n=this.safeString(t,"symbol");return this.filterBySymbolSinceLimit(o,n,i,s)}parseWsTrade(e,t){let i=this.safeInteger(e,"t");return this.safeTrade({info:e,id:this.safeString(e,"i"),order:void 0,timestamp:i,datetime:this.iso8601(i),symbol:this.safeString(t,"symbol"),type:void 0,side:this.safeString(e,"s"),takerOrMaker:void 0,price:this.safeString(e,"p"),amount:this.safeString(e,"q"),cost:void 0,fee:void 0},t)}async watchOHLCV(e,t="1m",i,s,r={}){let a=this.safeString(this.timeframes,t,t),o={params:{symbols:[this.market(e).id]}};void 0!==s&&(o.params.limit=s);let n=await this.subscribePublic("candles/"+a,"candles",[e],this.deepExtend(o,r)),d=s;return this.newUpdates&&(d=n.getLimit(e,s)),this.filterBySinceLimit(n,i,d,0)}handleOHLCV(e,t){let i=this.safeDict2(t,"snapshot","update",{}),s=Object.keys(i),r=this.safeString(t,"ch","").split("/"),o=this.safeString(r,1),n=this.findTimeframe(o);if(void 0===n)return t;for(let t=0;t<s.length;t++){let r=s[t],o=this.safeMarket(r),d=o.symbol;this.ohlcvs[d]=this.safeDict(this.ohlcvs,d,{});let h=this.safeValue(this.safeDict(this.ohlcvs,d),n);if(void 0===h){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);h=new a.TG(e),this.ohlcvs[d][n]=h}let c=this.parseWsOHLCVs(i[r],o);for(let e=0;e<c.length;e++)h.append(c[e]);let l="candles::"+d;e.resolve(h,l)}return t}parseWsOHLCV(e,t){return[this.safeInteger(e,"t"),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}async watchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let[a,o]=this.handleMarketTypeAndParams("watchOrders",r,s),n=this.getSupportedMapping(a,{spot:"spot_subscribe",margin:"margin_subscribe",swap:"futures_subscribe",future:"futures_subscribe"}),d=await this.subscribePrivate(n,e,o),h=i;return this.newUpdates&&(h=d.getLimit(e,i)),this.filterBySinceLimit(d,t,h,"timestamp")}handleOrder(e,t){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit");this.orders=new a.Pt(e)}let i=this.safeValue(t,"params",[]);if(Array.isArray(i))for(let s=0;s<i.length;s++){let r=i[s];this.handleOrderHelper(e,t,r)}else this.handleOrderHelper(e,t,i);return t}handleOrderHelper(e,t,i){let s=this.orders;if(void 0===s)return;let r=this.safeStringLower2(i,"instrument","symbol"),a=this.safeString(t,"method","").split("_order"),o=this.safeString(a,0),n=this.safeSymbol(r),d=this.parseOrder(i);s.append(d),e.resolve(s,o),void 0!==o&&e.resolve(s,o+"::"+n)}parseWsOrderTrade(e,t){let i=this.safeInteger(e,"created_at"),s=this.safeString(e,"symbol");return this.safeTrade({info:e,id:this.safeString(e,"trade_id"),order:this.safeString(e,"id"),timestamp:i,datetime:this.iso8601(i),symbol:this.safeMarket(s,t),type:void 0,side:this.safeString(e,"side"),takerOrMaker:this.safeString(e,"trade_taker"),price:this.safeString(e,"trade_price"),amount:this.safeString(e,"trade_quantity"),cost:void 0,fee:{cost:this.safeString(e,"trade_fee"),currency:void 0,rate:void 0}},t)}parseWsOrder(e,t){let i,s,r=this.safeString(e,"created_at"),a=this.safeString(e,"symbol"),o=this.safeMarket(a,t);void 0!==this.safeString(e,"trade_id")&&(i=[this.parseWsOrderTrade(e,o)]);let n=this.safeString(e,"status"),d=this.safeString(e,"report_type");return s="canceled"===d?this.parseOrderStatus(d):this.parseOrderStatus(n),this.safeOrder({info:e,id:this.safeString(e,"id"),clientOrderId:this.safeString(e,"client_order_id"),timestamp:r,datetime:this.iso8601(r),lastTradeTimestamp:void 0,symbol:o.symbol,price:this.safeString(e,"price"),amount:this.safeString(e,"quantity"),type:this.safeString(e,"type"),side:this.safeStringUpper(e,"side"),timeInForce:this.safeString(e,"time_in_force"),postOnly:this.safeString(e,"post_only"),reduceOnly:this.safeBool(e,"reduce_only"),filled:void 0,remaining:void 0,cost:void 0,status:s,average:void 0,trades:i,fee:void 0},o)}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleMarketTypeAndParams("watchBalance",void 0,e),s=this.getSupportedMapping(t,{spot:"spot_balance_subscribe",swap:"futures_balance_subscribe",future:"futures_balance_subscribe"}),r=this.safeString(i,"mode","batches"),a=this.omit(i,"mode");return await this.subscribePrivate(s,void 0,this.extend({mode:r},a))}async createOrderWs(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),[n,d]=this.handleMarketTypeAndParams("createOrder",o,a),[h,c]=this.handleMarginModeAndParams("createOrder",d),[l,u]=this.createOrderRequest(o,n,t,i,s,r,h,c),f=this.extend(l,u);return"swap"===n?await this.tradeRequest("futures_new_order",f):"margin"===n||void 0!==h?await this.tradeRequest("margin_new_order",f):await this.tradeRequest("spot_new_order",f)}async cancelOrderWs(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r={client_order_id:e};void 0!==t&&(s=this.market(t));let[a,o]=this.handleMarketTypeAndParams("cancelOrderWs",s,i),[n,d]=this.handleMarginModeAndParams("cancelOrderWs",o);return(r=this.extend(r,d),"swap"===a)?await this.tradeRequest("futures_cancel_order",r):"margin"===a||void 0!==n?await this.tradeRequest("margin_cancel_order",r):await this.tradeRequest("spot_cancel_order",r)}async cancelAllOrdersWs(e,t={}){let i;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(i=this.market(e));let[s,r]=this.handleMarketTypeAndParams("cancelAllOrdersWs",i,t),[a,n]=this.handleMarginModeAndParams("cancelAllOrdersWs",r);if("swap"===s)return await this.tradeRequest("futures_cancel_orders",n);if("margin"!==s&&void 0===a)return await this.tradeRequest("spot_cancel_orders",n);throw new o.NotSupported(this.id+" cancelAllOrdersWs is not supported for margin orders")}async fetchOpenOrdersWs(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a={};void 0!==e&&(a.symbol=(r=this.market(e)).id);let[o,n]=this.handleMarketTypeAndParams("fetchOpenOrdersWs",r,s),d=this.handleMarginModeAndParams("fetchOpenOrdersWs",n)[0];return"swap"===o?await this.tradeRequest("futures_get_orders",a):"margin"===o||void 0!==d?await this.tradeRequest("margin_get_orders",a):await this.tradeRequest("spot_get_orders",a)}handleBalance(e,t){let i=this.safeString(t,"method"),s=this.safeList(t,"params",[]),r=this.parseBalance(s);this.balance=this.deepExtend(this.balance,r),e.resolve(this.balance,i)}handleNotification(e,t){return t}handleOrderRequest(e,t){let i=this.safeString(t,"id"),s=this.safeValue(t,"result",{});if(Array.isArray(s)){let t=[];for(let e=0;e<s.length;e++){let i=this.parseWsOrder(s[e]);t.push(i)}e.resolve(t,i)}else{let t=this.parseWsOrder(s);e.resolve(t,i)}return t}handleMessage(e,t){if(this.handleError(e,t))return;let i=this.safeString2(t,"ch","method");if(void 0!==i){let s=i.split("/");if("orderbook"===(i=this.safeString(s,0))){let e=this.safeString(s,1);void 0!==e&&"top"===e&&(i="orderbook/top")}let r={candles:this.handleOHLCV,ticker:this.handleTicker,trades:this.handleTrades,orderbook:this.handleOrderBook,"orderbook/top":this.handleBidAsk,spot_order:this.handleOrder,spot_orders:this.handleOrder,margin_order:this.handleOrder,margin_orders:this.handleOrder,futures_order:this.handleOrder,futures_orders:this.handleOrder,spot_balance:this.handleBalance,futures_balance:this.handleBalance},a=void 0===i?void 0:this.safeValue(r,i);void 0!==a&&a.call(this,e,t)}else{let i=this.safeValue(t,"result");if(void 0!==this.safeString(i,"client_order_id")&&this.handleOrderRequest(e,t),!0!==i||"id"in t||this.handleAuthenticate(e,t),Array.isArray(i)){let s=this.safeDict(i,0,{});(0===i.length||"client_order_id"in s)&&this.handleOrderRequest(e,t)}}}handleAuthenticate(e,t){let i=this.safeBool(t,"result"),s="authenticated";if(!0===i)this.safeValue(e.futures,s).resolve(!0);else{let i=new o.AuthenticationError(this.id+" "+this.json(t));e.reject(i,s),s in e.subscriptions&&delete e.subscriptions[s]}return t}handleError(e,t){let i=this.safeDict(t,"error");if(void 0!==i)try{let e=this.safeString(i,"code"),t=this.safeString(i,"message"),s=this.safeString(i,"description"),r=this.id+" "+s;throw this.throwExactlyMatchedException(this.exceptions.exact,e,r),this.throwBroadlyMatchedException(this.exceptions.broad,t,r),new o.ExchangeError(r)}catch(r){let i=this.safeString(t,"id");if(r instanceof o.AuthenticationError){let t="authenticated";e.reject(r,t),t in e.subscriptions&&delete e.subscriptions[t]}else e.reject(r,i);let s=Object.keys(e.subscriptions);for(let t=0;t<s.length;t++){let a=s[t],o=this.safeString(e.subscriptions[a],"id");void 0!==o&&o===i&&(e.reject(r,a),delete e.subscriptions[a])}return!0}return!1}}i.d(t,{A:()=>n})},293(e,t,i){"use strict";var s=i(4721),r=i(33),a=i(1453),o=i(1697);class n extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchMyTrades:!1,watchOHLCV:!1,watchOrderBook:!0,watchOrders:!0,watchTicker:!1,watchTickers:!1,watchTrades:!0,watchTradesForSymbols:!1},urls:{api:{ws:"wss://api.hollaex.com/stream"},test:{ws:"wss://api.sandbox.hollaex.com/stream"}},options:{watchBalance:{},watchOrders:{}},streaming:{ping:this.ping},exceptions:{ws:{exact:{"Bearer or HMAC authentication required":a.BadSymbol,"Error: wrong input":a.BadRequest}}}})}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s="orderbook:"+this.market(e).id;return(await this.watchPublic(s,i)).limit()}handleOrderBook(e,t){let i,s=this.safeString(t,"symbol"),r=this.safeString(t,"topic"),a=this.safeMarket(s).symbol;if(void 0===a)return;let o=this.safeDict(t,"data"),n=this.safeString(o,"timestamp"),d=this.parse8601(n),h=this.parseOrderBook(o,a,d);if(a in this.orderbooks){if(void 0===(i=this.orderbooks[a]))return;i.reset(h)}else i=this.orderBook(h),this.orderbooks[a]=i;void 0!==r&&e.resolve(i,r+":"+s)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o="trade:"+r.id,n=await this.watchPublic(o,s),d=i;return this.newUpdates&&(d=n.getLimit(a,i)),this.filterBySinceLimit(n,t,d,"timestamp",!0)}handleTrades(e,t){let i=this.safeString(t,"topic"),s=this.safeString(t,"symbol"),r=this.safeMarket(s),a=r.symbol,n=this.safeValue(this.trades,a);if(void 0===n){let e=this.safeInteger(this.options,"tradesLimit",1e3);n=new o.I3(e),this.trades[a]=n}let d=this.safeList(t,"data",[]),h=this.parseTrades(d,r);for(let e=0;e<h.length;e++)n.append(h[e]);if(void 0!==i){let t=i+":"+s;e.resolve(n,t)}e.resolve(n,i)}async watchMyTrades(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o="usertrade";void 0!==e&&(r=this.market(e),a=this.safeString(r,"symbol"),o+=":"+r.id);let n=await this.watchPrivate(o,s),d=i;return this.newUpdates&&(d=n.getLimit(a,i)),this.filterBySymbolSinceLimit(n,a,t,d,!0)}handleMyTrades(e,t,i){let s=this.safeString(t,"topic"),r=this.safeValue(t,"data");if(0===r.length)return;if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new o.I3(e)}let a=this.myTrades,n={};for(let e=0;e<r.length;e++){let t=r[e],i=this.parseTrade(t);a.append(i);let s=t.symbol,o=this.market(s).id;void 0!==o&&(n[o]=!0)}e.resolve(this.myTrades,s);let d=Object.keys(n);for(let t=0;t<d.length;t++){let i=d[t];if(void 0!==s){let t=s+":"+i;e.resolve(this.myTrades,t)}}}async watchOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o="order";void 0!==e&&(r=this.market(e),a=this.safeString(r,"symbol"),o+=":"+r.id);let n=await this.watchPrivate(o,s),d=i;return this.newUpdates&&(d=n.getLimit(a,i)),this.filterBySymbolSinceLimit(n,a,t,d,!0)}handleOrder(e,t,i){let s,r=this.safeString(t,"topic"),a=this.safeValue(t,"data",{});if(0===a.length)return;if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}let n=this.orders;s=Array.isArray(a)?a:[a];let d={};for(let e=0;e<s.length;e++){let t=s[e],i=this.parseOrder(t);n.append(i);let r=t.symbol,a=this.market(r).id;void 0!==a&&(d[a]=!0)}e.resolve(this.orders,r);let h=Object.keys(d);for(let t=0;t<h.length;t++){let i=h[t];if(void 0!==r){let t=r+":"+i;e.resolve(this.orders,t)}}}async watchBalance(e={}){return await this.watchPrivate("wallet",e)}handleBalance(e,t){let i=this.safeString(t,"topic"),s=this.safeValue(t,"data"),r=Object.keys(s),a=this.safeTimestamp(t,"time");this.balance.info=s,this.balance.timestamp=a,this.balance.datetime=this.iso8601(a);for(let e=0;e<r.length;e++){let t=r[e],i=t.split("_"),a=this.safeString(i,0),o=this.safeCurrencyCode(a),n=this.account();void 0!==o&&o in this.balance&&(n=this.balance[o]),n["available"===this.safeString(i,1)?"free":"total"]=this.safeString(s,t),void 0!==o&&(this.balance[o]=n)}this.balance=this.safeBalance(this.balance),e.resolve(this.balance,i)}async watchPublic(e,t={}){let i=this.urls.api.ws,s=this.extend({op:"subscribe",args:[e]},t);return await this.watch(i,e,s,e)}async watchPrivate(e,t={}){this.checkRequiredCredentials();let i=this.safeString(this.options,"ws-expires");if(void 0===i){let e=parseInt((this.timeout/1e3).toString());if(void 0===(i=this.sum(this.seconds(),e)))throw new a.ArgumentsRequired(this.id+" watchPrivate() expires is required");i=i.toString(),this.options["ws-expires"]=i}let r=this.urls.api.ws,o="CONNECT/stream"+i,n=this.hmac(this.encode(o),this.encode(this.secret),s.sc),d={"api-key":this.apiKey,"api-signature":n,"api-expires":i},h=r+"?"+this.urlencode(d),c=this.extend({op:"subscribe",args:[e]},t);return await this.watch(h,e,c,e)}handleErrorMessage(e,t){let i=this.safeInteger(t,"error");try{if(void 0!==i){let e=this.id+" "+this.json(t);this.throwExactlyMatchedException(this.exceptions.ws.exact,i,e)}}catch(e){if(e instanceof a.AuthenticationError)return!1}return!0}handleMessage(e,t){if(!0!==this.handleErrorMessage(e,t))return;if("pong"===this.safeString(t,"message"))return void this.handlePong(e,t);let i={trade:this.handleTrades,orderbook:this.handleOrderBook,order:this.handleOrder,wallet:this.handleBalance,usertrade:this.handleMyTrades},s=this.safeString(t,"topic"),r=this.safeValue(i,s);void 0!==r&&r.call(this,e,t)}ping(e){return{op:"ping"}}handlePong(e,t){return e.lastPong=this.milliseconds(),t}onError(e,t){this.options["ws-expires"]=void 0,super.onError(e,t)}onClose(e,t){this.options["ws-expires"]=void 0,super.onClose(e,t)}}i.d(t,{A:()=>n})},2404(e,t,i){"use strict";var s=i(4721),r=i(8552),a=i(1453),o=i(1697);class n extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,createOrderWs:!1,editOrderWs:!1,fetchOpenOrdersWs:!1,fetchOrderWs:!1,cancelOrderWs:!1,cancelOrdersWs:!1,cancelAllOrdersWs:!1,fetchTradesWs:!1,fetchBalanceWs:!1,watchOrderBook:!0,watchOrders:!0,watchTickers:!1,watchTicker:!0,watchTrades:!0,watchTradesForSymbols:!1,watchMyTrades:!0,watchBalance:!0,watchOHLCV:!0,unWatchTicker:!0,unWatchOHLCV:!0,unWatchTrades:!0,unWatchOrderBook:!0},urls:{api:{ws:{api:{spot:{public:"wss://{hostname}/ws",private:"wss://{hostname}/ws/v2",feed:"wss://{hostname}/feed"},future:{linear:{public:"wss://api.hbdm.vn/linear-swap-ws",private:"wss://api.hbdm.vn/linear-swap-notification",privateV5:"wss://api.hbdm.vn/ws/v5/notification"},inverse:{public:"wss://api.hbdm.vn/ws",private:"wss://api.hbdm.vn/notification"}},swap:{inverse:{public:"wss://api.hbdm.vn/swap-ws",private:"wss://api.hbdm.vn/swap-notification"},linear:{public:"wss://api.hbdm.vn/linear-swap-ws",private:"wss://api.hbdm.vn/linear-swap-notification",privateV5:"wss://api.hbdm.vn/ws/v5/notification"}}},"api-aws":{spot:{public:"wss://api-aws.huobi.pro/ws",private:"wss://api-aws.huobi.pro/ws/v2",feed:"wss://{hostname}/feed"},future:{linear:{public:"wss://api.hbdm.vn/linear-swap-ws",private:"wss://api.hbdm.vn/linear-swap-notification",privateV5:"wss://api.hbdm.vn/ws/v5/notification"},inverse:{public:"wss://api.hbdm.vn/ws",private:"wss://api.hbdm.vn/notification"}},swap:{linear:{public:"wss://api.hbdm.vn/linear-swap-ws",private:"wss://api.hbdm.vn/linear-swap-notification",privateV5:"wss://api.hbdm.vn/ws/v5/notification"},inverse:{public:"wss://api.hbdm.vn/swap-ws",private:"wss://api.hbdm.vn/swap-notification"}}}}}},options:{tradesLimit:1e3,OHLCVLimit:1e3,api:"api",watchOrderBook:{maxRetries:3,checksum:!0,depth:150},ws:{gunzip:!0},watchTicker:{name:"market.{marketId}.detail"}},exceptions:{ws:{exact:{"bad-request":a.BadRequest,2002:a.AuthenticationError,2021:a.BadRequest,2001:a.BadSymbol,2011:a.BadSymbol,2040:a.BadRequest,4007:a.BadRequest}}}})}requestId(){this.lockId();let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,this.unlockId(),e.toString()}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r=this.safeDict(this.options,"watchTicker",{}),o=this.safeString(r,"name","market.{marketId}.detail");if("market.{marketId}.ticker"===o&&"spot"!==i.type)throw new a.BadRequest(this.id+" watchTicker() with name market.{marketId}.ticker is only allowed for spot markets, use market.{marketId}.detail instead");let n=this.implodeParams(o,{marketId:i.id}),d=this.getUrlByMarketType(i.type,i.linear);return await this.subscribePublic(d,s,n,void 0,t)}async unWatchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.safeDict(this.options,"watchTicker",{}),r=this.safeString(s,"name","market.{marketId}.detail");if("market.{marketId}.ticker"===r&&"spot"!==i.type)throw new a.BadRequest(this.id+" watchTicker() with name market.{marketId}.ticker is only allowed for spot markets, use market.{marketId}.detail instead");let o=this.implodeParams(r,{marketId:i.id});return await this.unsubscribePublic(i,o,"ticker",t)}handleTicker(e,t){let i=this.safeDict(t,"tick",{}),s=this.safeString(t,"ch");if(void 0===s)return t;let r=s.split("."),a=this.safeString(r,1),o=this.safeMarket(a),n=this.parseTicker(i,o),d=this.safeInteger(t,"ts");n.timestamp=d,n.datetime=this.iso8601(d);let h=n.symbol;return void 0!==h&&(this.tickers[h]=n),e.resolve(n,s),t}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o="market."+r.id+".trade.detail",n=this.getUrlByMarketType(r.type,r.linear),d=await this.subscribePublic(n,a,o,void 0,s),h=i;return this.newUpdates&&(h=d.getLimit(a,i)),this.filterBySinceLimit(d,t,h,"timestamp",!0)}async unWatchTrades(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.safeDict(this.options,"watchTrades",{}),r=this.safeString(s,"name","market.{marketId}.trade.detail"),a=this.implodeParams(r,{marketId:i.id});return await this.unsubscribePublic(i,a,"trades",t)}handleTrades(e,t){let i=this.safeDict(t,"tick",{}),s=this.safeList(i,"data",[]),r=this.safeString(t,"ch");if(void 0===r)return t;let a=r.split("."),n=this.safeString(a,1),d=this.safeMarket(n),h=d.symbol,c=this.safeValue(this.trades,h);if(void 0===c){let e=this.safeInteger(this.options,"tradesLimit",1e3);c=new o.I3(e),this.trades[h]=c}for(let e=0;e<s.length;e++){let t=this.parseTrade(s[e],d);c.append(t)}return e.resolve(c,r),t}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n=this.safeString(this.timeframes,t,t),d="market."+a.id+".kline."+n,h=this.getUrlByMarketType(a.type,a.linear),c=await this.subscribePublic(h,o,d,void 0,r),l=s;return this.newUpdates&&(l=c.getLimit(o,s)),this.filterBySinceLimit(c,i,l,0,!0)}async unWatchOHLCV(e,t="1m",i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=this.safeString(this.timeframes,t,t),a="market."+s.id+".kline."+r;return i.symbolsAndTimeframes=[[s.symbol,t]],await this.unsubscribePublic(s,a,"ohlcv",i)}handleOHLCV(e,t){let i=this.safeString(t,"ch");if(void 0===i)return;let s=i.split("."),r=this.safeString(s,1),a=this.safeMarket(r),n=a.symbol,d=this.safeString(s,3),h=this.findTimeframe(d);this.ohlcvs[n]=this.safeDict(this.ohlcvs,n,{});let c=this.safeValue(this.safeDict(this.ohlcvs,n),h);if(void 0===c){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);c=new o.TG(e),void 0!==n&&void 0!==h&&(this.ohlcvs[n][h]=c)}let l=this.safeDict(t,"tick"),u=this.parseOHLCV(l,a);c.append(u),e.resolve(c,i)}async watchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),o=r.symbol,n=this.safeDict(this.options,"watchOrderBook",{}),d=void 0===t?this.safeInteger(n,"depth",150):t;if(!this.inArray(d,[5,20,150,400]))throw new a.ExchangeError(this.id+" watchOrderBook market accepts limits of 5, 20, 150 or 400 only");s=!0===r.spot?"market."+r.id+".mbp."+this.numberToString(d):"market."+r.id+".depth.size_"+this.numberToString(d)+".high_freq";let h=this.getUrlByMarketType(r.type,r.linear,!1,!0),c=this.handleOrderBookSubscription,l=i;return!0!==r.spot&&(l=this.extend(i,{data_type:"incremental"})),!0!==r.spot&&(c=void 0),(await this.subscribePublic(h,o,s,c,l)).limit()}async unWatchOrderBook(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=this.safeDict(this.options,"watchOrderBook",{}),a=this.safeInteger(r,"depth",150);return i=!0===s.spot?"market."+s.id+".mbp."+this.numberToString(a):"market."+s.id+".depth.size_"+this.numberToString(a)+".high_freq",!0!==s.spot&&(t.data_type="incremental"),await this.unsubscribePublic(s,i,"orderbook",t)}handleOrderBookSnapshot(e,t,i){let s=this.safeString(i,"symbol"),r=this.safeString(i,"messageHash");if(void 0===r)return;let o=this.safeString(t,"id"),n=this.safeInteger(i,"lastTimestamp");try{let d=this.safeValue(this.orderbooks,s),h=this.safeDict(t,"data"),c=d.cache,l=this.safeDict(c,0,{}),u=this.parseOrderBook(h,s),f=this.safeDict(l,"tick"),p=this.safeInteger(f,"prevSeqNum"),m=this.safeInteger(h,"seqNum");if(void 0===m)return;u.nonce=m;let g=this.safeInteger(t,"ts");i.lastTimestamp=g;let v=this.safeInteger(i,"limit"),y=this.orderBook(u,v);if(e.resolve(y,o),void 0===p||m<p){let o=this.handleOption("watchOrderBook","maxRetries",3),d=this.safeInteger(i,"numAttempts",0);if(d<o){if(r in e.subscriptions){d=this.sum(d,1);let s=1e3;void 0!==n&&void 0!==g&&(s=this.sum(1e3,n-g)),i.numAttempts=d,e.subscriptions[r]=i,this.delay(s,this.watchOrderBookSnapshot,e,t,i)}}else throw new a.InvalidNonce(this.id+" failed to synchronize WebSocket feed with the snapshot for symbol "+s+" in "+o.toString()+" attempts")}else{d.reset(u);for(let t=0;t<c.length;t++)this.handleOrderBookMessage(e,c[t]);d.cache=[],void 0!==s&&(this.orderbooks[s]=d),e.resolve(d,r)}}catch(t){void 0!==r&&delete e.subscriptions[r],void 0!==s&&delete this.orderbooks[s],e.reject(t,r)}}async watchOrderBookSnapshot(e,t,i){let s=this.safeString(i,"messageHash"),r=this.safeString(i,"symbol"),a=this.safeInteger(i,"limit"),o=this.safeInteger(t,"ts"),n=this.safeDict(i,"params"),d=this.safeInteger(i,"numAttempts",0),h=this.market(r),c=this.getUrlByMarketType(h.type,h.linear,!1,!0),l=this.requestId(),u={id:l,messageHash:s,symbol:r,limit:a,params:n,numAttempts:d,lastTimestamp:o,method:this.handleOrderBookSnapshot};try{return(await this.watch(c,l,{req:s,id:l},l,u)).limit()}catch(t){void 0!==s&&delete e.subscriptions[s],e.reject(t,s)}}handleDelta(e,t){let i=this.safeFloat(t,0),s=this.safeFloat(t,1);e.store(i,s)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}handleOrderBookMessage(e,t){let i=this.safeValue(t,"ch").split("."),s=this.safeString(i,1),r=this.safeMarket(s),o=r.symbol,n=this.orderbooks[o],d=this.safeDict(t,"tick",{}),h=this.safeInteger(d,"seqNum"),c=this.safeInteger(d,"prevSeqNum"),l=this.safeString(d,"event"),u=this.safeInteger(d,"version"),f=this.safeInteger(t,"ts");if("snapshot"===l){let e=this.parseOrderBook(d,o,f);n.reset(e),n.nonce=u}if(void 0!==c&&c>this.safeInteger(n,"nonce",0)&&!0===this.handleOption("watchOrderBook","checksum",!0))throw new a.ChecksumError(this.id+" "+this.orderbookChecksumMessage(o));let p=!0===r.spot&&c===n.nonce,m=!0===r.contract&&void 0!==u&&u-1===n.nonce;if(!0===p||!0===m){let e=this.safeList(d,"asks",[]),t=this.safeList(d,"bids",[]);this.handleDeltas(n.asks,e),this.handleDeltas(n.bids,t),n.nonce=!0===p?h:u,n.timestamp=f,n.datetime=this.iso8601(f)}}handleOrderBook(e,t){let i=this.safeString(t,"ch"),s=this.safeDict(t,"tick"),r=this.safeString(s,"event"),a=this.safeString(t,"ch");if(void 0===a)return;let o=a.split("."),n=this.safeString(o,1),d=this.safeSymbol(n);if(!(d in this.orderbooks)){let e=this.safeString(o,3);if(void 0===e)return;let t=e.split("_"),i=this.safeInteger(t,1);this.orderbooks[d]=this.orderBook({},i)}let h=this.orderbooks[d];void 0===r&&void 0===h.nonce?h.cache.push(t):(this.handleOrderBookMessage(e,t),e.resolve(h,i))}handleOrderBookSubscription(e,t,i){let s=this.safeString(i,"symbol"),r=this.market(s),a=this.safeInteger(i,"limit");void 0!==s&&(this.orderbooks[s]=this.orderBook({},a)),!0===r.spot&&this.spawn(this.watchOrderBookSnapshot,e,t,i)}async watchMyTrades(e,t,i,s={}){let r,o,n,d,h,c;this.checkRequiredCredentials(),void 0===this.markets&&await this.loadMarkets();let l="*";void 0!==e?(o=this.market(e),r=this.safeString(o,"type"),c=!0===o.linear?"linear":"inverse",l=o.lowercaseId):(r=this.safeString(this.options,"defaultType","spot"),r=this.safeString(s,"type",r),c=this.safeString2(this.options,"subType","defaultSubType","linear"),c=this.safeString(s,"subType",c));let u=void 0!==o?this.safeString(o,"symbol"):e,f=void 0!==e?s:this.omit(s,["type","subType"]),p="swap"===r,m="future"===r,g="linear"===c&&(p||m);if("spot"===r){let e;void 0===e&&(e=this.safeString2(this.options,"watchMyTrades","mode","0"),e=this.safeString(f,"mode",e),f=this.omit(f,"mode")),d=n="trade.clearing#"+l+"#"+e}else if(g){let e=this.getV5LinearChannelAndMessageHash("trade",o,f);d=this.safeString(e,0),n=this.safeString(e,1),f=this.safeDict(e,2,{})}else{let e=this.getOrderChannelAndMessageHash(r,c,o,f);d=this.safeString(e,0);let t=this.safeString(e,1);void 0!==t&&(n=t+":trade")}if(void 0===(h=await this.subscribePrivate(d,n,r,c,f,{isV5:g})))throw new a.ArgumentsRequired(this.id+" watchMyTrades() trades is required");let v=i;return this.newUpdates&&(v=h.getLimit(u,i)),this.filterBySymbolSinceLimit(h,u,t,v,!0)}getOrderChannelAndMessageHash(e,t,i,s={}){let r,a,o,n,d=this.safeString(this.options,"orderType","orders");d=this.safeString(s,"orderType",d);let h=this.omit(s,"orderType");void 0!==i&&void 0!==i.lowercaseId&&(o=i.lowercaseId.toLowerCase()),void 0!==i&&(n=i.baseId);let c=d;if(r=c,"linear"===t){let e=this.safeString(h,"margin","cross"),t=c;"cross"===e&&(t=c+"_cross"),r=t,void 0!==o?(r+="."+o,a=r):a=t+".*"}else"future"===e?void 0!==n?r=a=c+"."+n.toLowerCase():a=c+".*":void 0!==o?r=a=c+"."+o:a=c+".*";return[a,r]}getV5LinearChannelAndMessageHash(e,t,i={}){let s;s=void 0!==t?t.id:this.safeString(i,"contract_code","*");let r=e;void 0!==s&&"*"!==s&&(r=e+"."+s.toLowerCase());let a=this.omit(i,"contract_code");return[e,r,this.extend({contract_code:s},a)]}async watchOrders(e,t,i,s={}){let r,a,o,n,d;void 0===this.markets&&await this.loadMarkets();let h="*";void 0!==e?(o=this.market(e),r=this.safeString(o,"type"),h=o.lowercaseId,a=!0===o.linear?"linear":"inverse"):(r=this.safeString(this.options,"defaultType","spot"),r=this.safeString(s,"type",r),a=this.safeString2(this.options,"subType","defaultSubType","linear"),a=this.safeString(s,"subType",a));let c=void 0!==o?o.symbol:e,l=void 0!==e?s:this.omit(s,["type","subType"]),u="swap"===r,f="future"===r,p="linear"===a&&(u||f);if("spot"===r)d=n="orders#"+h;else if(p){let e=this.getV5LinearChannelAndMessageHash("orders",o,l);d=this.safeString(e,0),n=this.safeString(e,1),l=this.safeDict(e,2,{})}else{let e=this.getOrderChannelAndMessageHash(r,a,o,l);d=this.safeString(e,0),n=this.safeString(e,1)}let m=await this.subscribePrivate(d,n,r,a,l,{isV5:p}),g=i;return this.newUpdates&&(g=m.getLimit(c,i)),this.filterBySinceLimit(m,t,g,"timestamp",!0)}handleOrder(e,t){let i,s=this.safeString2(t,"ch","topic"),r=this.safeDict(t,"data"),a=this.safeString(t,"contract_code");void 0===a&&(a=this.safeString2(r,"contract_code","symbol"));let n=this.safeMarket(a);if(void 0!==r)if("trade"===this.safeString(r,"eventType")){let e=this.parseOrderTrade(r,n),t=this.safeString(e,"order"),s=this.parseOrderStatus(this.safeString2(r,"orderStatus","status","closed")),a=this.safeString(r,"execAmt"),o=this.safeString(r,"remainAmt");i={id:t,trades:[e],status:s,lastTradeTimestamp:this.safeInteger(r,"tradeTime"),symbol:n.symbol,filled:this.parseNumber(a),remaining:this.parseNumber(o),price:this.safeNumber(r,"orderPrice"),amount:this.safeNumber(r,"orderSize"),info:r}}else i=this.parseWsOrder(r,n);else{i=this.parseWsOrder(t,n);let r=this.safeList(t,"trade",[]);if(r.length>0){let t={trades:r,ch:s,symbol:a},o={order:this.safeString(i,"id"),type:this.safeString(i,"type"),side:this.safeString(i,"side")};this.handleMyTrade(e,t,o)}}if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}if(this.orders.append(i),e.resolve(this.orders,s),void 0!==s&&void 0!==a&&"orders"===s){let t=s+"."+a.toLowerCase();e.resolve(this.orders,t)}if(void 0===s)return;let d=s.replace("."+n.lowercaseId,""),h=this.safeStringLower(n,"baseId");d=d.replace("."+h,""),e.resolve(this.orders,d)}parseWsOrder(e,t){let i,s,r=this.safeIntegerN(e,["lastActTime","updated_time","ts"]),a=this.safeInteger2(e,"orderCreateTime","created_time"),o=this.safeString2(e,"contract_code","symbol"),n=this.safeMarket(o,t),d=this.safeSymbol(o,n),h=this.safeString2(e,"orderSize","volume"),c=this.parseOrderStatus(this.safeStringN(e,["orderStatus","state","status"])),l=this.safeString2(e,"orderId","order_id"),u=this.safeString2(e,"clientOrderId","client_order_id"),f=this.safeString2(e,"orderPrice","price"),p=this.safeString2(e,"execAmt","trade_volume"),m=this.safeString(e,"type"),g=this.safeString(e,"fee");if(void 0!==g){let t=this.safeString2(e,"fee_asset","fee_currency");i={cost:g,currency:this.safeCurrencyCode(t)}}let v=this.safeString(e,"trade_avg_price"),y=this.safeValue(e,"trade"),b=[];void 0!==m&&(m.indexOf("-")>=0?(b=m.split("-"),s=this.safeStringLower(b,1)):s=m),void 0===s&&(s=this.safeString(e,"order_price_type"));let w=this.safeStringLower(b,0);void 0===w&&(w=this.safeString2(e,"direction","side"));let k=this.safeString2(e,"orderValue","trade_turnover");return this.safeOrder({info:e,id:l,clientOrderId:u,timestamp:a,datetime:this.iso8601(a),lastTradeTimestamp:r,status:c,symbol:d,type:s,timeInForce:this.safeStringUpper(e,"time_in_force"),postOnly:void 0,side:w,price:f,amount:h,filled:p,remaining:void 0,cost:k,fee:i,average:v,trades:y,reduceOnly:this.safeBool(e,"reduce_only"),stopPrice:void 0,triggerPrice:void 0,takeProfitPrice:this.safeString2(e,"tp_trigger_price","tp_order_price"),stopLossPrice:this.safeString2(e,"sl_trigger_price","sl_order_price")},n)}parseOrderTrade(e,t){let i,s,r=this.safeMarket(void 0,t),a=r.symbol,o=this.safeString(e,"tradeId"),n=this.safeString(e,"tradePrice"),d=this.safeString(e,"tradeVolume"),h=this.safeString(e,"orderId"),c=this.safeInteger(e,"tradeTime"),l=this.safeString(e,"type");if(void 0!==l){let e=l.split("-");i=e[0],l=e[1]}let u=this.safeBool(e,"aggressor");return void 0!==u&&(s=!0===u?"taker":"maker"),this.safeTrade({info:e,timestamp:c,datetime:this.iso8601(c),symbol:a,id:o,order:h,type:l,takerOrMaker:s,side:i,price:n,amount:d,cost:void 0,fee:void 0},r)}async watchPositions(e,t,i,s={}){let r,a,o;void 0===this.markets&&await this.loadMarkets();let n="";this.isEmpty(e)||void 0===e||(r=this.getMarketFromSymbols(e),n="::"+e.join(","));let d={};if(void 0!==r)a=this.safeString(r,"type"),o=!0===r.linear?"linear":"inverse";else{let[e,t]=this.handleMarketTypeAndParams("watchPositions",r,s);a="spot"===e?"future":e,[o,d]=this.handleOptionStringAndParams(t,"watchPositions","subType",o)}let h=this.marketSymbols(e),c=void 0!==r?s:d,[l,u]=this.handleMarginModeAndParams("watchPositions",c,"cross"),f=u,p="swap"===a,m="future"===a,g="linear"===o&&(p||m),v="linear"===o,y=this.getUrlByMarketType(a,v,!0,!1,g);n=l+":positions"+n;let b="positions.*";if("cross"===l&&(b="positions_cross.*"),g){let e;void 0!==h&&1===h.length&&(e=r);let t=this.getV5LinearChannelAndMessageHash("positions",e,f);b=this.safeString(t,0),f=this.safeDict(t,2,{})}let w=await this.subscribePrivate(b,n,a,o,f,{isV5:g,margin:l});return this.newUpdates?w:this.filterBySymbolsSinceLimit(this.safeValue(this.safeValue(this.positions,y),l),h,t,i,!1)}handlePositions(e,t){let i=e.url,s=this.safeString(t,"topic",""),r="isolated";"positions_cross"===s&&(r="cross"),void 0===this.positions&&(this.positions={}),void 0===this.safeDict(this.positions,i)&&(this.positions[i]={});let a=this.safeList(t,"data",[]);if(this.isEmpty(a)){let t=["cross:positions","isolated:positions"];for(let i=0;i<t.length;i++){let s=this.findMessageHashes(e,t[i]);for(let t=0;t<s.length;t++)e.resolve([],s[t])}return}let n=[],d={},h=this.safeInteger(t,"ts");for(let e=0;e<a.length;e++){let t=a[e],s=this.parsePosition(t);s.timestamp=h,s.datetime=this.iso8601(h);let c=this.safeStringLower(s,"marginMode",r);"cross"!==c&&"isolated"!==c&&(c=r);let l=this.safeValue(this.positions[i],c);void 0===l&&(l=new o.Hk,this.positions[i][c]=l),n.push(s),d[c]=this.safeList(d,c,[]),d[c].push(s),l.append(s)}let c=Object.keys(d);for(let t=0;t<c.length;t++){let i=c[t],s=this.safeList(d,i,[]),r=this.findMessageHashes(e,i+":positions::");for(let t=0;t<r.length;t++){let i=r[t],a=i.split("::")[1].split(","),o=this.filterByArray(s,"symbol",a,!1);this.isEmpty(o)||e.resolve(o,i)}e.resolve(s,i+":positions")}}async watchBalance(e={}){let t,i,s,[r,a]=this.handleMarketTypeAndParams("watchBalance",void 0,e),[o,n]=this.handleSubTypeAndParams("watchBalance",void 0,a,"linear"),d=this.safeBool2(n,"isUnifiedAccount","unified",!1),h=this.omit(n,["isUnifiedAccount","unified"]),c="spot"!==r?this.omit(h,["currency","symbol","margin"]):h;void 0===this.markets&&await this.loadMarkets();let l="swap"===r,u="future"===r,f="linear"===o&&(l||u);if("spot"===r){let e=this.safeString2(this.options,"watchBalance","mode","2");i=t="accounts.update#"+(e=this.safeString(h,"mode",e))}else if(f)s=this.safeString(h,"margin","cross"),i="account",t="account";else{let e=this.safeString(h,"symbol"),a=this.safeString(h,"currency"),n=void 0!==e?this.market(e):void 0,c=void 0!==a?this.currency(a):void 0;s=this.safeString(h,"margin","cross");let l="accounts";t=l,"linear"===o?!0===d?(t=l="accounts_unify",i=l+".usdt"):(t=l="cross"===s?l+"_cross":l,"isolated"===s?void 0!==e&&void 0!==n?(t+="."+n.id,i=t):i=l+".*":void 0!==c?t=i=l+"."+c.id:i=l+".*"):"future"===r?void 0!==c?(t+="."+c.id,i=t):i=l+".*":void 0!==n?(t+="."+n.id,i=t):i=l+".*"}let p={type:r,subType:o,margin:s,isV5:f};return await this.subscribePrivate(i,t,r,o,c,p)}handleBalance(e,t){let i=this.safeString(t,"ch"),s=this.safeList(t,"data",[]),r=this.safeInteger(s,"changeTime",this.safeInteger(t,"ts"));if(this.balance.timestamp=r,this.balance.datetime=this.iso8601(r),this.balance.info=s,void 0!==i){let t=this.safeString(s,"currency"),r=this.safeCurrencyCode(t),a=this.account();a.free=this.safeString(s,"available"),a.total=this.safeString(s,"balance"),void 0!==r&&(this.balance[r]=a),this.balance=this.safeBalance(this.balance),e.resolve(this.balance,i)}else{let i=this.safeString(t,"topic");if(void 0===i)return;if("account"===i){let i=this.safeDict(t,"data",{}),s=this.safeList(i,"details",[]),r=s.length;for(let e=0;e<r;e++){let t=this.safeDict(s,e),i=this.safeString(t,"currency"),r=this.safeCurrencyCode(i);if(void 0===r)continue;let a=this.account();a.free=this.safeString(t,"withdraw_available"),a.total=this.safeString(t,"equity"),this.balance[r]=a}this.balance=this.safeBalance(this.balance),e.resolve(this.balance,"account");return}if(0===s.length)return;let r=this.safeDict(s,0,{}),a=i.split("."),o=this.safeString(a,0),n=this.safeDict2(e.subscriptions,o,o+".*");if(void 0===n){let t=this.safeString2(r,"margin_asset","symbol");if(void 0===t)return;o+="."+t.toLowerCase(),n=this.safeDict(e.subscriptions,o)}let d=this.safeString(n,"subType");if("accounts_unify"===i){let t=this.safeString(r,"margin_asset"),i=this.safeCurrencyCode(t),s=this.safeString(r,"margin_frozen"),a=this.account();a.free=this.safeString(r,"withdraw_available"),a.used=s,void 0!==i&&(this.balance[i]=a),this.balance=this.safeBalance(this.balance),e.resolve(this.balance,"accounts_unify")}else if("linear"===d)if("cross"===this.safeString(n,"margin")){let e=this.safeString2(r,"margin_asset","margin_account"),t=this.safeCurrencyCode(e);if(void 0!==t){let e=this.account();e.free=this.safeString2(r,"withdraw_available","margin_available"),e.used=this.safeString(r,"margin_frozen"),e.total=this.safeString(r,"margin_balance"),this.balance[t]=e,this.balance=this.safeBalance(this.balance)}}else for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),i=this.account();i.free=this.safeString(t,"margin_balance","margin_available"),i.used=this.safeString(t,"margin_frozen");let r=this.safeString2(t,"margin_asset","symbol"),a=this.safeCurrencyCode(r);void 0!==a&&(this.balance[a]=i),this.balance=this.safeBalance(this.balance)}else for(let e=0;e<s.length;e++){let t=this.safeDict(s,e),i=this.safeString(t,"symbol"),r=this.safeCurrencyCode(i),a=this.account();a.free=this.safeString(t,"margin_available"),a.used=this.safeString(t,"margin_frozen"),void 0!==r&&(this.balance[r]=a),this.balance=this.safeBalance(this.balance)}e.resolve(this.balance,o)}}handleSubscriptionStatus(e,t){let i=this.safeString(t,"id");if(void 0===i)return;let s=this.indexBy(e.subscriptions,"id"),r=this.safeDict(s,i);if(void 0!==r){let s=this.safeValue(r,"method");void 0!==s&&s.call(this,e,t,r),i in e.subscriptions&&void 0!==i&&delete e.subscriptions[i]}"unsubbed"in t&&this.handleUnSubscription(e,r)}handleUnSubscription(e,t){let i=this.safeList(t,"messageHashes",[]),s=this.safeList(t,"subMessageHashes",[]);for(let t=0;t<i.length;t++){let r=i[t],a=s[t];this.cleanUnsubscription(e,a,r)}this.cleanCache(t)}handleSystemStatus(e,t){return t}handleSubject(e,t){let i=this.safeString(t,"ch",""),s=i.split(".");if("market"===this.safeString(s,0)){let i=this.safeString(s,2),r={depth:this.handleOrderBook,mbp:this.handleOrderBook,detail:this.handleTicker,bbo:this.handleTicker,ticker:this.handleTicker,trade:this.handleTrades,kline:this.handleOHLCV},a=this.safeValue(r,i);if(void 0!==a)return void a.call(this,e,t)}let r=i.split("#"),a=this.safeString(r,0,"");if("trade.clearing"===a)return void this.handleMyTrade(e,t);if(a.indexOf("accounts.update")>=0)return void this.handleBalance(e,t);if("orders"===a)return void this.handleOrder(e,t);if("notify"===this.safeString(t,"op")){let i=this.safeString(t,"topic","");i.indexOf("orders")>=0&&this.handleOrder(e,t),i.indexOf("trade")>=0&&this.handleMyTrade(e,t),i.indexOf("account")>=0&&this.handleBalance(e,t),i.indexOf("positions")>=0&&this.handlePositions(e,t)}}async pong(e,t){try{let i=this.safeInteger(t,"ping");if(void 0!==i)return void await e.send({pong:i});let s=this.safeString(t,"action");if("ping"===s){let i=this.safeDict(t,"data"),s=this.safeInteger(i,"ts");await e.send({action:"pong",data:{ts:s}});return}let r=this.safeString(t,"op");if("ping"===r){let i=this.safeInteger(t,"ts");await e.send({op:"pong",ts:i})}}catch(i){let t=new a.NetworkError(this.id+" pong failed "+this.exceptionMessage(i));e.reset(t)}}handlePing(e,t){this.spawn(this.pong,e,t)}handleAuthenticate(e,t){e.futures.auth.resolve(t)}handleErrorMessage(e,t){if("error"===this.safeString(t,"status")){let i=this.safeString(t,"id");if(void 0===i)return!1;let s=this.indexBy(e.subscriptions,"id"),r=this.safeDict(s,i);if(void 0!==r){let s=this.safeString(t,"err-code");try{throw this.throwExactlyMatchedException(this.exceptions.ws.exact,s,this.json(t)),new a.ExchangeError(this.json(t))}catch(s){let t=this.safeString(r,"messageHash");e.reject(s,t),e.reject(s,i),i in e.subscriptions&&void 0!==i&&delete e.subscriptions[i],void 0!==t&&t in e.subscriptions&&delete e.subscriptions[t]}}return!1}let i=this.safeString2(t,"code","err-code");if(void 0!==i&&"200"!==i&&"0"!==i){let s=this.id+" "+this.json(t);try{throw this.throwExactlyMatchedException(this.exceptions.ws.exact,i,s),new a.ExchangeError(s)}catch(t){if(t instanceof a.AuthenticationError){e.reject(t,"auth");let i="auth";return i in e.subscriptions&&delete e.subscriptions[i],!1}e.reject(t)}}return!0}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t)){if("id"in t)return void this.handleSubscriptionStatus(e,t);if("action"in t){let i=this.safeString(t,"action");if("ping"===i)return void this.handlePing(e,t);if("sub"===i)return void this.handleSubscriptionStatus(e,t)}if("ch"in t)if("auth"===this.safeString(t,"ch"))return void this.handleAuthenticate(e,t);else return void this.handleSubject(e,t);if("op"in t){let i=this.safeString(t,"op");if("ping"===i)return void this.handlePing(e,t);if("auth"===i)return void this.handleAuthenticate(e,t);if("sub"===i)return void this.handleSubscriptionStatus(e,t);if("notify"===i)return void this.handleSubject(e,t)}"ping"in t&&this.handlePing(e,t)}}handleMyTrade(e,t,i={}){if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new o.Pt(e)}let s=this.myTrades,r=this.safeString2(t,"ch","topic");if(void 0!==r){let a=this.safeValue(t,"data");if(void 0!==a){let i=this.safeString(t,"contract_code"),o=void 0!==i?this.safeMarket(i):void 0;if(Array.isArray(a))for(let e=0;e<a.length;e++){let t=this.parseWsTrade(a[e],o);void 0!==this.safeString(t,"symbol")&&s.append(t)}else{let e=this.parseWsTrade(a,o);void 0!==this.safeString(e,"symbol")&&s.append(e)}if(e.resolve(this.myTrades,r),"trade"===r&&void 0!==i){let t=r+"."+i.toLowerCase();e.resolve(this.myTrades,t)}}else{let a=this.safeList(t,"trades",[]),o=this.safeString(t,"symbol"),n=this.market(o);for(let e=0;e<a.length;e++){let t=a[e],r=this.parseTrade(t,n);r=this.extend(r,i),s.append(r)}let d=r+":trade";e.resolve(this.myTrades,d);let h=r.replace("."+n.lowercaseId,""),c=this.safeStringLower(n,"baseId"),l=(h=h.replace("."+c,""))+":trade";e.resolve(this.myTrades,l)}}}parseWsTrade(e,t){let i,s,r,a=this.safeString2(e,"symbol","contract_code"),o=this.safeMarket(a,t),n=this.safeString(o,"symbol"),d=this.safeStringN(e,["side","orderSide","direction"]),h=this.safeStringN(e,["tradeId","trade_id","id"]),c=this.safeString2(e,"tradePrice","trade_price"),l=this.safeString2(e,"tradeVolume","trade_volume"),u=this.safeString2(e,"orderId","order_id"),f=this.safeIntegerN(e,["tradeTime","updated_time","created_time"]),p=this.safeString2(e,"orderType","type"),m=this.safeBool(e,"aggressor");i=void 0!==m?!0===m?"taker":"maker":this.safeStringLower(e,"role");let g=[];void 0!==p&&(g=p.split("-"),s=this.safeString(g,1,p));let v=this.safeCurrencyCode(this.safeStringN(e,["feeCurrency","fee_currency","fee_asset"]));return void 0!==v&&(r={cost:this.safeStringN(e,["transactFee","fee","trade_fee"]),currency:v}),this.safeTrade({info:e,timestamp:f,datetime:this.iso8601(f),symbol:n,id:h,order:u,type:s,takerOrMaker:i,side:d,price:c,amount:l,cost:void 0,fee:r},o)}getUrlByMarketType(e,t=!0,i=!1,s=!1,r=!1){let a,o,n=this.safeString(this.options,"api","api"),d={hostname:this.hostname};if("spot"===e)a=i?this.urls.api.ws[n].spot.private:s?this.urls.api.ws[n].spot.feed:this.urls.api.ws[n].spot.public,o=this.implodeParams(a,d);else{let s=this.urls.api.ws[n][e],a=t?s.linear:s.inverse;o=i?r&&t?this.safeString(a,"privateV5",a.private):a.private:a.public}return o}async subscribePublic(e,t,i,s,r={}){let a=this.requestId(),o={id:a,messageHash:i,symbol:t,params:r};return void 0!==s&&(o.method=s),await this.watch(e,i,this.extend({sub:i,id:a},r),i,o)}async unsubscribePublic(e,t,i,s={}){let r=this.requestId(),o="unsubscribe::"+t;if(void 0===e)throw new a.ArgumentsRequired(this.id+" unsubscribePublic() market is required");let n=this.getUrlByMarketType(e.type,e.linear,!1,"orderbook"===i),d={unsubscribe:!0,id:r,subMessageHashes:[t],messageHashes:[o],symbols:[e.symbol],topic:i},h=this.safeList(s,"symbolsAndTimeframes"),c=void 0!==h?this.omit(s,"symbolsAndTimeframes"):s;return void 0!==h&&(d.symbolsAndTimeframes=h),await this.watch(n,o,this.extend({unsub:t,id:r},c),o,d)}async subscribePrivate(e,t,i,s,r={},a={}){let o,n=this.requestId(),d=this.extend({id:n,messageHash:t,params:r},a);o="spot"===i?{action:"sub",ch:e}:{op:"sub",topic:e,cid:n};let h=this.safeBool(a,"isV5",!1),c=this.getUrlByMarketType(i,"linear"===s,!0,!1,h),l="spot"===i?this.urls.hostnames.spot:this.urls.hostnames.contract;return await this.authenticate({type:i,url:c,hostname:l}),await this.watch(c,t,this.extend(o,r),e,d)}async authenticate(e={}){let t=this.safeString(e,"url"),i=this.safeString(e,"hostname"),r=this.safeString(e,"type");if(void 0===t||void 0===i||void 0===r)throw new a.ArgumentsRequired(this.id+" authenticate requires a url, hostname and type argument");this.checkRequiredCredentials();let o="auth",n=t.replace("wss://"+i,""),d=this.client(t),h=d.reusableFuture(o);if(void 0===this.safeValue(d.subscriptions,o)){let a,d,h=this.ymdhms(this.milliseconds(),"T");a="spot"===r?{accessKey:this.apiKey,signatureMethod:"HmacSHA256",signatureVersion:"2.1",timestamp:h}:{AccessKeyId:this.apiKey,SignatureMethod:"HmacSHA256",SignatureVersion:"2",Timestamp:h},a=this.keysort(a);let c=["GET",i,n,this.urlencode(a,!0)].join("\n"),l=this.hmac(this.encode(c),this.encode(this.secret),s.sc,"base64");d="spot"===r?{params:{authType:"api",accessKey:this.apiKey,signatureMethod:"HmacSHA256",signatureVersion:"2.1",timestamp:h,signature:l},action:"req",ch:"auth"}:{op:"auth",type:"api",AccessKeyId:this.apiKey,SignatureMethod:"HmacSHA256",SignatureVersion:"2",Timestamp:h,Signature:l};let u=this.requestId();this.watch(t,o,d,o,{id:u,messageHash:o,params:e})}return await h}}i.d(t,{A:()=>n})},8334(e,t,i){"use strict";var s=i(7450),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,cancelOrderWs:!0,cancelOrdersWs:!0,createOrderWs:!0,createOrdersWs:!0,editOrderWs:!0,watchBalance:!0,watchMyTrades:!0,watchOHLCV:!0,watchOrderBook:!0,watchOrders:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!1,watchPosition:!1,unWatchBalance:!0,watchPositions:!0,unWatchPositions:!0,unWatchOrderBook:!0,unWatchTicker:!0,unWatchTickers:!0,unWatchTrades:!0,unWatchOHLCV:!0,unWatchMyTrades:!0,unWatchOrders:!0},urls:{api:{ws:{public:"wss://api.hyperliquid.xyz/ws"}},test:{ws:{public:"wss://api.hyperliquid-testnet.xyz/ws"}}},options:{unsubscribeTimeout:1e4},streaming:{ping:this.ping,keepAlive:2e4},exceptions:{ws:{exact:{}}}})}async createOrdersWs(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.urls.api.ws.public,s=this.createOrdersRequest(e,t),r=this.wrapAsPostAction(s),a=this.safeDict(r,"request",{}),o=this.safeString(r,"requestId"),n=await this.watch(i,o,a,o),d=this.safeDict(n,"response",{}),h=this.safeDict(d,"data",{}),c=this.safeList(h,"statuses",[]);return this.parseOrders(c,void 0)}async createOrderWs(e,t,i,s,r,a={}){void 0===this.markets&&await this.loadMarkets();let[o,n]=this.parseCreateEditOrderArgs(void 0,e,t,i,s,r,a),d=await this.createOrdersWs([o],n);return 0===d.length?this.safeOrder({}):d[0]}async editOrderWs(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(t),d=this.urls.api.ws.public,[h,c]=this.parseCreateEditOrderArgs(e,t,i,s,r,a,o),l=this.editOrdersRequest([h],c),u=this.wrapAsPostAction(l),f=this.safeDict(u,"request",{}),p=this.safeString(u,"requestId"),m=await this.watch(d,p,f,p),g=this.safeDict(m,"response",{}),v=this.safeDict(g,"data",{}),y=this.safeList(v,"statuses",[]),b=this.safeDict(y,0,{});return this.parseOrder(b,n)}async cancelOrdersWs(e,t,i={}){this.checkRequiredCredentials(),void 0===this.markets&&await this.loadMarkets();let s=this.cancelOrdersRequest(e,t,i),r=this.urls.api.ws.public,a=this.wrapAsPostAction(s),o=this.safeDict(a,"request",{}),n=this.safeString(a,"requestId"),d=await this.watch(r,n,o,n),h=this.safeDict(d,"response",{}),c=this.safeDict(h,"data",{}),l=this.safeList(c,"statuses",[]),u=[];for(let e=0;e<l.length;e++){let t=l[e];u.push(this.safeOrder({info:t,status:t}))}return u}async cancelOrderWs(e,t,i={}){let s=await this.cancelOrdersWs([e],t,i);return this.safeDict(s,0)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="orderbook:"+s.symbol,a=this.urls.api.ws.public,o={method:"subscribe",subscription:{type:"l2Book",coin:!0===s.swap?s.baseName:s.id}},n=this.extend(o,i);return await this.waitForPendingUnsubscribe(a,r),(await this.watch(a,r,n,r)).limit()}async unWatchOrderBook(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="unsubscribe:orderbook:"+i.symbol,r=this.urls.api.ws.public,a={id:this.incrementingNonce().toString(),method:"unsubscribe",subscription:{type:"l2Book",coin:!0===i.swap?i.baseName:i.id}},o=this.extend(a,t);return await this.watch(r,s,o,s)}handleOrderBook(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"coin"),r=this.coinToMarketId(s),a=this.market(r).symbol,o=this.safeList(i,"levels",[]),n={bids:this.safeList(o,0,[]),asks:this.safeList(o,1,[])},d=this.safeInteger(i,"time"),h=this.parseOrderBook(n,a,d,"bids","asks","px","sz");if(!(a in this.orderbooks)){let e=this.orderBook(h);this.orderbooks[a]=e}let c=this.orderbooks[a];c.reset(h);let l="orderbook:"+a;e.resolve(c,l)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="ticker:"+i.symbol,r=this.urls.api.ws.public,a={method:"subscribe",subscription:{type:"activeAssetCtx",coin:!0===i.swap?i.baseName:i.id}};return await this.waitForPendingUnsubscribe(r,s),await this.watch(r,s,this.extend(a,t),s)}async unWatchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="unsubscribe:ticker:"+i.symbol,r=this.urls.api.ws.public,a={method:"unsubscribe",subscription:{type:"activeAssetCtx",coin:!0===i.swap?i.baseName:i.id}};return await this.watch(r,s,this.extend(a,t),s)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0),s="tickers",r=this.urls.api.ws.public,a={method:"subscribe",subscription:{type:"allMids"}},o=this.safeString(t,"dex"),n=this.safeString(i,0);if(void 0!==n){let e=this.market(n),t=this.safeString(this.safeDict(e,"info",{}),"dex");void 0!==t&&(o=t)}let d=void 0!==o?this.omit(t,"dex"):t;void 0!==o&&(s="tickers:"+o,a.subscription.type="allMids",a.subscription.dex=o),await this.waitForPendingUnsubscribe(r,"tickers");let h=await this.watch(r,s,this.extend(a,d),s);return this.newUpdates?this.filterByArrayTickers(h,"symbol",i):this.tickers}async unWatchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets(),this.marketSymbols(e,void 0,!0);let i="unsubscribe:tickers",s=this.urls.api.ws.public;return await this.watch(s,i,this.extend({method:"unsubscribe",subscription:{type:"allMids"}},t),i)}async watchMyTrades(e,t,i,s={}){let a,o=this.handlePublicAddress("watchMyTrades",s);a=this.safeString(o,0);let n=this.safeDict(o,1,s);void 0===this.markets&&await this.loadMarkets();let d="myTrades",h=void 0!==e?this.symbol(e):e;void 0!==h&&(d+=":"+h);let c=this.urls.api.ws.public,l=this.extend({method:"subscribe",subscription:{type:"userFills",user:a}},n);if(void 0===a)throw new r.ArgumentsRequired(this.id+" watchMyTrades() requires a user address");let u="subscribe:userFills::"+a.toLowerCase();await this.waitForPendingUnsubscribe(c,"myTrades");let f=await this.watch(c,d,l,u),p=i;return this.newUpdates&&(p=f.getLimit(h,i)),this.filterBySymbolSinceLimit(f,h,t,p,!0)}async unWatchMyTrades(e,t={}){let i;if(void 0===this.markets&&await this.loadMarkets(),void 0!==e)throw new r.NotSupported(this.id+" unWatchMyTrades does not support a symbol argument, unWatch from all markets only");let s=this.handlePublicAddress("unWatchMyTrades",t);i=this.safeString(s,0);let a=this.safeDict(s,1,t),o="unsubscribe:myTrades",n=this.urls.api.ws.public,d=this.extend({method:"unsubscribe",subscription:{type:"userFills",user:i}},a);return await this.watch(n,o,d,o)}handleWsTickers(e,t){let i=this.safeDict(t,"data",{}),s=this.safeDict(i,"mids",{});if(void 0!==s){let t=Object.keys(s);for(let e=0;e<t.length;e++){let i=t[e],r=this.coinToMarketId(i),a=this.safeMarket(r,void 0,void 0,"swap"),o=a.symbol,n=this.parseWsTicker({price:this.safeNumber(s,i)},a);this.tickers[o]=n}let r="tickers",a=this.safeString(i,"dex");void 0!==a&&(r+=":"+a),e.resolve(this.tickers,r)}return!0}handleActiveAssetCtx(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"coin"),r=this.coinToMarketId(s),a=this.safeMarket(r),o=a.symbol,n=this.safeDict(i,"ctx",{}),d=this.parseWsTicker(n,a);return this.tickers[o]=d,e.resolve(d,"ticker:"+o),!0}parseWsTicker(e,t){return this.parseTicker(e,t)}handleMyTrades(e,t){let i=this.safeDict(t,"data",{});if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new a.Pt(e)}let s=this.myTrades,r={},o=this.safeList(i,"fills",[]);if(0===o.length)return;for(let e=0;e<o.length;e++){let t=o[e],i=this.parseWsTrade(t);r[i.symbol]=!0,s.append(i)}let n=Object.keys(r);for(let t=0;t<n.length;t++){let i="myTrades:"+n[t];e.resolve(s,i)}e.resolve(s,"myTrades")}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o="trade:"+a,n=this.urls.api.ws.public,d={method:"subscribe",subscription:{type:"trades",coin:!0===r.swap?r.baseName:r.id}},h=this.extend(d,s);await this.waitForPendingUnsubscribe(n,o);let c=await this.watch(n,o,h,o),l=i;return this.newUpdates&&(l=c.getLimit(a,i)),this.filterBySinceLimit(c,t,l,"timestamp",!0)}async unWatchTrades(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="unsubscribe:trade:"+i.symbol,r=this.urls.api.ws.public,a={method:"unsubscribe",subscription:{type:"trades",coin:!0===i.swap?i.baseName:i.id}},o=this.extend(a,t);return await this.watch(r,s,o,s)}handleTrades(e,t){let i=this.safeList(t,"data",[]);if(0===i.length)return;let s=this.safeDict(i,0,{}),r=this.safeString(s,"coin"),o=this.coinToMarketId(r),n=this.market(o).symbol;if(!(n in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3),t=new a.I3(e);this.trades[n]=t}let d=this.trades[n];for(let e=0;e<i.length;e++){let t=this.safeDict(i,e,{}),s=this.parseWsTrade(t);d.append(s)}e.resolve(d,"trade:"+n)}parseWsTrade(e,t){let i=this.safeInteger(e,"time"),s=this.safeString(e,"px"),r=this.safeString(e,"sz"),a=this.safeString(e,"coin"),o=this.coinToMarketId(a),n=this.safeMarket(o),d=n.symbol,h=this.safeString(e,"tid"),c=this.safeString(e,"side");void 0!==c&&(c="A"===c?"sell":"buy");let l=this.safeString(e,"fee");return this.safeTrade({info:e,timestamp:i,datetime:this.iso8601(i),symbol:d,id:h,order:this.safeString(e,"oid"),type:void 0,side:c,takerOrMaker:void 0,price:s,amount:r,cost:void 0,fee:{cost:l,currency:"USDC"}},n)}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n=this.urls.api.ws.public,d={method:"subscribe",subscription:{type:"candle",coin:!0===a.swap?a.baseName:a.id,interval:t}},h="candles:"+t+":"+o,c=this.extend(d,r);await this.waitForPendingUnsubscribe(n,h);let l=await this.watch(n,h,c,h),u=s;return this.newUpdates&&(u=l.getLimit(o,s)),this.filterBySinceLimit(l,i,u,0,!0)}async unWatchOHLCV(e,t="1m",i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=s.symbol,a=this.urls.api.ws.public,o={method:"unsubscribe",subscription:{type:"candle",coin:!0===s.swap?s.baseName:s.id,interval:t}},n="unsubscribe:"+("candles:"+t+":")+r,d=this.extend(o,i);return await this.watch(a,n,d,n)}handleOHLCV(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"s"),r=this.coinToMarketId(s),o=this.safeSymbol(r),n=this.safeString(i,"i");if(o in this.ohlcvs||(this.ohlcvs[o]={}),!(n in this.ohlcvs[o])){let e=this.safeInteger(this.options,"OHLCVLimit",1e3),t=new a.TG(e);this.ohlcvs[o][n]=t}let d=this.ohlcvs[o][n],h=this.parseOHLCV(i);d.append(h),e.resolve(d,"candles:"+n+":"+o)}handleWsPost(e,t){let i=this.safeDict(t,"data"),s=this.safeString(i,"id"),r=this.safeDict(i,"response"),a=this.safeDict(r,"payload");e.resolve(a,s)}async watchBalance(e={}){let t,i;void 0===this.markets&&await this.loadMarkets();let s=this.handlePublicAddress("watchBalance",e);t=this.safeString(s,0);let r=this.safeDict(s,1,e),[a,o]=this.handleMarketTypeAndParams("watchBalance",void 0,r),n=await this.isUnifiedEnabled("watchBalance",t,!1,o);i=this.safeBool(n,0);let d=this.safeDict(n,1,o),h=this.safeString(d,"dex"),c=("spot"===a||!0===i)&&void 0===h,l="clearinghouseState";!0===c&&(l="spotState");let u=l+"::balance",f=this.urls.api.ws.public,p={type:l,user:t};!0===c?!0===i&&(p.isPortfolioMargin=!0):void 0!==h&&(p.dex=h);let m=this.extend({method:"subscribe",subscription:p},d);return await this.waitForPendingUnsubscribe(f,l),await this.watch(f,u,m,l)}async unWatchBalance(e={}){let t,i;void 0===this.markets&&await this.loadMarkets();let s=this.urls.api.ws.public,r=this.handlePublicAddress("unWatchBalance",e);t=this.safeString(r,0);let a=this.safeDict(r,1,e),[o,n]=this.handleMarketTypeAndParams("unWatchBalance",void 0,a),d=await this.isUnifiedEnabled("unWatchBalance",t,!1,n);i=this.safeBool(d,0);let h=this.safeDict(d,1,n),c=this.safeString(h,"dex"),l="clearinghouseState";!0==(("spot"===o||!0===i)&&void 0===c)&&(l="spotState");let u="unsubscribe:"+l,f={method:"unsubscribe",subscription:{type:l,user:t}},p=this.extend(f,h);return await this.watch(s,u,p,u)}handleBalance(e,t){let i,s,r;void 0===this.balance&&(this.balance={});let a=this.safeString(t,"channel"),o=[],n=this.safeDict(t,"data",{});if("spotState"===a){let e=this.safeDict(n,"spotState");o=this.safeList(e,"balances",[]),s="spot",i=o}if("clearinghouseState"===a){s="swap";let a=this.safeDict(n,"clearinghouseState");o.push(a),i=a,r=this.safeInteger(a,"time"),this.handlePositions(e,t)}for(let e=0;e<o.length;e++)this.parseWsBalance(o[e],s);void 0===this.safeValue(this.balance,s)&&(this.balance[s]={}),this.balance[s].info=i,this.balance[s].timestamp=r,this.balance[s].datetime=this.iso8601(r),this.balance[s]=this.safeBalance(this.balance[s]),void 0!==a&&e.resolve(this.balance[s],a+"::balance")}parseWsBalance(e,t){let i,s=this.account(),r=this.safeString(e,"coin");if(void 0===r){i="USDC";let t=this.safeDict(e,"marginSummary",{});s.free=this.safeString(e,"withdrawable"),s.used=this.safeString(t,"totalMarginUsed"),s.total=this.safeString(t,"accountValue")}else i=this.safeCurrencyCode(r),s.used=this.safeString(e,"hold"),s.total=this.safeString(e,"total");void 0!==t?(void 0===this.safeValue(this.balance,t)&&(this.balance[t]={}),void 0!==t&&void 0!==i&&(this.balance[t][i]=s)):void 0!==i&&(this.balance[i]=s)}async watchPositions(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.handlePublicAddress("watchPositions",s);r=this.safeString(a,0);let o=this.safeDict(a,1,s),n="clearinghouseState",d=n+"::positions",h=void 0!==e&&!this.isEmpty(e),c=e;h&&(c=this.marketSymbols(e)),h&&void 0!==c&&(d+="::"+c.join(","));let l=this.urls.api.ws.public,u={type:n,user:r},f=this.getDexFromSymbols("watchPositions",c);void 0!==f&&(u.dex=f);let p=this.extend({method:"subscribe",subscription:u},o);await this.waitForPendingUnsubscribe(l,n);let m=this.client(l);this.setPositionsCache(m,c);let g=this.positions,v=await this.watch(l,d,p,n);return this.newUpdates?v:this.filterBySymbolsSinceLimit(g,c,t,i,!0)}setPositionsCache(e,t){void 0===this.positions&&(this.positions=new a.Hk)}handlePositions(e,t){void 0===this.positions&&(this.positions=new a.Hk);let i=this.positions,s=this.safeDict(t,"data",{}),r=this.safeDict(s,"clearinghouseState",{}),o=[],n=this.safeList(r,"assetPositions",[]);for(let e=0;e<n.length;e++){let t=n[e],s=this.parsePosition(t);o.push(s),i.append(s)}let d="clearinghouseState::positions",h=this.findMessageHashes(e,d);for(let t=0;t<h.length;t++){let i=h[t],s=i.split("::"),r=this.safeString(s,2);if(void 0===r)continue;let a=r.split(","),n=this.filterByArray(o,"symbol",a,!1);this.isEmpty(n)||e.resolve(n,i)}e.resolve(o,d)}async unWatchPositions(e,t={}){let i;if(void 0===this.markets&&await this.loadMarkets(),void 0!==e&&!this.isEmpty(e))throw new r.NotSupported(this.id+" unWatchPositions() does not support a symbol parameter, you must unwatch all orders");let s="unsubscribe:clearinghouseState",a=this.urls.api.ws.public,o=this.handlePublicAddress("unWatchPositions",t);i=this.safeString(o,0);let n=this.safeDict(o,1,t),d=this.extend({method:"unsubscribe",subscription:{type:"clearinghouseState",user:i}},n);return await this.watch(a,s,d,s)}async watchOrders(e,t,i,s={}){let a,o;void 0===this.markets&&await this.loadMarkets();let n=this.handlePublicAddress("watchOrders",s);a=this.safeString(n,0);let d=this.safeDict(n,1,s),h="order";void 0!==e&&(h=h+":"+(o=this.market(e)).symbol);let c=void 0!==o?this.safeString(o,"symbol"):e,l=this.urls.api.ws.public,u=this.extend({method:"subscribe",subscription:{type:"orderUpdates",user:a}},d);if(void 0===a)throw new r.ArgumentsRequired(this.id+" watchOrders() requires a user address");let f="subscribe:orderUpdates::"+a.toLowerCase();await this.waitForPendingUnsubscribe(l,"order");let p=await this.watch(l,h,u,f),m=i;return this.newUpdates&&(m=p.getLimit(c,i)),this.filterBySymbolSinceLimit(p,c,t,m,!0)}async unWatchOrders(e,t={}){let i;if(void 0===this.markets&&await this.loadMarkets(),void 0!==e)throw new r.NotSupported(this.id+" unWatchOrders() does not support a symbol argument, unWatch from all markets only");let s="unsubscribe:order",a=this.urls.api.ws.public,o=this.handlePublicAddress("unWatchOrders",t);i=this.safeString(o,0);let n=this.safeDict(o,1,t),d=this.extend({method:"unsubscribe",subscription:{type:"orderUpdates",user:i}},n);return await this.watch(a,s,d,s)}handleOrder(e,t){let i=this.safeList(t,"data",[]);if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}if(0===i.length)return;let s=this.orders,r="order",o={};for(let e=0;e<i.length;e++){let t=i[e],r=this.parseOrder(t);s.append(r),o[this.safeString(r,"symbol")]=!0}let n=Object.keys(o);for(let t=0;t<n.length;t++){let i=r+":"+n[t];e.resolve(s,i)}e.resolve(s,r)}handleErrorMessage(e,t){if("error"===this.safeString(t,"channel","")){let i=this.safeString(t,"data","");if(i.indexOf("Already subscribed")>=0)return!0;let s=new r.ExchangeError(this.id+" "+i);return e.reject(s),!0}let i=this.safeDict(t,"data",{}),s=this.safeString(t,"id");void 0===s&&(s=this.safeString(i,"id"));let a=this.safeDict(i,"response",{}),o=this.safeDict(a,"payload",{}),n=this.safeString(o,"status");if(void 0!==n&&"ok"!==n||"error"===this.safeString(o,"type")){let t=new r.ExchangeError(this.id+" "+this.json(o));return e.reject(t,s),!0}try{this.handleErrors(0,"","","",{},this.json(o),o,{},{})}catch(t){return e.reject(t,s),!0}return!1}async waitForPendingUnsubscribe(e,t){if(e in this.clients){let i=this.client(e),s="unsubscribe:"+t;if(s in i.subscriptions){let e=this.safeInteger(this.options,"unsubscribeTimeout",1e4);this.delay(e,this.expirePendingUnsubscribe,i,t,s);try{await i.future(s)}catch(e){if(!(e instanceof r.RequestTimeout))throw e}}}}async expirePendingUnsubscribe(e,t,i){if(i in e.subscriptions){let s=new r.RequestTimeout(this.id+" unsubscribe "+t+" was not acknowledged");e.reject(s,i),this.cleanUnsubscription(e,t,i)}}handleOrderBookUnsubscription(e,t){let i=this.safeString(t,"coin"),s=this.coinToMarketId(i),r=this.safeSymbol(s),a="orderbook:"+r;this.cleanUnsubscription(e,a,"unsubscribe:"+a),r in this.orderbooks&&delete this.orderbooks[r]}handleTradesUnsubscription(e,t){let i=this.safeString(t,"coin"),s=this.coinToMarketId(i),r=this.safeSymbol(s),a="trade:"+r;this.cleanUnsubscription(e,a,"unsubscribe:"+a),r in this.trades&&delete this.trades[r]}handleTickersUnsubscription(e,t){let i="tickers";this.cleanUnsubscription(e,i,"unsubscribe:"+i);let s=Object.keys(this.tickers);for(let e=0;e<s.length;e++)delete this.tickers[s[e]]}handleTickerUnsubscription(e,t){let i=this.safeString(t,"coin"),s=this.coinToMarketId(i),r=this.safeSymbol(s),a="ticker:"+r;this.cleanUnsubscription(e,a,"unsubscribe:"+a),r in this.tickers&&delete this.tickers[r]}handleOHLCVUnsubscription(e,t){let i=this.safeString(t,"coin"),s=this.coinToMarketId(i),r=this.safeSymbol(s),a=this.safeString(t,"interval"),o=this.findTimeframe(a),n="candles:"+o+":"+r;this.cleanUnsubscription(e,n,"unsubscribe:"+n),r in this.ohlcvs&&o in this.ohlcvs[r]&&delete this.ohlcvs[r][o]}handleOrderUnsubscription(e,t){let i="order";this.cleanUnsubscription(e,i,"unsubscribe:"+i,!0);let s=this.safeStringLower(t,"user");if(void 0!==s){let t="subscribe:orderUpdates::"+s;t in e.subscriptions&&delete e.subscriptions[t]}this.cleanCache({topic:"orders"})}handleMyTradesUnsubscription(e,t){let i="myTrades";this.cleanUnsubscription(e,i,"unsubscribe:"+i,!0);let s=this.safeStringLower(t,"user");if(void 0!==s){let t="subscribe:userFills::"+s;t in e.subscriptions&&delete e.subscriptions[t]}this.cleanCache({topic:"myTrades"})}handlePositionsUnsubscription(e,t){let i="clearinghouseState";this.cleanUnsubscription(e,i,"unsubscribe:"+i,!0),this.cleanCache({topic:"positions"}),"swap"in this.balance&&delete this.balance.swap}handleSpotBalanceUnsubscription(e,t){let i="spotState";this.cleanUnsubscription(e,i,"unsubscribe:"+i,!0),"spot"in this.balance&&delete this.balance.spot}handleSubscriptionResponse(e,t){let i=this.safeDict(t,"data",{});if("unsubscribe"===this.safeString(i,"method")){let t=this.safeDict(i,"subscription",{}),s=this.safeString(t,"type");"l2Book"===s?this.handleOrderBookUnsubscription(e,t):"trades"===s?this.handleTradesUnsubscription(e,t):"candle"===s?this.handleOHLCVUnsubscription(e,t):"orderUpdates"===s?this.handleOrderUnsubscription(e,t):"userFills"===s?this.handleMyTradesUnsubscription(e,t):"clearinghouseState"===s?this.handlePositionsUnsubscription(e,t):"spotState"===s?this.handleSpotBalanceUnsubscription(e,t):"activeAssetCtx"===s||"activeSpotAssetCtx"===s?this.handleTickerUnsubscription(e,t):"allMids"===s&&this.handleTickersUnsubscription(e,t)}}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;let i=this.safeString(t,"channel",""),s={pong:this.handlePong,trades:this.handleTrades,l2Book:this.handleOrderBook,candle:this.handleOHLCV,orderUpdates:this.handleOrder,userFills:this.handleMyTrades,allMids:this.handleWsTickers,activeAssetCtx:this.handleActiveAssetCtx,activeSpotAssetCtx:this.handleActiveAssetCtx,post:this.handleWsPost,subscriptionResponse:this.handleSubscriptionResponse,clearinghouseState:this.handleBalance,spotState:this.handleBalance},r=this.safeValue(s,i);if(void 0!==r)return void r.call(this,e,t);let a=Object.keys(s);for(let r=0;r<a.length;r++){let o=a[r];if(i.indexOf(a[r])>=0)return void s[o].call(this,e,t)}}ping(e){return{method:"ping"}}handlePong(e,t){return e.lastPong=this.safeInteger(t,"pong",this.milliseconds()),t}requestId(){let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,e}wrapAsPostAction(e){let t=this.requestId();return{requestId:t,request:{method:"post",id:t,request:{type:"action",payload:e}}}}}i.d(t,{A:()=>o})},6164(e,t,i){"use strict";var s=i(7392),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!1,watchTicker:!1,watchTickers:!1,watchTrades:!0,watchTradesForSymbols:!1,watchMyTrades:!1,watchOrders:!1,watchOrderBook:!0,watchOHLCV:!1},urls:{api:{ws:"wss://websockets.independentreserve.com"}},options:{watchOrderBook:{checksum:!0}},streaming:{},exceptions:{}})}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n=this.safeString(this.urls.api,"ws");if(void 0===n)throw new r.ExchangeError(this.id+" watchTrades() has no websocket url");let d=n+"?subscribe=ticker-"+a.base+"-"+a.quote,h="trades:"+o,c=await this.watch(d,h,void 0,h);return this.filterBySinceLimit(c,t,i,"timestamp",!0)}handleTrades(e,t){let i=this.safeDict(t,"Data",{}),s=this.safeString(i,"Pair"),r=this.safeSymbol(s,void 0,"-"),o=this.safeValue(this.trades,r);if(void 0===o){let e=this.safeInteger(this.options,"tradesLimit",1e3);o=new a.I3(e),this.trades[r]=o}let n=this.parseWsTrade(i);o.append(n),this.trades[r]=o,e.resolve(this.trades[r],"trades:"+r)}parseWsTrade(e,t){let i=this.safeString(e,"TradeDate"),s=this.safeString(t,"Pair");return this.safeTrade({info:e,id:this.safeString(e,"TradeGuid"),order:this.safeString(e,"orderNo"),symbol:this.safeSymbol(s,t,"-"),side:this.safeStringLower(e,"Side"),type:void 0,takerOrMaker:void 0,price:this.safeString(e,"Price"),amount:this.safeString(e,"Volume"),cost:void 0,fee:void 0,timestamp:this.parse8601(i),datetime:i},t)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),a=s.symbol,o=this.numberToString(void 0===t?100:t),n=this.safeString(this.urls.api,"ws");if(void 0===n)throw new r.ExchangeError(this.id+" watchOrderBook() has no websocket url");let d=n+"/orderbook/"+o+"?subscribe="+s.base+"-"+s.quote,h="orderbook:"+a+":"+o;return(await this.watch(d,h,void 0,h,{receivedSnapshot:!1})).limit()}handleOrderBook(e,t){let i=this.safeString(t,"Event"),s=this.safeString(t,"Channel");if(void 0===s)return;let a=s.split("/"),o=this.safeString(a,1),n=this.safeString(a,2),d=this.safeString(a,3),h=this.safeCurrencyCode(n),c=this.safeCurrencyCode(d);if(void 0===h||void 0===c)return;let l=h+"/"+c,u=this.safeDict(t,"Data",{}),f="orderbook:"+l+":"+o,p=this.safeDict(e.subscriptions,f,{}),m=this.safeBool(p,"receivedSnapshot",!1),g=this.safeInteger(t,"Time");l in this.orderbooks||(this.orderbooks[l]=this.orderBook({}));let v=this.orderbooks[l];if("OrderBookSnapshot"===i){let t=this.parseOrderBook(u,l,g,"Bids","Offers","Price","Volume");v.reset(t),e.subscriptions[f]=this.extend(p,{receivedSnapshot:!0})}else{let e=this.safeList(u,"Offers",[]),t=this.safeList(u,"Bids",[]);this.handleDeltas(v.asks,e),this.handleDeltas(v.bids,t),v.timestamp=g,v.datetime=this.iso8601(g)}if(!0===this.handleOption("watchOrderBook","checksum",!0)&&!0===m){let t=v.asks,i=v.bids,s=t.length,a=i.length,o="";for(let e=0;e<10;e++)e<a&&(o=o+this.valueToChecksum(i[e][0])+this.valueToChecksum(i[e][1]));for(let e=0;e<10;e++)e<s&&(o=o+this.valueToChecksum(t[e][0])+this.valueToChecksum(t[e][1]));if(this.crc32(o,!1)!==this.safeInteger(u,"Crc32")){let t=new r.ChecksumError(this.id+" "+this.orderbookChecksumMessage(l));delete e.subscriptions[f],delete this.orderbooks[l],e.reject(t,f);return}}!0===m&&e.resolve(v,f)}valueToChecksum(e){let t=this.decimalToPrecision(e,1,8,2,6);return t=t.replace(".",""),t=this.parseNumber(t),t=this.numberToString(t)}handleDelta(e,t){let i=this.parseOrderBookBidAsk(t,"Price","Volume");e.storeArray(i)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}handleHeartbeat(e,t){return t}handleSubscriptions(e,t){return t}handleMessage(e,t){let i=this.safeString(t,"Event"),s={Subscriptions:this.handleSubscriptions,Heartbeat:this.handleHeartbeat,Trade:this.handleTrades,OrderBookSnapshot:this.handleOrderBook,OrderBookChange:this.handleOrderBook},a=void 0===i?void 0:this.safeValue(s,i);if(void 0!==a)return void a.call(this,e,t);throw new r.NotSupported(this.id+" received an unsupported message: "+this.json(t))}}i.d(t,{A:()=>o})},4400(e,t,i){"use strict";var s=i(4436),r=i(1453),a=i(1697),o=i(7749);class n extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchMyTrades:!0,watchOHLCV:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOrders:!0,watchTicker:!0,watchTickers:!0,watchBidsAsks:!0,watchTrades:!0,watchTradesForSymbols:!0,createOrderWs:!0,editOrderWs:!0,cancelOrderWs:!0,cancelOrdersWs:!0,cancelAllOrdersWs:!0},urls:{api:{ws:{public:"wss://ws.kraken.com",private:"wss://ws-auth.kraken.com",privateV2:"wss://ws-auth.kraken.com/v2",publicV2:"wss://ws.kraken.com/v2",beta:"wss://beta-ws.kraken.com","beta-private":"wss://beta-ws-auth.kraken.com"}}},options:{tradesLimit:1e3,OHLCVLimit:1e3,ordersLimit:1e3,symbolsByOrderId:{},watchOrderBook:{checksum:!1}},streaming:{ping:this.ping,keepAlive:6e3},exceptions:{ws:{exact:{"Event(s) not found":r.BadRequest},broad:{"Already subscribed":r.BadRequest,"Currency pair not in ISO 4217-A3 format":r.BadSymbol,"Currency pair not supported":r.BadSymbol,"Malformed request":r.BadRequest,"Pair field must be an array":r.BadRequest,"Pair field unsupported for this subscription type":r.BadRequest,"Pair(s) not found":r.BadSymbol,"Subscription book depth must be an integer":r.BadRequest,"Subscription depth not supported":r.BadRequest,"Subscription field must be an object":r.BadRequest,"Subscription name invalid":r.BadRequest,"Subscription object unsupported field":r.BadRequest,"Subscription ohlc interval must be an integer":r.BadRequest,"Subscription ohlc interval not supported":r.BadRequest,"Subscription ohlc requires interval":r.BadRequest,"EAccount:Invalid permissions":r.PermissionDenied,"EAuth:Account temporary disabled":r.AccountSuspended,"EAuth:Account unconfirmed":r.AuthenticationError,"EAuth:Rate limit exceeded":r.RateLimitExceeded,"EAuth:Too many requests":r.RateLimitExceeded,"EDatabase: Internal error (to be deprecated)":r.ExchangeError,"EGeneral:Internal error[:<code>]":r.ExchangeError,"EGeneral:Invalid arguments":r.BadRequest,"EOrder:Cannot open opposing position":r.InvalidOrder,"EOrder:Cannot open position":r.InvalidOrder,"EOrder:Insufficient funds (insufficient user funds)":r.InsufficientFunds,"EOrder:Insufficient margin (exchange does not have sufficient funds to allow margin trading)":r.InsufficientFunds,"EOrder:Invalid price":r.InvalidOrder,"EOrder:Margin allowance exceeded":r.InvalidOrder,"EOrder:Margin level too low":r.InvalidOrder,"EOrder:Margin position size exceeded (client would exceed the maximum position size for this pair)":r.InvalidOrder,"EOrder:Order minimum not met (volume too low)":r.InvalidOrder,"EOrder:Orders limit exceeded":r.InvalidOrder,"EOrder:Positions limit exceeded":r.InvalidOrder,"EOrder:Rate limit exceeded":r.RateLimitExceeded,"EOrder:Scheduled orders limit exceeded":r.InvalidOrder,"EOrder:Unknown position":r.OrderNotFound,"EOrder:Unknown order":r.OrderNotFound,"EOrder:Invalid order":r.InvalidOrder,"EService:Deadline elapsed":r.ExchangeNotAvailable,"EService:Market in cancel_only mode":r.NotSupported,"EService:Market in limit_only mode":r.NotSupported,"EService:Market in post_only mode":r.NotSupported,"EService:Unavailable":r.ExchangeNotAvailable,"ETrade:Invalid request":r.BadRequest,"ESession:Invalid session":r.AuthenticationError}}}})}orderRequestWs(e,t,i,s,a,o,n={}){let d,h,c,l,u=i.endsWith("limit");if(u){if(void 0===o)throw new r.ArgumentsRequired(this.id+" limit orders require a price argument");s.params.limit_price=this.parseToNumeric(this.priceToPrecision(t,o))}let f="market"===i,[p,m]=this.handlePostOnly(f,!1,n);!0===p&&(s.params.post_only=!0);let g=this.safeString(m,"clientOrderId");void 0!==g&&(s.params.cl_ord_id=g);let v=this.safeString(m,"cost");void 0!==v&&(s.params.order_qty=this.parseToNumeric(this.costToPrecision(t,v)));let y=this.safeDict(m,"stopLoss",{}),b=this.safeDict(m,"takeProfit",{}),w=this.safeString(y,"triggerPrice"),k=this.safeString(b,"triggerPrice"),S=this.safeString(y,"price"),O=this.safeString(b,"price"),T=void 0!==w,P=void 0!==k,I=this.safeString(m,"stopLossPrice"),A=this.safeString(m,"takeProfitPrice"),x=void 0!==I,M=void 0!==A,_=this.safeString(m,"trailingAmount"),C=this.safeString(m,"trailingPercent"),B=this.safeString(m,"trailingLimitAmount"),E=this.safeString(m,"trailingLimitPercent"),R=void 0!==_,L=void 0!==C,N=void 0!==B,D=void 0!==E,q=this.safeString(m,"offset","");void 0!==_&&(d=q+this.numberToString(_)),void 0!==C&&(h=q+this.numberToString(C)),void 0!==B&&(c=q+this.numberToString(B)),void 0!==E&&(l=q+this.numberToString(E));let F="quote";if((L||D)&&(F="pct"),"createOrderWs"===e){!0===this.safeBool(m,"reduceOnly")&&(s.params.reduce_only=!0);let e=this.safeStringLower(m,"timeInForce");void 0!==e&&(s.params.time_in_force=e),(x||M||R||L||N||D)&&(s.params.triggers={}),T||P?(s.params.conditional={},T?(s.params.conditional.order_type="stop-loss",s.params.conditional.trigger_price=this.parseToNumeric(this.priceToPrecision(t,w))):P&&(s.params.conditional.order_type="take-profit",s.params.conditional.trigger_price=this.parseToNumeric(this.priceToPrecision(t,k))),void 0!==S?(s.params.conditional.order_type="stop-loss-limit",s.params.conditional.limit_price=this.parseToNumeric(this.priceToPrecision(t,S))):void 0!==O&&(s.params.conditional.order_type="take-profit-limit",s.params.conditional.limit_price=this.parseToNumeric(this.priceToPrecision(t,O)))):x||M?x?(s.params.triggers.price=this.parseToNumeric(this.priceToPrecision(t,I)),u?s.params.order_type="stop-loss-limit":s.params.order_type="stop-loss"):(s.params.triggers.price=this.parseToNumeric(this.priceToPrecision(t,A)),u?s.params.order_type="take-profit-limit":s.params.order_type="take-profit"):(R||L||N||D)&&(s.params.triggers.price_type=F,!u&&(R||L)?(s.params.order_type="trailing-stop",R?s.params.triggers.price=this.parseToNumeric(d):s.params.triggers.price=this.parseToNumeric(h)):(s.params.limit_price_type=F,s.params.order_type="trailing-stop-limit",N?s.params.triggers.price=this.parseToNumeric(c):s.params.triggers.price=this.parseToNumeric(l)))}else if("editOrderWs"===e){if(T||P)throw new r.NotSupported(this.id+" editing the stopLoss and takeProfit on existing orders is currently not supported");x||M?x?s.params.trigger_price=this.parseToNumeric(this.priceToPrecision(t,I)):s.params.trigger_price=this.parseToNumeric(this.priceToPrecision(t,A)):(R||L||N||D)&&(s.params.trigger_price_type=F,!u&&(R||L)?R?s.params.trigger_price=this.parseToNumeric(d):s.params.trigger_price=this.parseToNumeric(h):(s.params.limit_price_type=F,N?s.params.trigger_price=this.parseToNumeric(c):s.params.trigger_price=this.parseToNumeric(l)))}let V="createOrderWs"===e,G=m;V&&(G=this.omit(m,["reduceOnly","timeInForce"]));let H=G;return V&&(T||P)&&(H=this.omit(G,["stopLoss","takeProfit"])),[s,this.omit(H,["clientOrderId","cost","offset","stopLossPrice","takeProfitPrice","trailingAmount","trailingPercent","trailingLimitAmount","trailingLimitPercent"])]}async createOrderWs(e,t,i,s,r,a={}){await this.loadMarkets();let o=await this.authenticate(),n=this.market(e),d=this.urls.api.ws.privateV2,h=this.requestId(),c=this.numberToString(h),l={method:"add_order",params:{order_type:t,side:i,order_qty:this.parseToNumeric(this.amountToPrecision(e,s)),symbol:n.symbol,token:o},req_id:h},[u,f]=this.orderRequestWs("createOrderWs",e,t,l,s,r,a);return await this.watch(d,c,this.extend(u,f),c)}handleCreateEditOrder(e,t){let i=this.safeDict(t,"result",{}),s=this.parseOrder(i),r=this.safeString2(t,"reqid","req_id");e.resolve(s,r)}async editOrderWs(e,t,i,s,r,a,o={}){await this.loadMarkets();let n=await this.authenticate(),d=this.urls.api.ws.privateV2,h=this.requestId(),c=this.numberToString(h),l={method:"amend_order",params:{order_id:e,order_qty:this.parseToNumeric(this.amountToPrecision(t,r)),token:n},req_id:h},[u,f]=this.orderRequestWs("editOrderWs",t,i,l,r,a,o);return await this.watch(d,c,this.extend(u,f),c)}async cancelOrdersWs(e,t,i={}){if(void 0!==t)throw new r.NotSupported(this.id+" cancelOrdersWs () does not support cancelling orders for a specific symbol.");await this.loadMarkets();let s=await this.authenticate(),a=this.urls.api.ws.privateV2,o=this.requestId(),n=this.numberToString(o);return await this.watch(a,n,this.extend({method:"cancel_order",params:{order_id:e,token:s},req_id:o},i),n)}async cancelOrderWs(e,t,i={}){if(void 0!==t)throw new r.NotSupported(this.id+" cancelOrderWs () does not support cancelling orders for a specific symbol.");await this.loadMarkets();let s=await this.authenticate(),a=this.urls.api.ws.privateV2,o=this.requestId(),n=this.numberToString(o);return await this.watch(a,n,this.extend({method:"cancel_order",params:{order_id:[e],token:s},req_id:o},i),n)}handleCancelOrder(e,t){let i=this.safeString(t,"req_id");e.resolve(t,i)}async cancelAllOrdersWs(e,t={}){if(void 0!==e)throw new r.NotSupported(this.id+" cancelAllOrdersWs () does not support cancelling orders in a specific market.");await this.loadMarkets();let i=await this.authenticate(),s=this.urls.api.ws.privateV2,a=this.requestId(),o=this.numberToString(a);return await this.watch(s,o,this.extend({method:"cancel_all",params:{token:i},req_id:a},t),o)}handleCancelAllOrders(e,t){let i=this.safeString(t,"req_id");e.resolve(t,i)}handleTicker(e,t){let i,s=this.safeList(t,"data",[]),r=this.safeDict(s,0),a=this.safeString(r,"symbol"),n=this.getMessageHash("ticker",void 0,a),d=this.safeString(r,"vwap"),h=this.safeString(r,"volume");void 0!==h&&void 0!==d&&(i=o.Y.stringMul(h,d));let c=this.safeString(r,"last"),l=this.safeTicker({symbol:a,timestamp:void 0,datetime:void 0,high:this.safeString(r,"high"),low:this.safeString(r,"low"),bid:this.safeString(r,"bid"),bidVolume:this.safeString(r,"bid_qty"),ask:this.safeString(r,"ask"),askVolume:this.safeString(r,"ask_qty"),vwap:d,open:void 0,close:c,last:c,previousClose:void 0,change:this.safeString(r,"change"),percentage:this.safeString(r,"change_pct"),average:void 0,baseVolume:h,quoteVolume:i,info:r});this.tickers[a]=l,e.resolve(l,n)}handleTrades(e,t){let i=this.safeList(t,"data",[]),s=this.safeDict(i,0),r=this.safeString(s,"symbol"),o=this.getMessageHash("trade",void 0,r),n=this.safeValue(this.trades,r);if(void 0===n){let e=this.safeInteger(this.options,"tradesLimit",1e3);n=new a.I3(e),this.trades[r]=n}let d=this.market(r),h=this.parseTrades(i,d);for(let e=0;e<h.length;e++)n.append(h[e]);e.resolve(n,o)}handleOHLCV(e,t){let i=this.safeList(t,"data",[]),s=this.safeDict(i,0),r=this.safeString(s,"symbol"),o=this.safeSymbol(r);o in this.ohlcvs||(this.ohlcvs[o]={});let n=this.safeInteger(s,"interval"),d=this.findTimeframe(n),h=this.getMessageHash("ohlcv",void 0,o),c=this.safeValue(this.safeDict(this.ohlcvs,o),d);if(this.ohlcvs[o]=this.safeDict(this.ohlcvs,o,{}),void 0===c){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);c=new a.TG(e),this.ohlcvs[o][d]=c}let l=i.length;for(let e=0;e<l;e++){let t=this.safeDict(i,e),s=this.safeString(t,"interval_begin"),r=[this.parse8601(s),this.safeNumber(t,"open"),this.safeNumber(t,"high"),this.safeNumber(t,"low"),this.safeNumber(t,"close"),this.safeNumber(t,"volume")];c.append(r)}e.resolve(c,h)}requestId(){this.lockId();let e=this.sum(this.safeInteger(this.options,"reqid",0),1);return this.options.reqid=e,this.unlockId(),e}async watchTicker(e,t={}){await this.loadMarkets();let i=this.symbol(e);return(await this.watchTickers([i],t))[i]}async watchTickers(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=await this.watchMultiHelper("ticker","ticker",i,void 0,t);if(this.newUpdates){let e={},t=this.safeString(s,"symbol");return void 0!==t&&(e[t]=s),e}return this.filterByArray(this.tickers,"symbol",i)}async watchBidsAsks(e,t={}){await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1);t.event_trigger="bbo";let s=await this.watchMultiHelper("bidask","ticker",i,void 0,t);if(this.newUpdates){let e={},t=this.safeString(s,"symbol");return void 0!==t&&(e[t]=s),e}return this.filterByArray(this.bidsasks,"symbol",i)}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){let r=await this.watchMultiHelper("trade","trade",e,void 0,s),a=i;if(this.newUpdates){let e=this.safeList(r,0),t=this.safeString(e,"symbol");a=r.getLimit(t,i)}return this.filterBySinceLimit(r,t,a,"timestamp",!0)}watchOrderBook(e,t,i={}){return this.watchOrderBookForSymbols([e],t,i)}async watchOrderBookForSymbols(e,t,i={}){let s={};if(void 0!==t)if(this.inArray(t,[10,25,100,500,1e3]))s.depth=t;else throw new r.NotSupported(this.id+" watchOrderBook accepts limit values of 10, 25, 100, 500 and 1000 only");return(await this.watchMultiHelper("orderbook","book",e,{limit:t},this.extend(s,i))).limit()}async watchOHLCV(e,t="1m",i,s,r={}){await this.loadMarkets();let a=this.market(e).symbol,o=this.urls.api.ws.publicV2,n=this.requestId(),d=this.getMessageHash("ohlcv",void 0,a),h={method:"subscribe",params:{channel:"ohlc",symbol:[a],interval:this.safeValue(this.timeframes,t,t)},req_id:n},c=this.deepExtend(h,r),l=await this.watch(o,d,c,d),u=s;return this.newUpdates&&(u=l.getLimit(a,s)),this.filterBySinceLimit(l,i,u,"timestamp",!0)}async loadMarkets(e=!1,t={}){let i=await super.loadMarkets(e,t),s=this.safeDict(this.options,"marketsByWsName");if(void 0===s||e){s={};let e=this.symbols;if(void 0!==e)for(let t=0;t<e.length;t++){let i=e[t],r=this.market(i),a=this.safeDict(r,"info",{});s[this.safeString(a,"wsname")]=r}this.options.marketsByWsName=s}return i}ping(e){let t=e.url,i={};return t.indexOf("v2")>=0?i.method="ping":i.event="ping",i}handlePong(e,t){return e.lastPong=this.milliseconds(),t}async watchHeartbeat(e={}){await this.loadMarkets();let t=this.urls.api.ws.publicV2;return await this.watch(t,"heartbeat")}handleHeartbeat(e,t){let i=this.safeString(t,"channel");e.resolve(t,i)}handleOrderBook(e,t){let i,s=this.safeString(t,"type"),a=this.safeList(t,"data",[]),o=this.safeDict(a,0,{}),n=this.safeString(o,"symbol"),d=this.safeList(o,"asks",[]),h=this.safeList(o,"bids",[]),c=this.safeInteger(o,"checksum"),l=this.getMessageHash("orderbook",void 0,n);if("update"===s){let e=(i=this.orderbooks[n]).asks,t=i.bids;void 0!==d&&this.customHandleDeltas(e,d),void 0!==h&&this.customHandleDeltas(t,h);let s=this.safeString(o,"timestamp");i.symbol=n,i.timestamp=this.parse8601(s),i.datetime=s}else{let e=d.length;this.orderbooks[n]=this.orderBook({},e),i=this.orderbooks[n];let t=["asks","bids"];for(let e=0;e<t.length;e++){let s=t[e],r=i[s],a=this.safeList(o,s,[]);a.length>0&&this.customHandleDeltas(r,a)}i.symbol=n}if(i.limit(),!0===this.handleOption("watchOrderBook","checksum",!1)){let t=[];if(void 0!==c){let e=i.asks,s=i.bids;for(let i=0;i<10;i++){let s=this.safeValue(e,i,{}),r=this.formatNumber(s[0])+this.formatNumber(s[1]);t.push(r)}for(let e=0;e<10;e++){let i=this.safeValue(s,e,{}),r=this.formatNumber(i[0])+this.formatNumber(i[1]);t.push(r)}}let s=t.join("");if(this.crc32(s,!1)!==c){let t=new r.ChecksumError(this.id+" "+this.orderbookChecksumMessage(n));delete e.subscriptions[l],delete this.orderbooks[n],e.reject(t,l);return}}e.resolve(i,l)}customHandleDeltas(e,t){for(let i=0;i<t.length;i++){let s=this.safeDict(t,i),r=this.safeNumber(s,"price"),a=this.safeNumber(s,"qty");e.store(r,a)}}formatNumber(e){let t=e.split("."),i=this.safeString(t,0)+this.safeString(t,1,""),s=0;for(;"0"===i[s];)s+=1;return s>0&&(i=i.slice(s)),i}handleSystemStatus(e,t){return t}async authenticate(e={}){let t=this.urls.api.ws.private,i=this.client(t),s="authenticated",a=this.safeValue(i.subscriptions,s),o=this.seconds(),n=this.safeInteger(a,"start"),d=this.safeInteger(a,"expires");if(void 0===a||void 0!==a&&n+d<=o){let t="authenticateFlight";if(t in i.futures)return await i.future(t),a=this.safeDict(i.subscriptions,s),this.safeString(a,"token");let n=i.reusableFuture(t);try{let n=await this.privatePostGetWebSocketsToken(e);a=this.safeDict(n,"result");let d=this.safeString(a,"token");if(void 0===d)throw new r.AuthenticationError(this.id+" authenticate() received an empty token");a.start=o,i.subscriptions[s]=a,i.resolve(d,t)}catch(e){i.reject(e,t)}await n,a=this.safeDict(i.subscriptions,s)}return this.safeString(a,"token")}async watchPrivate(e,t,i,s,r={}){await this.loadMarkets();let a=await this.authenticate(),o=e,n=void 0!==t?this.symbol(t):void 0;void 0!==n&&(o+=":"+n);let d=this.urls.api.ws.privateV2,h={method:"subscribe",params:{channel:"executions",token:a},req_id:this.requestId()};void 0!==r&&(h.params=this.deepExtend(h.params,r));let c=await this.watch(d,o,h,"executions"),l=s;return this.newUpdates&&(l=c.getLimit(n,s)),this.filterBySymbolSinceLimit(c,n,i,l,!0)}async watchMyTrades(e,t,i,s={}){return s.snap_trades=!0,await this.watchPrivate("myTrades",e,t,i,s)}handleMyTrades(e,t,i){let s=this.safeList(t,"data",[]);if(s.length>0){if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new a.I3(e)}let t=this.myTrades,i={};for(let e=0;e<s.length;e++){let r=this.safeDict(s,e,{}),a=this.parseWsTrade(r);t.append(a),i[a.symbol]=!0}let r="myTrades";e.resolve(this.myTrades,r);let o=Object.keys(i);for(let t=0;t<o.length;t++){let i=r+":"+o[t];e.resolve(this.myTrades,i)}}}parseWsTrade(e,t){let i,s=this.safeString(e,"symbol");if(void 0!==t&&(s=this.safeString(t,"symbol")),"fees"in e){let t=this.safeList(e,"fees",[]),s=this.safeDict(t,0,{});i={cost:this.safeNumber(s,"qty"),currency:this.safeString(s,"asset")}}let r=this.safeString(e,"timestamp"),a=this.safeString(e,"liquidity_ind"),o="maker";return"t"===a&&(o="taker"),{info:e,id:this.safeString(e,"exec_id"),order:this.safeString(e,"order_id"),timestamp:this.parse8601(r),datetime:r,symbol:s,type:this.safeString(e,"order_type"),side:this.safeString(e,"side"),takerOrMaker:o,price:this.safeNumber(e,"last_price"),amount:this.safeNumber(e,"last_qty"),cost:this.safeNumber(e,"cost"),fee:i}}watchOrders(e,t,i,s={}){return this.watchPrivate("orders",e,t,i,this.extend(s,{snap_orders:!0}))}handleOrders(e,t,i){let s=this.safeList(t,"data",[]);if(s.length>0){let t=this.safeInteger(this.options,"ordersLimit",1e3);void 0===this.orders&&(this.orders=new a.Pt(t));let i=this.orders,r={};for(let e=0;e<s.length;e++){let a=this.safeDict(s,e,{}),o=this.safeString(a,"order_id"),n=this.parseWsOrder(a),d=this.safeString(a,"symbol"),h=this.safeDict(i.hashmap,d),c=this.safeDict(h,o),l=n;if(void 0!==c){let e=this.extend(c.info,l.info);l=this.parseWsOrder(e)}if(i.length===t&&void 0===c){let e=i[0],t=this.safeDict(this.options,"symbolsByOrderId",{});e.id in t&&delete t[e.id]}i.append(l),void 0!==d&&(r[d]=!0)}let o="orders";e.resolve(this.orders,o);let n=Object.keys(r);for(let t=0;t<n.length;t++){let i=o+":"+n[t];e.resolve(this.orders,i)}}}parseWsOrder(e,t){let i={cost:this.safeString(e,"fee_usd_equiv"),currency:"USD"},s=this.safeString(e,"stop_price"),r=this.safeString(e,"timestamp");return this.safeOrder({id:this.safeString(e,"order_id"),clientOrderId:this.safeString(e,"order_userref"),info:e,timestamp:this.parse8601(r),datetime:r,lastTradeTimestamp:void 0,status:this.parseOrderStatus(this.safeString(e,"order_status")),symbol:this.safeString(e,"symbol"),type:this.safeString(e,"order_type"),timeInForce:this.safeString(e,"time_in_force"),postOnly:void 0,side:this.safeString(e,"side"),price:this.safeString(e,"limit_price"),stopPrice:s,triggerPrice:s,cost:this.safeString(e,"cum_cost"),amount:this.safeString2(e,"order_qty","cum_qty"),filled:void 0,average:this.safeString(e,"avg_price"),remaining:void 0,fee:i,trades:void 0})}async watchMultiHelper(e,t,i,s,r={}){await this.loadMarkets();let a=this.marketSymbols(i,void 0,!1,!0,!1);if(void 0===a)return;let o=[];for(let i=0;i<a.length;i++)void 0!==this.safeString(r,"event_trigger")?o.push(this.getMessageHash(t,void 0,this.symbol(a[i]))):o.push(this.getMessageHash(e,void 0,this.symbol(a[i])));let n={method:"subscribe",params:{channel:t,symbol:a},req_id:this.requestId()};n.params=this.deepExtend(n.params,r);let d=this.urls.api.ws.publicV2;return await this.watchMultiple(d,o,n,o,s)}async watchBalance(e={}){await this.loadMarkets();let t=await this.authenticate(),i="balances",s=this.urls.api.ws.privateV2,r=this.requestId(),a=this.deepExtend({method:"subscribe",req_id:r,params:{channel:"balances",token:t}},e);return await this.watch(s,i,a,i)}handleBalance(e,t){let i=this.safeList(t,"data",[]),s={info:t};for(let e=0;e<i.length;e++){let t=this.safeString(i[e],"asset"),r=this.safeCurrencyCode(t),a=this.account();a.total=this.safeString(i[e],"balance"),s[r]=a}let r="spot",a=this.safeBalance(s),o=this.safeDict(this.balance,r,{}),n=this.deepExtend(o,a);this.balance[r]=this.safeBalance(n);let d=this.safeString(t,"channel");e.resolve(this.balance[r],d)}getMessageHash(e,t,i){let s=e;return void 0!==i?s+="@"+i:s+="s",void 0!==t&&(s+="#"+t),s}handleSubscriptionStatus(e,t){let i=this.safeString(t,"channelID");void 0!==i&&(e.subscriptions[i]=t)}handleErrorMessage(e,t){let i=this.safeString2(t,"errorMessage","error");if(void 0!==i){let s,a=this.safeString2(t,"reqid","req_id"),o=this.exceptions.ws.broad,n=this.findBroadlyMatchedKey(o,i);return s=void 0===n?new r.ExchangeError(i):new o[n](i),void 0!==a&&e.reject(s,a),!1}return!0}handleMessage(e,t){let i=this.safeString(t,"channel");if(void 0!==i){if("executions"===i){let e=this.safeList(t,"data",[]),s=this.safeDict(e,0,{});i="trade"===this.safeString(s,"exec_type")?"myTrades":"orders"}let s={balances:this.handleBalance,book:this.handleOrderBook,ohlc:this.handleOHLCV,ticker:this.handleTicker,trade:this.handleTrades,myTrades:this.handleMyTrades,orders:this.handleOrders},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}if(!0===this.handleErrorMessage(e,t)){let i=this.safeString2(t,"event","method"),s={heartbeat:this.handleHeartbeat,systemStatus:this.handleSystemStatus,subscriptionStatus:this.handleSubscriptionStatus,add_order:this.handleCreateEditOrder,amend_order:this.handleCreateEditOrder,cancel_order:this.handleCancelOrder,cancel_all:this.handleCancelAllOrders,pong:this.handlePong},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}}}i.d(t,{A:()=>n})},3690(e,t,i){"use strict";var s=i(4721),r=i(5262),a=i(1453),o=i(1697),n=i(7749);class d extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,cancelAllOrdersWs:!1,cancelOrdersWs:!1,cancelOrderWs:!1,createOrderWs:!1,editOrderWs:!1,fetchBalanceWs:!1,fetchOpenOrdersWs:!1,fetchOrderWs:!1,fetchTradesWs:!1,watchOHLCV:!1,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchTicker:!0,watchTickers:!0,watchBidsAsks:!0,watchTrades:!0,watchTradesForSymbols:!0,watchBalance:!0,watchOrders:!0,watchMyTrades:!0,watchPositions:!0},urls:{api:{ws:"wss://futures.kraken.com/ws/v1"},test:{ws:"wss://demo-futures.kraken.com/ws/v1"}},options:{tradesLimit:1e3,ordersLimit:1e3,OHLCVLimit:1e3,connectionLimit:100,requestLimit:100,fetchBalance:{type:void 0}},streaming:{keepAlive:3e4}})}async authenticate(e={}){this.checkRequiredCredentials();let t=this.urls.api.ws,i="challenge",s=this.client(t),r=s.reusableFuture(i);if(void 0===this.safeValue(s.subscriptions,i)){let s={event:"challenge",api_key:this.apiKey},r=this.extend(s,e);this.watch(t,i,r,i)}return await r}async watchOrderBookForSymbols(e,t,i={}){return(await this.watchMultiHelper("orderbook","book",e,{limit:t},i)).limit()}async subscribePublic(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.urls.api.ws,r={event:"subscribe",feed:e},a=[],o=e,n=void 0===t?[]:t;for(let e=0;e<n.length;e++){let t=n[e];a.push(this.marketId(t))}1===n.length&&(o=o+":"+this.market(a[0]).symbol),r.product_ids=a;let d=this.extend(r,i);return await this.watch(s,o,d,o)}async subscribePrivate(e,t,i={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let s=this.urls.api.ws,r={event:"subscribe",feed:e,api_key:this.apiKey,original_challenge:this.options.challenge,signed_challenge:this.options.signedChallenge},a=this.extend(r,i);return await this.watch(s,t,a,t)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.symbol(e);return(await this.watchTickers([i],t))[i]}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=await this.watchMultiHelper("ticker","ticker",i,void 0,t);if(this.newUpdates){let e={},t=this.safeString(s,"symbol");return void 0!==t&&(e[t]=s),e}return this.filterByArray(this.tickers,"symbol",i)}async watchBidsAsks(e,t={}){let i=await this.watchMultiHelper("bidask","ticker_lite",e,void 0,t);if(this.newUpdates){let e={},t=this.safeString(i,"symbol");return void 0!==t&&(e[t]=i),e}return this.filterByArray(this.bidsasks,"symbol",e)}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){let r=await this.watchMultiHelper("trade","trade",e,void 0,s),a=this.safeList(r,0),o=this.safeString(a,"symbol"),n=i;return this.newUpdates&&(n=r.getLimit(o,i)),this.filterBySinceLimit(r,t,n,"timestamp",!0)}watchOrderBook(e,t,i={}){return this.watchOrderBookForSymbols([e],t,i)}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r="",a=this.marketSymbols(e);void 0===a||this.isEmpty(a)||(r="::"+a.join(",")),r="positions"+r;let o=await this.subscribePrivate("open_positions",r,s);return this.newUpdates?o:this.filterBySymbolsSinceLimit(this.positions,a,t,i,!0)}handlePositions(e,t){void 0===this.positions&&(this.positions=new o.Hk);let i=this.positions,s=this.safeList(t,"positions");if(void 0===s)return;let r=[];for(let e=0;e<s.length;e++){let a=s[e],o=this.parseWsPosition(a),n=this.safeInteger(t,"timestamp");o.timestamp=n,o.datetime=this.iso8601(n),r.push(o),i.append(o)}let a=this.findMessageHashes(e,"positions::");for(let t=0;t<a.length;t++){let i=a[t],s=i.split("::")[1].split(","),o=this.filterByArray(r,"symbol",s,!1);this.isEmpty(o)||e.resolve(o,i)}e.resolve(r,"positions")}parseWsPosition(e,t){let i,s=this.safeString(e,"instrument"),r=this.safeString(e,"balance");return n.Y.stringGt(r,"0")?i="long":n.Y.stringLt(r,"0")&&(i="short"),this.safePosition({info:e,id:void 0,symbol:this.safeSymbol(s),notional:void 0,marginMode:void 0,liquidationPrice:this.safeNumber(e,"liquidation_threshold"),entryPrice:this.safeNumber(e,"entry_price"),unrealizedPnl:this.safeNumber(e,"pnl"),percentage:this.safeNumber(e,"return_on_equity"),contracts:this.parseNumber(n.Y.stringAbs(r)),contractSize:void 0,markPrice:this.safeNumber(e,"mark_price"),side:i,hedged:"both",timestamp:void 0,datetime:void 0,maintenanceMargin:this.safeNumber(e,"maintenance_margin"),maintenanceMarginPercentage:void 0,collateral:void 0,initialMargin:this.safeNumber(e,"initial_margin"),initialMarginPercentage:void 0,leverage:void 0,marginRatio:void 0})}async watchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let[r,a]=this.handleOptionBoolAndParams(s,"watchOrders","verbose",!1),o="open_orders",n="orders";r&&(o="open_orders_verbose",n="orders:verbose");let d=this.safeString(a,"feed");void 0!==d&&(o=d,n="orders","open_orders_verbose"===d&&(n="orders:verbose")),void 0!==e&&(n+=":"+this.market(e).symbol);let h=await this.subscribePrivate(o,n,a),c=i;return this.newUpdates&&(c=h.getLimit(e,i)),this.filterBySinceLimit(h,t,c,"timestamp",!0)}async watchMyTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r="myTrades";void 0!==e&&(r+=":"+this.market(e).symbol);let a=await this.subscribePrivate("fills",r,s),o=i;return this.newUpdates&&(o=a.getLimit(e,i)),this.filterBySinceLimit(a,t,o,"timestamp",!0)}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t="balances",i=t,[s,r]=this.handleOptionStringAndParams(e,"watchBalance","account");if(void 0!==s){if("futures"!==s&&"flex_futures"!==s)throw new a.ArgumentsRequired(this.id+" watchBalance account must be either 'futures' or 'flex_futures'");i+=":"+s}return await this.subscribePrivate(t,i,r)}handleTrade(e,t){let i=this.safeString(t,"feed"),s=this.safeString(t,"product_id");if(void 0!==s){let r=this.market(s).symbol,a=this.getMessageHash("trade",void 0,r);if(void 0===this.safeList(this.trades,r)){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.trades[r]=new o.I3(e)}let n=this.trades[r];if("trade_snapshot"===i){let e=this.safeList(t,"trades",[]),i=e.length;for(let t=0;t<i;t++){let s=e[i-1-t],r=this.parseWsTrade(s);n.append(r)}}else{let e=this.parseWsTrade(t);n.append(e)}e.resolve(n,a)}}parseWsTrade(e,t){let i=this.safeString(e,"product_id"),s=this.safeMarket(i,t),r=this.safeInteger(e,"time");return this.safeTrade({info:e,id:this.safeString(e,"uid"),symbol:this.safeString(s,"symbol"),timestamp:r,datetime:this.iso8601(r),order:void 0,type:this.safeString(e,"type"),side:this.safeString(e,"side"),takerOrMaker:"taker",price:this.safeString2(e,"price","limit_price"),amount:this.safeString2(e,"filled","qty"),cost:void 0,fee:{rate:void 0,cost:void 0,currency:void 0}},s)}parseWsOrderTrade(e,t){let i=this.safeInteger(e,"tradeTime"),s=this.safeString(e,"symbol");return this.safeTrade({info:e,id:this.safeString(e,"tradeId"),symbol:this.safeSymbol(s,t),timestamp:i,datetime:this.iso8601(i),order:this.safeString(e,"orderId"),type:this.safeStringLower(e,"type"),side:this.safeString(e,"side"),takerOrMaker:this.safeString(e,"matchRole"),price:this.safeString2(e,"price","limit_price"),amount:this.safeString(e,"tradeAmount"),cost:void 0,fee:{rate:void 0,cost:this.safeString(e,"tradeFee"),currency:this.safeString(e,"feeCurrency")}},t)}handleOrder(e,t){let i=this.orders;if(void 0===i){let e=this.safeInteger(this.options,"ordersLimit");i=new o.Pt(e),this.orders=i}let s=this.safeDict(t,"order");if(void 0!==s){let r=this.safeString(s,"instrument"),a=this.safeString(t,"feed"),o="orders";"open_orders_verbose"===a&&(o="orders:verbose");let d=this.safeSymbol(r),h=this.safeString(s,"order_id"),c=this.safeDict(i.hashmap,d,{}),l=this.safeDict(c,h),u=this.safeString(t,"reason");if(void 0===l||"edited_by_user"===u){let t=this.parseWsOrder(s);i.append(t),e.resolve(i,o),e.resolve(i,o+":"+d)}else{let t=this.parseWsTrade(s);void 0===l.trades&&(l.trades=[]),l.trades.push(t),l.lastTradeTimestamp=t.timestamp;let r="0",a="0",h=l.trades;for(let e=0;e<h.length;e++){let t=h[e];r=n.Y.stringAdd(r,this.numberToString(t.cost)),a=n.Y.stringAdd(a,this.numberToString(t.amount))}n.Y.stringGt(a,"0")&&(l.average=n.Y.stringDiv(r,a)),l.cost=r;let c=this.numberToString(t.amount),u=this.safeString(l,"filled","0"),f=n.Y.stringAdd(u,c);l.filled=f;let p=this.safeString(l,"amount");if(l.remaining=n.Y.stringSub(p,f),void 0===l.fee&&(l.fee={rate:void 0,cost:"0",currency:this.numberToString(this.safeString(t.fee,"currency"))}),void 0!==l.fee.cost&&void 0!==this.safeNumber(t.fee,"cost")){let e=this.numberToString(l.fee.cost),i=this.numberToString(this.safeNumber(t.fee,"cost"));l.fee.cost=n.Y.stringAdd(e,i)}i.append(this.safeOrder(l)),e.resolve(i,o+":"+d),e.resolve(i,o)}}else if(!0===this.safeBool(t,"is_cancel")){let s=this.safeString(t,"reason"),r="canceled";"full_fill"===s&&(r="closed");let a=this.safeString(t,"feed"),o="orders";"open_orders_verbose"===a&&(o="orders:verbose");for(let a=0;a<i.length;a++){let n=i[a];if(n.id===t.order_id){let t=this.extend(this.safeDict(n,"info",{}),{reason:s});i[a]=this.extend(n,{status:r,info:t}),e.resolve(i,o),e.resolve(i,o+":"+n.symbol);break}}}return t}handleOrderSnapshot(e,t){let i=this.safeList(t,"orders",[]),s=this.safeInteger(this.options,"ordersLimit");this.orders=new o.Pt(s);let r=this.safeString(t,"feed"),a="orders";"open_orders_verbose_snapshot"===r&&(a="orders:verbose");let n={},d=this.orders;for(let e=0;e<i.length;e++){let t=i[e],s=this.parseWsOrder(t),r=s.symbol;void 0!==r&&(n[r]=!0),d.append(s)}if(this.orders.length>0){e.resolve(this.orders,a);let t=Object.keys(n);for(let i=0;i<t.length;i++){let s=a+":"+t[i];e.resolve(this.orders,s)}}}parseWsOrder(e,t){let i,s=this.safeBool(e,"is_cancel"),r=e;void 0!==s&&(r=this.safeValue(e,"order"),!0===s&&(i="cancelled"));let a=this.safeString(r,"instrument"),o=this.safeString(r,"time"),n=this.safeInteger(r,"direction");return this.safeOrder({info:e,symbol:this.safeSymbol(a,t),id:this.safeString(r,"order_id"),clientOrderId:void 0,timestamp:o,datetime:this.iso8601(o),lastTradeTimestamp:void 0,type:this.safeString(r,"type"),timeInForce:void 0,postOnly:void 0,side:0===n?"buy":"sell",price:this.safeString(r,"limit_price"),stopPrice:this.safeString(r,"stop_price"),triggerPrice:this.safeString(r,"stop_price"),amount:void 0,cost:void 0,average:void 0,filled:this.safeString(r,"filled"),remaining:this.safeString(r,"qty"),status:i,fee:{rate:void 0,cost:void 0,currency:void 0},trades:void 0})}handleTicker(e,t){if(void 0!==this.safeString(t,"product_id")){let i=this.parseWsTicker(t),s=i.symbol;void 0!==s&&(this.tickers[s]=i);let r=this.getMessageHash("ticker",void 0,s);e.resolve(i,r)}}handleBidAsk(e,t){if(void 0!==this.safeString(t,"product_id")){let i=this.parseWsTicker(t),s=i.symbol;void 0!==s&&(this.bidsasks[s]=i);let r=this.getMessageHash("bidask",void 0,s);e.resolve(i,r)}}parseWsTicker(e,t){let i=this.safeString(e,"product_id"),s=this.safeMarket(i,t).symbol,r=this.parse8601(this.safeString(e,"lastTime")),a=this.safeString(e,"last");return this.safeTicker({info:e,symbol:s,timestamp:r,datetime:this.iso8601(r),high:void 0,low:void 0,bid:this.safeString(e,"bid"),bidVolume:this.safeString(e,"bid_size"),ask:this.safeString(e,"ask"),askVolume:this.safeString(e,"ask_size"),vwap:void 0,open:void 0,close:a,last:a,previousClose:void 0,change:this.safeString(e,"change"),percentage:void 0,average:void 0,baseVolume:this.safeString(e,"volume"),quoteVolume:this.safeString(e,"volumeQuote"),markPrice:this.safeString(e,"markPrice"),indexPrice:this.safeString(e,"index")})}handleOrderBookSnapshot(e,t){let i=this.safeString(t,"product_id"),s=this.safeMarket(i).symbol,r=this.getMessageHash("orderbook",void 0,s),a=this.safeDict(e.subscriptions,r,{}),o=this.safeInteger(a,"limit"),n=this.safeInteger(t,"timestamp");this.orderbooks[s]=this.orderBook({},o);let d=this.orderbooks[s],h=this.safeList(t,"bids");if(void 0===h)return;let c=this.safeList(t,"asks");if(void 0!==c){for(let e=0;e<h.length;e++){let t=this.safeDict(h,e),i=this.safeNumber(t,"price"),s=this.safeNumber(t,"qty");d.bids.store(i,s)}for(let e=0;e<c.length;e++){let t=this.safeDict(c,e),i=this.safeNumber(t,"price"),s=this.safeNumber(t,"qty");d.asks.store(i,s)}d.timestamp=n,d.datetime=this.iso8601(n),d.symbol=s,e.resolve(d,r)}}handleOrderBook(e,t){let i=this.safeString(t,"product_id"),s=this.safeMarket(i).symbol,r=this.getMessageHash("orderbook",void 0,s),a=this.orderbooks[s],o=this.safeString(t,"side"),n=this.safeNumber(t,"price"),d=this.safeNumber(t,"qty"),h=this.safeInteger(t,"timestamp");"sell"===o?a.asks.store(n,d):a.bids.store(n,d),a.timestamp=h,a.datetime=this.iso8601(h),e.resolve(a,r)}handleBalance(e,t){let i=this.safeDict(t,"holding"),s=this.safeDict(t,"futures"),r=this.safeDict(t,"flex_futures"),a="balances",o=this.safeInteger(t,"timestamp");if(void 0!==i){let s=Object.keys(i),r={info:t,timestamp:o,datetime:this.iso8601(o)};for(let e=0;e<s.length;e++){let t=s[e],a=this.safeCurrencyCode(t),o=this.account();o.total=this.safeString(i,t),void 0!==a&&(r[a]=o)}this.balance.cash=r,this.balance.cash=this.safeBalance(this.balance.cash),e.resolve(r,a)}if(void 0!==s){let i=Object.keys(s),r={info:t,timestamp:o,datetime:this.iso8601(o)};for(let e=0;e<i.length;e++){let t=i[e],a=this.safeSymbol(t),o=this.account(),n=this.safeDict(s,t),d=this.safeString(n,"unit"),h=this.safeCurrencyCode(d);o.free=this.safeString(n,"available"),o.used=this.safeString(n,"initial_margin"),o.total=this.safeString(n,"balance"),r[a]={},void 0!==a&&void 0!==h&&(r[a][h]=o)}this.balance.margin=r,this.balance.margin=this.safeBalance(this.balance.margin),e.resolve(this.balance.margin,a+"futures")}if(void 0!==r){let i=this.safeDict(r,"currencies",{}),s=Object.keys(i),n={info:t,timestamp:o,datetime:this.iso8601(o)};for(let e=0;e<s.length;e++){let t=s[e],r=this.safeDict(i,t),a=this.safeCurrencyCode(t),o=this.account();o.free=this.safeString(r,"available"),o.used=this.safeString(r,"collateral_value"),o.total=this.safeString(r,"quantity"),void 0!==a&&(n[a]=o)}this.balance.flex=n,this.balance.flex=this.safeBalance(this.balance.flex),e.resolve(this.balance.flex,a+"flex_futures")}e.resolve(this.balance,a)}handleMyTrades(e,t){let i=this.safeList(t,"fills",[]),s=this.myTrades;if(void 0===s){let e=this.safeInteger(this.options,"tradesLimit",1e3);s=new o.Pt(e),this.myTrades=s}let r={};for(let e=0;e<i.length;e++){let t=i[e],a=this.parseWsMyTrade(t);void 0!==a.symbol&&(r[a.symbol]=!0),s.append(a)}let a=Object.keys(r);for(let t=0;t<a.length;t++){let i="myTrades:"+a[t];e.resolve(s,i)}e.resolve(s,"myTrades")}parseWsMyTrade(e,t){let i=this.safeInteger(e,"time"),s=this.safeString(e,"instrument"),r=this.safeMarket(s,t),a=this.safeBool(e,"buy"),o=this.safeString(e,"fee_currency");return this.safeTrade({info:e,id:this.safeString(e,"fill_id"),timestamp:i,datetime:this.iso8601(i),symbol:this.safeString(r,"symbol"),order:this.safeString(e,"order_id"),type:this.safeString(e,"type"),side:!0===a?"buy":"sell",takerOrMaker:this.safeString(e,"fill_type"),price:this.safeString(e,"price"),amount:this.safeString(e,"qty"),cost:void 0,fee:{currency:this.safeCurrencyCode(o),cost:this.safeString(e,"fee_paid"),rate:void 0}})}async watchMultiHelper(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.urls.api.ws,o=this.marketSymbols(i,void 0,!1,!0,!1),n=[],d=[];for(let t=0;t<o.length;t++){let i=this.getMessageHash(e,void 0,this.symbol(o[t]));n.push(i);let s=this.market(o[t]);this.subscriptionExistsForHash(a,i)||d.push(s.id)}let h={};return d.length>0&&(h={event:"subscribe",feed:t,product_ids:d}),await this.watchMultiple(a,n,this.extend(h,r),n,s)}subscriptionExistsForHash(e,t){return t in this.client(e).subscriptions}getMessageHash(e,t,i){let s=e;return void 0!==i?s+=":"+i:s+="s",void 0!==t&&(s+="#"+t),s}handleErrorMessage(e,t){let i=this.safeString(t,"message");if(void 0!==i&&i.indexOf("Already subscribed")>=0)return!1;try{throw new a.ExchangeError(this.id+" "+i)}catch(t){return e.reject(t),!1}}handleMessage(e,t){let i=this.safeString(t,"event");if("challenge"===i)this.handleAuthenticate(e,t);else if("alert"===i)this.handleErrorMessage(e,t);else if("pong"===i)e.lastPong=this.milliseconds();else if(void 0===i){let i=this.safeString(t,"feed"),s={ticker:this.handleTicker,ticker_lite:this.handleBidAsk,trade:this.handleTrade,trade_snapshot:this.handleTrade,book:this.handleOrderBook,book_snapshot:this.handleOrderBookSnapshot,open_orders_verbose:this.handleOrder,open_orders_verbose_snapshot:this.handleOrderSnapshot,fills:this.handleMyTrades,fills_snapshot:this.handleMyTrades,open_orders:this.handleOrder,open_orders_snapshot:this.handleOrderSnapshot,balances:this.handleBalance,balances_snapshot:this.handleBalance,open_positions:this.handlePositions},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}}handleAuthenticate(e,t){let i=this.safeString(t,"event"),r="challenge";if("error"!==i){let i=this.safeValue(t,"message"),a=this.hash(this.encode(i),s.sc,"binary"),o=this.base64ToBinary(this.secret),n=this.hmac(a,o,s.Zf,"base64");this.options.challenge=i,this.options.signedChallenge=n,this.safeValue(e.futures,r).resolve(!0)}else{let i=new a.AuthenticationError(this.id+" "+this.json(t));e.reject(i,r),r in e.subscriptions&&delete e.subscriptions[r]}return t}}i.d(t,{A:()=>d})},4427(e,t,i){"use strict";var s=i(455),r=i(1453),a=i(7749),o=i(1697);class n extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,createOrderWs:!1,editOrderWs:!1,fetchOpenOrdersWs:!1,fetchOrderWs:!1,cancelOrderWs:!1,cancelOrdersWs:!1,cancelAllOrdersWs:!1,watchBidsAsks:!0,watchFundingRate:!0,watchMarkPrice:!0,watchOrderBook:!0,watchOrders:!0,watchPosition:!0,watchPositions:!0,watchMyTrades:!0,watchTickers:!0,watchTicker:!0,watchTrades:!0,watchTradesForSymbols:!0,watchOrderBookForSymbols:!0,watchBalance:!0,watchOHLCV:!0,unWatchFundingRate:!0,unWatchMarkPrice:!0,unWatchTicker:!0,unWatchOHLCV:!0,unWatchOrderBook:!0,unWatchTrades:!0,unWatchTradesForSymbols:!0},urls:{api:{ws:{spot:"wss://x-push-spot.kucoin.com",futures:"wss://x-push-futures.kucoin.com",private:"wss://wsapi-push.kucoin.com"}}},options:{utaToken:void 0,utaTokenLastUpdate:0,utaTokenRefreshInterval:864e5,tradesLimit:1e3,watchTicker:{spotMethod:"/market/snapshot"},watchOrderBook:{snapshotDelay:5,snapshotMaxRetries:3,utaDepth:"increment",spotMethod:"/market/level2",contractMethod:"/contractMarket/level2"},watchMyTrades:{spotMethod:"/spotMarket/tradeOrders"},watchBalance:{fetchBalanceSnapshot:!0,awaitBalanceSnapshot:!0},watchPosition:{fetchPositionSnapshot:!0,awaitPositionSnapshot:!0},watchPositions:{fetchPositionsSnapshot:!0,awaitPositionsSnapshot:!0}},streaming:{ping:this.ping}})}async negotiate(e,t=!1,i={}){let s="public";!0===e&&(s="private"),t&&(s+="Futures");let r=this.safeDict(this.options,"urls",{}),a=this.safeValue(r,s);return void 0!==a||(r[s]=this.spawn(this.negotiateHelper,e,s,i),this.options.urls=r,a=r[s]),await a}async negotiateHelper(e,t,i={}){let s;try{s="private"===t?await this.privatePostBulletPrivate(i):"public"===t?await this.publicPostBulletPublic(i):"privateFutures"===t?await this.futuresPrivatePostBulletPrivate(i):await this.futuresPublicPostBulletPublic(i);let a=this.safeDict(s,"data",{}),o=this.safeList(a,"instanceServers",[]),n=this.safeDict(o,0),d=this.safeInteger(n,"pingInterval"),h=this.safeString(n,"endpoint");if(void 0===h)throw new r.ExchangeError(this.id+" negotiate() response has no websocket endpoint");let c=this.safeString(a,"token"),l=h+"?"+this.urlencode({token:c,privateChannel:e,connectId:t});return this.client(l).keepAlive=d,l}catch(e){this.safeValue(this.options.urls,t).reject(e),delete this.options.urls[t]}}requestId(){this.lockId();let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,this.unlockId(),e}async subscribe(e,t,i,s={},r){let a=this.requestId().toString(),o=this.extend({id:a,type:"subscribe",topic:i,response:!0},s),n=this.client(e);return i in n.subscriptions||(n.subscriptions[a]=i),await this.watch(e,t,o,i,r)}async subscribePublicUta(e,t,i,s={},r){let a=this.requestId().toString(),o=this.market(i),n="spot";!0===o.contract&&(n="futures");let d=n.toUpperCase(),h="subscribe";void 0!==r&&(h=!0===this.safeBool(r,"unsubscribe",!1)?"unsubscribe":h);let c={id:a,action:h,channel:t,tradeType:d,symbol:o.id},l=this.extend(c,s),u=this.safeString(this.urls.api.ws,n),f=this.client(u);return e in f.subscriptions||(f.subscriptions[a]=e),await this.watch(u,e,l,e,r)}async subscribePrivateUta(e,t,i,s,r={},a){this.checkRequiredCredentials();let o=this.requestId().toString(),n="subscribe";void 0!==a&&(n=!0===this.safeBool(a,"unsubscribe",!1)?"unsubscribe":n);let d={id:o,action:n,channel:i};void 0!==s&&(d.symbol=this.market(s).id);let h=this.extend(d,r),c=await this.getUtaUrl(),l=this.client(c);return t in l.subscriptions||(l.subscriptions[o]=t),await this.watchMultiple(c,e,h,[t],a)}async getUtaUrl(){let e=await this.authenticateUta(),t=this.safeString(this.urls.api.ws,"private");if(void 0===t)throw new r.ExchangeError(this.id+" getUtaUrl() has no private websocket url");return t+"?token="+e}async authenticateUta(){this.checkRequiredCredentials();let e=this.safeString(this.options,"utaToken"),t=this.safeInteger(this.options,"utaTokenLastUpdate",0),i=864e5;i=this.safeInteger(this.options,"utaTokenRefreshInterval",i);let s=this.milliseconds(),r=s-t>=i,a="utaToken",o=this.urls.api.ws.private,n=this.client(o);if(void 0===e||r)if(a in n.futures)await n.future(a);else{n.future(a);try{let e=await this.privatePostBulletPrivate({version:"v2"}),t=this.safeDict(e,"data",{}),i=this.safeString(t,"token");this.options.utaTokenLastUpdate=s,this.options.utaToken=i,n.resolve(i,a)}catch(e){this.options.utaToken=void 0,n.reject(e,a)}}return this.safeString(this.options,"utaToken")}unSubscribe(e,t,i,s,r={},a){return this.unSubscribeMultiple(e,[t],i,[s],r,a)}async subscribeMultiple(e,t,i,s,r={},a){let o=this.requestId().toString(),n=this.extend({id:o,type:"subscribe",topic:i,response:!0},r),d=this.client(e);for(let e=0;e<s.length;e++){let t=s[e];t in d.subscriptions||(d.subscriptions[o]=t)}return await this.watchMultiple(e,t,n,s,a)}async unSubscribeMultiple(e,t,i,s,r={},a){let o=this.requestId().toString(),n=this.extend({id:o,type:"unsubscribe",topic:i,response:!0},r);void 0!==a&&(a[o]=o);let d=this.client(e);for(let e=0;e<s.length;e++){let t=s[e];t in d.subscriptions||(d.subscriptions[o]=t)}return await this.watchMultiple(e,t,n,s,a)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r="ticker:"+s,[a,o]=this.handleOptionBoolAndParams(t,"watchTicker","uta",!1);if(a)return r="uta:"+r,await this.subscribePublicUta(r,"ticker",s,o);let n=i.contract,d=await this.negotiate(!1,n),[h,c]=this.handleOptionStringAndParams(o,"watchTicker","spotMethod","/market/snapshot"),l=!0===n?"/contractMarket/ticker":h,u=!0===n?o:c,f=l+":"+i.id;return await this.subscribe(d,r,f,u)}async unWatchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r=i.contract,[a,o]=this.handleOptionBoolAndParams(t,"unWatchTicker","uta",!1),n={symbols:[s],topic:"ticker",unsubscribe:!0},d="ticker:"+s;if(a){n.subMessageHashes=[d="uta:"+d];let e="unsubscribe:"+d;return n.messageHashes=[e],await this.subscribePublicUta(e,"ticker",s,o,n)}{let e=await this.negotiate(!1,r),[t,s]=this.handleOptionStringAndParams(o,"watchTicker","spotMethod","/market/snapshot"),a=!0===r?"/contractMarket/ticker":t,h=!0===r?o:s,c=a+":"+i.id,l="unsubscribe:"+d;return n.messageHashes=[l,c],n.subMessageHashes=[d,c],await this.unSubscribe(e,l,c,d,h,n)}}async watchTickers(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!0,!0),a=this.getMarketFromSymbols(s),[o,n]=this.handleMarketTypeAndParams("watchTickers",a,t),[d,h]=this.handleOptionBoolAndParams(n,"watchTickers","uta",!1),c="spot"!==o&&"margin"!==o;if((c||d)&&void 0===s)throw new r.ArgumentsRequired(this.id+" watchTickers() requires a list of symbols for "+o+" markets and unified trading account (uta)");let[l,u]=this.handleOptionStringAndParams2(h,"watchTickers","method","spotMethod","/market/ticker"),f=l;c&&(f="/contractMarket/ticker");let p=u;c&&(p=h);let m=[],g=[];if(void 0!==s)for(let e=0;e<s.length;e++){let t=s[e];m.push("ticker:"+t);let i=this.market(t);g.push(f+":"+i.id)}let v=await this.negotiate(!1,c);if(void 0===s){let e=f+":all";if(i=await this.subscribe(v,"tickers",e,p),this.newUpdates)return i}else{let e=f+":"+this.marketIds(s).join(",");if(i=await this.subscribeMultiple(v,m,e,g,p),this.newUpdates){let e={},t=this.safeString(i,"symbol");return void 0!==t&&(e[t]=i),e}}return this.filterByArray(this.tickers,"symbol",s)}async subscribePublicMultipleUta(e,t,i,s={},r){let a=this.requestId().toString(),o=this.getMarketFromSymbols(i),n=this.safeBool(o,"contract",!1),d="spot";n&&(d="futures");let h=d.toUpperCase(),c="subscribe";void 0!==r&&(c=!0===this.safeBool(r,"unsubscribe",!1)?"unsubscribe":c);let l={id:a,action:c,channel:t,tradeType:h,symbols:this.marketIds(i)},u=this.extend(l,s),f=this.safeString(this.urls.api.ws,d),p=this.client(f),m=t+":"+i.join(",");return m in p.subscriptions||(p.subscriptions[a]=m),await this.watchMultiple(f,e,u,e,r)}async watchUtaTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1,!0),s=[];for(let e=0;e<i.length;e++){let t=this.safeString(i,e),r="uta:ticker:"+this.market(t).symbol;s.push(r)}let r=await this.subscribePublicMultipleUta(s,"ticker",i,t);return this.newUpdates?r:this.filterByArray(this.tickers,"symbol",i)}handleTicker(e,t){let i=this.safeString(t,"topic");if(0>i.indexOf("contractMarket")){let s;if(void 0!==i){let e,r=i.split(":"),a=this.safeString(r,1);e="all"===a?this.safeString(t,"subject"):a,s=this.safeMarket(e,s,"-")}let r=this.safeDict(t,"data",{}),a=this.safeDict(r,"data",r),o=this.parseSpotOrUtaTicker(a,s),n=o.symbol;this.tickers[n]=o,e.resolve(o,"ticker:"+n);let d={};d[n]=o,e.resolve(d,"tickers")}else this.handleContractTicker(e,t)}handleContractTicker(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"symbol"),r=this.safeMarket(s,void 0,"-"),a=this.parseTicker(i,r);this.tickers[r.symbol]=a;let o="ticker:"+r.symbol;e.resolve(a,o)}handleUtaTicker(e,t){let i=this.safeDict(t,"d",{}),s=this.safeString(i,"s"),r=this.safeMarket(s),a=this.parseWsUtaTicker(i,r);this.tickers[r.symbol]=a;let o="uta:ticker:"+r.symbol;e.resolve(a,o)}parseWsUtaTicker(e,t){let i=this.safeString(t,"symbol"),s=this.safeMarket(i,t),r=this.safeInteger(e,"ts");return void 0===r&&(r=this.safeIntegerProduct(e,"M",1e-6)),this.safeTicker({symbol:i,timestamp:r,datetime:this.iso8601(r),high:void 0,low:void 0,bid:this.safeString(e,"a"),bidVolume:this.safeString(e,"A"),ask:this.safeString(e,"b"),askVolume:this.safeString(e,"B"),vwap:void 0,open:void 0,close:void 0,last:this.safeString(e,"l"),previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:void 0,quoteVolume:void 0,markPrice:this.safeString(e,"mp"),indexPrice:this.safeString(e,"ip"),info:e},s)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1,!0,!1),s=this.getMarketFromSymbols(i),r=this.safeBool(s,"contract",!1),a="/spotMarket/level1:";r&&(a="/contractMarket/tickerV2:");let o=await this.watchMultiHelper("watchBidsAsks",a,r,i,t);if(this.newUpdates){let e={},t=this.safeString(o,"symbol");return void 0!==t&&(e[t]=o),e}return this.filterByArray(this.bidsasks,"symbol",i)}async watchMultiHelper(e,t,i,s,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.marketSymbols(s,void 0,!1,!0,!1);if(o.length>100)throw new r.ArgumentsRequired(this.id+" "+e+"() accepts a maximum of 100 symbols");let n=[];for(let e=0;e<o.length;e++){let t=o[e],i=this.market(t);n.push("bidask@"+i.symbol)}let d=await this.negotiate(!1,i),h=this.marketIds(o).join(","),c=this.requestId().toString(),l=this.extend({id:c,type:"subscribe",topic:t+h,response:!0},a);return await this.watchMultiple(d,n,l,n)}handleBidAsk(e,t){let i=this.parseWsBidAsk(t),s=i.symbol;this.bidsasks[s]=i,e.resolve(i,"bidask@"+s)}parseWsBidAsk(e,t){let i=this.safeString(e,"topic");if(0>i.indexOf("contractMarket")){let s=i.split(":")[1],r=this.safeMarket(s,t),a=this.safeString(r,"symbol"),o=this.safeDict(e,"data",{}),n=this.safeList(o,"asks",[]),d=this.safeList(o,"bids",[]),h=this.safeInteger(o,"timestamp");return this.safeTicker({symbol:a,timestamp:h,datetime:this.iso8601(h),ask:this.safeNumber(n,0),askVolume:this.safeNumber(n,1),bid:this.safeNumber(d,0),bidVolume:this.safeNumber(d,1),info:e},r)}{let i=this.safeDict(e,"data",{}),s=this.safeString(i,"symbol"),r=this.safeMarket(s,t),a=this.safeString(r,"symbol"),o=this.safeIntegerProduct(i,"ts",1e-6);return this.safeTicker({symbol:a,timestamp:o,datetime:this.iso8601(o),ask:this.safeNumber(i,"bestAskPrice"),askVolume:this.safeNumber(i,"bestAskSize"),bid:this.safeNumber(i,"bestBidPrice"),bidVolume:this.safeNumber(i,"bestBidSize"),info:e},r)}}async watchOHLCV(e,t="1m",i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=o.symbol,d=this.safeString(this.timeframes,t,t),h="candles:"+n+":"+t,[c,l]=this.handleOptionBoolAndParams(r,"watchOHLCV","uta",!1);if(c)h="uta:"+h,a=await this.subscribePublicUta(h,"kline",n,this.extend({interval:d},l));else{let e=o.contract,t=await this.negotiate(!1,e),i="/market/candles:";!0===e&&(i="/contractMarket/limitCandle:");let s=i+o.id+"_"+d;a=await this.subscribe(t,h,s,l)}let u=s;return this.newUpdates&&(u=a.getLimit(n,s)),this.filterBySinceLimit(a,i,u,0,!0)}async unWatchOHLCV(e,t="1m",i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=s.symbol,[a,o]=this.handleOptionBoolAndParams(i,"unWatchOHLCV","uta",!1),n=this.safeString(this.timeframes,t,t),d=[r,t],h={symbols:[r],symbolsAndTimeframes:[d],topic:"ohlcv",unsubscribe:!0},c="candles:"+r+":"+t;if(a){h.subMessageHashes=[c="uta:"+c];let e="unsubscribe:"+c;return h.messageHashes=[e],await this.subscribePublicUta(e,"kline",r,this.extend({interval:n},o),h)}{let e=s.contract,t=await this.negotiate(!1,e),i="/market/candles:";!0===e&&(i="/contractMarket/limitCandle:");let r="unsubscribe:"+c,a=i+s.id+"_"+n;return h.messageHashes=[r,a],h.subMessageHashes=[c,a],await this.unSubscribe(t,r,a,r,o,h)}}handleOHLCV(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"symbol"),r=this.safeList(i,"candles",[]),a=this.safeString(t,"topic"),n=a.split("_"),d=this.safeString(n,1),h=this.findTimeframe(d),c=this.safeMarket(s).symbol,l="candles:"+c+":"+h;this.ohlcvs[c]=this.safeDict(this.ohlcvs,c,{});let u=this.safeValue(this.ohlcvs[c],h);if(void 0===u){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);u=new o.TG(e),this.ohlcvs[c][h]=u}let f=a.indexOf("contractMarket")>=0,p=5;f&&(p=6);let m=[this.safeTimestamp(r,0),this.safeNumber(r,1),this.safeNumber(r,3),this.safeNumber(r,4),this.safeNumber(r,2),this.safeNumber(r,p)];u.append(m),e.resolve(u,l)}handleUtaOHLCV(e,t){let i=this.safeDict(t,"d",{}),s=this.safeString(i,"s"),r=this.safeMarket(s).symbol,a=this.safeString(i,"i"),n=this.findTimeframe(a),d="uta:candles:"+r+":"+n;this.ohlcvs[r]=this.safeDict(this.ohlcvs,r,{});let h=this.safeValue(this.ohlcvs[r],n);if(void 0===h){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);h=new o.TG(e),this.ohlcvs[r][n]=h}let c=[this.safeIntegerProduct(i,"O",1e3),this.safeNumber(i,"o"),this.safeNumber(i,"h"),this.safeNumber(i,"l"),this.safeNumber(i,"c"),this.safeNumber(i,"v")];h.append(c),e.resolve(h,d)}async watchTrades(e,t,i,s={}){let[r,a]=this.handleOptionBoolAndParams(s,"watchTrades","uta",!1);if(r){await this.loadMarkets();let s=this.market(e).symbol,r=await this.subscribePublicUta("uta:trades:"+s,"trade",s,a),o=this.safeDict(r,0),n=this.safeString(o,"symbol"),d=i;return this.newUpdates&&(d=r.getLimit(n,i)),this.filterBySinceLimit(r,t,d,"timestamp",!0)}return await this.watchTradesForSymbols([e],t,i,a)}async watchTradesForSymbols(e,t,i,s={}){if(0===e.length)throw new r.ArgumentsRequired(this.id+" watchTradesForSymbols() requires a non-empty array of symbols");void 0===this.markets&&await this.loadMarkets();let a=this.marketSymbols(e,void 0,!1,!0),o=this.getMarketFromSymbols(a),n=this.safeBool(o,"contract",!1),d=this.marketIds(a),h=await this.negotiate(!1,n),c=[],l=[],u="/market/match:";n&&(u="/contractMarket/execution:");let f=u+d.join(",");for(let e=0;e<a.length;e++){let t=a[e];c.push("trades:"+t);let i=d[e];l.push(u+i)}let p=await this.subscribeMultiple(h,c,f,l,s),m=this.safeDict(p,0),g=this.safeString(m,"symbol"),v=i;return this.newUpdates&&(v=p.getLimit(g,i)),this.filterBySinceLimit(p,t,v,"timestamp",!0)}async unWatchTradesForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1,!0),s=this.marketIds(i),r=this.getMarketFromSymbols(i),a=this.safeBool(r,"contract",!1),o=await this.negotiate(!1,a),n=[],d=[],h="/market/match:";a&&(h="/contractMarket/execution:");let c=h+s.join(",");for(let e=0;e<i.length;e++){let t=i[e];n.push("unsubscribe:trades:"+t),d.push("trades:"+t)}return n.push(c),d.push(c),await this.unSubscribeMultiple(o,n,c,n,t,{messageHashes:n,subMessageHashes:d,topic:"trades",unsubscribe:!0,symbols:i})}async unWatchTrades(e,t={}){let[i,s]=this.handleOptionBoolAndParams(t,"watchTrades","uta",!1);if(i){await this.loadMarkets();let t=this.market(e).symbol,i="uta:trades:"+t,r="unsubscribe:"+i;return await this.subscribePublicUta(r,"trade",t,s,{messageHashes:[r],subMessageHashes:[i],topic:"trades",unsubscribe:!0,symbols:[t]})}return await this.unWatchTradesForSymbols([e],s)}handleTrade(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"symbol"),r=this.safeMarket(s),a=this.parseTrade(i,r),n=a.symbol;if(!(n in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3),t=new o.I3(e);this.trades[n]=t}let d=this.trades[n];d.append(a),e.resolve(d,"trades:"+n)}handleUtaTrade(e,t){let i=this.safeDict(t,"d",{}),s=this.safeString(i,"symbol"),r=this.safeMarket(s),a=this.parseWsUtaTrade(i,r),n=a.symbol;if(!(n in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3),t=new o.I3(e);this.trades[n]=t}let d=this.trades[n];d.append(a),e.resolve(d,"uta:trades:"+n)}parseWsUtaTrade(e,t){let i,s=this.safeString(e,"s"),r=this.safeMarket(s,t),a=this.safeIntegerProduct2(e,"M","E",1e-6),o=this.safeString(e,"f");if(void 0!==o){let t=this.safeString(e,"fC");i={cost:o,currency:this.safeCurrencyCode(t)}}return this.safeTrade({info:e,id:this.safeString(e,"ti"),order:this.safeString(e,"oi"),timestamp:a,datetime:this.iso8601(a),symbol:r.symbol,type:this.safeStringLower(e,"oT"),side:this.safeStringLower(e,"S"),takerOrMaker:this.safeStringLower(e,"lR"),price:this.safeString(e,"p"),amount:this.safeString(e,"q"),cost:void 0,fee:i},r)}async watchOrderBook(e,t,i={}){let[s,r]=this.handleOptionBoolAndParams(i,"watchOrderBook","uta",!1);if(s){await this.loadMarkets();let i=this.market(e).symbol,[s,a]=this.handleOptionStringAndParams(r,"watchOrderBook","utaDepth","increment"),o="uta:orderbook:"+i+":depth:"+s,n={};"increment"===s&&(n={method:this.handleOrderBookSubscription,symbols:[i],limit:t});let d=this.extend(a,{depth:s});return(await this.subscribePublicUta(o,"obu",i,d,n)).limit()}return await this.watchOrderBookForSymbols([e],t,r)}async unWatchOrderBook(e,t={}){let[i,s]=this.handleOptionBoolAndParams(t,"unWatchOrderBook","uta",!1);if(i){await this.loadMarkets();let t=this.market(e).symbol,[i,r]=this.handleOptionStringAndParams(s,"watchOrderBook","utaDepth","increment"),a=this.extend(r,{depth:i}),o="uta:orderbook:"+t+":depth:"+i,n="unsubscribe:"+o;return await this.subscribePublicUta(n,"obu",t,a,{messageHashes:[n],subMessageHashes:[o],topic:"orderbook",unsubscribe:!0,symbols:[t]})}return await this.unWatchOrderBookForSymbols([e],s)}async watchOrderBookForSymbols(e,t,i={}){if(0===e.length)throw new r.ArgumentsRequired(this.id+" watchOrderBookForSymbols() requires a non-empty array of symbols");if(void 0!==t&&20!==t&&100!==t&&50!==t&&5!==t)throw new r.ExchangeError(this.id+" watchOrderBook 'limit' argument must be undefined, 5, 20, 50 or 100");void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e),a=this.marketIds(s),o=this.getMarketFromSymbols(s),n=this.safeBool(o,"contract",!1),d=await this.negotiate(!1,n),h="/market/level2";n&&(h="/contractMarket/level2");let c="spotMethod";n&&(c="contractMethod");let[l,u]=this.handleOptionStringAndParams2(i,"watchOrderBook",c,"method",h),f=l;0>f.indexOf("Depth")&&(5===t||50===t)&&(n||(f="/spotMarket/level2"),f+="Depth"+t.toString());let p=f+":"+a.join(","),m=[],g=[];for(let e=0;e<s.length;e++){let t=s[e];m.push("orderbook:"+t);let i=a[e];g.push(f+":"+i)}let v={};return("/market/level2"===f||"/contractMarket/level2"===f)&&(v={method:this.handleOrderBookSubscription,symbols:s,limit:t}),(await this.subscribeMultiple(d,m,p,g,u,v)).limit()}async unWatchOrderBookForSymbols(e,t={}){let i=this.safeInteger(t,"limit"),s=this.omit(t,"limit");void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!1,!0),a=this.marketIds(r),o=this.getMarketFromSymbols(r),n=this.safeBool(o,"contract",!1),d=await this.negotiate(!1,n),h="/market/level2";n&&(h="/contractMarket/level2");let c="spotMethod";n&&(c="contractMethod");let[l,u]=this.handleOptionStringAndParams2(s,"watchOrderBook",c,"method",h),f=l;0>f.indexOf("Depth")&&(5===i||50===i)&&(n||(f="/spotMarket/level2"),f+="Depth"+i.toString());let p=f+":"+a.join(","),m=[],g=[];for(let e=0;e<r.length;e++){let t=r[e];m.push("unsubscribe:orderbook:"+t),g.push("orderbook:"+t)}return m.push(p),g.push(p),await this.unSubscribeMultiple(d,m,p,m,u,{messageHashes:m,symbols:r,unsubscribe:!0,topic:"orderbook",subMessageHashes:g})}handleOrderBook(e,t){let i=this.safeDict(t,"data"),s=this.safeString(t,"topic"),r=s.split(":"),a=this.safeString(r,1),o=this.safeString(r,0),n=this.safeString(i,"symbol",a),d=this.safeSymbol(n,void 0,"-"),h="orderbook:"+d;if(s.indexOf("Depth")>=0)d in this.orderbooks?this.orderbooks[d].reset():this.orderbooks[d]=this.orderBook(),this.orderbooks[d].symbol=d;else{d in this.orderbooks||(this.orderbooks[d]=this.orderBook());let t=this.orderbooks[d],s=this.safeInteger(t,"nonce"),r=this.safeInteger2(i,"sequenceEnd","timestamp");if(void 0===s){let s,r=t.cache.length,n=Object.keys(e.subscriptions);for(let t=0;t<n.length;t++){let i=n[t];if(i.indexOf(a)>=0&&i.indexOf(o)>=0){s=e.subscriptions[i];break}}let c=this.safeInteger(s,"limit");r===this.handleOption("watchOrderBook","snapshotDelay",5)&&this.spawn(this.loadOrderBook,e,h,d,c,{}),t.cache.push(i);return}if(s>=r)return}this.handleBookDelta(this.orderbooks[d],i),e.resolve(this.orderbooks[d],h)}handleUtaOrderBook(e,t){let i=this.safeString(t,"t"),s=this.safeDict(t,"d",{}),r=this.safeString(s,"s"),a=this.safeMarket(r).symbol,o=this.safeIntegerProduct(s,"M",1e-6);a in this.orderbooks||(this.orderbooks[a]=this.orderBook());let n=this.orderbooks[a],d="uta:orderbook:"+a+":depth:"+this.safeString(t,"dp");if("snapshot"===i){let e=this.parseOrderBook(s,a,o,"b","a",0,1);e.nonce=this.safeInteger(s,"O"),n.reset(e),this.orderbooks[a]=n}else{let t=this.safeInteger(n,"nonce"),i=this.safeInteger(s,"C");if(void 0===t){let t=n.cache.length,i=this.safeDict(e.subscriptions,d,{}),r=this.safeInteger(i,"limit");t===this.handleOption("watchOrderBook","snapshotDelay",5)&&this.spawn(this.loadOrderBook,e,d,a,r,{uta:!0}),n.cache.push(s);return}if(t>=i)return}this.handleBookDelta(this.orderbooks[a],s),e.resolve(this.orderbooks[a],d)}getCacheIndex(e,t){let i=this.safeDict(t,0),s=this.safeInteger(e,"nonce"),r=this.safeIntegerN(i,["sequenceStart","sequence","O"]);if(void 0===s||void 0===r||s<r-1)return -1;for(let e=0;e<t.length;e++){let i=this.safeDict(t,e),r=this.safeIntegerN(i,["sequenceStart","sequence","O"]),a=this.safeIntegerN(i,["sequenceEnd","sequence","C"]);if(void 0!==r&&void 0!==a&&s>=r-1&&s<a)return e}return t.length}handleBookDelta(e,t){let i=this.safeIntegerProduct(t,"M",1e-6);void 0===i&&(i=this.safeInteger2(t,"time","timestamp")),e.nonce=this.safeIntegerN(t,["sequenceEnd","sequence","C"],i),e.timestamp=i,e.datetime=this.iso8601(i);let s=this.safeString(t,"change"),r=this.safeDict(t,"changes",t),a=e.bids,o=e.asks;if(void 0!==s){let e=s.split(","),t=this.safeNumber(e,0),i=this.safeString(e,1),r=this.safeNumber(e,2),n="asks";"buy"===i&&(n="bids");let d=[t,r];"bids"===n?a.storeArray(d):o.storeArray(d)}else if(void 0!==r){let e=this.safeList(r,"bids",[]),t=this.safeList(r,"asks",[]);this.handleBidAsks(a,e),this.handleBidAsks(o,t)}else{let e=this.safeList2(t,"bids","b",[]),i=this.safeList2(t,"asks","a",[]);this.handleBidAsks(a,e),this.handleBidAsks(o,i)}}handleBidAsks(e,t){for(let i=0;i<t.length;i++){let s=this.parseOrderBookBidAsk(t[i]);e.storeArray(s)}}handleOrderBookSubscription(e,t,i){let s=this.safeInteger(i,"limit"),r=this.safeList(i,"symbols");if(void 0===r){let e=this.safeString(i,"symbol");this.orderbooks[e]=this.orderBook({},s)}else for(let e=0;e<r.length;e++){let t=r[e];this.orderbooks[t]=this.orderBook({},s)}}handleSubscriptionStatus(e,t){let i=this.safeString(t,"id");if(!(i in e.subscriptions))return;let s=this.safeString(e.subscriptions,i),r=this.safeDict(e.subscriptions,s);delete e.subscriptions[i];let a=this.safeValue(r,"method");if(void 0!==a&&a.call(this,e,t,r),!0===this.safeBool(r,"unsubscribe",!1)){let t=this.safeList(r,"messageHashes",[]),i=this.safeList(r,"subMessageHashes",[]);for(let s=0;s<t.length;s++){let r=t[s],a=i[s];this.cleanUnsubscription(e,a,r)}if("fundingRate"===this.safeString(r,"topic")){let e=this.safeList(r,"symbols",[]);for(let t=0;t<e.length;t++){let i=e[t];i in this.fundingRates&&delete this.fundingRates[i]}}else this.cleanCache(r)}}handleSystemStatus(e,t){let i=this.safeInteger(t,"pingInterval");return void 0!==i&&(e.keepAlive=i),t}async watchOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o=await this.isUTAEnabled(),[n,d]=this.handleOptionBoolAndParams(s,"watchOrders","uta",o);void 0!==e&&(r=this.market(e));let h=void 0!==r?this.safeString(r,"symbol"):e,c="orders";if(void 0!==h&&(c=c+":"+h),n){let e=this.extend(d,{tradeType:"UNIFIED"});c="uta:"+c;let t="order";void 0===h&&(t+="All"),a=await this.subscribePrivateUta([c],c,t,h,e)}else{let e=this.safeBool2(d,"stop","trigger"),t=this.omit(d,["stop","trigger"]),[i,s]=this.handleMarketTypeAndParams("watchOrders",r,t),o="spot"!==i&&"margin"!==i,n=await this.negotiate(!0,o),l="/spotMarket/tradeOrders";!0===e&&(l="/spotMarket/advancedOrders"),o&&(l=!0===e?"/contractMarket/advancedOrders":"/contractMarket/tradeOrders"),void 0===h&&(c+=this.getOrdersMessageHashSuffix(l)),a=await this.subscribe(n,c,l,this.extend({privateChannel:!0},s))}let l=i;return this.newUpdates&&(l=a.getLimit(h,i)),this.filterBySymbolSinceLimit(a,h,t,l,!0)}getOrdersMessageHashSuffix(e){let t="-spot";return"/spotMarket/advancedOrders"===e?t+="-trigger":"/contractMarket/tradeOrders"===e?t="-contract":"/contractMarket/advancedOrders"===e&&(t="-contract-trigger"),t}parseWsOrderStatus(e){return this.safeString({open:"open",filled:"closed",match:"open",update:"open",canceled:"canceled",cancel:"canceled",TRIGGERED:"triggered"},e,e)}parseWsOrder(e,t){let i=this.safeString(e,"type"),s=this.parseWsOrderStatus(i),r=this.safeInteger2(e,"orderTime","createdAt"),a=this.safeString(e,"symbol"),o=this.safeMarket(a,t);!0===o.contract&&(r=this.safeIntegerProduct(e,"orderTime",1e-6));let n=this.safeString(e,"stopPrice"),d=this.safeBool(e,"triggerSuccess");return"triggered"===s&&!0!==d&&void 0!==d&&(s="canceled"),this.safeOrder({info:e,symbol:o.symbol,id:this.safeString(e,"orderId"),clientOrderId:this.safeString(e,"clientOid"),timestamp:r,datetime:this.iso8601(r),lastTradeTimestamp:void 0,type:this.safeStringLower(e,"orderType"),timeInForce:void 0,postOnly:void 0,side:this.safeStringLower(e,"side"),price:this.safeString2(e,"price","orderPrice"),stopPrice:n,triggerPrice:n,amount:this.safeString(e,"size"),cost:void 0,average:void 0,filled:this.safeString(e,"filledSize"),remaining:void 0,status:s,fee:void 0,trades:void 0},o)}parseWsUtaOrder(e,t){let i=this.safeIntegerProduct(e,"O",1e-6),s=this.safeString(e,"os"),r=this.safeString(e,"s"),o=this.safeString(e,"tIF"),n=this.safeString(e,"rS"),d=this.safeString(e,"cS"),h=a.Y.stringAdd(n,d),c=this.safeMarket(r,t),l={cost:this.safeString(e,"f"),currency:this.safeCurrencyCode(this.safeString(e,"fC"))};return this.safeOrder({info:e,id:this.safeString(e,"oi"),clientOrderId:this.safeString(e,"ci"),datetime:this.iso8601(i),timestamp:i,lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeIntegerProduct(e,"U",1e-6),status:this.parseOrderStatus(s),symbol:c.symbol,type:this.safeStringLower(e,"oT"),timeInForce:this.parseOrderTimeInForce(o),side:this.safeStringLower(e,"S"),price:this.safeString(e,"p"),average:this.safeString(e,"aP"),amount:this.safeString(e,"q"),filled:this.safeString(e,"fS"),remaining:h,triggerPrice:this.safeString(e,"tP"),takeProfitPrice:this.safeString(e,"pP"),stopLossPrice:this.safeString(e,"lP"),cost:this.safeString(e,"c"),trades:void 0,fee:l,reduceOnly:this.safeBool(e,"rO"),postOnly:this.safeBool(e,"pO")},c)}handleOrder(e,t){let i=this.safeDict(t,"data");void 0!==this.safeString(i,"tradeId")&&this.handleMyTrade(e,t);let s=this.parseWsOrder(i),r=this.safeString(s,"symbol"),n=this.safeString(s,"id"),d=this.safeString(s,"triggerPrice");if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e),this.triggerOrders=new o.Pt(e)}let h=void 0!==d?this.triggerOrders:this.orders,c=this.safeDict(h.hashmap,r,{}),l=this.safeDict(c,n);void 0!==l&&("closed"===this.safeString(l,"status")&&(s.status="closed"),void 0!==l.average&&(s.average=l.average,s.cost=l.cost),void 0===s.filled&&(s.filled=l.filled));let u=this.safeString(i,"type"),f=this.safeString(i,"matchPrice"),p=this.safeString(i,"matchSize");if("match"===u&&void 0!==f&&void 0!==p){let e=a.Y.stringMul(f,p),t=void 0===l?"0":this.numberToString(this.safeNumber(l,"cost",0)),i=a.Y.stringAdd(t,e);s.cost=this.parseNumber(i);let r=this.numberToString(s.filled);void 0!==r&&a.Y.stringGt(r,"0")&&(s.average=this.parseNumber(a.Y.stringDiv(i,r)))}h.append(s);let m="orders",g=this.safeString(t,"topic"),v=this.getOrdersMessageHashSuffix(g);e.resolve(h,m+v);e.resolve(h,m+":"+r)}handleUtaOrder(e,t){let i=this.safeDict(t,"d",{}),s=this.parseWsUtaOrder(i),r=this.safeString(s,"symbol");if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}let a=this.orders;a.append(s);let n="uta:orders";e.resolve(a,n+":"+r),e.resolve(a,n)}async watchMyTrades(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o="myTrades";void 0!==e&&(r=this.market(e));let n=void 0!==r?this.safeString(r,"symbol"):e;void 0!==r&&(o=o+":"+r.symbol);let[d,h]=this.handleMarketTypeAndParams("watchMyTrades",r,s),c="spot"!==d&&"margin"!==d,l=await this.isUTAEnabled(),[u,f]=this.handleOptionBoolAndParams(h,"watchMyTrades","uta",l);if(u){let e=this.extend(f,{tradeType:"UNIFIED"});o="uta:"+o;let t="execution.lite";a=await this.subscribePrivateUta([o],t,t,void 0,e)}else{let e=await this.negotiate(!0,c),t="/spotMarket/tradeOrders";c&&(t="/contractMarket/tradeOrders");let i="spotMethod";c&&(i="contractMethod");let[s,r]=this.handleOptionStringAndParams2(f,"watchMyTrades",i,"method",t);void 0===n&&(o+=this.getMyTradesMessageHashSuffix(s)),a=await this.subscribe(e,o,s,this.extend({privateChannel:!0},r))}let p=i;return this.newUpdates&&(p=a.getLimit(n,i)),this.filterBySymbolSinceLimit(a,n,t,p,!0)}getMyTradesMessageHashSuffix(e){let t="-spot";return e.indexOf("contractMarket")>=0&&(t="-contract"),t}handleMyTrade(e,t){if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new o.Pt(e)}let i=this.safeDict(t,"data"),s=this.parseWsTrade(i);this.myTrades.append(s);let r="myTrades",a=this.safeString(t,"topic"),n=this.getMyTradesMessageHashSuffix(a);e.resolve(this.myTrades,r+n);let d=r+":"+s.symbol;e.resolve(this.myTrades,d)}handleUtaMyTrade(e,t){let i=this.safeDict(t,"d",{}),s=this.safeString(i,"s"),r=this.safeMarket(s),a=this.parseWsUtaTrade(i,r),n=a.symbol;if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new o.Pt(e)}let d=this.myTrades;d.append(a);let h="uta:myTrades";e.resolve(this.myTrades,h),e.resolve(d,h+":"+n)}parseWsTrade(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t,"-"),r=s.symbol,a=this.safeString(e,"orderType"),o=this.safeString(e,"side"),n=this.safeString(e,"tradeId"),d=this.safeString(e,"matchPrice"),h=this.safeString(e,"matchSize");void 0===d&&(d=this.safeString(e,"price"),h=this.safeString(e,"size"));let c=this.safeString(e,"orderId"),l=this.safeIntegerProduct2(e,"ts","time",1e-6),u=s.quote,f=this.safeString(e,"feeRate"),p=this.safeString(e,"fee");return this.safeTrade({info:e,timestamp:l,datetime:this.iso8601(l),symbol:r,id:n,order:c,type:a,takerOrMaker:this.safeString(e,"liquidity"),side:o,price:d,amount:h,cost:void 0,fee:{cost:p,rate:f,currency:u}},s)}async watchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let i=await this.isUTAEnabled(),[s,r]=this.handleOptionBoolAndParams(e,"watchBalance","uta",i),a="spot";s&&(a="unified");let o=a;s||(a=this.safeString(this.options,"defaultType",a),o=this.safeString(r,"type",a));let n=this.omit(r,"type"),d=this.safeDict(this.options,"accountsByType",{}),h=this.safeString(d,o,o),c="contract"===h,l="/account/balance";c&&(l="/contractAccount/wallet"),s?(t=await this.getUtaUrl(),l=h):t=await this.negotiate(!0,c);let u=this.client(t);this.setBalanceCache(u,h);let f=this.safeDict(this.options,"watchBalance"),p=this.safeBool(f,"fetchBalanceSnapshot",!1),m=this.safeBool(f,"awaitBalanceSnapshot",!0);!0===p&&!0===m&&await u.future(h+":fetchBalanceSnapshot");let g=h+":balance";if(s)return await this.subscribePrivateUta([g],l,"balance",void 0,this.extend({accountType:h},n));{let e=this.requestId().toString(),i={id:e,type:"subscribe",topic:l,response:!0,privateChannel:!0},s=this.extend(i,n);return l in u.subscriptions||(u.subscriptions[e]=l),await this.watch(t,g,s,h)}}setBalanceCache(e,t){if(t in e.subscriptions&&t in this.balance)return;let i=this.safeDict(this.options,"watchBalance");if(!0===this.safeBool(i,"fetchBalanceSnapshot",!1)){let i=t+":fetchBalanceSnapshot";i in e.futures||(e.future(i),this.spawn(this.loadBalanceSnapshot,e,i,t))}else this.balance[t]={}}async loadBalanceSnapshot(e,t,i){let s="unified"===i,r=await this.fetchBalance({type:i,uta:s});this.balance[i]=this.extend(r,this.safeDict(this.balance,i,{})),t in e.futures&&(e.futures[t].resolve(),e.resolve(this.balance[i],i+":balance"))}handleBalance(e,t){let i,s=this.safeDict(t,"data",{}),r=this.safeString(s,"currency"),o=this.safeString(s,"relationEvent");if(void 0!==o){let e=o.split(".");i=this.safeString(e,0)}"/contractAccount/wallet"===this.safeString(t,"topic")&&(i="contract");let n=this.safeDict(this.options,"accountsByType"),d=this.safeString(n,i,"trade");d in this.balance||(this.balance[d]={}),this.balance[d].info=s;let h=this.safeInteger2(s,"time","timestamp");this.balance[d].timestamp=h,this.balance[d].datetime=this.iso8601(h);let c=this.safeCurrencyCode(r),l=this.account(),u=this.safeString2(s,"hold","holdBalance"),f=this.omitZero(this.safeString(s,"isolatedPosMargin"));void 0!==f&&(u=a.Y.stringAdd(u,f)),l.free=this.safeString2(s,"available","availableBalance"),l.used=u,l.total=this.safeString(s,"total"),void 0!==d&&void 0!==c&&(this.balance[d][c]=l),this.balance[d]=this.safeBalance(this.balance[d]),e.resolve(this.balance[d],d+":balance")}handleUtaBalance(e,t){let i="unified",s=this.safeDict(t,"d",{}),r=this.safeString(s,"c"),a=this.safeCurrencyCode(r);i in this.balance||(this.balance[i]={}),this.balance[i].info=s;let o=this.safeIntegerProduct(s,"U",1e-6);this.balance[i].timestamp=o,this.balance[i].datetime=this.iso8601(o);let n=this.account();n.free=this.safeString(s,"a"),n.used=this.safeString(s,"h"),n.total=this.safeString(s,"b"),void 0!==a&&(this.balance[i][a]=n),this.balance[i]=this.safeBalance(this.balance[i]),e.resolve(this.balance[i],i+":balance")}async watchPosition(e,t={}){if(void 0===e)throw new r.ArgumentsRequired(this.id+" watchPosition() requires a symbol argument");void 0===this.markets&&await this.loadMarkets();let i=await this.negotiate(!0),s=this.market(e),a="/contract/position:"+s.id,o="position:"+s.symbol,n=this.client(i);this.setPositionCache(n,e);let d=this.handleOption("watchPosition","fetchPositionSnapshot",!0),h=this.handleOption("watchPosition","awaitPositionSnapshot",!0),c=this.getCurrentPosition(e);return!0===d&&!0===h&&void 0===c?await n.future("fetchPositionSnapshot:"+e):await this.subscribe(i,o,a,this.extend({privateChannel:!0},t))}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.isUTAEnabled(),[a,o]=this.handleOptionBoolAndParams(s,"watchPositions","uta",r),n="TRADE";a&&(n="UNIFIED");let d="positions",h=[],c=this.marketSymbols(e);if(void 0===c)h.push(d);else for(let e=0;e<c.length;e++){let t=c[e];h.push(d+":"+t)}let l=await this.getUtaUrl(),u=this.client(l);this.setPositionsCache(u,a);let f=this.handleOption("watchPositions","fetchPositionsSnapshot",!0),p=this.handleOption("watchPositions","awaitPositionsSnapshot",!0),m=this.positions;if(!0===f&&!0===p&&void 0===m){let e=await u.future("fetchPositionsSnapshot");return this.filterBySymbolsSinceLimit(e,c,t,i,!0)}let g="positionAll",v=this.extend(o,{tradeType:n}),y=await this.subscribePrivateUta(h,g,g,void 0,v);return this.newUpdates?y:this.filterBySymbolsSinceLimit(m,c,t,i,!0)}getCurrentPosition(e){if(void 0===this.positions)return;let t=this.positions.hashmap,i=Object.values(this.safeDict(t,e,{}));return this.safeDict(i,0)}setPositionsCache(e,t){if(this.isEmpty(this.positions))if(!0===this.handleOption("watchPositions","fetchPositionsSnapshot",!1)){let i="fetchPositionsSnapshot";i in e.futures||(e.future(i),this.spawn(this.loadPositionsSnapshot,e,i,t))}else this.positions=new o.Pt}async loadPositionsSnapshot(e,t,i){let s=await this.fetchPositions(void 0,{uta:i});this.positions=new o.Pt;let r=this.positions;for(let e=0;e<s.length;e++){let t=s[e];this.safeNumber(t,"contracts",0)>0&&r.append(t)}t in e.futures&&(e.futures[t].resolve(r),e.resolve(r,"positions"))}setPositionCache(e,t){if(!0===this.handleOption("watchPosition","fetchPositionSnapshot",!1)){let i="fetchPositionSnapshot:"+t;i in e.futures||(e.future(i),this.spawn(this.loadPositionSnapshot,e,i,t))}}async loadPositionSnapshot(e,t,i){let s=await this.fetchPosition(i);this.positions=new o.Pt;let r=this.positions;r.append(s),t in e.futures&&(e.futures[t].resolve(r),e.resolve(s,"position:"+i))}handlePosition(e,t){let i=this.safeString(t,"topic","").split(":"),s=this.safeString(i,1),r=this.safeSymbol(s,void 0,""),a=this.positions,o=this.getCurrentPosition(r),n="position:"+r,d=this.safeDict(t,"data",{}),h=this.parsePosition(d),c=Object.keys(h);for(let e=0;e<c.length;e++){let t=c[e];void 0===h[t]&&delete h[t]}let l=this.extend(o,h);a.append(l),e.resolve(l,n)}handleUtaPosition(e,t){void 0===this.positions&&(this.positions=new o.Pt);let i=this.safeDict(t,"d",{}),s=this.safeString(i,"s"),r=this.safeSymbol(s),a=this.positions,n=this.getCurrentPosition(r),d=this.parseWsUtaPosition(i),h=Object.keys(d);for(let e=0;e<h.length;e++){let t=h[e];void 0===d[t]&&delete d[t]}let c=this.extend(n,d);a.append(c);let l="positions",u=l+":"+r;e.resolve(this.positions,l),e.resolve(this.positions,u)}parseWsUtaPosition(e,t){let i=this.safeString(e,"s"),s=this.safeMarket(i,t),r=s.symbol,o=this.safeIntegerProduct(e,"O",1e-6),n=this.safeString(e,"q"),d=a.Y.stringAbs(n),h="short";return a.Y.stringGt(n,"0")&&(h="long"),this.safePosition({info:e,id:this.safeString(e,"pi"),symbol:r,timestamp:o,datetime:this.iso8601(o),lastUpdateTimestamp:this.safeIntegerProduct(e,"U",1e-6),initialMargin:this.safeNumber(e,"iM"),initialMarginPercentage:void 0,maintenanceMargin:this.safeNumber(e,"mtM"),maintenanceMarginPercentage:this.safeNumber(e,"mmr"),entryPrice:this.safeNumber(e,"eP"),notional:this.safeNumber(e,"pV"),leverage:this.safeNumber(e,"l"),unrealizedPnl:this.safeNumber(e,"uPL"),contracts:this.parseNumber(d),contractSize:this.safeNumber(s,"contractSize"),realizedPnl:this.safeNumber(e,"rPL"),marginRatio:void 0,liquidationPrice:this.safeNumber(e,"lP"),markPrice:this.safeNumber(e,"mP"),lastPrice:void 0,collateral:void 0,marginMode:this.safeStringLower(e,"mM"),side:h,percentage:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}async watchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeSymbol(e);return await this.subscribePublicUta("fundingRate:"+i,"funding-fee",i,t)}async unWatchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeSymbol(e),s="fundingRate:"+i,r="unsubscribe:"+s;return await this.subscribePublicUta(r,"funding-fee",i,t,{symbols:[i],topic:"fundingRate",unsubscribe:!0,subMessageHashes:[s],messageHashes:[r]})}handleUtaFundingRate(e,t){let i=this.safeDict(t,"d",{}),s=this.parseWsFundingRate(i),r=s.symbol;void 0!==r&&(this.fundingRates[r]=s),e.resolve(s,"fundingRate:"+r)}parseWsFundingRate(e,t){let i=this.safeInteger(e,"ft"),s=this.safeInteger(e,"nt"),r=this.safeString(e,"s"),a=this.safeString(e,"gl");return{info:e,symbol:this.safeSymbol(r,t,void 0,"contract"),markPrice:void 0,indexPrice:void 0,interestRate:void 0,estimatedSettlePrice:void 0,timestamp:void 0,datetime:void 0,fundingRate:this.safeNumber(e,"fr"),fundingTimestamp:i,fundingDatetime:this.iso8601(i),nextFundingRate:void 0,nextFundingTimestamp:s,nextFundingDatetime:this.iso8601(s),previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:this.parseFundingInterval(a)}}async watchMarkPrice(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeSymbol(e);return await this.subscribePublicUta("uta:ticker:"+i,"mark-price",i,t)}async unWatchMarkPrice(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeSymbol(e),s="uta:ticker:"+i,r="unsubscribe:"+s;return await this.subscribePublicUta(r,"mark-price",i,t,{symbols:[i],topic:"ticker",unsubscribe:!0,subMessageHashes:[s],messageHashes:[r]})}handleSubject(e,t){if("/market/ticker:all"===this.safeString(t,"topic"))return void this.handleTicker(e,t);let i=this.safeString2(t,"subject","T"),s={level1:this.handleBidAsk,level2:this.handleOrderBook,"trade.l2update":this.handleOrderBook,"trade.ticker":this.handleTicker,"trade.snapshot":this.handleTicker,"trade.l3match":this.handleTrade,"trade.candles.update":this.handleOHLCV,"account.balance":this.handleBalance,orderChange:this.handleOrder,stopOrder:this.handleOrder,"/spot/tradeFills":this.handleMyTrade,ticker:this.handleTicker,tickerV2:this.handleBidAsk,"candle.stick":this.handleOHLCV,match:this.handleTrade,orderUpdated:this.handleOrder,symbolOrderChange:this.handleOrder,"availableBalance.change":this.handleBalance,"walletBalance.change":this.handleBalance,"position.change":this.handlePosition,"position.settlement":this.handlePosition,"position.adjustRiskLimit":this.handlePosition,"ticker.SPOT":this.handleUtaTicker,"ticker.FUTURES":this.handleUtaTicker,"trade.SPOT":this.handleUtaTrade,"trade.FUTURES":this.handleUtaTrade,"kline.SPOT":this.handleUtaOHLCV,"kline.FUTURES":this.handleUtaOHLCV,"obu.SPOT":this.handleUtaOrderBook,"obu.FUTURES":this.handleUtaOrderBook,"order.UNIFIED":this.handleUtaOrder,"order.SPOT":this.handleUtaOrder,"order.FUTURES":this.handleUtaOrder,"order.CROSS":this.handleUtaOrder,"order.ISOLATED":this.handleUtaOrder,"orderAll.UNIFIED":this.handleUtaOrder,"orderAll.SPOT":this.handleUtaOrder,"orderAll.FUTURES":this.handleUtaOrder,"orderAll.CROSS":this.handleUtaOrder,"orderAll.ISOLATED":this.handleUtaOrder,"execution.UNIFIED":this.handleUtaMyTrade,"execution.SPOT":this.handleUtaMyTrade,"execution.FUTURES":this.handleUtaMyTrade,"execution.CROSS":this.handleUtaMyTrade,"execution.ISOLATED":this.handleUtaMyTrade,"execution.lite.UNIFIED":this.handleUtaMyTrade,"execution.lite.SPOT":this.handleUtaMyTrade,"execution.lite.FUTURES":this.handleUtaMyTrade,"execution.lite.CROSS":this.handleUtaMyTrade,"execution.lite.ISOLATED":this.handleUtaMyTrade,"position.UNIFIED":this.handleUtaPosition,"position.FUTURES":this.handleUtaPosition,"positionAll.UNIFIED":this.handleUtaPosition,"positionAll.FUTURES":this.handleUtaPosition,"balance.UNIFIED":this.handleUtaBalance,"funding-fee":this.handleUtaFundingRate,"mark-price":this.handleUtaTicker},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}ping(e){return{id:this.requestId().toString(),type:"ping"}}handlePong(e,t){e.lastPong=this.milliseconds()}handleErrorMessage(e,t){let i=this.safeString2(t,"data","reason","");if("token is expired"===i){let t="public";e.url.indexOf("connectId=private")>=0&&(t="private"),e.url.indexOf("connectId="+t+"Futures")>=0&&(t+="Futures"),this.options.urls[t]=void 0}return this.handleErrors(1,"",e.url,"",{},i,t,{},{}),!1}handleMessage(e,t){let i=this.safeString2(t,"type","message"),s={welcome:this.handleSystemStatus,ack:this.handleSubscriptionStatus,message:this.handleSubject,pong:this.handlePong,error:this.handleErrorMessage},r=this.safeValue(s,i);void 0!==r?r.call(this,e,t):"T"in t?this.handleSubject(e,t):"result"in t&&(!0!==this.safeBool(t,"result",!0)&&this.handleErrorMessage(e,t),this.handleSubscriptionStatus(e,t))}getMessageHash(e,t){return void 0!==t?e+":"+t:e+"s@all"}}i.d(t,{A:()=>n})},6335(e,t,i){"use strict";var s=i(4427),r=i(1453);class a extends s.A{describe(){return this.deepExtend(super.describe(),{id:"kucoinfutures",name:"KuCoin Futures",urls:{logo:"https://user-images.githubusercontent.com/1294454/147508995-9e35030a-d046-43a1-a006-6fabd981b554.jpg",www:"https://futures.kucoin.com/",referral:"https://futures.kucoin.com/?rcode=E5wkqe"},has:{CORS:void 0,spot:!1,margin:!1,swap:!0,future:!0,option:void 0,fetchBidsAsks:!0},options:{fetchMarkets:{types:["swap","future","contract"],fetchTickersFees:!1},defaultType:"swap",defaultAccountType:"contract"}})}async fetchBidsAsks(e,t={}){return await this.fetchTickers(e,this.extend({method:"futuresPublicGetAllTickers"},t))}async transfer(e,t,i,s,a={}){let o;void 0===this.markets&&await this.loadMarkets();let n=this.currency(e),d=this.currencyToPrecision(e,t),h={currency:this.safeString(n,"id"),amount:d},c=this.parseTransferType(s);if("TRADE"===c||"MAIN"===c)h.recAccountType=c,o=await this.futuresPrivatePostTransferOut(this.extend(h,a));else if("future"===s||"swap"===s||"contract"===s)h.payAccountType=this.parseTransferType(i),o=await this.futuresPrivatePostTransferIn(this.extend(h,a));else throw new r.BadRequest(this.id+" transfer() only supports transfers between future/swap, spot and funding accounts");let l=this.safeDict(o,"data",{});return this.extend(this.parseTransfer(l,n),{amount:this.parseNumber(d),fromAccount:i,toAccount:s})}parseTransferType(e){return this.safeStringUpper({spot:"TRADE",funding:"MAIN"},e,e)}}i.d(t,{A:()=>a})},5409(e,t,i){"use strict";var s=i(7162),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,fetchOHLCVWs:!0,fetchOrderBookWs:!0,fetchTickerWs:!0,fetchTradesWs:!0,watchBalance:!0,watchTicker:!0,watchTickers:!1,watchTrades:!0,watchTradesForSymbols:!1,watchMyTrades:!1,watchOrders:!0,watchOrderBook:!0,watchOHLCV:!0},urls:{api:{ws:"wss://www.lbkex.net/ws/V2/"}},options:{watchOHLCV:{timeframes:{"1m":"1min","5m":"5min","15m":"15min","30m":"30min","1h":"1hr","4h":"4hr","1d":"day","1w":"week","1M":"month","1y":"year"}}},streaming:{},exceptions:{}})}requestId(){this.lockId();let e=this.safeInteger(this.options,"requestId",0),t=this.sum(e,1);return this.options.requestId=t,this.unlockId(),t}checkContractMarket(e,t){if(void 0!==e&&!0===e.contract)throw new r.NotSupported(this.id+" "+t+"() does not support "+e.type+" markets yet")}async fetchOHLCVWs(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e);this.checkContractMarket(a,"fetchOHLCVWs");let o=this.urls.api.ws,n=this.safeDict(this.options,"watchOHLCV",{}),d=this.safeDict(n,"timeframes",{}),h=this.safeString(d,t,t),c="fetchOHLCV:"+a.symbol+":"+h,l={action:"request",request:"kbar",kbar:h,pair:a.id};void 0!==i&&(l.start=this.parseToInt(Math.floor(i/1e3))),void 0!==s&&(l.size=s);let u=this.deepExtend(l,r),f=this.requestId();return await this.watch(o,c,u,f,u)}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e);this.checkContractMarket(a,"watchOHLCV");let o=this.safeDict(this.options,"watchOHLCV",{}),n=this.safeDict(o,"timeframes",{}),d=this.safeString(n,t,t),h="ohlcv:"+a.symbol+":"+d,c=this.urls.api.ws,l={action:"subscribe",subscribe:"kbar",kbar:d,pair:a.id},u=this.deepExtend(l,r),f=await this.watch(c,h,u,h),p=s;return this.newUpdates&&(p=f.getLimit(e,s)),this.filterBySinceLimit(f,i,p,0,!0)}handleOHLCV(e,t){let i=this.safeString(t,"pair"),s=this.safeSymbol(i,void 0,"_"),r=this.safeDict(this.options,"watchOHLCV",{}),o=this.safeDict(r,"timeframes",{}),n=this.safeList(t,"records");if(void 0!==n){let i=this.safeList(n,0,[]),r=[this.safeInteger(i,0),this.safeNumber(i,1),this.safeNumber(i,2),this.safeNumber(i,3),this.safeNumber(i,4),this.safeNumber(i,5)],d=this.safeString(t,"kbar"),h=this.findTimeframe(d,o);this.ohlcvs[s]=this.safeDict(this.ohlcvs,s,{});let c=this.safeValue(this.ohlcvs[s],h);if(void 0===c){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);c=new a.TG(e),this.ohlcvs[s][h]=c}c.append(r);let l="fetchOHLCV:"+s+":"+d;e.resolve(c,l)}else{let i=this.safeDict(t,"kbar",{}),r=this.safeString(i,"slot"),n=this.safeString(i,"t"),d=[this.parse8601(n),this.safeNumber(i,"o"),this.safeNumber(i,"h"),this.safeNumber(i,"l"),this.safeNumber(i,"c"),this.safeNumber(i,"v")],h=this.findTimeframe(r,o);this.ohlcvs[s]=this.safeDict(this.ohlcvs,s,{});let c=this.safeValue(this.ohlcvs[s],h);if(void 0===c){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);c=new a.TG(e),this.ohlcvs[s][h]=c}c.append(d);let l="ohlcv:"+s+":"+r;e.resolve(c,l)}}async fetchTickerWs(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);this.checkContractMarket(i,"fetchTickerWs");let s=this.urls.api.ws,r="fetchTicker:"+i.symbol,a={action:"request",request:"tick",pair:i.id},o=this.deepExtend(a,t),n=this.requestId();return await this.watch(s,r,o,n,o)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);this.checkContractMarket(i,"watchTicker");let s=this.urls.api.ws,r="ticker:"+i.symbol,a={action:"subscribe",subscribe:"tick",pair:i.id},o=this.deepExtend(a,t);return await this.watch(s,r,o,r,o)}handleTicker(e,t){let i=this.safeString(t,"pair"),s=this.safeSymbol(i),r=this.safeMarket(i),a=this.parseWsTicker(t,r);this.tickers[s]=a;let o="ticker:"+s;e.resolve(a,o),o="fetchTicker:"+s,e.resolve(a,o)}parseWsTicker(e,t){let i=this.safeString(e,"pair"),s=this.safeSymbol(i,t),r=this.safeString(e,"TS"),a=this.safeDict(e,"tick");return this.safeTicker({symbol:s,timestamp:this.parse8601(r),datetime:r,high:this.safeString(a,"high"),low:this.safeString(a,"low"),bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:void 0,close:void 0,last:this.safeString(a,"latest"),previousClose:void 0,change:void 0,percentage:this.safeString(a,"change"),average:void 0,baseVolume:this.safeString(a,"vol"),quoteVolume:this.safeString(a,"turnover"),info:e},t)}async fetchTradesWs(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e);this.checkContractMarket(r,"fetchTradesWs");let a=this.urls.api.ws,o="fetchTrades:"+r.symbol,n={action:"request",request:"trade",pair:r.id,size:void 0===i?10:i},d=this.deepExtend(n,s),h=this.requestId();return await this.watch(a,o,d,h,d)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e);this.checkContractMarket(r,"watchTrades");let a=this.urls.api.ws,o="trades:"+r.symbol,n={action:"subscribe",subscribe:"trade",pair:r.id},d=this.deepExtend(n,s),h=await this.watch(a,o,d,o,d),c=this.filterBySinceLimit(h,t,i,"timestamp",!0);return this.sortBy(c,"timestamp")}handleTrades(e,t){let i=this.safeString(t,"pair"),s=this.safeSymbol(i),r=this.safeMarket(i),o=this.safeValue(this.trades,s);if(void 0===o){let e=this.safeInteger(this.options,"tradesLimit",1e3);o=new a.I3(e),this.trades[s]=o}let n=this.safeDict(t,"trade"),d=this.safeList(t,"trades",[n]);for(let e=0;e<d.length;e++){let t=this.parseWsTrade(d[e],r);t.symbol=s,o.append(t)}this.trades[s]=o;let h="trades:"+s;e.resolve(this.trades[s],h),h="fetchTrades:"+s,e.resolve(this.trades[s],h)}parseWsTrade(e,t){let i,s=this.safeInteger(e,0);i=void 0!==s?this.iso8601(s):this.safeString(e,"TS"),void 0===s&&(s=this.parse8601(i));let r=this.safeString2(e,"direction",3).split("_"),a=this.safeString(r,0),o=this.safeString(r,1),n=a;return void 0!==o&&"maker"===o&&(n="buy"===n?"sell":"buy"),this.safeTrade({timestamp:s,datetime:i,symbol:void 0,id:void 0,order:void 0,type:void 0,takerOrMaker:void 0,side:n,price:this.safeString2(e,"price",1),amount:this.safeString2(e,"volume",2),cost:this.safeString(e,"amount"),fee:void 0,info:e},t)}async watchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=await this.authenticate(s),o=this.urls.api.ws,n="all",d=void 0===e?void 0:this.symbol(e);if(void 0===e)r="orders:all";else{let t=this.market(e);r="orders:"+t.symbol,n=t.id}let h={action:"subscribe",subscribe:"orderUpdate",subscribeKey:a,pair:n},c=this.deepExtend(h,s),l=await this.watch(o,r,c,r,c);return this.filterBySymbolSinceLimit(l,d,t,i,!0)}handleOrders(e,t){let i=this.safeString(t,"pair"),s=this.safeSymbol(i,void 0,"_"),r=this.orders;if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);r=new a.Pt(e)}let o=this.parseWsOrder(t);void 0!==r&&(r.append(o),this.orders=r,e.resolve(r,"orders"),e.resolve(r,"orders:"+s))}parseWsOrder(e,t){let i,s,r=this.safeDict(e,"orderUpdate",{}),a=this.safeString(r,"type",""),o=a.split("_"),n=this.safeString(o,0),d=this.safeString(o,1);"buy"!==a&&"sell"!==a&&(i="market"===d?"market":"limit");let h=this.safeString(e,"pair"),c=this.safeSymbol(h,t,"_"),l=this.safeInteger(r,"updateTime"),u=this.safeString(r,"orderStatus"),f=this.safeString(r,"orderAmt");return"market"===i&&"buy"===n&&(s=f),this.safeOrder({info:e,id:this.safeString(r,"uuid"),clientOrderId:this.safeString(r,"customerID"),timestamp:l,datetime:this.iso8601(l),lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeInteger(r,"updateTime"),symbol:c,type:i,side:n,price:this.safeString2(r,"price","orderPrice"),stopPrice:void 0,average:this.safeString(r,"avgPrice"),amount:this.safeString2(r,"amount","orderAmt"),remaining:this.safeString(r,"remainAmt"),filled:this.safeString(r,"accAmt"),status:this.parseWsOrderStatus(u),fee:void 0,cost:s,trades:void 0},t)}parseWsOrderStatus(e){return this.safeString({"-1":"canceled",0:"open",1:"open",2:"closed",4:"closed"},e,e)}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.authenticate(e),i=this.urls.api.ws,s="balance",r=this.deepExtend({action:"subscribe",subscribe:"assetUpdate",subscribeKey:t},e);return await this.watch(i,s,r,s,r)}handleBalance(e,t){let i=this.safeDict(t,"data",{}),s=this.parse8601(this.safeString(t,"TS")),r=this.iso8601(s);this.balance.info=i,this.balance.timestamp=s,this.balance.datetime=r;let a=this.safeString(i,"assetCode"),o=this.safeCurrencyCode(a),n=this.account();n.free=this.safeString(i,"free"),n.used=this.safeString(i,"freeze"),n.total=this.safeString(i,"asset"),void 0!==o&&(this.balance[o]=n),this.balance=this.safeBalance(this.balance),e.resolve(this.balance,"balance")}async fetchOrderBookWs(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e);this.checkContractMarket(s,"fetchOrderBookWs");let r=this.urls.api.ws,a="fetchOrderbook:"+s.symbol,o={action:"request",request:"depth",depth:void 0===t?100:t,pair:s.id},n=this.deepExtend(o,i);return(await this.watch(r,a,n,a)).limit()}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e);this.checkContractMarket(s,"watchOrderBook");let r=this.urls.api.ws,a="orderbook:"+s.symbol,o=this.omit(i,"aggregation"),n={action:"subscribe",subscribe:"depth",depth:void 0===t?100:t,pair:s.id},d=this.deepExtend(n,o);return(await this.watch(r,a,d,a)).limit()}handleOrderBook(e,t){let i=this.safeString(t,"pair"),s=this.safeSymbol(i),r=this.safeValue(t,"depth",t),a=this.safeString(t,"TS"),o=this.parse8601(a);s in this.orderbooks||(this.orderbooks[s]=this.orderBook({}));let n=this.orderbooks[s],d=this.parseOrderBook(r,s,o,"bids","asks");n.reset(d);let h="orderbook:"+s;e.resolve(n,h),h="fetchOrderbook:"+s,e.resolve(n,h)}handleErrorMessage(e,t){let i=this.safeString(t,"message",""),s=new r.ExchangeError(this.id+" "+i);e.reject(s)}async handlePing(e,t){e.lastPong=this.milliseconds();let i=this.safeString(t,"ping");try{await e.send({action:"pong",pong:i})}catch(t){this.onError(e,t)}}handleMessage(e,t){if("error"===this.safeString(t,"status"))return void this.handleErrorMessage(e,t);let i=this.safeString2(t,"type","action");if("ping"===i)return void this.spawn(this.handlePing,e,t);let s={kbar:this.handleOHLCV,depth:this.handleOrderBook,trade:this.handleTrades,tick:this.handleTicker,orderUpdate:this.handleOrders,assetUpdate:this.handleBalance},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}async authenticate(e={}){this.checkRequiredCredentials();let t=this.urls.api.ws,i=this.client(t),s=this.milliseconds(),a="authenticateFlight";if(a in i.futures)return await i.future(a),this.safeString(this.safeDict(i.subscriptions,"authenticated"),"key");let o=i.reusableFuture(a);try{let t=this.safeDict(i.subscriptions,"authenticated");if(void 0===t){let t=await this.spotPrivatePostSubscribeGetKey(e),a=this.safeBool(t,"result");if(!0!==a)throw new r.ExchangeError(this.id+" failed to get subscribe key");i.subscriptions.authenticated={key:this.safeString(t,"data"),expires:this.sum(s,33e5)}}else if(this.safeInteger(t,"expires",0)<s){let a={subscribeKey:t.key},o=await this.spotPrivatePostSubscribeRefreshKey(this.extend(a,e)),n=this.safeString(o,"result");if("true"!==n)throw new r.ExchangeError(this.id+" failed to refresh the SubscribeKey");i.subscriptions.authenticated.expires=this.sum(s,33e5)}i.resolve(i.subscriptions.authenticated.key,a)}catch(e){i.reject(e,a)}return await o,this.safeString(this.safeDict(i.subscriptions,"authenticated"),"key")}}i.d(t,{A:()=>o})},975(e,t,i){"use strict";var s=i(7749),r=i(1453),a=i(1697),o=i(1723);class n extends o.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchTicker:!0,watchMarkPrice:!0,watchMarkPrices:!0,watchTickers:!0,watchBidsAsks:!1,watchOrderBook:!0,watchTrades:!0,watchTradesForSymbols:!1,watchOrderBookForSymbols:!1,watchBalance:!0,watchLiquidations:!0,watchLiquidationsForSymbols:!1,watchMyLiquidations:!1,watchMyLiquidationsForSymbols:!1,watchOHLCV:!1,watchOHLCVForSymbols:!1,watchOrders:!0,watchMyTrades:!0,watchPositions:!1,watchFundingRate:!1,watchFundingRates:!1,unWatchOrderBook:!0,unWatchTicker:!0,unWatchTickers:!0,unWatchTrades:!0,unWatchMyTrades:!0,unWatchMarkPrice:!0,unWatchMarkPrices:!0,unWatchOrders:!0,createOrderWs:!0,cancelOrderWs:!0,cancelAllOrdersWs:!0},urls:{api:{ws:"wss://mainnet.zklighter.elliot.ai/stream"},test:{ws:"wss://testnet.zklighter.elliot.ai/stream"}},options:{requestId:this.createSafeDictionary()}})}getMessageHash(e,t,i){let s=e;return void 0!==t?s+="::"+t:s+="s",void 0!==i&&(s+="::"+i),s}async subscribePublic(e,t={}){let i=this.urls.api.ws;return await this.watch(i,e,this.extend({type:"subscribe"},t),e,{messageHash:e,params:t})}async subscribePublicMultiple(e,t={}){let i=this.urls.api.ws;return await this.watchMultiple(i,e,this.extend({type:"subscribe"},t),e,{messageHashes:e,params:t})}async unsubscribe(e,t={}){let i=this.urls.api.ws;return await this.watch(i,e,this.extend({type:"unsubscribe"},t),e,{messageHash:e,params:t})}async subscribePrivate(e,t={}){return await this.preLoadLighterLibrary(),t.auth=this.createAuth(t),await this.subscribePublic(e,t)}handleDelta(e,t){let i=this.safeFloat(t,"price"),s=this.safeFloat(t,"size");e.store(i,s)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}handleOrderBookMessage(e,t,i){let s=this.safeDict(t,"order_book",{});this.handleDeltas(i.asks,this.safeList(s,"asks",[])),this.handleDeltas(i.bids,this.safeList(s,"bids",[])),i.nonce=this.safeInteger(s,"offset");let r=this.safeInteger(t,"timestamp");return i.timestamp=r,i.datetime=this.iso8601(r),i}handleOrderBook(e,t){let i=this.safeDict(t,"order_book",{}),s=this.safeString(t,"channel","").split(":")[1],r=this.safeMarket(s).symbol,a=this.safeInteger(t,"timestamp");r in this.orderbooks||(this.orderbooks[r]=this.orderBook());let o=this.orderbooks[r],n=this.safeString(t,"type","");if("subscribed/order_book"===n){let e=this.parseOrderBook(i,r,a,"bids","asks","price","size");e.nonce=this.safeInteger(i,"offset"),o.reset(e)}else"update/order_book"===n&&this.handleOrderBookMessage(e,t,o);let d=this.getMessageHash("orderbook",r);e.resolve(o,d)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=s.symbol,a={channel:"order_book/"+s.id},o=this.getMessageHash("orderbook",r);return(await this.subscribePublic(o,this.extend(a,i))).limit()}async unWatchOrderBook(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r={channel:"order_book/"+i.id},a=this.getMessageHash("orderbook",s);return await this.unsubscribe("unsubscribe:"+a,this.extend(r,t))}handleTicker(e,t){let i=this.safeDict(t,"market_stats",{});if("market_stats:all"===this.safeString(t,"channel")){let t=Object.keys(i);for(let s=0;s<t.length;s++){let r=t[s],a=this.safeMarket(r),o=a.symbol,n=this.parseTicker(i[r],a);this.tickers[o]=n,e.resolve(n,this.getMessageHash("ticker",o)),e.resolve(n,this.getMessageHash("ticker"))}}else{let t=this.safeString(i,"market_id"),s=this.safeMarket(t),r=s.symbol,a=this.parseTicker(i,s);this.tickers[r]=a,e.resolve(a,this.getMessageHash("ticker",r))}}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol;if(!0!==i.swap)throw new r.NotSupported(this.id+" watchTicker() is only supported for swap markets");let a={channel:"market_stats/"+i.id},o=this.getMessageHash("ticker",s);return await this.subscribePublic(o,this.extend(a,t))}async unWatchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol;if(!0!==i.swap)throw new r.NotSupported(this.id+" unWatchTicker() is only supported for swap markets");let a={channel:"market_stats/"+i.id},o=this.getMessageHash("ticker",s);return await this.unsubscribe("unsubscribe:"+o,this.extend(a,t))}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0),s=this.getMarketFromSymbols(i);if(void 0!==s&&!0!==s.swap)throw new r.NotSupported(this.id+" watchTickers() is only supported for swap markets");let a=[],o=0;if(void 0!==i&&(o=i.length),void 0===i||0===o)a.push(this.getMessageHash("ticker"));else for(let e=0;e<i.length;e++){let t=i[e];a.push(this.getMessageHash("ticker",t))}let n=await this.subscribePublicMultiple(a,this.extend({channel:"market_stats/all"},t));if(this.newUpdates){let e={},t=this.safeString(n,"symbol");return void 0!==t&&(e[t]=n),e}return this.filterByArray(this.tickers,"symbol",i)}async unWatchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!0),s=this.getMarketFromSymbols(i);if(void 0!==s&&!0!==s.swap)throw new r.NotSupported(this.id+" unWatchTickers() is only supported for swap markets");let a=this.getMessageHash("ticker");return await this.unsubscribe("unsubscribe:"+a,this.extend({channel:"market_stats/all"},t))}watchMarkPrice(e,t={}){return this.watchTicker(e,t)}watchMarkPrices(e,t={}){return this.watchTickers(e,t)}unWatchMarkPrice(e,t={}){return this.unWatchTicker(e,t)}unWatchMarkPrices(e,t={}){return this.unWatchTickers(e,t)}parseWsTrade(e,t){let i=this.safeInteger(e,"timestamp"),s=this.safeString(e,"trade_id"),r=this.safeString(e,"price"),a=this.safeString(e,"size"),o=this.safeBool(e,"is_maker_ask"),n="sell";return!0===o&&(n="buy"),this.safeTrade({info:e,id:s,order:void 0,timestamp:i,datetime:this.iso8601(i),symbol:this.safeSymbol(void 0,t),type:void 0,side:n,takerOrMaker:"taker",price:r,amount:a,cost:this.safeString(e,"usd_amount"),fee:void 0},t)}handleTrades(e,t){this.safeList(t,"liquidation_trades",[]).length>0&&this.handleLiquidation(e,t);let i=this.safeList(t,"trades",[]),s=this.safeString(t,"channel","").split(":")[1],r=this.safeMarket(s),o=r.symbol,n=this.safeValue(this.trades,o);if(void 0===n){let e=this.safeInteger(this.options,"tradesLimit",1e3);n=new a.I3(e),this.trades[o]=n}let d=i.length;for(let e=0;e<d;e++){let t=d-1-e,s=this.parseWsTrade(i[t],r);n.append(s)}let h=this.getMessageHash("trade",o);e.resolve(n,h)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a={channel:"trade/"+r.id},o=this.getMessageHash("trade",this.safeString(r,"symbol")),n=await this.subscribePublic(o,this.extend(a,s));return this.filterBySinceLimit(n,t,i,"timestamp",!0)}async unWatchTrades(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s={channel:"trade/"+i.id},r=this.getMessageHash("trade",this.safeString(i,"symbol"));return await this.unsubscribe("unsubscribe:"+r,this.extend(s,t))}parseWsOrderTrade(e,t){let i,r,a,o,n=this.safeInteger(e,"timestamp"),d=this.safeString(e,"trade_id"),h=this.safeString(e,"price"),c=this.safeString(e,"size"),l=this.safeString(e,"usd_amount"),u=this.safeBool(e,"is_maker_ask"),f=this.safeInteger(e,"accountIndex"),p=this.safeInteger(e,"bid_account_id"),m=this.safeInteger(e,"ask_account_id");if(void 0!==f&&(p===f?(i="buy",r=this.safeString(e,"bid_id"),a=!0===u?"taker":"maker"):m===f&&(i="sell",r=this.safeString(e,"ask_id"),a=!0===u?"maker":"taker")),void 0===i&&(i=!0===u?"buy":"sell"),void 0!==a){let t,i=void 0!==(t="maker"===a?this.safeString(e,"maker_fee"):this.safeString(e,"taker_fee"))?s.A.stringDiv(t,"1000000"):"0";o={cost:s.A.stringMul(l,i),currency:"USDC",rate:i}}return this.safeTrade({info:e,id:d,order:r,timestamp:n,datetime:this.iso8601(n),symbol:this.safeSymbol(void 0,t),type:void 0,side:i,takerOrMaker:a,price:h,amount:c,cost:l,fee:o},t)}handleMyTrades(e,t){let i=this.safeString(t,"channel","").split(":")[1],s=this.safeDict(t,"trades",{}),r=Object.keys(s);if(0===r.length)return!1;if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new a.I3(e)}let o=this.myTrades,n=this.getMessageHash("myTrades");for(let t=0;t<r.length;t++){let a=r[t],n=this.safeMarket(a),d=this.safeList(s,a,[]),h=d.length;for(let t=0;t<h;t++){let s=d[h-1-t];s.accountIndex=i;let r=this.parseWsOrderTrade(s,n);o.append(r);let a=r.symbol;if(void 0!==a){let t=this.getMessageHash("myTrades",a);e.resolve(o,t)}}}return e.resolve(o,n),!0}async watchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=await this.handleAccountIndex(s,"watchMyTrades","accountIndex","account_index"),n=this.getMessageHash("myTrades");if(void 0!==e){let t=this.market(e);r=this.safeString(t,"symbol"),n=this.getMessageHash("myTrades",r)}let d={channel:"account_all_trades/"+this.numberToString(a)},h=await this.subscribePublic(n,this.extend(d,o)),c=i;return this.newUpdates&&(c=h.getLimit(r,i)),this.filterBySymbolSinceLimit(h,r,t,c,!0)}async unWatchMyTrades(e,t={}){if(void 0!==e)throw new r.NotSupported(this.id+" unWatchMyTrades() does not support a symbol argument, the account trades channel covers every market, unWatch from all markets only");let[i,s]=await this.handleAccountIndex(t,"unWatchMyTrades","accountIndex","account_index"),a=this.getMessageHash("myTrades"),o={channel:"account_all_trades/"+this.numberToString(i)};return await this.unsubscribe("unsubscribe:"+a,this.extend(o,s))}parseWsLiquidation(e,t){let i=this.safeInteger(e,"timestamp"),r=this.safeBool(e,"is_maker_ask"),a="sell";!0===r&&(a="buy");let o=this.safeString(e,"size"),n=this.safeString(t,"contractSize"),d=this.safeString(e,"price"),h=s.A.stringMul(o,n),c=s.A.stringMul(h,d);if(void 0!==t)return this.safeLiquidation({info:e,symbol:t.symbol,contracts:o,contractSize:n,price:d,side:a,baseValue:h,quoteValue:c,timestamp:i,datetime:this.iso8601(i)})}handleLiquidation(e,t){let i=this.safeList(t,"liquidation_trades",[]),s=this.safeString(t,"channel","").split(":")[1],r=this.safeMarket(s),o=r.symbol,n=this.safeValue(this.liquidations,o);if(void 0===n){let e=this.safeInteger(this.options,"liquidationsLimit",1e3);this.liquidations=new a.I3(e),n=this.liquidations}let d=i.length;for(let e=0;e<d;e++){let t=d-1-e,s=this.parseWsLiquidation(i[t],r);n.append(s)}let h=this.getMessageHash("liquidations",o);e.resolve(n,h)}async watchLiquidations(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={channel:"trade/"+this.market(e).id},a=this.getMessageHash("liquidations",e);return await this.subscribePublic(a,this.extend(r,s))}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=this.safeString2(this.options,"watchBalance","defaultType","spot"),[i,s]=this.handleParamString(e,"type",t),[r,a]=await this.handleAccountIndex(s,"watchBalance","accountIndex","account_index"),o=this.getMessageHash("balances",void 0,i),n={};return"spot"===i?(n.channel="account_all_assets/"+this.numberToString(r),await this.subscribePrivate(o,this.extend(n,a))):(n.channel="user_stats/"+this.numberToString(r),await this.subscribePublic(o,this.extend(n,a)))}handleBalance(e,t){let i=this.safeString(t,"channel",""),s="spot";i.indexOf("user_stats:")>=0&&(s="swap");let r=this.safeDict(this.balance,s,{});if("spot"===s){let e=this.safeDict(t,"assets",{}),i=Object.keys(e);for(let t=0;t<i.length;t++){let s=i[t],a=this.safeDict(e,s),o=this.safeString(a,"symbol"),n=this.safeCurrencyCode(o),d=this.account();d.used=this.safeString(a,"locked_balance"),d.total=this.safeString(a,"balance"),void 0!==n&&(r[n]=d)}}else{let e=this.safeDict(t,"stats",{}),i=this.account();i.free=this.safeString(e,"available_balance"),i.total=this.safeString(e,"collateral"),i.info=e,r.USDC=i}let a=this.safeInteger(t,"timestamp");r.timestamp=a,r.datetime=this.iso8601(a),this.balance[s]=this.safeBalance(r);let o=this.getMessageHash("balances",void 0,s);return e.resolve(this.balance[s],o),!0}async watchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let[a,o]=await this.handleAccountIndex(s,"watchOrders","accountIndex","account_index"),n={};if(void 0!==e){let t=this.market(e);r=this.getMessageHash("orders",this.safeString(t,"symbol")),n.channel="account_orders/"+t.id+"/"+this.numberToString(a)}else r=this.getMessageHash("orders"),n.channel="account_all_orders/"+this.numberToString(a);let d=await this.subscribePrivate(r,this.extend(n,o)),h=i;return this.newUpdates&&(h=d.getLimit(e,i)),this.filterBySymbolSinceLimit(d,e,t,h,!0)}async unWatchOrders(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let[s,r]=await this.handleAccountIndex(t,"unWatchOrders","accountIndex","account_index"),a={};if(void 0!==e){let t=this.market(e);i=this.getMessageHash("orders",this.safeString(t,"symbol")),a.channel="account_orders/"+t.id+"/"+this.numberToString(s)}else i=this.getMessageHash("orders"),a.channel="account_all_orders/"+this.numberToString(s);let o="unsubscribe:"+i;return await this.unsubscribe(o,this.extend(a,r))}requestId(e){let t=this.safeDict(this.options,"requestId",this.createSafeDictionary()),i=this.safeInteger(t,e,0),s=this.sum(i,1);return this.options.requestId[e]=s,this.numberToString(s)}async createOrderWs(e,t,i,s,r,a={}){let o=this.urls.api.ws,n=this.requestId(o),d="jsonapi/sendtx:"+n,[h,c,l]=await this.signAndCreateOrder("createOrderWs",e,t,i,s,r,a),u=this.market(e),f=this.parseJson(c),p=await this.watch(o,d,{type:"jsonapi/sendtx",data:{id:n,tx_type:h,tx_info:f}},d,{id:n});return this.parseOrder(this.deepExtend(p,l),u)}async cancelOrderWs(e,t,i={}){let s=this.urls.api.ws,r=this.requestId(s),a="jsonapi/sendtx:"+r,[o,n]=await this.signAndCancelOrder("cancelOrderWs",e,t,i),d=this.market(t),h=this.parseJson(n),c=await this.watch(s,a,{type:"jsonapi/sendtx",data:{id:r,tx_type:o,tx_info:h}},a,{id:r});return this.parseOrder(c,d)}async cancelAllOrdersWs(e,t={}){let i=this.urls.api.ws,s=this.requestId(i),r="jsonapi/sendtx:"+s,[a,o]=await this.signAndCancelAllOrders("cancelAllOrdersWs",e,t),n=this.parseJson(o),d=await this.watch(i,r,{type:"jsonapi/sendtx",data:{id:s,tx_type:a,tx_info:n}},r,{id:s});return this.parseOrders([d])}handleWsSendtxApi(e,t){let i=this.safeString(t,"id");e.resolve(t,"jsonapi/sendtx:"+i)}handleOrders(e,t){let i=this.safeDict(t,"orders",{}),s=Object.keys(i);if(0===s.length)return!1;if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.I3(e)}let r=this.orders,o=this.getMessageHash("orders");for(let t=0;t<s.length;t++){let a=s[t],o=this.safeMarket(a),n=this.safeList(i,a,[]);for(let t=0;t<n.length;t++){let i=this.parseOrder(n[t],o);r.append(i);let s=i.symbol;if(void 0!==s){let t=this.getMessageHash("orders",s);e.resolve(r,t)}}}return e.resolve(r,o),!0}handleErrorMessage(e,t){let i=this.safeDict(t,"error"),s=this.safeString(i,"code");if("30003"===s)return!0;if("30002"===s){let t=this.safeString(i,"message","").split(" : "),s=this.safeString(t,1);if(void 0!==s)return this.handleUnSubscription(e,{channel:s}),!0}try{if(void 0!==i){let e=this.safeString(i,"code"),s=this.safeString(i,"message"),a=this.id+" "+this.json(t);throw this.throwExactlyMatchedException(this.exceptions.exact,e,a),this.throwBroadlyMatchedException(this.exceptions.broad,s,a),new r.ExchangeError(a)}}catch(r){let i=this.safeString(t,"id"),s=!1;if(void 0!==i){let t=Object.keys(e.subscriptions);for(let a=0;a<t.length;a++){let o=t[a],n=this.safeString(e.subscriptions[o],"id"),d=this.safeString(e.subscriptions[o],"subscription");i===n&&(e.reject(r,o),s=!0,void 0!==d&&delete e.subscriptions[d])}}s||e.reject(r)}return!0}handleMessage(e,t){if(!this.handleErrorMessage(e,t))return;let i=this.safeString(t,"type","");if("ping"===i)return void this.handlePing(e,t);if("jsonapi/sendtx"===i)return void this.handleWsSendtxApi(e,t);if("unsubscribed"===i)return void this.handleUnSubscription(e,t);let s=this.safeString(t,"channel","");s.indexOf("order_book:")>=0?this.handleOrderBook(e,t):s.indexOf("market_stats:")>=0?this.handleTicker(e,t):s.indexOf("trade:")>=0?this.handleTrades(e,t):s.indexOf("account_all_trades:")>=0?this.handleMyTrades(e,t):s.indexOf("account_all_assets:")>=0||s.indexOf("user_stats:")>=0?this.handleBalance(e,t):s.indexOf("account_orders:")>=0||s.indexOf("account_all_orders:")>=0?this.handleOrders(e,t):""===s&&this.handleSubscriptionStatus(e,t)}handleSubscriptionStatus(e,t){return t}handleUnSubscription(e,t){let i=this.safeString(t,"channel","").split(":"),s=this.safeString(i,0,""),r=this.safeString(i,1);"order_book"===s?this.handleOrderBookUnSubscription(e,r):"market_stats"===s?this.handleTickerUnSubscription(e,r):"trade"===s?this.handleTradesUnSubscription(e,r):"account_all_trades"===s?this.handleMyTradesUnSubscription(e):"account_orders"===s?this.handleOrdersUnSubscription(e,r):"account_all_orders"===s&&this.handleAllOrdersUnSubscription(e)}handleOrderBookUnSubscription(e,t){let i=this.safeSymbol(t),s=this.getMessageHash("orderbook",i);this.cleanUnsubscription(e,s,"unsubscribe:"+s),i in this.orderbooks&&delete this.orderbooks[i]}handleTickerUnSubscription(e,t){if("all"===t){let t=Object.keys(e.subscriptions);for(let i=0;i<t.length;i++){let s=t[i];if(s.startsWith("ticker")){let t=this.safeDict(e.subscriptions,s),i=this.safeDict(t,"params");if("market_stats/all"===this.safeString(i,"channel")&&(delete e.subscriptions[s],s in e.futures)){let t=new r.UnsubscribeError(this.id+" "+s);e.reject(t,s)}}}let i="unsubscribe:"+this.getMessageHash("ticker");i in e.subscriptions&&delete e.subscriptions[i],e.resolve(!0,i),this.cleanCache({topic:"ticker"});return}let i=this.safeSymbol(t),s=this.getMessageHash("ticker",i);this.cleanUnsubscription(e,s,"unsubscribe:"+s),i in this.tickers&&delete this.tickers[i]}handleTradesUnSubscription(e,t){let i=this.safeSymbol(t),s=this.getMessageHash("trade",i);this.cleanUnsubscription(e,s,"unsubscribe:"+s),i in this.trades&&delete this.trades[i]}handleMyTradesUnSubscription(e){let t="unsubscribe:"+this.getMessageHash("myTrades");this.cleanUnsubscription(e,"myTrades",t,!0),this.cleanCache({topic:"myTrades"})}handleOrdersUnSubscription(e,t){let i=this.safeSymbol(t),s=this.getMessageHash("orders",i);this.cleanUnsubscription(e,s,"unsubscribe:"+s)}handleAllOrdersUnSubscription(e){let t=this.getMessageHash("orders");this.cleanUnsubscription(e,t,"unsubscribe:"+t),this.cleanCache({topic:"orders"})}handlePing(e,t){this.spawn(this.pong,e,t)}async pong(e,t){await e.send({type:"pong"})}}i.d(t,{A:()=>n})},2678(e,t,i){"use strict";var s=i(5642),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchTicker:!1,watchTickers:!1,watchTrades:!0,watchTradesForSymbols:!1,watchMyTrades:!1,watchOrders:void 0,watchOrderBook:!0,watchOHLCV:!1},urls:{api:{ws:"wss://ws.luno.com/api/1"}},options:{sequenceNumbers:{}},streaming:{},exceptions:{}})}async watchTrades(e,t,i,s={}){this.checkRequiredCredentials(),void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n="/stream/"+a.id,d=this.safeString(this.urls.api,"ws");if(void 0===d)throw new r.ExchangeError(this.id+" watchTrades() has no websocket url");let h="trades:"+o,c={api_key_id:this.apiKey,api_key_secret:this.secret},l=this.deepExtend(c,s),u=await this.watch(d+n,h,l,n,{symbol:o}),f=i;return this.newUpdates&&(f=u.getLimit(o,i)),this.filterBySinceLimit(u,t,f,"timestamp",!0)}handleTrades(e,t,i){let s=this.safeList(t,"trade_updates",[]);if(0===s.length)return;let r=i.symbol,o=this.market(r),n="trades:"+r,d=this.safeValue(this.trades,r);if(void 0===d){let e=this.safeInteger(this.options,"tradesLimit",1e3);d=new a.I3(e),this.trades[r]=d}for(let e=0;e<s.length;e++){let t=s[e],i=this.parseTrade(t,o);d.append(i)}this.trades[r]=d,e.resolve(this.trades[r],n)}parseTrade(e,t){let i;return i=void 0===t?void 0:t.symbol,this.safeTrade({info:e,id:void 0,timestamp:void 0,datetime:void 0,symbol:i,order:void 0,type:void 0,side:void 0,takerOrMaker:void 0,price:void 0,amount:this.safeString(e,"base"),cost:this.safeString(e,"counter"),fee:void 0},t)}async watchOrderBook(e,t,i={}){this.checkRequiredCredentials(),void 0===this.markets&&await this.loadMarkets();let s=this.market(e),a=s.symbol,o="/stream/"+s.id,n=this.safeString(this.urls.api,"ws");if(void 0===n)throw new r.ExchangeError(this.id+" watchOrderBook() has no websocket url");let d={api_key_id:this.apiKey,api_key_secret:this.secret},h=this.deepExtend(d,i);return(await this.watch(n+o,"orderbook:"+a,h,o,{symbol:a})).limit()}handleOrderBook(e,t,i){let s=i.symbol,r="orderbook:"+s,a=this.safeInteger(t,"timestamp");if(s in this.orderbooks||(this.orderbooks[s]=this.indexedOrderBook({})),void 0!==this.safeList(t,"asks")){let e=this.customParseOrderBook(t,s,a,"bids","asks","price","volume","id");this.orderbooks[s]=this.indexedOrderBook(e)}else{let e=this.orderbooks[s];this.handleBookDelta(e,t),e.timestamp=a,e.datetime=this.iso8601(a)}let o=this.orderbooks[s];o.nonce=this.safeInteger(t,"sequence"),e.resolve(o,r)}customParseOrderBook(e,t,i,s="bids",r="asks",a="price",o="volume",n=2){let d=this.parseOrderBookBidsAsks(this.safeList(e,s,[]),a,o,n),h=this.parseOrderBookBidsAsks(this.safeList(e,r,[]),a,o,n);return{symbol:t,bids:this.sortBy(d,0,!0),asks:this.sortBy(h,0),timestamp:i,datetime:this.iso8601(i),nonce:void 0}}parseOrderBookBidsAsks(e,t="price",i="volume",s=2){let r=this.toArray(e),a=[];for(let e=0;e<r.length;e++)a.push(this.customParseBidAsk(r[e],t,i,s));return a}customParseBidAsk(e,t="price",i="volume",s=2){let r=[this.safeNumber(e,t),this.safeNumber(e,i)];if(void 0!==s){let t=this.safeString(e,s);r.push(t)}return r}handleBookDelta(e,t){let i=this.safeDict(t,"create_update"),s=e.asks,r=e.bids;if(void 0!==i){let e=this.customParseBidAsk(i,"price","volume","order_id"),t=this.safeString(i,"type");"ASK"===t?s.storeArray(e):"BID"===t&&r.storeArray(e)}let a=this.safeDict(t,"delete_update");if(void 0!==a){let e=this.safeString(a,"order_id");s.storeArray([0,0,e]),r.storeArray([0,0,e])}}handleMessage(e,t){if(""===t)return;let i=Object.values(e.subscriptions),s=[this.handleOrderBook,this.handleTrades];for(let r=0;r<s.length;r++)s[r].call(this,e,t,i[0])}}i.d(t,{A:()=>o})},941(e,t,i){"use strict";var s=i(4721),r=i(2641),a=i(1453),o=i(1697);class n extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,cancelAllOrdersWs:!1,cancelOrdersWs:!1,cancelOrderWs:!1,createOrderWs:!1,editOrderWs:!1,fetchBalanceWs:!1,fetchOpenOrdersWs:!1,fetchOrderWs:!1,fetchTradesWs:!1,watchBalance:!0,watchFundingRate:!0,watchFundingRates:!1,watchMyTrades:!0,watchOHLCV:!0,watchOrderBook:!0,watchOrders:!0,watchTicker:!0,watchTickers:!0,watchBidsAsks:!0,watchTrades:!0,watchTradesForSymbols:!1,unWatchTicker:!0,unWatchTickers:!0,unWatchBidsAsks:!0,unWatchOHLCV:!0,unWatchOrderBook:!0,unWatchTrades:!0},urls:{api:{ws:{spot:"wss://wbs-api.mexc.com/ws",swap:"wss://contract.mexc.com/edge"}}},options:{listenKeyRefreshRate:12e5,decompressBinary:!1,timeframes:{"1m":"Min1","5m":"Min5","15m":"Min15","30m":"Min30","1h":"Min60","4h":"Hour4","8h":"Hour8","1d":"Day1","1w":"Week1","1M":"Month1"},watchOrderBook:{snapshotDelay:25,snapshotMaxRetries:3},listenKey:void 0},streaming:{ping:this.ping,keepAlive:8e3},exceptions:{}})}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="ticker:"+i.symbol;if(!0===i.spot){let e="spot@public.aggre.bookTicker.v3.api.pb@100ms@"+i.id;return await this.watchSpotPublic(e,s,t)}{let e={symbol:i.id};return await this.watchSwapPublic("sub.ticker",s,e,t)}}handleTicker(e,t){let i;this.handleBidAsk(e,t);let s=this.safeDictN(t,["d","data","publicAggreBookTicker"]),r=this.safeString2(t,"s","symbol"),a=this.safeInteger2(t,"t","sendTime"),o=this.safeMarket(r),n=o.symbol;if(!0===o.spot)(i=this.parseWsTicker(s,o)).timestamp=a,i.datetime=this.iso8601(a);else{if(void 0===s)return;i=this.parseTicker(s,o)}this.tickers[n]=i,e.resolve(i,"ticker:"+n)}async watchTickers(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0),r=[],o=this.safeString(s,0);void 0!==o&&(i=this.market(o));let[n,d]=this.handleMarketTypeAndParams("watchTickers",i,t),h="spot"===n,c=h?this.urls.api.ws.spot:this.urls.api.ws.swap,l={};if(h)throw new a.NotSupported(this.id+" watchTickers does not support spot markets");l.method="sub.tickers",l.params={},r.push("ticker");let u=await this.watchMultiple(c,r,this.extend(l,d),r);if(h&&this.newUpdates){let e={},t=this.safeString(u,"symbol");return void 0!==t&&(e[t]=u),e}return this.filterByArray(this.tickers,"symbol",s)}handleTickers(e,t){let i=this.safeList2(t,"data","d",[]),s=this.safeString(t,"c",""),r=this.safeString(t,"s"),a=this.safeMarket(r),o=s.startsWith("spot"),n=void 0===r?o:a.spot,d="";!0===n&&(d="spot:");let h=d+"ticker",c=[];for(let t=0;t<i.length;t++){let s,r=i[t],o=(s=!0===n?this.parseWsTicker(r,a):this.parseTicker(r)).symbol;void 0!==o&&(this.tickers[o]=s),c.push(s);let d="ticker:"+o;e.resolve(s,d)}e.resolve(c,h)}parseWsTicker(e,t){let i=this.safeString(e,"s"),s=this.safeInteger(e,"t"),r=this.safeString(e,"p");return this.safeTicker({info:e,symbol:this.safeSymbol(i,t),timestamp:s,datetime:this.iso8601(s),open:void 0,high:this.safeNumber(e,"h"),low:this.safeNumber(e,"l"),close:r,last:r,bid:this.safeNumber2(e,"b","bidPrice"),bidVolume:this.safeNumber2(e,"B","bidQuantity"),ask:this.safeNumber2(e,"a","askPrice"),askVolume:this.safeNumber2(e,"A","askQuantity"),vwap:void 0,previousClose:void 0,change:void 0,percentage:this.safeNumber(e,"tr"),average:void 0,baseVolume:this.safeNumber(e,"v"),quoteVolume:this.safeNumber(e,"q")},t)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!1,!0);if(void 0===i)throw new a.ArgumentsRequired(this.id+" watchBidsAsks required symbols argument");let s=this.requireValue(this.marketsForSymbols(i),"watchBidsAsks() markets is required"),[r,o]=this.handleMarketTypeAndParams("watchBidsAsks",s[0],t),n="spot"===r;if(!n)throw new a.NotSupported(this.id+" watchBidsAsks only support spot market");let d=[],h=[];for(let e=0;e<i.length;e++){if(n){let t=this.market(i[e]);h.push("spot@public.aggre.bookTicker.v3.api.pb@100ms@"+t.id)}d.push("bidask:"+i[e])}let c=this.urls.api.ws.spot,l=await this.watchMultiple(c,d,this.extend({method:"SUBSCRIPTION",params:h},o),d);if(this.newUpdates){let e={},t=this.safeString(l,"symbol");return void 0!==t&&(e[t]=l),e}return this.filterByArray(this.bidsasks,"symbol",i)}handleBidAsk(e,t){let i=this.parseWsBidAsk(t),s=this.safeString(i,"symbol");void 0!==s&&(this.bidsasks[s]=i,e.resolve(i,"bidask:"+s))}parseWsBidAsk(e,t){let i=this.safeDict(e,"d"),s=this.safeString(e,"s"),r=this.safeMarket(s,t),a=this.safeString(r,"symbol"),o=this.safeInteger(e,"t");return this.safeTicker({symbol:a,timestamp:o,datetime:this.iso8601(o),ask:this.safeNumber(i,"a"),askVolume:this.safeNumber(i,"A"),bid:this.safeNumber(i,"b"),bidVolume:this.safeNumber(i,"B"),info:e},r)}async watchSpotPublic(e,t,i={}){let s=this.safeBool(i,"unsubscribed",!1),r=this.omit(i,["unsubscribed"]),a=this.urls.api.ws.spot,o="SUBSCRIPTION";!0===s&&(o="UNSUBSCRIPTION");let n={method:o,params:[e]};return await this.watch(a,t,this.extend(n,r),t)}async watchSpotPrivate(e,t,i={}){this.checkRequiredCredentials();let s=await this.authenticate(e),r=this.safeString(this.urls.api.ws,"spot");if(void 0===r)throw new a.ExchangeError(this.id+" watchSpotPrivate() has no spot websocket url");return await this.watch(r+"?listenKey="+s,t,this.extend({method:"SUBSCRIPTION",params:[e]},i),e)}async watchSwapPublic(e,t,i,s={}){let r=this.urls.api.ws.swap,a=this.extend({method:e,param:i},s);return await this.watch(r,t,a,t)}async watchSwapPrivate(e,t={}){this.checkRequiredCredentials();let i="login",r=this.urls.api.ws.swap,a=this.milliseconds().toString(),o=this.apiKey+a,n=this.hmac(this.encode(o),this.encode(this.secret),s.sc),d={method:i,param:{apiKey:this.apiKey,signature:n,reqTime:a}},h=this.extend(d,t);return await this.watch(r,e,h,i)}async watchOHLCV(e,t="1m",i,s,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=o.symbol,d=this.safeDict(this.options,"timeframes",{}),h=this.safeString(d,t),c="candles:"+n+":"+t;if(!0===o.spot){let e="spot@public.kline.v3.api.pb@"+o.id+"@"+h;a=await this.watchSpotPublic(e,c,r)}else{let e={symbol:o.id,interval:h};a=await this.watchSwapPublic("sub.kline",c,e,r)}a=this.requireValue(a,"watchOHLCV() ohlcv is required");let l=s;return this.newUpdates&&(l=a.getLimit(n,s)),this.filterBySinceLimit(a,i,l,0,!0)}handleOHLCV(e,t){let i,s,r;if("publicSpotKline"in t){s=this.symbol(this.safeString(t,"symbol"));let e=this.safeDict(t,"publicSpotKline",{}),a=this.safeString(e,"interval");r=this.findTimeframe(a,this.options.timeframes),i=this.parseWsOHLCV(e,this.safeMarket(s))}else{let e=this.safeDict2(t,"d","data",{}),a=this.safeDict(e,"k",e),o=this.safeString2(a,"i","interval"),n=this.safeDict(this.options,"timeframes",{});r=this.findTimeframe(o,n);let d=this.safeString2(t,"s","symbol"),h=this.safeMarket(d);s=h.symbol,i=this.parseWsOHLCV(a,h)}let a="candles:"+s+":"+r,n=this.safeDict(this.ohlcvs,s,{});this.ohlcvs[s]=n;let d=this.safeValue(n,r);if(void 0===d){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);d=new o.TG(e),void 0!==r&&(n[r]=d)}d.append(i),e.resolve(d,a)}parseWsOHLCV(e,t){let i=this.safeNumber2(e,"v","volume");return void 0===t||this.safeBool(t,"spot",!1)||void 0!==i||(i=this.safeNumber2(e,"q","v")),[this.safeTimestamp2(e,"t","windowStart"),this.safeNumber2(e,"o","openingPrice"),this.safeNumber2(e,"h","highestPrice"),this.safeNumber2(e,"l","lowestPrice"),this.safeNumber2(e,"c","closingPrice"),i]}async watchOrderBook(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a="orderbook:"+r.symbol;if(!0===r.spot){let[e,t]=this.handleOptionStringAndParams(i,"watchOrderBook","frequency","100ms"),o="spot@public.aggre.depth.v3.api.pb@"+e+"@"+r.id;s=await this.watchSpotPublic(o,a,t)}else{let e={symbol:r.id};s=await this.watchSwapPublic("sub.depth",a,e,i)}return(s=this.requireValue(s,"watchOrderBook() orderbook is required")).limit()}handleOrderBookSubscription(e,t){let i=this.safeString(t,"msg","").split("@"),s=this.safeString(i,2),r=this.safeSymbol(s);this.orderbooks[r]=this.orderBook({})}getCacheIndex(e,t){let i=this.safeInteger(e,"nonce"),s=this.safeDict(t,0),r=this.safeIntegerN(s,["r","version","fromVersion"]);if(void 0===i||void 0===r||i<r-1)return -1;for(let e=0;e<t.length;e++){let s=this.safeDict(t,e),r=this.safeIntegerN(s,["r","version","fromVersion"]);if(void 0!==r&&r>=i)return e}return t.length}handleOrderBook(e,t){let i=this.safeDictN(t,["d","data","publicAggreDepths"]),s=this.safeString2(t,"s","symbol"),r=this.safeSymbol(s),a="orderbook:"+r,o=this.safeDict(e.subscriptions,a),n=this.safeInteger(o,"limit");r in this.orderbooks||(this.orderbooks[r]=this.orderBook());let d=this.orderbooks[r],h=this.safeInteger(d,"nonce"),c=!1;if(void 0===h){d.cache.length===this.handleOption("watchOrderBook","snapshotDelay",25)&&this.spawn(this.loadOrderBook,e,a,r,n,{}),d.cache.push(i);return}try{this.handleBookDelta(d,i);let e=this.safeIntegerN(t,["t","ts","sendTime"]);d.timestamp=e,d.datetime=this.iso8601(e)}catch(t){delete e.subscriptions[a],e.reject(t,a),c=!0}c||e.resolve(d,a)}handleBooksideDelta(e,t){for(let i=0;i<t.length;i++){let s=t[i];if(Array.isArray(s))e.storeArray(s);else{let t=this.safeFloat2(s,"p","price"),i=this.safeFloat2(s,"v","quantity");e.store(t,i)}}}handleBookDelta(e,t){let i=this.safeInteger(e,"nonce"),s=this.safeIntegerN(t,["r","version","fromVersion"]);if(void 0!==s&&void 0!==i&&s<i)return;e.nonce=s;let r=this.safeList(t,"asks",[]),a=this.safeList(t,"bids",[]),o=e.asks,n=e.bids;this.handleBooksideDelta(o,r),this.handleBooksideDelta(n,a)}async watchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n="trades:"+o;if(!0===a.spot){let e="spot@public.aggre.deals.v3.api.pb@100ms@"+a.id;r=await this.watchSpotPublic(e,n,s)}else{let e={symbol:a.id};r=await this.watchSwapPublic("sub.deal",n,e,s)}r=this.requireValue(r,"watchTrades() trades is required");let d=i;return this.newUpdates&&(d=r.getLimit(o,i)),this.filterBySinceLimit(r,t,d,"timestamp",!0)}handleTrades(e,t){let i=this.safeString2(t,"s","symbol"),s=this.safeMarket(i),r=s.symbol,a="trades:"+r,n=this.safeValue(this.trades,r);if(void 0===n){let e=this.safeInteger(this.options,"tradesLimit",1e3);n=new o.I3(e),this.trades[r]=n}let d=this.safeDictN(t,["d","publicAggreDeals"]),h=this.safeList2(d,"deals","dealsList",[d]);void 0===d&&(h=this.safeList(t,"data",[]));for(let e=0;e<h.length;e++){let t;t=!0===s.spot?this.parseWsTrade(h[e],s):this.parseTrade(h[e],s),n.append(t)}e.resolve(n,a)}async watchMyTrades(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o="myTrades";void 0!==e&&(r=this.market(e));let n=void 0!==r?this.safeString(r,"symbol"):void 0;void 0!==e&&(o=o+":"+n);let[d,h]=this.handleMarketTypeAndParams("watchMyTrades",r,s);a="spot"===d?await this.watchSpotPrivate("spot@private.deals.v3.api.pb",o,h):await this.watchSwapPrivate(o,h),a=this.requireValue(a,"watchMyTrades() trades is required");let c=i;return this.newUpdates&&(c=a.getLimit(n,i)),this.filterBySymbolSinceLimit(a,n,t,c,!0)}handleMyTrade(e,t,i){let s,r="myTrades",a=this.safeDictN(t,["d","data","privateDeals"]),n=this.safeString(a,"symbol"),d=this.safeString2(t,"s","symbol",n),h=this.safeMarket(d),c=h.symbol;if(!0===h.spot)s=this.parseWsTrade(a,h);else{if(void 0===a)return;s=this.parseTrade(a,h)}let l=this.myTrades;if(void 0===l){let e=this.safeInteger(this.options,"tradesLimit",1e3);l=new o.Pt(e),this.myTrades=l}l.append(s),e.resolve(l,r),e.resolve(l,r+":"+c)}parseWsTrade(e,t){let i=this.safeInteger2(e,"T","time"),s=this.safeString2(e,"t","tradeId");void 0===i&&(i=this.safeInteger(e,"t"),s=void 0);let r=this.safeString2(e,"p","price"),a=this.safeString2(e,"v","quantity"),o=this.safeString2(e,"S","tradeType"),n="sell";"1"===o&&(n="buy");let d=this.safeInteger(e,"m"),h=this.safeString2(e,"n","feeAmount"),c=this.safeString2(e,"N","feeCurrency");return this.safeTrade({info:e,id:s,order:this.safeString2(e,"i","orderId"),timestamp:i,datetime:this.iso8601(i),symbol:this.safeSymbol(void 0,t),type:void 0,side:n,takerOrMaker:void 0!==d&&0!==d?"maker":"taker",price:r,amount:a,cost:this.safeString(e,"amount"),fee:{cost:h,currency:this.safeCurrencyCode(c)}},t)}async watchOrders(e,t,i,s={}){let r,a;void 0===this.markets&&await this.loadMarkets();let o="orders";void 0!==e&&(r=this.market(e));let n=void 0!==r?this.safeString(r,"symbol"):void 0;void 0!==e&&(o=o+":"+n);let[d,h]=this.handleMarketTypeAndParams("watchOrders",r,s);a="spot"===d?await this.watchSpotPrivate("spot@private.orders.v3.api.pb",o,h):await this.watchSwapPrivate(o,h),a=this.requireValue(a,"watchOrders() orders is required");let c=i;return this.newUpdates&&(c=a.getLimit(n,i)),this.filterBySymbolSinceLimit(a,n,t,c,!0)}handleOrder(e,t){let i,s="orders",r=this.safeDictN(t,["d","data","privateOrders"]),a=this.safeString(r,"symbol"),n=this.safeString2(t,"s","symbol",a),d=this.safeMarket(n),h=d.symbol;if(!0===d.spot){i=this.parseWsOrder(r,d);let e=this.safeInteger(t,"sendTime");void 0!==e&&(i.lastTradeTimestamp=e)}else{if(void 0===r)return;i=this.parseOrder(r,d)}let c=this.orders;if(void 0===c){let e=this.safeInteger(this.options,"ordersLimit",1e3);c=new o.Pt(e),this.orders=c}c.append(i),e.resolve(c,s),e.resolve(c,s+":"+h)}parseWsOrder(e,t){let i,s=this.safeInteger(e,"createTime"),r=this.safeString(e,"tradeType"),a=this.safeString2(e,"status","state"),o=this.safeString(e,"orderType"),n=this.safeString(e,"N");return void 0!==n&&(i={currency:n,cost:void 0}),this.safeOrder({id:this.safeString(e,"id"),clientOrderId:this.safeString(e,"clientId"),timestamp:s,datetime:this.iso8601(s),lastTradeTimestamp:void 0,status:this.parseWsOrderStatus(a,t),symbol:this.safeSymbol(void 0,t),type:this.parseWsOrderType(o),timeInForce:this.parseWsTimeInForce(o),side:"1"===r?"buy":"sell",price:this.safeString(e,"price"),stopPrice:this.safeString2(e,"triggerPrice","P"),triggerPrice:this.safeString2(e,"triggerPrice","P"),average:this.safeString(e,"avgPrice"),amount:this.safeString(e,"quantity"),cost:this.safeString(e,"amount"),filled:this.safeString(e,"cumulativeQuantity"),remaining:this.safeString(e,"remainQuantity"),fee:i,trades:void 0,info:e},t)}parseWsOrderStatus(e,t){return this.safeString({0:"open",1:"open",2:"closed",3:"open",4:"canceled",5:"closed",NEW:"open",CANCELED:"canceled",EXECUTED:"closed",FAILED:"rejected"},e,e)}parseWsOrderType(e){return this.safeString({1:"limit",2:"limit",3:void 0,4:void 0,5:"market",100:"limit",101:"limit",102:"limit"},e)}parseWsTimeInForce(e){return this.safeString({1:"GTC",2:"PO",3:"IOC",4:"FOK",5:"GTC",100:"GTC",101:"GTC",102:"GTC"},e)}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleMarketTypeAndParams("watchBalance",void 0,e),s="balance:"+t;return"spot"===t?await this.watchSpotPrivate("spot@private.account.v3.api.pb",s,i):await this.watchSwapPrivate(s,i)}handleBalance(e,t){let i=this.safeString(t,"channel"),s="swap";"spot@private.account.v3.api.pb"===i&&(s="spot");let r="balance:"+s,a=this.safeDictN(t,["data","privateAccount"]),o=this.safeInteger2(t,"ts","createTime"),n=this.safeInteger2(a,"time",o);s in this.balance||(this.balance[s]={}),this.balance[s].info=a,this.balance[s].timestamp=n,this.balance[s].datetime=this.iso8601(n);let d=this.safeString2(a,"currency","vcoinName"),h=this.safeCurrencyCode(d),c=this.account();c.free=this.safeString2(a,"balanceAmount","availableBalance"),c.used=this.safeString2(a,"frozenBalance","frozenAmount"),void 0!==h&&(this.balance[s][h]=c),this.balance[s]=this.safeBalance(this.balance[s]),e.resolve(this.balance[s],r)}async watchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="fundingRate:"+i.symbol,r={symbol:i.id};return await this.watchSwapPublic("sub.funding.rate",s,r,t)}async unWatchFundingRate(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="unsubscribe:fundingRate:"+s.symbol,a={symbol:s.id};i=this.urls.api.ws.swap,this.spawn(this.watchSwapPublic,"unsub.funding.rate",r,a,t);let o=this.client(i);this.handleUnsubscriptions(o,[r])}handleFundingRate(e,t){let i=this.safeDict(t,"data",{}),s=this.parseFundingRate(i),r=s.symbol;void 0!==r&&(this.fundingRates[r]=s),e.resolve(s,"fundingRate:"+r)}async unWatchTicker(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a="unsubscribe:ticker:"+r.symbol;if(!0===r.spot)s="spot@public.aggre.bookTicker.v3.api.pb@100ms@"+r.id,i=this.urls.api.ws.spot,t.unsubscribed=!0,this.spawn(this.watchSpotPublic,s,a,t);else{s="unsub.ticker";let e={symbol:r.id};i=this.urls.api.ws.swap,this.spawn(this.watchSwapPublic,s,a,e,t)}let o=this.client(i);this.handleUnsubscriptions(o,[a])}async unWatchTickers(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0),r=[],o=this.safeString(s,0);void 0!==o&&(i=this.market(o));let[n,d]=this.handleMarketTypeAndParams("watchTickers",i,t),h="spot"===n,c=h?this.urls.api.ws.spot:this.urls.api.ws.swap,l={};if(h)throw new a.NotSupported(this.id+" watchTickers does not support spot markets");l.method="unsub.tickers",l.params={},r.push("unsubscribe:ticker");let u=this.client(c);this.watchMultiple(c,r,this.extend(l,d),r),this.handleUnsubscriptions(u,r)}async unWatchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0,!1,!0);if(void 0===i)throw new a.ArgumentsRequired(this.id+" watchBidsAsks required symbols argument");let s=this.requireValue(this.marketsForSymbols(i),"unWatchBidsAsks() markets is required"),[r,o]=this.handleMarketTypeAndParams("watchBidsAsks",s[0],t),n="spot"===r;if(!n)throw new a.NotSupported(this.id+" watchBidsAsks only support spot market");let d=[],h=[];for(let e=0;e<i.length;e++){if(n){let t=this.market(i[e]);h.push("spot@public.aggre.bookTicker.v3.api.pb@100ms@"+t.id)}d.push("unsubscribe:bidask:"+i[e])}let c=this.urls.api.ws.spot,l=this.client(c);this.watchMultiple(c,d,this.extend({method:"UNSUBSCRIPTION",params:h},o),d),this.handleUnsubscriptions(l,d)}async unWatchOHLCV(e,t="1m",i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o=this.safeDict(this.options,"timeframes",{}),n=this.safeString(o,t),d="unsubscribe:candles:"+a+":"+t;if(!0===r.spot){s=this.urls.api.ws.spot;let e="spot@public.kline.v3.api.pb@"+r.id+"@"+n;i.unsubscribed=!0,this.spawn(this.watchSpotPublic,e,d,i)}else{s=this.urls.api.ws.swap;let e={symbol:r.id,interval:n};this.spawn(this.watchSwapPublic,"unsub.kline",d,e,i)}let h=this.client(s);this.handleUnsubscriptions(h,[d])}async unWatchOrderBook(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="unsubscribe:orderbook:"+s.symbol;if(!0===s.spot){i=this.urls.api.ws.spot;let[e,a]=this.handleOptionStringAndParams(t,"watchOrderBook","frequency","100ms"),o="spot@public.aggre.depth.v3.api.pb@"+e+"@"+s.id;a.unsubscribed=!0,this.spawn(this.watchSpotPublic,o,r,a)}else{i=this.urls.api.ws.swap;let e={symbol:s.id};this.spawn(this.watchSwapPublic,"unsub.depth",r,e,t)}let a=this.client(i);this.handleUnsubscriptions(a,[r])}async unWatchTrades(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="unsubscribe:trades:"+s.symbol;if(!0===s.spot){i=this.urls.api.ws.spot;let e="spot@public.aggre.deals.v3.api.pb@100ms@"+s.id;t.unsubscribed=!0,this.spawn(this.watchSpotPublic,e,r,t)}else{i=this.urls.api.ws.swap;let e={symbol:s.id};this.spawn(this.watchSwapPublic,"unsub.deal",r,e,t)}let a=this.client(i);this.handleUnsubscriptions(a,[r])}handleUnsubscriptions(e,t){for(let i=0;i<t.length;i++){let s=t[i],r=s.replace("unsubscribe:","");if(this.cleanUnsubscription(e,r,s),s.indexOf("ticker")>=0){let e=s.replace("unsubscribe:ticker:","");if(e.indexOf("unsubscribe")>=0){let e=Object.keys(this.tickers);for(let t=0;t<e.length;t++)delete this.tickers[e[t]]}else e in this.tickers&&delete this.tickers[e]}else if(s.indexOf("bidask")>=0){let e=s.replace("unsubscribe:bidask:","");e in this.bidsasks&&delete this.bidsasks[e]}else if(s.indexOf("candles")>=0){let e=s.split(":"),t=this.safeString(e,2);e.length>4&&(t+=":"+this.safeString(e,3)),void 0!==t&&t in this.ohlcvs&&delete this.ohlcvs[t]}else if(s.indexOf("orderbook")>=0){let e=s.replace("unsubscribe:orderbook:","");e in this.orderbooks&&delete this.orderbooks[e]}else if(s.indexOf("trades")>=0){let e=s.replace("unsubscribe:trades:","");e in this.trades&&delete this.trades[e]}else if(s.indexOf("fundingRate")>=0){let e=s.replace("unsubscribe:fundingRate:","");e in this.fundingRates&&delete this.fundingRates[e]}}}async authenticate(e,t={}){let i,s=this.safeString(this.options,"listenKey");if(void 0!==s)return s;let r=this.client(this.urls.api.ws.spot),a="authenticate:listenKey";if(!0===this.safeBool(this.options,"listenKeyFetching",!1))return await r.future(a),this.safeString(this.options,"listenKey");this.options.listenKeyFetching=!0,r.future(a);try{i=await this.spotPrivatePostUserDataStream(t)}catch(e){throw this.options.listenKeyFetching=!1,r.reject(e,a),e}this.options.listenKeyFetching=!1,s=this.safeString(i,"listenKey"),this.options.listenKey=s,r.resolve(s,a);let o=this.safeInteger(this.options,"listenKeyRefreshRate",12e5);return this.delay(o,this.keepAliveListenKey,s,t),s}async keepAliveListenKey(e,t={}){if(void 0!==e)try{await this.spotPrivatePutUserDataStream(this.extend({listenKey:e},t));let i=this.safeInteger(this.options,"listenKeyRefreshRate",12e5);this.delay(i,this.keepAliveListenKey,e,t)}catch(r){let t=this.safeString(this.urls.api.ws,"spot");if(void 0===t)throw new a.ExchangeError(this.id+" keepAliveListenKey() has no spot websocket url");let i=t+"?listenKey="+e,s=this.client(i);this.options.listenKey=void 0,s.reject(r),delete this.clients[i]}}handlePong(e,t){return e.lastPong=this.milliseconds(),t}handleSubscriptionStatus(e,t){let i=this.safeString(t,"msg","");if("PONG"===i)this.handlePong(e,t);else if(i.indexOf("@")>-1){let s=i.split("@"),r=this.safeString(s,1),a={"public.increase.depth.v3.api":this.handleOrderBookSubscription,"public.aggre.depth.v3.api.pb":this.handleOrderBookSubscription},o=this.safeValue(a,r);void 0!==o&&o.call(this,e,t)}}handleProtobufMessage(e,t){let i=this.safeString(t,"channel","").split("@"),s=this.safeString(i,1);return"public.kline.v3.api.pb"===s?this.handleOHLCV(e,t):"public.aggre.deals.v3.api.pb"===s?this.handleTrades(e,t):"public.aggre.bookTicker.v3.api.pb"===s?this.handleTicker(e,t):"public.aggre.depth.v3.api.pb"===s?this.handleOrderBook(e,t):"private.account.v3.api.pb"===s?this.handleBalance(e,t):"private.deals.v3.api.pb"===s?this.handleMyTrade(e,t):"private.orders.v3.api.pb"===s&&this.handleOrder(e,t),!0}handleMessage(e,t){let i;if("string"==typeof t&&"Invalid listen key"===t){let t=new a.AuthenticationError(this.id+" invalid listen key");e.reject(t);return}if(this.isBinaryMessage(t)){let i=this.decodeProtoMsg(t);this.handleProtobufMessage(e,i);return}if("msg"in t)return void this.handleSubscriptionStatus(e,t);let s=this.safeString(t,"c");if(void 0===s)i=this.safeString(t,"channel");else{let e=s.split("@");i=this.safeString(e,1,"")}let r={"public.deals.v3.api":this.handleTrades,"push.deal":this.handleTrades,"public.kline.v3.api":this.handleOHLCV,"push.kline":this.handleOHLCV,"public.bookTicker.v3.api":this.handleTicker,"public.miniTicker.v3.api":this.handleTicker,"public.miniTickers.v3.api":this.handleTickers,"push.ticker":this.handleTicker,"push.tickers":this.handleTickers,"public.increase.depth.v3.api":this.handleOrderBook,"push.depth":this.handleOrderBook,"private.orders.v3.api":this.handleOrder,"push.personal.order":this.handleOrder,"private.account.v3.api":this.handleBalance,"push.personal.asset":this.handleBalance,"private.deals.v3.api":this.handleMyTrade,"push.personal.order.deal":this.handleMyTrade,pong:this.handlePong,"push.funding.rate":this.handleFundingRate};void 0!==i&&i in r&&r[i].call(this,e,t)}ping(e){return{method:"ping"}}}i.d(t,{A:()=>n})},5931(e,t,i){"use strict";var s=i(7468),r=i(6479),a=i(1453),o=i(1697),n=i(7749),d=i(1093);class h extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchMyTrades:!0,watchOHLCV:!0,watchOrderBook:!0,watchOrders:!0,watchTicker:!0,watchTickers:!0,watchBidsAsks:!0,watchTrades:!0,watchTradesForSymbols:!1,watchPositions:!0},urls:{api:{ws:{public:"wss://ws-evm.orderly.org/ws/stream",private:"wss://ws-private-evm.orderly.org/v2/ws/private/stream"}},test:{ws:{public:"wss://testnet-ws-evm.orderly.org/ws/stream",private:"wss://testnet-ws-private-evm.orderly.org/v2/ws/private/stream"}}},requiredCredentials:{apiKey:!0,secret:!0,accountId:!0},options:{tradesLimit:1e3,ordersLimit:1e3,requestId:{},watchPositions:{fetchPositionsSnapshot:!0,awaitPositionsSnapshot:!0}},streaming:{ping:this.ping,keepAlive:1e4},exceptions:{ws:{exact:{"Auth is needed.":a.AuthenticationError}}}})}requestId(e){let t=this.safeDict(this.options,"requestId",{}),i=this.safeInteger(t,e,0),s=this.sum(i,1);return this.options.requestId[e]=s,s}async watchPublic(e,t){let i="OqdphuyCtYWxwzhxyLLjOWNdFP7sQt8RPWzmb5xY";void 0!==this.accountId&&""!==this.accountId&&(i=this.accountId);let s=this.safeString(this.urls.api.ws,"public");if(void 0===s)throw new a.ExchangeError(this.id+" watchPublic() has no public websocket url");let r=s+"/"+i,o={id:this.requestId(r)},n=this.extend(o,t);return await this.watch(r,e,n,e,o)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e).id+"@orderbook",r=this.extend({event:"subscribe",topic:s},i);return(await this.watchPublic(s,r)).limit()}handleOrderBook(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"symbol"),r=this.safeMarket(s).symbol,a=this.safeString(t,"topic");r in this.orderbooks||(this.orderbooks[r]=this.orderBook());let o=this.orderbooks[r],n=this.safeInteger(t,"ts"),d=this.parseOrderBook(i,r,n,"bids","asks");o.reset(d),e.resolve(o,a)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e).id+"@ticker",s=this.extend({event:"subscribe",topic:i},t);return await this.watchPublic(i,s)}parseWsTicker(e,t){return this.safeTicker({symbol:this.safeSymbol(void 0,t),timestamp:void 0,datetime:void 0,high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:this.safeString(e,"open"),close:this.safeString(e,"close"),last:void 0,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"volume"),quoteVolume:this.safeString(e,"amount"),info:e},t)}handleTicker(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(t,"topic"),r=this.safeString(i,"symbol"),a=this.safeMarket(r);i.date=this.safeInteger(t,"ts");let o=this.parseWsTicker(i,a);return o.symbol=a.symbol,this.tickers[a.symbol]=o,e.resolve(o,s),t}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s="tickers",r=this.extend({event:"subscribe",topic:s},t),a=await this.watchPublic(s,r);return this.filterByArray(a,"symbol",i)}handleTickers(e,t){let i=this.safeString(t,"topic"),s=this.safeList(t,"data",[]),r=this.safeInteger(t,"ts"),a=[];for(let e=0;e<s.length;e++){let t=this.safeString(s[e],"symbol"),i=this.safeMarket(t),o=this.parseWsTicker(this.extend(s[e],{date:r}),i);this.tickers[i.symbol]=o,a.push(o)}e.resolve(a,i)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s="bbos",r=this.extend({event:"subscribe",topic:s},t),a=await this.watchPublic(s,r);return this.filterByArray(a,"symbol",i)}handleBidAsk(e,t){let i=this.safeString(t,"topic"),s=this.safeList(t,"data",[]),r=this.safeInteger(t,"ts"),a=[];for(let e=0;e<s.length;e++){let t=this.parseWsBidAsk(this.extend(s[e],{ts:r})),i=t.symbol;void 0!==i&&(this.tickers[i]=t),a.push(t)}e.resolve(a,i)}parseWsBidAsk(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeString(s,"symbol"),a=this.safeInteger(e,"ts");return this.safeTicker({symbol:r,timestamp:a,datetime:this.iso8601(a),ask:this.safeString(e,"ask"),askVolume:this.safeString(e,"askSize"),bid:this.safeString(e,"bid"),bidVolume:this.safeString(e,"bidSize"),info:e},s)}async watchOHLCV(e,t="1m",i,s,r={}){if(void 0===this.markets&&await this.loadMarkets(),"1m"!==t&&"5m"!==t&&"15m"!==t&&"30m"!==t&&"1h"!==t&&"1d"!==t&&"1w"!==t&&"1M"!==t)throw new a.NotSupported(this.id+" watchOHLCV timeframe argument must be 1m, 5m, 15m, 30m, 1h, 1d, 1w, 1M");let o=this.market(e),n=this.safeString(this.timeframes,t,t),d=o.id+"@kline_"+n,h=this.extend({event:"subscribe",topic:d},r),c=await this.watchPublic(d,h),l=s;return this.newUpdates&&(l=c.getLimit(o.symbol,s)),this.filterBySinceLimit(c,i,l,0,!0)}handleOHLCV(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(t,"topic"),r=this.safeString(i,"symbol"),a=this.safeMarket(r).symbol,n=this.safeString(i,"type"),d=this.findTimeframe(n);if(void 0===d)return;let h=[this.safeInteger(i,"startTime"),this.safeNumber(i,"open"),this.safeNumber(i,"high"),this.safeNumber(i,"low"),this.safeNumber(i,"close"),this.safeNumber(i,"volume")];this.ohlcvs[a]=this.safeDict(this.ohlcvs,a,{});let c=this.safeValue(this.safeDict(this.ohlcvs,a),d);if(void 0===c){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);c=new o.TG(e),this.ohlcvs[a][d]=c}let l=this.ohlcvs[a][d];l.append(h),e.resolve(l,s)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o=r.id+"@trade",n=this.extend({event:"subscribe",topic:o},s),d=await this.watchPublic(o,n),h=i;return this.newUpdates&&(h=d.getLimit(r.symbol,i)),this.filterBySymbolSinceLimit(d,a,t,h,!0)}handleTrade(e,t){let i=this.safeString(t,"topic"),s=this.safeInteger(t,"ts"),r=this.safeDict(t,"data",{}),a=this.safeString(r,"symbol"),n=this.safeMarket(a),d=n.symbol,h=this.parseWsTrade(this.extend(r,{timestamp:s}),n);if(!(d in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3),t=new o.I3(e);this.trades[d]=t}let c=this.trades[d];c.append(h),this.trades[d]=c,e.resolve(c,i)}parseWsTrade(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=r.symbol,o=this.safeString2(e,"executedPrice","price"),d=this.safeString2(e,"executedQuantity","size"),h=n.Y.stringMul(o,d),c=this.safeStringLower(e,"side"),l=this.safeInteger(e,"timestamp"),u=this.safeBool(e,"maker");void 0!==u&&(i=u?"maker":"taker");let f={},p=this.safeString(e,"fee");return void 0!==p&&(f={cost:p,currency:this.safeCurrencyCode(this.safeString(e,"feeAsset"))}),this.safeTrade({id:this.safeString(e,"tradeId"),timestamp:l,datetime:this.iso8601(l),symbol:a,side:c,price:o,amount:d,cost:h,order:this.safeString(e,"orderId"),takerOrMaker:i,type:this.safeStringLower(e,"type"),fee:f,info:e},r)}handleAuth(e,t){let i="authenticated";if(!0===this.safeBool(t,"success"))this.safeValue(e.futures,"authenticated").resolve(!0);else{let s=new a.AuthenticationError(this.json(t));e.reject(s,i),i in e.subscriptions&&delete e.subscriptions.authenticated}}async authenticate(e={}){this.checkRequiredCredentials();let t=this.safeString(this.urls.api.ws,"private");if(void 0===t)throw new a.ExchangeError(this.id+" authenticate() has no private websocket url");let i=t+"/"+this.accountId,r=this.client(i),o="authenticated",n=r.reusableFuture(o);if(void 0===this.safeValue(r.subscriptions,o)){let t=this.nonce().toString(),r=this.secret;r.indexOf("ed25519:")>=0&&(r=r.split("ed25519:")[1]);let a=(0,d.q4)(this.encode(t),this.base58ToBinary(r),s.ev),n={event:"auth",params:{orderly_key:this.apiKey,sign:a,timestamp:t}},h=this.extend(n,e);this.watch(i,o,h,o)}return await n}async watchPrivate(e,t,i={}){await this.authenticate(i);let s=this.safeString(this.urls.api.ws,"private");if(void 0===s)throw new a.ExchangeError(this.id+" watchPrivate() has no private websocket url");let r=s+"/"+this.accountId,o={id:this.requestId(r)},n=this.extend(o,t);return await this.watch(r,e,n,e,o)}async watchPrivateMultiple(e,t,i={}){await this.authenticate(i);let s=this.safeString(this.urls.api.ws,"private");if(void 0===s)throw new a.ExchangeError(this.id+" watchPrivateMultiple() has no private websocket url");let r=s+"/"+this.accountId,o={id:this.requestId(r)},n=this.extend(o,t);return await this.watchMultiple(r,e,n,e,o)}async watchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.safeBool2(s,"stop","trigger",!1),o="executionreport";!0===a&&(o="algoexecutionreport");let n=this.omit(s,["stop","trigger"]),d=o;if(void 0!==e){let t=this.market(e);d+=":"+(r=this.safeString(t,"symbol"))}let h={event:"subscribe",topic:o},c=this.extend(h,n),l=await this.watchPrivate(d,c),u=i;return this.newUpdates&&(u=l.getLimit(r,i)),this.filterBySymbolSinceLimit(l,r,t,u,!0)}async watchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.safeBool2(s,"stop","trigger",!1),o="executionreport";!0===a&&(o="algoexecutionreport");let n=this.omit(s,"stop"),d="myTrades";if(void 0!==e){let t=this.market(e);d+=":"+(r=this.safeString(t,"symbol"))}let h={event:"subscribe",topic:o},c=this.extend(h,n),l=await this.watchPrivate(d,c),u=i;return this.newUpdates&&(u=l.getLimit(r,i)),this.filterBySymbolSinceLimit(l,r,t,u,!0)}parseWsOrder(e,t){let i=this.safeString(e,"orderId"),s=this.safeString(e,"symbol"),r=this.safeMarket(s,t).symbol,a=this.safeInteger(e,"timestamp"),o={cost:this.safeString(e,"totalFee"),currency:this.safeString(e,"feeAsset")},d=this.safeString(e,"price"),h=this.safeNumber(e,"price"),c=this.safeNumber(e,"avgPrice");n.Y.stringEq(d,"0")&&void 0!==c&&(h=c);let l=this.safeString(e,"quantity"),u=this.safeStringLower(e,"side"),f=this.safeStringLower(e,"type"),p=this.safeNumber(e,"totalExecutedQuantity"),m=this.safeString(e,"totalExecutedQuantity"),g=l;n.Y.stringGe(l,m)&&(g=n.Y.stringSub(g,m));let v=this.safeString(e,"status"),y=this.parseOrderStatus(v),b=this.safeString(e,"clientOrderId"),w=this.safeNumber(e,"triggerPrice");return this.safeOrder({info:e,symbol:r,id:i,clientOrderId:b,timestamp:a,datetime:this.iso8601(a),lastTradeTimestamp:a,type:f,timeInForce:void 0,postOnly:void 0,side:u,price:h,stopPrice:w,triggerPrice:w,amount:l,cost:void 0,average:void 0,filled:p,remaining:g,status:y,fee:o,trades:void 0})}handleOrderUpdate(e,t){let i=this.safeString(t,"topic"),s=this.safeValue(t,"data");if(Array.isArray(s))for(let t=0;t<s.length;t++){let r=s[t],a=this.safeString(s,"tradeId");void 0!==(void 0===a?void 0:this.omitZero(a))&&this.handleMyTrade(e,r),this.handleOrder(e,r,i)}else{let t=this.safeString(s,"tradeId");void 0!==(void 0===t?void 0:this.omitZero(t))&&this.handleMyTrade(e,s),this.handleOrder(e,s,i)}}handleOrder(e,t,i){let s=this.parseWsOrder(t),r=this.safeString(s,"symbol"),a=this.safeString(s,"id");if(void 0!==r){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}let t=this.orders,n=this.safeDict(t.hashmap,r,{}),d=void 0===a?void 0:this.safeDict(n,a);if(void 0!==d){let e=this.safeValue(d,"fee");void 0!==e&&(s.fee=e);let t=this.safeList(d,"fees");void 0!==t&&(s.fees=t),s.trades=this.safeList(d,"trades",[]),s.timestamp=this.safeInteger(d,"timestamp"),s.datetime=this.safeString(d,"datetime")}t.append(s),e.resolve(this.orders,i);e.resolve(this.orders,i+":"+r)}}handleMyTrade(e,t){let i="myTrades",s=this.safeString(t,"symbol"),r=this.safeMarket(s),a=r.symbol,n=this.parseWsTrade(t,r),d=this.myTrades;if(void 0===d){let e=this.safeInteger(this.options,"tradesLimit",1e3);d=new o.Pt(e),this.myTrades=d}d.append(n),e.resolve(d,i),e.resolve(d,i+":"+a)}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=[],o=this.marketSymbols(e);if(void 0===o||this.isEmpty(o))r.push("positions");else for(let e=0;e<o.length;e++){let t=o[e];r.push("positions::"+t)}let n=this.safeString(this.urls.api.ws,"private");if(void 0===n)throw new a.ExchangeError(this.id+" watchPositions() has no private websocket url");let d=n+"/"+this.accountId,h=this.client(d);this.setPositionsCache(h,o);let c=this.handleOption("watchPositions","fetchPositionsSnapshot",!0),l=this.handleOption("watchPositions","awaitPositionsSnapshot",!0);if(!0===c&&!0===l&&void 0===this.positions){let e=await h.future("fetchPositionsSnapshot");return this.filterBySymbolsSinceLimit(e,o,t,i,!0)}let u=await this.watchPrivateMultiple(r,{event:"subscribe",topic:"position"},s);return this.newUpdates?u:this.filterBySymbolsSinceLimit(this.positions,o,t,i,!0)}setPositionsCache(e,t,i){if(!0===this.handleOption("watchPositions","fetchPositionsSnapshot",!1)){let t="fetchPositionsSnapshot";t in e.futures||(e.future(t),this.spawn(this.loadPositionsSnapshot,e,t))}else this.positions=new o.Hk}async loadPositionsSnapshot(e,t){let i=await this.fetchPositions();this.positions=new o.Hk;let s=this.positions;for(let e=0;e<i.length;e++){let t=i[e],r=this.safeString(t,"contracts","0");n.Y.stringGt(r,"0")&&s.append(t)}t in e.futures&&(e.futures[t].resolve(s),e.resolve(s,"positions"))}handlePositions(e,t){let i=this.safeDict(t,"data",{}),s=this.safeList(i,"positions",[]);void 0===this.positions&&(this.positions=new o.Hk);let r=this.positions,a=[];for(let t=0;t<s.length;t++){let i=this.safeDict(s,t),o=this.safeString(i,"symbol"),n=this.safeMarket(o),d=this.parseWsPosition(i,n);a.push(d),r.append(d);let h="positions::"+n.symbol;e.resolve(d,h)}e.resolve(a,"positions")}parseWsPosition(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=this.safeString(e,"positionQty");i=n.Y.stringGt(a,"0")?"long":"short";let o=this.safeString(r,"contractSize"),d=this.safeString(e,"markPrice"),h=this.safeInteger(e,"timestamp"),c=this.safeString(e,"averageOpenPrice"),l=this.safeString(e,"unsettledPnl");a=n.Y.stringAbs(a);let u=n.Y.stringMul(a,d);return this.safePosition({info:e,id:void 0,symbol:this.safeString(r,"symbol"),timestamp:h,datetime:this.iso8601(h),lastUpdateTimestamp:void 0,initialMargin:void 0,initialMarginPercentage:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,entryPrice:this.parseNumber(c),notional:this.parseNumber(u),leverage:void 0,unrealizedPnl:this.parseNumber(l),contracts:this.parseNumber(a),contractSize:this.parseNumber(o),marginRatio:void 0,liquidationPrice:this.safeNumber(e,"estLiqPrice"),markPrice:this.parseNumber(d),lastPrice:void 0,collateral:void 0,marginMode:"cross",marginType:void 0,side:i,percentage:void 0,hedged:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t="balance",i=this.extend({event:"subscribe",topic:t},e);return await this.watchPrivate(t,i)}handleBalance(e,t){let i=this.safeDict(t,"data",{}),s=this.safeDict(i,"balances",{}),r=Object.keys(s),a=this.safeInteger(t,"ts");this.balance.info=i,this.balance.timestamp=a,this.balance.datetime=this.iso8601(a);for(let e=0;e<r.length;e++){let t=r[e],i=this.safeDict(s,t),a=this.safeCurrencyCode(t),o=this.account();void 0!==a&&a in this.balance&&(o=this.balance[a]);let d=this.safeString(i,"holding"),h=this.safeString(i,"frozen");o.total=d,o.used=h,o.free=n.Y.stringSub(d,h),void 0!==a&&(this.balance[a]=o)}this.balance=this.safeBalance(this.balance),e.resolve(this.balance,"balance")}handleErrorMessage(e,t){if(!("success"in t)||!0===this.safeBool(t,"success"))return!1;let i=this.safeString(t,"errorMsg");try{if(void 0!==i){let e=this.id+" "+this.json(t);this.throwExactlyMatchedException(this.exceptions.exact,i,e)}return!1}catch(t){if(t instanceof a.AuthenticationError){let i="authenticated";e.reject(t,i),i in e.subscriptions&&delete e.subscriptions[i]}else e.reject(t);return!0}}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;let i={ping:this.handlePing,pong:this.handlePong,subscribe:this.handleSubscribe,orderbook:this.handleOrderBook,ticker:this.handleTicker,tickers:this.handleTickers,kline:this.handleOHLCV,trade:this.handleTrade,auth:this.handleAuth,executionreport:this.handleOrderUpdate,algoexecutionreport:this.handleOrderUpdate,position:this.handlePositions,balance:this.handleBalance,bbos:this.handleBidAsk},s=this.safeString(t,"event"),r=void 0===s?void 0:this.safeValue(i,s);if(void 0!==r)return void r.call(this,e,t);let a=this.safeString(t,"topic");if(void 0!==a){if(void 0!==(r=this.safeValue(i,a)))return void r.call(this,e,t);let s=a.split("@");if(2===s.length){let a=this.safeString(s,1);if(void 0===a)return;if(void 0!==(r=this.safeValue(i,a)))return void r.call(this,e,t);let o=a.split("_");if(2===s.length){let s=this.safeString(o,0);void 0!==(r=void 0===s?void 0:this.safeValue(i,s))&&r.call(this,e,t)}}}}ping(e){return{event:"ping"}}async pong(e,t){await e.send({event:"pong"})}handlePing(e,t){this.spawn(this.pong,e,t)}handlePong(e,t){return e.lastPong=this.milliseconds(),t}handleSubscribe(e,t){return t}}i.d(t,{A:()=>h})},9671(e,t,i){"use strict";var s=i(6555),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchOHLCV:!0,watchTicker:!0,watchTickers:!0},urls:{api:{ws:"wss://trade.mudrex.com/fapi/v1/price/ws/linear"}},options:{broker:"42ce8902-8585-448c-a1e8-0371a6ca7ca8"},streaming:{ping:this.ping,keepAlive:2e4}})}ping(e){return{id:this.requestId(),method:"PING"}}requestId(){let e=this.sum(this.safeInteger(this.options,"correlationId",0),1);return this.options.correlationId=e,e}setBrokerHeaders(){let e=this.safeString(this.options,"broker");if(void 0===e)return;let t=this.safeDict(this.options,"ws",{}),i=this.safeDict(t,"options",{}),s=this.safeDict(i,"headers",{});s["Partner-Id"]=e,i.headers=s,t.options=i,this.options.ws=t}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="ticker:"+i.symbol,r=this.urls.api.ws;this.setBrokerHeaders();let a=void 0!==i.baseId?i.baseId:"",o=void 0!==i.quoteId?i.quoteId:"",n=a.toLowerCase()+o.toLowerCase(),d={id:this.requestId(),method:"SUBSCRIBE",params:["ticker@1s"],assets:[n]},h=this.extend(d,t);return await this.watch(r,s,h,s)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=[],r=[];if(void 0!==i)for(let e=0;e<i.length;e++){let t=this.market(i[e]);s.push("ticker:"+t.symbol);let a=void 0!==t.baseId?t.baseId:"",o=void 0!==t.quoteId?t.quoteId:"";r.push(a.toLowerCase()+o.toLowerCase())}let a=this.urls.api.ws;this.setBrokerHeaders();let o={id:this.requestId(),method:"SUBSCRIBE",params:["ticker@1s"],assets:r},n=this.extend(o,t),d=await this.watchMultiple(a,s,n,s);if(this.newUpdates){let e={},t=this.safeString(d,"symbol");return void 0!==t&&(e[t]=d),e}return this.filterByArrayTickers(this.tickers,"symbol",i)}async watchOHLCV(e,t="1m",i,s,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=o.symbol,d=this.safeString(a,"price"),h=this.omit(a,"price"),c=this.safeString(this.timeframes,t,t);if("1s"!==c&&"1m"!==c)throw new r.NotSupported(this.id+" watchOHLCV() supports 1s and 1m timeframes only");let l="kline";"mark"===d&&(l="markKline");let u=void 0!==o.baseId?o.baseId:"",f=void 0!==o.quoteId?o.quoteId:"",p=l+"@"+c+"@"+u.toLowerCase()+f.toLowerCase(),m=this.urls.api.ws;this.setBrokerHeaders();let g={id:this.requestId(),method:"SUBSCRIBE",params:[p]},v=this.extend(g,h),y=await this.watch(m,p,v,p),b=s;return this.newUpdates&&(b=y.getLimit(n,s)),this.filterBySinceLimit(y,i,b,0,!0)}handleMessage(e,t){if("PONG"===this.safeString(t,"method"))return;if(void 0!==this.safeDict(t,"error"))return void this.handleErrorMessage(e,t);let i=this.safeString(t,"stream");void 0!==i&&(i.indexOf("kline")>=0||i.indexOf("markKline")>=0?this.handleOHLCV(e,t):i.indexOf("ticker")>=0&&this.handleTicker(e,t))}handleErrorMessage(e,t){let i=this.safeDict(t,"error",{}),s=this.safeString(i,"code"),a=this.safeString(i,"msg"),o=this.id+" "+a;if("429"===s)throw new r.RateLimitExceeded(o);throw new r.ExchangeError(o)}handleOHLCV(e,t){let i=this.safeString(t,"stream");if(void 0===i)return;let s=i.split("@")[1],r=this.findTimeframe(s),o=this.safeDict(t,"data",{}),n=this.safeString(o,"s");if(void 0===n)return;let d=this.safeMarket(n.toUpperCase()).symbol,h=[this.safeTimestamp(o,"t"),this.safeNumber(o,"o"),this.safeNumber(o,"h"),this.safeNumber(o,"l"),this.safeNumber(o,"c"),this.safeNumber(o,"v")];this.ohlcvs[d]=this.safeDict(this.ohlcvs,d,{});let c=this.safeValue(this.safeDict(this.ohlcvs,d),r);if(void 0===c){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);c=new a.TG(e),void 0!==d&&void 0!==r&&(this.ohlcvs[d][r]=c)}c.append(h),e.resolve(c,i)}handleTicker(e,t){let i=this.safeList(t,"data",[]);for(let t=0;t<i.length;t++){let s=i[t],r=this.safeString(s,"s");if(void 0===r)continue;let a=this.safeMarket(r.toUpperCase()).symbol,o=this.milliseconds(),n=this.safeNumber(s,"p"),d=this.safeTicker({symbol:a,timestamp:o,datetime:this.iso8601(o),last:n,close:n,info:s});this.tickers[a]=d;let h="ticker:"+a;e.resolve(d,h),e.resolve(d,"tickers")}}}i.d(t,{A:()=>o})},2472(e,t,i){"use strict";var s=i(4302);class r extends s.A{describe(){return this.deepExtend(super.describe(),{id:"myokx",name:"MyOKX (EEA)",hostname:"eea.okx.com",urls:{api:{rest:"https://{hostname}",ws:"wss://wseea.okx.com:8443/ws/v5"},www:"https://my.okx.com",doc:"https://my.okx.com/docs-v5/en/#overview",fees:"https://my.okx.com/pages/products/fees.html",referral:{url:"https://www.my.okx.com/join/CCXT2023",discount:.2},test:{ws:"wss://wseeapap.okx.com:8443/ws/v5"}},has:{swap:!1,future:!1,option:!1}})}}i.d(t,{A:()=>r})},2934(e,t,i){"use strict";var s=i(1586),r=i(1453),a=i(1697),o=i(7749),n=i(6834);class d extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,cancelAllOrdersWs:!0,cancelOrderWs:!0,cancelOrdersWs:!0,createOrderWs:!0,editOrderWs:!0,watchBalance:!1,watchBidsAsks:!0,watchFundingRate:!1,watchFundingRates:!1,watchLiquidations:!1,watchLiquidationsForSymbols:!1,watchMyTrades:!0,unWatchBidsAsks:!0,unWatchMyTrades:!0,unWatchOHLCV:!0,unWatchOHLCVForSymbols:!0,unWatchOrderBook:!0,unWatchOrderBookForSymbols:!0,unWatchOrders:!0,unWatchPositions:!0,unWatchTicker:!0,unWatchTickers:!0,unWatchTrades:!0,unWatchTradesForSymbols:!0,watchOHLCV:!0,watchOHLCVForSymbols:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOrders:!0,watchPositions:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!0},streaming:{ping:this.ping,keepAlive:3e4},options:{tradesLimit:1e3,requestId:0},urls:{api:{ws:{gateway:"wss://gateway.prod.nado.xyz/ws/v2",subscriptions:"wss://gateway.prod.nado.xyz/v1/subscribe"}},test:{ws:{gateway:"wss://gateway.test.nado.xyz/ws/v2",subscriptions:"wss://gateway.test.nado.xyz/v1/subscribe"}}}})}requestId(){let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,e}async watchTrades(e,t,i,s={}){await this.loadMarkets();let r=this.market(e),a="trade:"+r.symbol,o=await this.watchPublic("trade",r,a,s),n=i;return this.newUpdates&&(n=o.getLimit(r.symbol,i)),this.filterBySinceLimit(o,t,n,"timestamp",!0)}async unWatchTrades(e,t={}){return await this.loadMarkets(),await this.unWatchTradesForSymbols([e],t)}async watchTradesForSymbols(e,t,i,s={}){if(await this.loadMarkets(),0===e.length)throw new r.ArgumentsRequired(this.id+" watchTradesForSymbols() requires a non-empty array of symbols");let a=this.marketSymbols(e,void 0,!1,!0,!0),o=[],n=[];for(let e=0;e<a.length;e++){let t=this.market(a[e]);o.push(t),n.push("trade:"+t.symbol)}let d=await this.watchPublicMultiple("trade",o,n,s),h=this.safeDict(d,0),c=this.safeString(h,"symbol"),l=i;return this.newUpdates&&(l=d.getLimit(c,i)),this.filterBySinceLimit(d,t,l,"timestamp",!0)}async unWatchTradesForSymbols(e,t={}){if(await this.loadMarkets(),0===e.length)throw new r.ArgumentsRequired(this.id+" unWatchTradesForSymbols() requires a non-empty array of symbols");let i=this.marketSymbols(e,void 0,!1,!0,!0),s=[],a=[];for(let e=0;e<i.length;e++){let t=this.market(i[e]);s.push(t),a.push("trade:"+t.symbol)}return await this.unWatchPublicMultiple("trade",s,a,t)}async watchOrderBook(e,t,i={}){await this.loadMarkets();let s=this.market(e),r="orderbook:"+s.symbol;if(!(s.symbol in this.orderbooks)){let i=await this.fetchOrderBook(e,t);this.orderbooks[s.symbol]=this.orderBook(i,t)}return(await this.watchPublic("book_depth",s,r,i)).limit()}async unWatchOrderBook(e,t={}){return await this.loadMarkets(),await this.unWatchOrderBookForSymbols([e],t)}async watchOrderBookForSymbols(e,t,i={}){if(await this.loadMarkets(),0===e.length)throw new r.ArgumentsRequired(this.id+" watchOrderBookForSymbols() requires a non-empty array of symbols");let s=this.marketSymbols(e,void 0,!1,!0,!0),a=[],o=[];for(let e=0;e<s.length;e++){let i=s[e],r=this.market(i),n="orderbook:"+r.symbol;if(a.push(r),o.push(n),!(r.symbol in this.orderbooks)){let e=await this.fetchOrderBook(i,t);this.orderbooks[r.symbol]=this.orderBook(e,t)}}return(await this.watchPublicMultiple("book_depth",a,o,i)).limit()}async unWatchOrderBookForSymbols(e,t={}){if(await this.loadMarkets(),0===e.length)throw new r.ArgumentsRequired(this.id+" unWatchOrderBookForSymbols() requires a non-empty array of symbols");let i=this.marketSymbols(e,void 0,!1,!0,!0),s=[],a=[];for(let e=0;e<i.length;e++){let t=this.market(i[e]);s.push(t),a.push("orderbook:"+t.symbol)}return await this.unWatchPublicMultiple("book_depth",s,a,t)}async watchOHLCV(e,t="1m",i,s,r={}){await this.loadMarkets();let a=this.market(e),o="ohlcv:"+t+":"+a.symbol,n={granularity:this.safeInteger(this.timeframes,t,this.parseTimeframe(t))},d=(await this.watchPublic("latest_candlestick",a,o,this.extend(n,r)))[2],h=s;return this.newUpdates&&(h=d.getLimit(a.symbol,s)),this.filterBySinceLimit(d,i,h,0,!0)}async watchOHLCVForSymbols(e,t,i,s={}){if(0===e.length||!Array.isArray(e[0]))throw new r.ArgumentsRequired(this.id+" watchOHLCVForSymbols() requires a an array of symbols and timeframes, like  [['BTC/USDT0:USDT0', '1m'], ['ETH/USDT0:USDT0', '5m']]");await this.loadMarkets();let a=[],o=[],n=[];for(let t=0;t<e.length;t++){let i=this.safeList(e,t),r=this.safeString(i,0),d=this.safeString(i,1,"1m"),h=this.market(r);a.push(h),o.push("ohlcv:"+d+":"+h.symbol),n.push(this.extend({granularity:this.safeInteger(this.timeframes,d,this.parseTimeframe(d))},s))}let[d,h,c]=await this.watchPublicMultiple("latest_candlestick",a,o,s,n),l=i;this.newUpdates&&(l=c.getLimit(d,i));let u=this.filterBySinceLimit(c,t,l,0,!0);return this.createOHLCVObject(d,h,u)}async unWatchOHLCV(e,t="1m",i={}){return await this.loadMarkets(),await this.unWatchOHLCVForSymbols([[e,t]],i)}async unWatchOHLCVForSymbols(e,t={}){if(0===e.length||!Array.isArray(e[0]))throw new r.ArgumentsRequired(this.id+" unWatchOHLCVForSymbols() requires a an array of symbols and timeframes, like  [['BTC/USDT0:USDT0', '1m'], ['ETH/USDT0:USDT0', '5m']]");await this.loadMarkets();let i=[],s=[],a=[];for(let r=0;r<e.length;r++){let o=this.safeList(e,r),n=this.safeString(o,0),d=this.safeString(o,1,"1m"),h=this.market(n);i.push(h),s.push("ohlcv:"+d+":"+h.symbol),a.push(this.extend({granularity:this.safeInteger(this.timeframes,d,this.parseTimeframe(d))},t))}return await this.unWatchPublicMultiple("latest_candlestick",i,s,t,a)}async watchTicker(e,t={}){await this.loadMarkets();let i=this.symbol(e);return(await this.watchTickers([i],t))[i]}async unWatchTicker(e,t={}){return await this.loadMarkets(),await this.unWatchTickers([e],t)}async watchTickers(e,t={}){let i;await this.loadMarkets();let s=this.marketSymbols(e,void 0,!0,!0,!0),r="ticker",a="all_bbo";void 0!==s&&1===s.length&&(r="ticker:"+(i=this.market(s[0])).symbol,a="best_bid_offer");let o=await this.watchPublic(a,i,r,t);if(this.newUpdates){if("ticker"===r)return this.filterByArray(o,"symbol",s);let e={},t=this.safeString(o,"symbol");return void 0!==t&&(e[t]=o),e}return this.filterByArray(this.tickers,"symbol",s)}async unWatchTickers(e,t={}){let i;await this.loadMarkets();let s=this.marketSymbols(e,void 0,!0,!0,!0),r="ticker",a="all_bbo";return void 0!==s&&1===s.length&&(r="ticker:"+(i=this.market(s[0])).symbol,a="best_bid_offer"),await this.unWatchPublic(a,i,r,t)}async watchBidsAsks(e,t={}){let i;await this.loadMarkets();let s=this.marketSymbols(e,void 0,!0,!0,!0),r="bidask",a="all_bbo";void 0!==s&&1===s.length&&(r="bidask:"+(i=this.market(s[0])).symbol,a="best_bid_offer");let o=await this.watchPublic(a,i,r,t);if(this.newUpdates){if("bidask"===r)return this.filterByArray(o,"symbol",s);let e={},t=this.safeString(o,"symbol");return void 0!==t&&(e[t]=o),e}return this.filterByArray(this.bidsasks,"symbol",s)}async unWatchBidsAsks(e,t={}){let i;await this.loadMarkets();let s=this.marketSymbols(e,void 0,!0,!0,!0),r="bidask",a="all_bbo";return void 0!==s&&1===s.length&&(r="bidask:"+(i=this.market(s[0])).symbol,a="best_bid_offer"),await this.unWatchPublic(a,i,r,t)}async watchOrders(e,t,i,s={}){let r,a,o;this.checkRequiredCredentials(),await this.loadMarkets(),await this.authenticate(this.extend({},s));let n="orders";void 0!==e&&(r=this.market(e),n+=":"+(o=this.safeString(r,"symbol")),a=this.parseToInt(r.id));let[d,h]=this.handleOptionStringAndParams(s,"watchOrders","subaccount","default"),c={type:"order_update",subaccount:this.createSubaccount(this.walletAddress,d),product_id:a},l=await this.watchPrivate("order_update",c,n,h),u=i;return this.newUpdates&&(u=l.getLimit(o,i)),this.filterBySymbolSinceLimit(l,o,t,u,!0)}async unWatchOrders(e,t={}){let i,s;this.checkRequiredCredentials(),await this.loadMarkets(),await this.authenticate(this.extend({},t));let r="orders";void 0!==e&&(r+=":"+(i=this.market(e)).symbol,s=this.parseToInt(i.id));let[a,o]=this.handleOptionStringAndParams(t,"unWatchOrders","subaccount","default"),n={type:"order_update",subaccount:this.createSubaccount(this.walletAddress,a),product_id:s};return await this.unWatchPrivate(n,r,o)}async watchMyTrades(e,t,i,s={}){let r,a,o;this.checkRequiredCredentials(),await this.loadMarkets(),await this.authenticate(this.extend({},s));let n="myTrades";void 0!==e&&(r=this.market(e),n+=":"+(o=this.safeString(r,"symbol")),a=this.parseToInt(r.id));let[d,h]=this.handleOptionStringAndParams(s,"watchMyTrades","subaccount","default"),c={type:"fill",subaccount:this.createSubaccount(this.walletAddress,d),product_id:a},l=await this.watchPrivate("fill",c,n,h),u=i;return this.newUpdates&&(u=l.getLimit(o,i)),this.filterBySymbolSinceLimit(l,o,t,u,!0)}async unWatchMyTrades(e,t={}){let i,s;this.checkRequiredCredentials(),await this.loadMarkets(),await this.authenticate(this.extend({},t));let r="myTrades";void 0!==e&&(r+=":"+(i=this.market(e)).symbol,s=this.parseToInt(i.id));let[a,o]=this.handleOptionStringAndParams(t,"unWatchMyTrades","subaccount","default"),n={type:"fill",subaccount:this.createSubaccount(this.walletAddress,a),product_id:s};return await this.unWatchPrivate(n,r,o)}async watchPositions(e,t,i,s={}){let r;this.checkRequiredCredentials(),await this.loadMarkets(),await this.authenticate(this.extend({},s));let a=this.marketSymbols(e,void 0,!1,!0,!0),o="positions";if(void 0!==a&&1===a.length){let e=this.market(a[0]);o+=":"+e.symbol,r=this.parseToInt(e.id)}let[n,d]=this.handleOptionStringAndParams(s,"watchPositions","subaccount","default"),h={type:"position_change",subaccount:this.createSubaccount(this.walletAddress,n),product_id:r},c=await this.watchPrivate("position_change",h,o,d);return this.newUpdates?c:this.filterBySymbolsSinceLimit(this.positions,a,t,i,!0)}async unWatchPositions(e,t={}){let i;this.checkRequiredCredentials(),await this.loadMarkets(),await this.authenticate(this.extend({},t));let s=this.marketSymbols(e,void 0,!1,!0,!0),r="positions";if(void 0!==s&&1===s.length){let e=this.market(s[0]);r+=":"+e.symbol,i=this.parseToInt(e.id)}let[a,o]=this.handleOptionStringAndParams(t,"unWatchPositions","subaccount","default"),n={type:"position_change",subaccount:this.createSubaccount(this.walletAddress,a),product_id:i};return await this.unWatchPrivate(n,r,o)}async createOrderWs(e,t,i,s,a,o={}){this.checkRequiredCredentials(),await this.loadMarkets();let n=this.market(e),d=this.extend({id:this.requestId()},o),h=this.safeString(d,"id");if(void 0===h)throw new r.ArgumentsRequired(this.id+" ws execute requires params.id");let c=await this.createOrderRequest(e,t,i,s,a,d),l=this.safeDict(c,"place_order",{});if("trigger"in l)throw new r.NotSupported(this.id+" createOrderWs() does not support trigger orders, use createOrder() instead");let u=await this.watchExecuteRequest(h,c);return this.parseOrder(this.extend({place_order:l},u),n)}async editOrderWs(e,t,i,s,a,o,n={}){this.checkRequiredCredentials(),await this.loadMarkets();let d=this.market(t),h=this.extend({id:this.requestId()},n),c=this.safeString(h,"id");if(void 0===c)throw new r.ArgumentsRequired(this.id+" ws execute requires params.id");let l=await this.editOrderRequest(e,t,i,s,a,o,h),u=await this.watchExecuteRequest(c,l),f=this.safeDict(l,"cancel_and_place",{}),p=this.safeDict(f,"place_order",{});return this.parseOrder(this.extend({place_order:p},u),d)}async cancelOrderWs(e,t,i={}){let s=await this.cancelOrdersWs([e],t,i);return this.safeDict(s,0)}async cancelOrdersWs(e,t,i={}){if(this.checkRequiredCredentials(),void 0===t)throw new r.ArgumentsRequired(this.id+" cancelOrdersWs() requires a symbol argument");await this.loadMarkets();let s=this.market(t);if(!0===this.safeBool2(i,"stop","trigger"))throw new r.NotSupported(this.id+" cancelOrdersWs() does not support trigger orders, use cancelOrders() instead");let a=this.extend({id:this.requestId()},i),o=this.safeString(a,"id");if(void 0===o)throw new r.ArgumentsRequired(this.id+" ws execute requires params.id");let n=await this.cancelOrdersRequest(e,t,a),d=await this.watchExecuteRequest(o,n),h=this.safeDict(d,"data",{}),c=this.safeList(h,"cancelled_orders",[]),l=[];for(let e=0;e<c.length;e++)l.push(this.parseOrder(this.extend({status:"canceled"},c[e]),s));return l}async cancelAllOrdersWs(e,t={}){let i;if(this.checkRequiredCredentials(),await this.loadMarkets(),void 0!==e&&(i=this.market(e)),!0===this.safeBool2(t,"stop","trigger"))throw new r.NotSupported(this.id+" cancelAllOrdersWs() does not support trigger orders, use cancelAllOrders() instead");let s=this.extend({id:this.requestId()},t),a=this.safeString(s,"id");if(void 0===a)throw new r.ArgumentsRequired(this.id+" ws execute requires params.id");let o=await this.cancelAllOrdersRequest(e,s),n=await this.watchExecuteRequest(a,o),d=this.safeDict(n,"data",{}),h=this.safeList(d,"cancelled_orders",[]),c=[];for(let e=0;e<h.length;e++)c.push(this.parseOrder(this.extend({status:"canceled"},h[e]),i));return c}async watchExecuteRequest(e,t){if(void 0===e)throw new r.ArgumentsRequired(this.id+" watchExecuteRequest() requires requestIdString");let i=this.urls.api.ws.gateway,s="execute:"+e;return await this.watch(i,s,t,s)}async watchPublic(e,t,i,s={}){let r=this.urls.api.ws.subscriptions,a={type:e};void 0!==t&&(a.product_id=this.parseToInt(t.id));let o={method:"subscribe",stream:this.deepExtend(a,s),id:this.requestId()},n="subscribe:"+this.json(o.stream),d={streamType:e,symbol:this.safeString(t,"symbol")},h=this.client(r);if(void 0===this.safeValue(h.subscriptions,n)){let e=this.safeString(o,"id");h.subscriptions["subscription:"+e]={subscribeHash:n},this.watchMultiple(r,[n],o,[n],d)}return await this.watch(r,i)}async watchPrivate(e,t,i,s={}){let r=this.urls.api.ws.subscriptions,a=this.client(r);if(void 0!==this.safeValue(a.subscriptions,i))return await this.watch(r,i);let o=this.requestId(),n="subscribe:"+i,d={method:"subscribe",stream:this.deepExtend(t,s),id:o};return a.subscriptions["subscription:"+this.numberToString(o)]={subscribeHash:n},this.watchMultiple(r,[n],d,[i],{streamType:e}),await this.watch(r,i)}async unWatchPrivate(e,t,i={}){let s=this.urls.api.ws.subscriptions,r=this.requestId(),a="unsubscribe:"+t,o={method:"unsubscribe",stream:this.deepExtend(e,i),id:r};return this.client(s).subscriptions["unsubscription:"+this.numberToString(r)]={messageHash:t,unsubscribeHash:a},await this.watch(s,a,o,a,{id:r,messageHash:t})}async authenticate(e={}){this.checkRequiredCredentials();let t=this.urls.api.ws.subscriptions,i=this.client(t),s="authenticated",a=this.safeValue(i.subscriptions,s);if(void 0!==a){let e=this.safeValue(i.futures,s);return void 0!==e?await e:a}let[o,n]=this.handleOptionIntegerAndParams(e,"authenticate","recvWindow",5e3),[d,h]=this.handleOptionStringAndParams(n,"authenticate","subaccount","default"),c=this.requestId(),l=this.createSubaccount(this.walletAddress,d),u=this.sum(this.milliseconds(),o),f={sender:l,expiration:this.numberToString(u)},p=await this.queryContracts(),m=this.safeString(p,"chain_id"),g=this.safeString(p,"endpoint_addr");if(void 0===g)throw new r.ExchangeError(this.id+" authenticate() requires endpoint_addr from contracts query");let v=this.signStreamAuthentication(f,m,g);return i.subscriptions["authentication:"+this.numberToString(c)]=s,await this.watch(t,s,this.extend({method:"authenticate",id:c,tx:f,signature:v},h),s)}signStreamAuthentication(e,t,i){let s=this.ethEncodeStructuredData({name:"Nado",version:"0.0.1",chainId:t,verifyingContract:i},{StreamAuthentication:[{name:"sender",type:"bytes32"},{name:"expiration",type:"uint64"}]},e),r="0x"+this.hash(s,n.lY,"hex");return this.signHash(r,this.privateKey)}createPublicSubscriptionRequest(e,t,i,s,r={}){let a={type:t};return void 0!==i&&(a.product_id=this.parseToInt(i.id)),{method:e,stream:this.deepExtend(a,r),id:s}}async watchPublicMultiple(e,t,i,s={},r){let a=this.urls.api.ws.subscriptions,o=this.client(a);for(let n=0;n<i.length;n++){let d=i[n];if(void 0===this.safeValue(o.subscriptions,d)){let i=t[n],d=this.requestId(),h=void 0===r?s:r[n],c=this.createPublicSubscriptionRequest("subscribe",e,i,d,h),l="subscribe:"+this.json(c.stream);if(void 0===this.safeValue(o.subscriptions,l)){let t={streamType:e,symbol:this.safeString(i,"symbol")};o.subscriptions["subscription:"+this.numberToString(d)]={subscribeHash:l},this.watchMultiple(a,[l],c,[l],t)}}}return await this.watchMultiple(a,i,void 0,i)}async unWatchPublic(e,t,i,s={}){let r=this.urls.api.ws.subscriptions,a=this.requestId(),o=this.createPublicSubscriptionRequest("unsubscribe",e,t,a,s),n="unsubscribe:"+i;return this.client(r).subscriptions["unsubscription:"+this.numberToString(a)]={messageHash:i,unsubscribeHash:n},await this.watch(r,n,o,n,{id:a,messageHash:i})}async unWatchPublicMultiple(e,t,i,s={},r){let a=this.urls.api.ws.subscriptions,o=this.client(a),n=[];for(let d=0;d<i.length;d++){let h=i[d],c=this.requestId(),l="unsubscribe:"+h,u=void 0===r?s:r[d],f=this.createPublicSubscriptionRequest("unsubscribe",e,t[d],c,u),p={id:c,messageHash:h};o.subscriptions["unsubscription:"+this.numberToString(c)]={messageHash:h,unsubscribeHash:l},n.push(await this.watchMultiple(a,[l],f,[l],p))}return n}parseWsTimestamp(e,t){let i=this.safeString(e,t);if(void 0!==i)return i.length>13?this.parseToInt(i.slice(0,i.length-6)):this.safeInteger(e,t)}parseWsTrade(e,t){let i,s=this.safeString(e,"product_id"),r=this.safeMarket(s,t),a=this.parseWsTimestamp(e,"timestamp"),o=this.safeBool(e,"is_taker_buyer");return void 0!==o&&(i=o?"buy":"sell"),this.safeTrade({info:e,id:void 0,timestamp:a,datetime:this.iso8601(a),symbol:r.symbol,order:void 0,type:void 0,side:i,takerOrMaker:"taker",price:this.parseX18(this.safeString(e,"price")),amount:this.parseX18(this.safeString(e,"taker_qty")),cost:void 0,fee:void 0},r)}parseWsMyTrade(e,t){let i,s,r,a=this.safeString(e,"product_id"),o=this.safeMarket(a,t),n=this.parseWsTimestamp(e,"timestamp"),d=this.safeBool(e,"is_bid");void 0!==d&&(i=d?"buy":"sell");let h=this.safeBool(e,"is_taker");void 0!==h&&(s=h?"taker":"maker");let c=this.parseX18(this.safeString(e,"fee"));return void 0!==c&&(r={cost:c,currency:o.quote}),this.safeTrade({info:e,id:this.safeString2(e,"id","submission_idx"),timestamp:n,datetime:this.iso8601(n),symbol:o.symbol,order:this.safeString(e,"order_digest"),type:void 0,side:i,takerOrMaker:s,price:this.parseX18(this.safeString(e,"price")),amount:this.parseX18(this.safeString(e,"filled_qty")),cost:void 0,fee:r},o)}handleTrade(e,t){let i=this.safeString(t,"product_id"),s=this.safeMarket(i),r=s.symbol,o="trade:"+r,n=this.safeValue(this.trades,r);if(void 0===n){let e=this.safeInteger(this.options,"tradesLimit",1e3);n=new a.I3(e),this.trades[r]=n}let d=this.parseWsTrade(t,s);n.append(d),e.resolve(n,o)}handleMyTrade(e,t){let i=this.parseWsMyTrade(t);if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new a.Pt(e)}let s=this.myTrades;s.append(i);let r=i.symbol;e.resolve(s,"myTrades"),e.resolve(s,"myTrades:"+r)}handleOHLCV(e,t){let i=this.safeString(t,"product_id"),s=this.safeMarket(i),r=s.symbol,o=this.safeInteger(t,"granularity"),n=this.findTimeframe(o);if(void 0===n)return;r in this.ohlcvs||(this.ohlcvs[r]={});let d=this.safeValue(this.ohlcvs[r],n);if(void 0===d){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);d=new a.TG(e),this.ohlcvs[r][n]=d}let h=this.parseOHLCV(t,s);d.append(h);let c="ohlcv:"+n+":"+r;e.resolve([r,n,d],c)}parseWsOrder(e,t){let i,s,r=this.safeString(e,"product_id"),a=this.safeMarket(r,t),n=this.parseWsTimestamp(e,"timestamp"),d=this.safeString(e,"digest"),h=this.safeString(e,"amount");void 0!==h&&(i=this.parseX18(h));let c=this.parseX18(this.safeString(e,"filled_qty")),l=this.parseX18(this.safeString(e,"filled_price")),u=this.safeString(e,"reason");return"placed"===u?s="open":"filled"===u?(s="open",void 0!==h&&o.Y.stringEq(h,"0")&&(s="closed")):"cancelled"===u&&(s="canceled"),this.safeOrder({info:e,id:d,clientOrderId:void 0,timestamp:n,datetime:this.iso8601(n),lastTradeTimestamp:void 0===c?void 0:n,lastUpdateTimestamp:n,symbol:a.symbol,type:void 0,timeInForce:void 0,postOnly:void 0,side:void 0,price:void 0,stopPrice:void 0,triggerPrice:void 0,amount:void 0,cost:void 0,average:l,filled:c,remaining:i,status:s,fee:void 0,trades:void 0},a)}handleOrder(e,t){let i=this.parseWsOrder(t);if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}let s=this.orders;s.append(i);let r=i.symbol;e.resolve(s,"orders"),e.resolve(s,"orders:"+r)}parseWsPosition(e,t){let i,s,r,a=this.safeString(e,"product_id"),n=this.safeMarket(a,t),d=this.parseWsTimestamp(e,"timestamp"),h=this.safeString(e,"amount"),c=this.safeString(e,"v_quote_amount");if(void 0!==h){o.Y.stringGt(h,"0")?i="long":o.Y.stringLt(h,"0")&&(i="short");let e=o.Y.stringAbs(h);s=this.parseX18(e),void 0===c||o.Y.stringEquals(e,"0")||(r=this.parseNumber(o.Y.stringDiv(o.Y.stringAbs(c),e)))}return this.safePosition({info:e,id:void 0,symbol:n.symbol,timestamp:d,datetime:this.iso8601(d),isolated:this.safeBool(e,"isolated"),hedged:!1,side:i,contracts:s,contractSize:this.safeNumber(n,"contractSize"),entryPrice:r,markPrice:void 0,notional:void 0,leverage:void 0,collateral:void 0,initialMargin:void 0,initialMarginPercentage:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,unrealizedPnl:void 0,liquidationPrice:void 0,marginMode:void 0,marginRatio:void 0,percentage:void 0})}handlePosition(e,t){let i=this.safeString(t,"product_id"),s=this.safeMarket(i);if(!this.safeBool(s,"contract",!1))return;let r=this.parseWsPosition(t,s);void 0===this.positions&&(this.positions=new a.Hk);let o=this.positions;if(void 0===this.safeString(r,"side")){let e=this.extend({},r);e.side="long",o.append(e);let t=this.extend({},r);t.side="short",o.append(t)}else o.append(r);let n=r.symbol;e.resolve(o,"positions"),e.resolve(o,"positions:"+n)}parseWsBidAsk(e,t){let i=this.safeString(e,"product_id"),s=this.safeMarket(i,t),r=this.parseWsTimestamp(e,"timestamp");return this.safeTicker({symbol:s.symbol,timestamp:r,datetime:this.iso8601(r),ask:this.parseX18(this.safeString(e,"ask_price")),askVolume:this.parseX18(this.safeString(e,"ask_qty")),bid:this.parseX18(this.safeString(e,"bid_price")),bidVolume:this.parseX18(this.safeString(e,"bid_qty")),info:e},s)}handleBidAsk(e,t){let i=this.parseWsBidAsk(t),s=this.safeString(i,"symbol");if(void 0===s)return;this.bidsasks[s]=i,this.tickers[s]=i;let r={};r[s]=i,e.resolve(i,"bidask:"+s),e.resolve(i,"ticker:"+s),e.resolve(r,"bidask"),e.resolve(r,"ticker")}parseWsAllBidsAsks(e){let t=this.safeInteger(e,"time"),i=this.safeDict(e,"bbos",{}),s=Object.keys(i),r={};for(let e=0;e<s.length;e++){let a=s[e],n=this.safeMarket(a),d=this.safeDict(i,a,{}),h=this.safeString(d,"bid"),c=this.safeString(d,"ask"),l="170141183460469231731687303715884105727";if(o.Y.stringGt(h,"0")&&o.Y.stringGt(c,"0")&&!o.Y.stringEquals(h,l)&&!o.Y.stringEquals(c,l)){let e=this.safeTicker({symbol:n.symbol,timestamp:t,datetime:this.iso8601(t),ask:this.parseX18(c),bid:this.parseX18(h),info:d},n);r[n.symbol]=e}}return r}handleAllBidsAsks(e,t){let i=this.parseWsAllBidsAsks(t),s=Object.keys(i);for(let t=0;t<s.length;t++){let r=s[t],a=i[r];this.bidsasks[r]=a,this.tickers[r]=a,e.resolve(a,"bidask:"+r),e.resolve(a,"ticker:"+r)}e.resolve(i,"bidask"),e.resolve(i,"ticker")}handleDelta(e,t){let i=[this.parseX18(this.safeString(t,0)),this.parseX18(this.safeString(t,1))];e.storeArray(i)}handleOrderBook(e,t){let i=this.safeString(t,"product_id"),s=this.safeMarket(i).symbol;if(!(s in this.orderbooks))return;let a=this.orderbooks[s],o="orderbook:"+s,n=this.safeString(a,"maxTimestamp"),d=this.safeString(t,"last_max_timestamp");if(void 0!==n&&void 0!==d&&n!==d){let t=Object.keys(e.subscriptions);for(let i=0;i<t.length;i++){let r=t[i],a=this.safeDict(e.subscriptions,r),o=this.safeString(a,"streamType"),n=this.safeString(a,"symbol");"book_depth"===o&&n===s&&delete e.subscriptions[r]}void 0!==this.safeValue(e.subscriptions,o)&&delete e.subscriptions[o],delete this.orderbooks[s];let i=new r.InvalidNonce(this.id+" watchOrderBook received invalid nonce");e.reject(i,o);return}let h=this.safeList(t,"asks",[]),c=this.safeList(t,"bids",[]);this.handleDeltas(a.asks,h),this.handleDeltas(a.bids,c);let l=this.parseWsTimestamp(t,"max_timestamp");a.symbol=s,a.timestamp=l,a.datetime=this.iso8601(l),a.maxTimestamp=this.safeString(t,"max_timestamp"),e.resolve(a,o)}handleExecuteResponse(e,t){let i=this.safeString(t,"id");if(void 0===i)return;let s="execute:"+i;void 0!==this.safeValue(e.subscriptions,s)&&delete e.subscriptions[s],e.resolve(t,s)}handleSubscription(e,t){let i=this.safeString(t,"id"),s=this.safeDict(e.subscriptions,"subscription:"+i);if(void 0!==s){let r=this.safeString(s,"subscribeHash");delete e.subscriptions["subscription:"+i],e.resolve(t,r)}}handleAuthentication(e,t){let i=this.safeString(t,"id"),s=this.safeString(e.subscriptions,"authentication:"+i);void 0!==s&&(delete e.subscriptions["authentication:"+i],e.subscriptions[s]=!0,e.resolve(t,s))}handleUnsubscription(e,t){let i=this.safeString(t,"id"),s=this.safeDict(e.subscriptions,"unsubscription:"+i);if(void 0!==s){let r=this.safeString(s,"messageHash"),a=this.safeString(s,"unsubscribeHash");delete e.subscriptions["unsubscription:"+i],void 0!==r&&(this.cleanUnsubscription(e,r,a),this.handleUnsubscriptionCache(r)),e.resolve(t,a);return}let r=Object.keys(e.subscriptions);for(let s=0;s<r.length;s++){let a=r[s],o=this.safeDict(e.subscriptions,a);if(this.safeString(o,"id")!==i)continue;let n=this.safeString(o,"messageHash");void 0!==n&&(this.cleanUnsubscription(e,n,a),this.handleUnsubscriptionCache(n)),e.resolve(t,a);return}}handleUnsubscriptionCache(e){if(void 0!==e)if(0===e.indexOf("trade:")){let t=e.replace("trade:","");t in this.trades&&delete this.trades[t]}else if(0===e.indexOf("orderbook:")){let t=e.replace("orderbook:","");t in this.orderbooks&&delete this.orderbooks[t]}else if(0===e.indexOf("ohlcv:")){let t=e.split(":"),i=this.safeString(t,1),s=this.safeString(t,2);void 0!==s&&void 0!==i&&s in this.ohlcvs&&i in this.ohlcvs[s]&&delete this.ohlcvs[s][i]}else if(0===e.indexOf("ticker:")){let t=e.replace("ticker:","");t in this.tickers&&delete this.tickers[t]}else if("ticker"===e){let e=Object.keys(this.tickers);for(let t=0;t<e.length;t++)delete this.tickers[e[t]]}else if(0===e.indexOf("bidask:")){let t=e.replace("bidask:","");t in this.bidsasks&&delete this.bidsasks[t]}else if("bidask"===e){let e=Object.keys(this.bidsasks);for(let t=0;t<e.length;t++)delete this.bidsasks[e[t]]}else 0===e.indexOf("orders")?this.orders=void 0:0===e.indexOf("myTrades")?this.myTrades=void 0:0===e.indexOf("positions")&&(this.positions=void 0)}ping(e){let t=this.urls.api.ws.gateway;if(e.url!==t)return{method:"ping",id:this.requestId(),client_time:this.numberToString(this.milliseconds())}}handlePong(e,t){let i=this.safeDict(t,"result",{});return e.lastPong=this.safeInteger(i,"server_time",this.milliseconds()),t}handleErrorMessage(e,t){let i=this.safeValue(t,"error"),s=this.safeString(t,"status");if(void 0===i&&"failure"!==s)return!1;let a=new r.ExchangeError(this.id+" "+this.json(t)),o=this.safeString(t,"id");if(void 0!==o){let t="execute:"+o;if(void 0!==this.safeValue(e.subscriptions,t))return delete e.subscriptions[t],e.reject(a,t),!0}let n=this.safeDict(e.subscriptions,"subscription:"+o);if(void 0!==n){let t=this.safeString(n,"subscribeHash");delete e.subscriptions["subscription:"+o],e.reject(a,t)}else e.reject(a);return!0}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;let i=this.safeString(t,"id"),s="result"in t,r=this.safeDict(t,"result");if("pong"===this.safeString(r,"method"))return void this.handlePong(e,t);if(void 0!==this.safeString(t,"request_type"))return void this.handleExecuteResponse(e,t);if(void 0!==i&&s)return void 0!==this.safeString(e.subscriptions,"authentication:"+i)?void this.handleAuthentication(e,t):void 0!==this.safeDict(e.subscriptions,"subscription:"+i)?void this.handleSubscription(e,t):void 0===r?void this.handleUnsubscription(e,t):void this.handleSubscription(e,t);let a=this.safeString(t,"type"),o={trade:this.handleTrade,all_bbo:this.handleAllBidsAsks,best_bid_offer:this.handleBidAsk,book_depth:this.handleOrderBook,fill:this.handleMyTrade,latest_candlestick:this.handleOHLCV,order_update:this.handleOrder,position_change:this.handlePosition},n=this.safeValue(o,a);void 0!==n&&n.call(this,e,t)}}i.d(t,{A:()=>d})},4825(e,t,i){"use strict";var s=i(8573),r=i(1697);class a extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchOrderBook:!0,watchTrades:!0,watchTradesForSymbols:!1,watchTicker:!0,watchOHLCV:!0},urls:{test:{ws:"wss://ndaxmarginstaging.cdnhop.net:10456/WSAdminGatewa/"},api:{ws:"wss://api.ndax.io/WSGateway"}}})}requestId(){let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,e}async watchTicker(e,t={}){let i=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="SubscribeLevel1",a=r+":"+s.id,o=this.urls.api.ws,n=this.requestId(),d={OMSId:i,InstrumentId:this.safeInteger(s,"id")},h={m:0,i:n,n:r,o:this.json(d)},c=this.extend(h,t);return await this.watch(o,a,c,a)}handleTicker(e,t){let i=this.safeDict(t,"o",{}),s=this.parseTicker(i),r=s.symbol,a=this.market(r);void 0!==r&&(this.tickers[r]=s);let o="SubscribeLevel1:"+a.id;e.resolve(s,o)}async watchTrades(e,t,i,s={}){let r=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n="SubscribeTrades",d=n+":"+a.id,h=this.urls.api.ws,c=this.requestId(),l={OMSId:r,InstrumentId:this.safeInteger(a,"id"),IncludeLastCount:100},u={m:0,i:c,n:n,o:this.json(l)},f=this.extend(u,s),p=await this.watch(h,d,f,d),m=i;return this.newUpdates&&(m=p.getLimit(o,i)),this.filterBySinceLimit(p,t,m,"timestamp",!0)}handleTrades(e,t){let i=this.safeList(t,"o",[]),s={};for(let e=0;e<i.length;e++){let t=this.parseTrade(i[e]),a=t.symbol,o=void 0===a?void 0:this.safeValue(this.trades,a);if(void 0===o){let e=this.safeInteger(this.options,"tradesLimit",1e3);o=new r.I3(e)}o.append(t),void 0!==a&&(this.trades[a]=o),void 0!==a&&(s[a]=!0)}let a=Object.keys(s);for(let t=0;t<a.length;t++){let i=a[t],s="SubscribeTrades:"+this.market(i).id,r=this.safeValue(this.trades,i);e.resolve(r,s)}}async watchOHLCV(e,t="1m",i,s,r={}){let a=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=o.symbol,d="SubscribeTicker",h=d+":"+t+":"+o.id,c=this.urls.api.ws,l=this.requestId(),u={OMSId:a,InstrumentId:this.safeInteger(o,"id"),Interval:parseInt(this.safeString(this.timeframes,t,t)),IncludeLastCount:100},f={m:0,i:l,n:d,o:this.json(u)},p=this.extend(f,r),m=await this.watch(c,h,p,h),g=s;return this.newUpdates&&(g=m.getLimit(n,s)),this.filterBySinceLimit(m,i,g,0,!0)}handleOHLCV(e,t){let i=this.safeList(t,"o",[]),s={};for(let e=0;e<i.length;e++){let t=this.safeList(i,e),r=this.safeString(t,8),a=this.safeMarket(r).symbol;void 0!==r&&(s[r]={}),this.ohlcvs[a]=this.safeDict(this.ohlcvs,a,{});let o=Object.keys(this.timeframes);for(let e=0;e<o.length;e++){let i=o[e],n=1e3*parseInt(this.safeString(this.timeframes,i,i)),d=this.safeInteger(t,0);if(void 0===d)continue;let h=[this.parseToInt(d/n*n),this.safeFloat(t,3),this.safeFloat(t,1),this.safeFloat(t,2),this.safeFloat(t,4),this.safeFloat(t,5)],c=this.safeValue(this.ohlcvs[a],i,[]),l=c.length;if(l>0&&h[0]===c[l-1][0]){let e=c[l-1],t=h[1];void 0===h[1]?t=e[1]:void 0!==e[1]&&(t=Math.max(h[1],e[1]));let a=h[2];void 0===h[2]?a=e[2]:void 0!==e[2]&&(a=Math.min(h[2],e[2])),c[l-1]=[h[0],e[1],t,a,h[4],this.sum(h[5],e[5])],void 0!==r&&(s[r][i]=!0)}else{if(l>0&&this.parseToInt(h[0])<this.parseToInt(c[l-1][0]))continue;c.push(h),l>=this.safeInteger(this.options,"OHLCVLimit",1e3)&&c.shift(),void 0!==r&&(s[r][i]=!0)}this.ohlcvs[a][i]=c}}let r=Object.keys(s);for(let t=0;t<r.length;t++){let i=r[t],a=Object.keys(s[i]);for(let t=0;t<a.length;t++){let s=a[t],r="SubscribeTicker:"+s+":"+i,o=this.safeMarket(i).symbol,n=this.safeList(this.ohlcvs[o],s,[]);e.resolve(n,r)}}}async watchOrderBook(e,t,i={}){let s=this.safeInteger(this.options,"omsId",1);void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o="SubscribeLevel2",n=o+":"+r.id,d=this.urls.api.ws,h=this.requestId(),c=void 0===t?100:t,l={OMSId:s,InstrumentId:this.safeInteger(r,"id"),Depth:c},u={m:0,i:h,n:o,o:this.json(l)},f={id:h,messageHash:n,name:o,symbol:a,marketId:r.id,method:this.handleOrderBookSubscription,limit:c,params:i},p=this.extend(u,i);return(await this.watch(d,n,p,n,f)).limit()}handleOrderBook(e,t){let i,s,r=this.safeList(t,"o",[]),a=this.safeList(r,0,[]),o=this.safeString(a,7);if(void 0===o)return;let n=this.safeMarket(o).symbol,d=this.safeValue(this.orderbooks,n);if(void 0!==d){for(let e=0;e<r.length;e++){let t=this.safeList(r,e);if(void 0===i)i=this.safeInteger(t,2);else{let e=this.safeInteger(t,2);i=Math.max(void 0===i?0:i,void 0===e?0:e)}if(void 0===s)s=this.safeInteger(t,0);else{let e=this.safeInteger(t,0);s=Math.max(void 0===s?0:s,void 0===e?0:e)}let a=this.safeInteger(t,3),o=this.safeFloat(t,6),n=this.safeFloat(t,8),h=0===this.safeInteger(t,9)?d.bids:d.asks;0===a||1===a?h.store(o,n):2===a&&h.store(o,0)}d.nonce=s,d.timestamp=i,d.datetime=this.iso8601(i),this.orderbooks[n]=d,e.resolve(d,"SubscribeLevel2:"+o)}}handleOrderBookSubscription(e,t,i){let s=this.safeList(t,"o",[]),r=this.safeString(i,"symbol"),a=this.parseOrderBook(s,r),o=this.safeInteger(i,"limit"),n=this.orderBook(a,o);void 0!==r&&(this.orderbooks[r]=n);let d=this.safeString(i,"messageHash");e.resolve(n,d)}handleSubscriptionStatus(e,t){let i=this.indexBy(e.subscriptions,"id"),s=this.safeInteger(t,"i"),r=void 0===s?void 0:this.safeDict(i,s);if(void 0!==r){let i=this.safeValue(r,"method");void 0!==i&&i.call(this,e,t,r)}}handleMessage(e,t){let i=this.safeString(t,"o");if(void 0===i)return;t.o=JSON.parse(i);let s={SubscribeLevel2:this.handleSubscriptionStatus,SubscribeLevel1:this.handleTicker,Level2UpdateEvent:this.handleOrderBook,Level1UpdateEvent:this.handleTicker,SubscribeTrades:this.handleTrades,TradeDataUpdateEvent:this.handleTrades,SubscribeTicker:this.handleOHLCV,TickerDataUpdateEvent:this.handleOHLCV},r=this.safeString(t,"n"),a=void 0===r?void 0:this.safeValue(s,r);void 0!==a&&a.call(this,e,t)}}i.d(t,{A:()=>a})},4302(e,t,i){"use strict";var s=i(4721),r=i(5058),a=i(1453),o=i(1697);class n extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchTicker:!0,watchMarkPrice:!0,watchMarkPrices:!0,watchTickers:!0,watchBidsAsks:!0,watchOrderBook:!0,watchTrades:!0,watchTradesForSymbols:!0,watchOrderBookForSymbols:!0,watchBalance:!0,watchLiquidations:"emulated",watchLiquidationsForSymbols:!0,watchMyLiquidations:"emulated",watchMyLiquidationsForSymbols:!0,watchOHLCV:!0,watchOHLCVForSymbols:!0,watchOrders:!0,watchMyTrades:!0,watchPositions:!0,watchFundingRate:!0,watchFundingRates:!0,unWatchTicker:!0,unWatchTickers:!0,unWatchOHLCV:!0,unWatchOHLCVForSymbols:!0,unWatchOrderBook:!0,unWatchOrderBookForSymbols:!0,unWatchTrades:!0,unWatchTradesForSymbols:!0,unWatchMyTrades:!1,unWatchOrders:!1,unWatchPositions:!1,createOrderWs:!0,editOrderWs:!0,cancelOrderWs:!0,cancelOrdersWs:!0,cancelAllOrdersWs:!0},urls:{api:{ws:"wss://ws.okx.com:8443/ws/v5"},test:{ws:"wss://wspap.okx.com:8443/ws/v5"}},options:{watchOrderBook:{depth:"books"},watchBalance:"spot",watchTicker:{channel:"tickers"},watchTickers:{channel:"tickers"},watchBidsAsks:{channel:"bbo-tbt"},watchOrders:{type:"ANY"},watchMyTrades:{type:"ANY"},createOrderWs:{op:"batch-orders"},editOrderWs:{op:"amend-order"},ws:{}},streaming:{ping:this.ping,keepAlive:18e3}})}getUrl(e,t="public"){if(void 0===e)throw new a.ArgumentsRequired(this.id+" getUrl() requires a channel argument");let i=this.options.sandboxMode,s="";!0===i&&(s="?brokerId=9999");let r=this.urls.api.ws;return"business"===t||e.indexOf("candle")>-1||"orders-algo"===e?r+"/business"+s:"public"===t?r+"/public"+s:r+"/private"+s}async subscribeMultiple(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=i;void 0===i&&(r=this.symbols);let o=this.marketSymbols(r),n=this.getUrl(t,e),d=[],h=[];if(void 0===o)throw new a.ArgumentsRequired(this.id+" subscribeMultiple() symbols is required");for(let e=0;e<o.length;e++){if(void 0===o)throw new a.ArgumentsRequired(this.id+" subscribeMultiple() symbols is required");let i={channel:t,instId:this.marketId(o[e])};if(h.push(this.extend(i,s)),void 0===o)throw new a.ArgumentsRequired(this.id+" subscribeMultiple() symbols is required");d.push(t+"::"+o[e])}return await this.watchMultiple(n,d,{op:"subscribe",args:h},d)}async subscribe(e,t,i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.getUrl(i,e),o={channel:i},n=t;if(void 0!==s){let e=this.market(s);n+=":"+e.id,o.instId=e.id}let d={op:"subscribe",args:[this.deepExtend(o,r)]};return await this.watch(a,n,d,n)}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){if(0===e.length)throw new a.ArgumentsRequired(this.id+" watchTradesForSymbols() requires a non-empty array of symbols");void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e),o=this.handleOptionStringAndParams(s,"watchTrades","channel","trades")[0],n=[],d=[];for(let e=0;e<r.length;e++){let t=r[e];d.push(o+":"+t);let i={channel:o,instId:this.marketId(t)};n.push(i)}let h="public";"trades-all"===o&&(h="business",await this.authenticate({access:h}));let c=this.getUrl(o,h),l=await this.watchMultiple(c,d,{op:"subscribe",args:n},d),u=this.safeDict(l,0),f=this.safeString(u,"symbol"),p=i;return this.newUpdates&&(p=l.getLimit(f,i)),this.filterBySinceLimit(l,t,p,"timestamp",!0)}async unWatchTradesForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=this.handleOptionStringAndParams(t,"watchTrades","channel","trades")[0],r=[],a=[];for(let e=0;e<i.length;e++){let t=i[e];a.push("unsubscribe:"+s+":"+t);let o={channel:s,instId:this.marketId(t)};r.push(o)}let o="public";"trades-all"===s&&(o="business",await this.authenticate({access:o}));let n=this.getUrl(s,o);return await this.watchMultiple(n,a,{op:"unsubscribe",args:r},a)}unWatchTrades(e,t={}){return this.unWatchTradesForSymbols([e],t)}handleTrades(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeString(i,"channel"),r=this.safeString(i,"instId"),a=this.safeSymbol(r),n=this.safeList(t,"data",[]),d=this.safeInteger(this.options,"tradesLimit",1e3);for(let t=0;t<n.length;t++){let i=this.parseTrade(n[t]),r=this.safeValue(this.trades,a);if(void 0===r&&(r=new o.I3(d),this.trades[a]=r),r.append(i),void 0!==s){let t=s+":"+a;e.resolve(r,t)}}}async watchFundingRate(e,t={}){let i=this.symbol(e);return(await this.watchFundingRates([i],t))[i]}async watchFundingRates(e,t={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" watchFundingRates() requires an array of symbols");void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s="funding-rate",r=[],o=[];for(let e=0;e<i.length;e++){let t=i[e];o.push(s+":"+t);let a={channel:s,instId:this.marketId(t)};r.push(a)}let n=this.getUrl(s,"public"),d=await this.watchMultiple(n,o,{op:"subscribe",args:r},o);if(this.newUpdates){let e=this.safeString(d,"symbol"),t={};return void 0!==e&&(t[e]=d),t}return this.filterByArray(this.fundingRates,"symbol",i)}handleFundingRate(e,t){let i=this.safeList(t,"data",[]);for(let t=0;t<i.length;t++){let s=this.safeDict(i,t),r=this.parseFundingRate(s),a=r.symbol;void 0!==a&&(this.fundingRates[a]=r),e.resolve(r,"funding-rate:"+r.symbol)}}async watchTicker(e,t={}){let[i,s]=this.handleOptionStringAndParams(t,"watchTicker","channel","tickers");s.channel=i;let r=this.market(e).symbol,a=await this.watchTickers([r],s);return this.safeValue(a,r)}unWatchTicker(e,t={}){return this.unWatchTickers([e],t)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),[s,r]=this.handleOptionStringAndParams(t,"watchTickers","channel","tickers"),a=await this.subscribeMultiple("public",s,i,r);return this.newUpdates?a:this.filterByArray(this.tickers,"symbol",i)}async watchMarkPrice(e,t={}){let[i,s]=this.handleOptionStringAndParams(t,"watchMarkPrice","channel","mark-price");s.channel=i;let r=this.market(e).symbol;return(await this.watchMarkPrices([r],s))[r]}async watchMarkPrices(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),[s,r]=this.handleOptionStringAndParams(t,"watchMarkPrices","channel","mark-price"),a=await this.subscribeMultiple("public",s,i,r);return this.newUpdates?a:this.filterByArray(this.tickers,"symbol",i)}async unWatchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=this.handleOptionStringAndParams(t,"watchTickers","channel","tickers")[0],r=[],a=[];for(let e=0;e<i.length;e++){let t=i[e];a.push("unsubscribe:ticker:"+t);let o={channel:s,instId:this.marketId(t)};r.push(o)}let o=this.getUrl(s,"public");return await this.watchMultiple(o,a,{op:"unsubscribe",args:r},a)}handleTicker(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeString(i,"instId"),r=this.safeMarket(s,void 0,"-").symbol,a=this.safeString(i,"channel");"tickers"===a&&this.handleBidAsk(e,t);let o=this.safeList(t,"data",[]),n={};for(let e=0;e<o.length;e++){let t=this.parseTicker(o[e]);this.tickers[r]=t,n[r]=t}void 0!==a&&e.resolve(n,a+"::"+r)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),[s,r]=this.handleOptionStringAndParams(t,"watchBidsAsks","channel","bbo-tbt"),a=this.getUrl(s,"public"),o=[],n=[];for(let e=0;e<i.length;e++){let t={channel:s,instId:this.marketId(i[e])};n.push(this.extend(t,r)),o.push("bidask::"+i[e])}let d=await this.watchMultiple(a,o,{op:"subscribe",args:n},o);if(this.newUpdates){let e={},t=this.safeString(d,"symbol");return void 0!==t&&(e[t]=d),e}return this.filterByArray(this.bidsasks,"symbol",i)}handleBidAsk(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeString(i,"instId"),r=this.safeMarket(s),a=this.safeList(t,"data",[]),o=this.safeDict(a,0,{}),n=this.parseWsBidAsk(o,r),d=n.symbol;void 0!==d&&(this.bidsasks[d]=n),e.resolve(n,"bidask::"+d)}parseWsBidAsk(e,t){let i=this.safeString(e,"instId"),s=this.safeMarket(i,t),r=this.safeString(s,"symbol"),a=this.safeInteger(e,"ts"),o=this.safeString(e,"askPx"),n=this.safeString(e,"askSz"),d=this.safeString(e,"bidPx"),h=this.safeString(e,"bidSz");if(void 0===o){let t=this.safeList(e,"asks",[]),i=this.safeList(t,0,[]);o=this.safeString(i,0),n=this.safeString(i,1)}if(void 0===d){let t=this.safeList(e,"bids",[]),i=this.safeList(t,0,[]);d=this.safeString(i,0),h=this.safeString(i,1)}return this.safeTicker({symbol:r,timestamp:a,datetime:this.iso8601(a),ask:o,askVolume:n,bid:d,bidVolume:h,info:e},s)}async watchLiquidationsForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!0,!0),o="liquidations",n=[];if(void 0!==r)for(let e=0;e<r.length;e++){let t=r[e];n.push(o+"::"+t)}else n.push(o);let d=this.getMarketFromSymbols(r),h=this.handleMarketTypeAndParams("watchLiquidationsForSymbols",d,s)[0],c="liquidation-orders",l=h;if("spot"===h?l="SWAP":"future"===h&&(l="futures"),void 0===l)throw new a.ArgumentsRequired(this.id+" watchLiquidationsForSymbols() type is required");let u=l.toUpperCase(),f=this.getUrl(c,"public"),p=await this.watchMultiple(f,n,{op:"subscribe",args:[{channel:c,instType:u}]},n);return this.newUpdates?p:this.filterBySymbolsSinceLimit(this.liquidations,r,t,i,!0)}handleLiquidation(e,t){let i=this.safeList(t,"data",[]);for(let t=0;t<i.length;t++){let s=i[t],r=this.parseWsLiquidation(s),a=this.safeString(r,"symbol");if(void 0===this.liquidations){let e=this.safeInteger(this.options,"liquidationsLimit",1e3);this.liquidations=new o.I3(e)}this.liquidations.append(r),e.resolve([r],"liquidations"),e.resolve([r],"liquidations::"+a)}}async watchMyLiquidationsForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.safeBool2(s,"stop","trigger",!1),a=this.omit(s,["stop","trigger"]),o="private";!0===r&&(o="business"),await this.authenticate({access:o});let n=this.marketSymbols(e,void 0,!0,!0),d="myLiquidations",h=[];if(void 0!==n)for(let e=0;e<n.length;e++){let t=n[e];h.push(d+"::"+t)}else h.push(d);let c="balance_and_position",l=this.getUrl(c,"private"),u=await this.watchMultiple(l,h,this.deepExtend({op:"subscribe",args:[{channel:c}]},a),h);return this.newUpdates?u:this.filterBySymbolsSinceLimit(this.liquidations,n,t,i,!0)}handleMyLiquidation(e,t){let i=this.safeList(t,"data",[]);for(let t=0;t<i.length;t++){let s=i[t];if("liquidation"!==this.safeString(s,"eventType"))return;let r=this.parseWsMyLiquidation(s),a=this.safeString(r,"symbol");if(void 0===this.liquidations){let e=this.safeInteger(this.options,"liquidationsLimit",1e3);this.liquidations=new o.I3(e)}this.liquidations.append(r),e.resolve([r],"myLiquidations"),e.resolve([r],"myLiquidations::"+a)}}parseWsMyLiquidation(e,t){let i=this.safeList(e,"posData",[]),s=this.safeDict(i,0,{}),r=this.safeString(s,"instId"),a=this.safeMarket(r,t),o=this.safeInteger(s,"uTIme");return this.safeLiquidation({info:e,symbol:this.safeSymbol(r,a),contracts:this.safeNumber(s,"pos"),contractSize:this.safeNumber(a,"contractSize"),price:this.safeNumber(e,"avgPx"),baseValue:void 0,quoteValue:void 0,timestamp:o,datetime:this.iso8601(o)})}parseWsLiquidation(e,t){let i=this.safeList(e,"details",[]),s=this.safeDict(i,0,{}),r=this.safeString(e,"instId"),a=this.safeMarket(r,t),o=this.safeInteger(s,"ts");return this.safeLiquidation({info:e,symbol:this.safeSymbol(r,a),contracts:this.safeNumber(s,"sz"),contractSize:this.safeNumber(a,"contractSize"),price:this.safeNumber(s,"bkPx"),side:this.safeString(s,"side"),baseValue:void 0,quoteValue:void 0,timestamp:o,datetime:this.iso8601(o)})}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.symbol(e),o="candle"+this.safeString(this.timeframes,t,t),n=await this.subscribe("public",o,o,a,r),d=s;return this.newUpdates&&(d=n.getLimit(a,s)),this.filterBySinceLimit(n,i,d,0,!0)}unWatchOHLCV(e,t="1m",i={}){return this.unWatchOHLCVForSymbols([[e,t]],i)}async watchOHLCVForSymbols(e,t,i,s={}){if(0===e.length||!Array.isArray(e[0]))throw new a.ArgumentsRequired(this.id+" watchOHLCVForSymbols() requires a an array of symbols and timeframes, like  [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]");void 0===this.markets&&await this.loadMarkets();let r=[],o=[];for(let t=0;t<e.length;t++){let i=e[t],s=i[0],a=i[1],n=this.marketId(s),d="candle"+this.safeString(this.timeframes,a,a),h={channel:d,instId:n};r.push(h),o.push("multi:"+d+":"+s)}let n=this.getUrl("candle","public"),[d,h,c]=await this.watchMultiple(n,o,{op:"subscribe",args:r},o),l=i;this.newUpdates&&(l=c.getLimit(d,i));let u=this.filterBySinceLimit(c,t,l,0,!0);return this.createOHLCVObject(d,h,u)}async unWatchOHLCVForSymbols(e,t={}){if(0===e.length||!Array.isArray(e[0]))throw new a.ArgumentsRequired(this.id+" watchOHLCVForSymbols() requires a an array of symbols and timeframes, like  [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]");void 0===this.markets&&await this.loadMarkets();let i=[],s=[];for(let t=0;t<e.length;t++){let r=e[t],a=r[0],o=r[1],n=this.marketId(a),d="candle"+this.safeString(this.timeframes,o,o),h={channel:d,instId:n};i.push(h),s.push("unsubscribe:multi:"+d+":"+a)}let r=this.getUrl("candle","public");return await this.watchMultiple(r,s,{op:"unsubscribe",args:i},s)}handleOHLCV(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeString(i,"channel");if(void 0===s)return;let r=this.safeList(t,"data",[]),a=this.safeString(i,"instId"),n=this.safeMarket(a),d=n.symbol,h=s.replace("candle",""),c=this.findTimeframe(h);for(let t=0;t<r.length;t++){let i=this.parseOHLCV(r[t],n);this.ohlcvs[d]=this.safeDict(this.ohlcvs,d,{});let a=this.safeValue(this.safeDict(this.ohlcvs,d),c);if(void 0===a){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);a=new o.TG(e),void 0!==d&&void 0!==c&&(this.ohlcvs[d][c]=a)}a.append(i);let h=s+":"+n.id;e.resolve(a,h);let l="multi:"+s+":"+d;e.resolve([d,c,a],l)}}watchOrderBook(e,t,i={}){return this.watchOrderBookForSymbols([e],t,i)}async watchOrderBookForSymbols(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e),r=this.handleOptionStringAndParams(i,"watchOrderBook","depth","books")[0];if(void 0!==t&&(1===t?r="bbo-tbt":t>1&&t<=5?r="books5":50===t?r="books50-l2-tbt":400===t&&(r="books")),"books-l2-tbt"===r||"books50-l2-tbt"===r){if(!this.checkRequiredCredentials(!1))throw new a.AuthenticationError(this.id+" watchOrderBook/watchOrderBookForSymbols requires authentication for this depth. Add credentials or change the depth option to books or books5");await this.authenticate({access:"public"})}let o=[],n=[];for(let e=0;e<s.length;e++){let t=s[e];n.push(r+":"+t);let i={channel:r,instId:this.marketId(t)};o.push(i)}let d=this.getUrl(r,"public");return(await this.watchMultiple(d,n,{op:"subscribe",args:o},n)).limit()}async unWatchOrderBookForSymbols(e,t={}){let i,s;void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!1);[i,s]=this.handleOptionStringAndParams(t,"watchOrderBook","depth","books");let a=this.safeInteger(s,"limit");void 0!==a&&(1===a?i="bbo-tbt":a>1&&a<=5?i="books5":50===a?i="books50-l2-tbt":400===a&&(i="books"));let o=[],n=[],d=[];for(let e=0;e<r.length;e++){let t=r[e];n.push(i+":"+t),d.push("unsubscribe:orderbook:"+t);let s={channel:i,instId:this.marketId(t)};o.push(s)}let h=this.getUrl(i,"public");return await this.watchMultiple(h,d,{op:"unsubscribe",args:o},d)}unWatchOrderBook(e,t={}){return this.unWatchOrderBookForSymbols([e],t)}handleDelta(e,t){let i=this.safeFloat(t,0),s=this.safeFloat(t,1);e.store(i,s)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}handleOrderBookMessage(e,t,i,s,r){let o,n=this.safeList(t,"asks",[]),d=this.safeList(t,"bids",[]),h=i.asks,c=i.bids;this.handleDeltas(h,n),this.handleDeltas(c,d);let l=this.safeString(t,"instId"),u=this.safeSymbol(l,r),f=this.safeInteger(t,"seqId"),p=this.safeInteger(t,"prevSeqId"),m=i.nonce;if(void 0!==p&&-1!==p&&m!==p&&(o=new a.InvalidNonce(this.id+" watchOrderBook received invalid nonce")),void 0!==o)return delete e.subscriptions[s],void 0!==u&&delete this.orderbooks[u],e.reject(o,s),i;let g=this.safeInteger(t,"ts");return i.nonce=f,i.timestamp=g,i.datetime=this.iso8601(g),i}handleOrderBook(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeString(i,"channel"),r=this.safeString(t,"action"),a=this.safeList(t,"data",[]),o=this.safeString(i,"instId"),n=this.safeMarket(o),d=n.symbol,h=this.safeInteger({"bbo-tbt":1,books:400,books5:5,"books-rpi":400,"books-l2-tbt":400,"books50-l2-tbt":50},s),c=s+":"+d;if("snapshot"===r)for(let t=0;t<a.length;t++){let i=a[t],s=this.orderBook({},h);if(this.orderbooks[d]=s,s.symbol=d,this.handleOrderBookMessage(e,i,s,c,n),!(c in e.subscriptions))break;e.resolve(s,c)}else if("update"===r){if(d in this.orderbooks){let t=this.orderbooks[d];for(let i=0;i<a.length;i++){let s=a[i];if(this.handleOrderBookMessage(e,s,t,c,n),!(c in e.subscriptions))break;e.resolve(t,c)}}}else if(("books5"===s||"bbo-tbt"===s)&&c in e.subscriptions){d in this.orderbooks||(this.orderbooks[d]=this.orderBook({},h));let t=this.orderbooks[d];for(let i=0;i<a.length;i++){let s=a[i],r=this.safeInteger(s,"ts"),o=this.parseOrderBook(s,d,r,"bids","asks",0,1);t.reset(o),e.resolve(t,c)}}return"bbo-tbt"===s&&this.handleBidAsk(e,t),t}async authenticate(e={}){this.checkRequiredCredentials();let t=this.safeString(e,"access","private"),i=this.omit(e,["access"]),r=this.getUrl("users",t),a="authenticated",o=this.client(r),n=o.reusableFuture(a);if(void 0===this.safeValue(o.subscriptions,a)){let e=this.seconds().toString(),t=e+"GET/users/self/verify",o=this.hmac(this.encode(t),this.encode(this.secret),s.sc,"base64"),n={op:"login",args:[{apiKey:this.apiKey,passphrase:this.password,timestamp:e,sign:o}]};"access"in i&&(n.access=i.access),this.watch(r,a,n,a)}return await n}async watchBalance(e={}){return void 0===this.markets&&await this.loadMarkets(),await this.authenticate(),await this.subscribe("private","account","account",void 0,e)}handleBalanceAndPosition(e,t){this.handleMyLiquidation(e,t)}handleBalance(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeString(i,"channel"),r=this.parseTradingBalance(t),a=this.deepExtend(this.balance,r);this.balance=this.safeBalance(a),e.resolve(this.balance,s)}orderToTrade(e,t){let i=this.safeDict(e,"info",{}),s=this.safeInteger(i,"fillTime"),r=this.safeString(i,"fillFeeCcy"),a="T"===this.safeString(i,"execType","");return this.safeTrade({info:i,timestamp:s,datetime:this.iso8601(s),symbol:this.safeString(e,"symbol"),id:this.safeString(i,"tradeId"),order:this.safeString(e,"id"),type:this.safeString(e,"type"),takerOrMaker:a?"taker":"maker",side:this.safeString(e,"side"),price:this.safeNumber(i,"fillPx"),amount:this.safeNumber(i,"fillSz"),cost:this.safeNumber(e,"cost"),fee:{cost:this.safeNumber(i,"fillFee"),currency:this.safeCurrencyCode(r)}},t)}async watchMyTrades(e,t,i,s={}){let r,o,[n,d]=this.handleOptionStringAndParams(s,"watchMyTrades","type","ANY"),h=this.safeBool2(d,"trigger","stop",!1),c=this.omit(d,["trigger","stop"]);void 0===this.markets&&await this.loadMarkets();let l="private";!0===h&&(l="business"),await this.authenticate({access:l});let u="orders";!0===h&&(u="orders-algo");let f=u+"::myTrades",p=n;if(void 0!==e&&(o=(r=this.market(e)).symbol,p=this.safeString(r,"type"),f=f+"::"+o),"future"===p&&(p="futures"),void 0===p)throw new a.ArgumentsRequired(this.id+" watchMyTrades() type is required");let m=p.toUpperCase(),[g,v]=this.handleMarginModeAndParams("watchMyTrades",c);"SPOT"===m&&void 0!==g&&(m="MARGIN");let y={instType:m},b=await this.subscribe("private",f,u,void 0,this.extend(y,v)),w=i;return this.newUpdates&&(w=b.getLimit(o,i)),this.filterBySymbolSinceLimit(b,o,t,w,!0)}async watchPositions(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),await this.authenticate(s);let a=this.marketSymbols(e),o="positions";if(void 0===a){let e=[this.extend({channel:"positions",instType:"ANY"},s)],t=this.getUrl(o,"private");r=await this.watch(t,o,{op:"subscribe",args:e},o)}else r=await this.subscribeMultiple("private",o,a,this.extend({instType:"ANY"},s));return this.newUpdates?void 0===r?[]:r:this.filterBySymbolsSinceLimit(this.positions,a,t,i,!0)}handlePositions(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeString(i,"instId"),r=this.safeMarket(s,void 0,"-").symbol,a=this.safeString(i,"channel",""),n=this.safeList(t,"data",[]);void 0===this.positions&&(this.positions=new o.Hk);let d=this.positions,h=[];for(let e=0;e<n.length;e++){let t=n[e],i=this.parsePosition(t);if(0===i.contracts&&"net"===this.safeString(t,"posSide")){i.side="long";let e=this.clone(i);e.side="short",d.append(e),h.push(e)}h.push(i),d.append(i)}let c=a;void 0!==r&&(c=a+"::"+r),e.resolve(h,c)}async watchOrders(e,t,i,s={}){let r,o,[n,d]=this.handleOptionStringAndParams(s,"watchOrders","type","ANY"),h=this.safeBool2(d,"stop","trigger",!1),c=this.omit(d,["stop","trigger"]);void 0===this.markets&&await this.loadMarkets();let l="private";!0===h&&(l="business"),await this.authenticate({access:l});let u=n;if(void 0!==e&&(r=this.market(e),o=this.safeString(r,"symbol"),u=this.safeString(r,"type")),"future"===u&&(u="futures"),void 0===u)throw new a.ArgumentsRequired(this.id+" watchOrders() type is required");let f=u.toUpperCase(),[p,m]=this.handleMarginModeAndParams("watchOrders",c);"SPOT"===f&&void 0!==p&&(f="MARGIN");let g={instType:f},v="orders";!0===h&&(v="orders-algo");let y=await this.subscribe("private",v,v,o,this.extend(g,m)),b=i;return this.newUpdates&&(b=y.getLimit(o,i)),this.filterBySymbolSinceLimit(y,o,t,b,!0)}handleOrders(e,t){this.handleMyTrades(e,t);let i=this.safeDict(t,"arg",{}),s=this.safeString(i,"channel"),r=this.safeList(t,"data",[]);if(r.length>0){let t=this.safeInteger(this.options,"ordersLimit",1e3);void 0===this.orders&&(this.orders=new o.Pt(t),this.triggerOrders=new o.Pt(t));let i="orders-algo"===s?this.triggerOrders:this.orders,a=[],n=this.parseOrders(r);for(let e=0;e<n.length;e++){let t=n[e];i.append(t);let s=t.symbol,r=this.market(s);a.push(r.id)}e.resolve(i,s);for(let t=0;t<a.length;t++)if(void 0!==s){let r=s+":"+a[t];e.resolve(i,r)}}}handleMyTrades(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeString(i,"channel"),r=this.safeList(t,"data",[]),a=[];for(let e=0;e<r.length;e++){let t=r[e];if(this.safeString(t,"tradeId","").length>0){let e=this.parseOrder(t);a.push(e)}}if(0===a.length)return;if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new o.Pt(e)}let n=this.myTrades,d={};for(let e=0;e<a.length;e++){let t=a[e],i=this.orderToTrade(t);n.append(i);let s=i.symbol;void 0!==s&&(d[s]=!0)}if(void 0!==s){let t=s+"::myTrades";e.resolve(this.myTrades,t);let i=Object.keys(d);for(let s=0;s<i.length;s++){let r=t+"::"+i[s];e.resolve(this.myTrades,r)}}}requestId(){return this.milliseconds().toString()+this.randNumber(4).toString()}async createOrderWs(e,t,i,s,r,o={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let n=this.getUrl("private","private"),d=this.requestId(),[h,c]=this.handleOptionStringAndParams(o,"createOrderWs","op","batch-orders"),l=this.createOrderRequest(e,t,i,s,r,c),u=this.market(e),f=this.safeInteger(u,"instIdCode");void 0!==f&&(delete l.instId,l.instIdCode=f);let p=this.safeString(l,"ordType");if("trigger"===p||"conditional"===p||"oco"===t||"move_order_stop"===t||"iceberg"===t||"twap"===t)throw new a.BadRequest(this.id+' createOrderWs() does not support algo trading. this.options["createOrderWs"]["op"] must be either order or batch-order');if("order"!==h&&"batch-orders"!==h)throw new a.BadRequest(this.id+' createOrderWs() does not support algo trading. this.options["createOrderWs"]["op"] must be either order or privatePostTradeOrder or privatePostTradeOrderAlgo');return await this.watch(n,d,{id:d,op:h,args:[l]},d)}handlePlaceOrders(e,t){let i=this.safeString(t,"id"),s=this.safeList(t,"data",[]);if(s=this.filterBy(s,"sCode","0"),this.isEmpty(s)){let i=this.safeString(t,"op"),s=this.json(t);this.handleErrors(1,"",e.url,i,{},s,t,{},{})}let r=this.parseOrders(s,void 0,void 0,void 0),a=this.safeDict(r,0,{});e.resolve(a,i)}async editOrderWs(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let n=this.getUrl("private","private"),d=this.requestId(),[h,c]=this.handleOptionStringAndParams(o,"editOrderWs","op","amend-order"),l=this.editOrderRequest(e,t,i,s,r,a,c),u=this.market(t),f=this.safeInteger(u,"instIdCode");return void 0!==f&&(delete l.instId,l.instIdCode=f),await this.watch(n,d,this.extend({id:d,op:h,args:[l]},c),d)}async cancelOrderWs(e,t,i={}){if(void 0===t)throw new a.BadRequest(this.id+" cancelOrderWs() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let s=this.getUrl("private","private"),r=this.requestId(),o=this.safeString2(i,"clOrdId","clientOrderId"),n=this.omit(i,["clientOrderId","clOrdId"]),d=this.market(t),h={instIdCode:this.safeInteger(d,"instIdCode")};void 0!==o?h.clOrdId=o:h.ordId=e;let c={id:r,op:"cancel-order",args:[this.extend(h,n)]};return await this.watch(s,r,c,r)}async cancelOrdersWs(e,t,i={}){let s=e.length;if(s>20)throw new a.BadRequest(this.id+" cancelOrdersWs() accepts up to 20 ids at a time");if(void 0===t)throw new a.BadRequest(this.id+" cancelOrdersWs() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.getUrl("private","private"),o=this.requestId(),n=[],d=this.market(t),h={instIdCode:this.safeInteger(d,"instIdCode")};for(let t=0;t<s;t++){let i=this.extend(h,{ordId:e[t]});n.push(i)}return await this.watch(r,o,this.deepExtend({id:o,op:"batch-cancel-orders",args:n},i),o)}async cancelAllOrdersWs(e,t={}){if(void 0===e)throw new a.BadRequest(this.id+" cancelAllOrdersWs() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let i=this.market(e);if("option"!==i.type)throw new a.BadRequest(this.id+" cancelAllOrdersWs is only applicable to Option in Portfolio Margin mode, and MMP privilege is required.");let s=this.getUrl("private","private"),r=this.requestId(),o={id:r,op:"mass-cancel",args:[this.extend({instType:"OPTION",instFamily:i.id},t)]};return await this.watch(s,r,o,r)}handleCancelAllOrders(e,t){let i=this.safeString(t,"id"),s=this.safeList(t,"data",[]);e.resolve(s,i)}handleSubscriptionStatus(e,t){return t}handleAuthenticate(e,t){this.safeValue(e.futures,"authenticated").resolve(!0)}ping(e){return"ping"}handlePong(e,t){return e.lastPong=this.milliseconds(),t}handleErrorMessage(e,t){let i=this.safeString(t,"code");try{if(void 0!==i&&""!==i&&"0"!==i){let e=this.id+" "+this.json(t);"1"!==i&&this.throwExactlyMatchedException(this.exceptions.exact,i,e);let s=this.safeString(t,"msg");if(void 0!==s)this.throwBroadlyMatchedException(this.exceptions.broad,s,e);else{let r=this.safeList(t,"data",[]);for(let t=0;t<r.length;t++){let a=this.safeDict(r,t);i=this.safeString(a,"sCode"),void 0!==i&&this.throwExactlyMatchedException(this.exceptions.exact,i,e),s=this.safeString(a,"sMsg"),void 0!==s&&this.throwBroadlyMatchedException(this.exceptions.broad,s,e)}}throw new a.ExchangeError(e)}}catch(s){let i=this.safeString(t,"id");if(void 0===i){let e=this.safeString(t,"msg");if(void 0!==e&&e.startsWith("Illegal request: {")){let t=e.replace("Illegal request: ",""),s=this.parseJson(t);i=this.safeString(s,"id")}}if(void 0!==i)return e.reject(s,i),!1;return e.reject(s),!1}return!0}handleMessage(e,t){if(!0!==this.handleErrorMessage(e,t))return;if("string"==typeof t){"pong"===t&&this.handlePong(e,t);return}let i=this.safeString2(t,"event","op");if(void 0!==i){let s={login:this.handleAuthenticate,subscribe:this.handleSubscriptionStatus,unsubscribe:this.handleUnsubscription,order:this.handlePlaceOrders,"batch-orders":this.handlePlaceOrders,"amend-order":this.handlePlaceOrders,"batch-amend-orders":this.handlePlaceOrders,"cancel-order":this.handlePlaceOrders,"mass-cancel":this.handleCancelAllOrders},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}else{let i=this.safeDict(t,"arg",{}),s=this.safeString(i,"channel");if(void 0===s)return;let r={"bbo-tbt":this.handleOrderBook,books:this.handleOrderBook,books5:this.handleOrderBook,"books-rpi":this.handleOrderBook,"books50-l2-tbt":this.handleOrderBook,"books-l2-tbt":this.handleOrderBook,tickers:this.handleTicker,"mark-price":this.handleTicker,positions:this.handlePositions,"index-tickers":this.handleTicker,"sprd-tickers":this.handleTicker,"block-tickers":this.handleTicker,trades:this.handleTrades,"trades-all":this.handleTrades,account:this.handleBalance,"funding-rate":this.handleFundingRate,orders:this.handleOrders,"orders-algo":this.handleOrders,"liquidation-orders":this.handleLiquidation,balance_and_position:this.handleBalanceAndPosition},a=this.safeValue(r,s);void 0===a?0===s.indexOf("candle")&&this.handleOHLCV(e,t):a.call(this,e,t)}}handleUnSubscriptionTrades(e,t,i){let s=i+":"+t;this.cleanUnsubscription(e,s,"unsubscribe:"+s),t in this.trades&&delete this.trades[t]}handleUnsubscriptionOrderBook(e,t,i){this.cleanUnsubscription(e,i+":"+t,"unsubscribe:orderbook:"+t),t in this.orderbooks&&delete this.orderbooks[t]}handleUnsubscriptionOHLCV(e,t,i){let s=i.replace("candle",""),r=this.findTimeframe(s);if(void 0===r)return;let a="multi:"+i+":"+t;this.cleanUnsubscription(e,a,"unsubscribe:"+a),void 0!==t&&void 0!==r&&r in this.ohlcvs[t]&&delete this.ohlcvs[t][r]}handleUnsubscriptionTicker(e,t,i){this.cleanUnsubscription(e,i+"::"+t,"unsubscribe:ticker:"+t),t in this.tickers&&delete this.tickers[t]}handleUnsubscription(e,t){let i=this.safeDict(t,"arg",{}),s=this.safeString(i,"channel",""),r=this.safeString(i,"instId"),a=this.safeSymbol(r);"trades"===s||"trades-all"===s?this.handleUnSubscriptionTrades(e,a,s):s.startsWith("bbo")||s.startsWith("book")?this.handleUnsubscriptionOrderBook(e,a,s):s.indexOf("tickers")>-1?this.handleUnsubscriptionTicker(e,a,s):s.startsWith("candle")&&this.handleUnsubscriptionOHLCV(e,a,s)}}i.d(t,{A:()=>n})},9302(e,t,i){"use strict";var s=i(4302);class r extends s.A{describe(){return this.deepExtend(super.describe(),{id:"okxus",name:"OKX (US)",hostname:"us.okx.com",urls:{api:{rest:"https://{hostname}",ws:"wss://wsus.okx.com:8443/ws/v5"},www:"https://app.okx.com",doc:"https://app.okx.com/docs-v5/en/#overview",fees:"https://app.okx.com/pages/products/fees.html",referral:{url:"https://www.app.okx.com/join/CCXT2023",discount:.2},test:{ws:"wss://wsuspap.okx.com:8443/ws/v5"}},has:{swap:!0,future:!1,option:!1}})}}i.d(t,{A:()=>r})},1503(e,t,i){"use strict";var s=i(363),r=i(1453),a=i(1697),o=i(7749);class n extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchTicker:!0,watchTickers:!0,watchTrades:!1,watchTradesForSymbols:!1,watchMyTrades:!0,watchOrders:!0,watchOrderBook:!0,watchOHLCV:!0},urls:{api:{ws:"wss://streams.fast.onetrading.com"}},options:{bp_remaining_quota:200,timeframes:{"1m":{unit:"MINUTES",period:1},"5m":{unit:"MINUTES",period:5},"15m":{unit:"MINUTES",period:15},"30m":{unit:"MINUTES",period:30},"1h":{unit:"HOURS",period:1},"4h":{unit:"HOURS",period:4},"1d":{unit:"DAYS",period:1},"1w":{unit:"WEEKS",period:1},"1M":{unit:"MONTHS",period:1}}},streaming:{},exceptions:{}})}async watchBalance(e={}){await this.authenticate(e);let t=this.urls.api.ws,i=this.safeInteger(this.options,"bp_remaining_quota",200),s=this.deepExtend({type:"SUBSCRIBE",bp_remaining_quota:i,channels:[{name:"ACCOUNT_HISTORY"}]},e);return await this.watch(t,"balance",s,"ACCOUNT_HISTORY",s)}handleBalanceSnapshot(e,t){this.balance=this.parseBalance(t),e.resolve(this.balance,"balance")}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e).symbol;return await this.watchMany("ticker."+i,{type:"SUBSCRIBE",channels:[{name:"MARKET_TICKER",price_points_mode:"INLINE"}]},"MARKET_TICKER",[i],t)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s=void 0===i?[]:i,r=await this.watchMany("tickers",{type:"SUBSCRIBE",channels:[{name:"MARKET_TICKER",price_points_mode:"INLINE"}]},"MARKET_TICKER",s,t);return this.filterByArray(r,"symbol",s)}handleTicker(e,t){let i=this.safeList(t,"ticker_updates",[]),s=this.safeString(t,"time");for(let t=0;t<i.length;t++){let r=i[t],a=this.safeString(r,"instrument"),o=this.safeSymbol(a);this.tickers[o]=this.parseWSTicker(r);let n=this.parse8601(s);this.tickers[o].timestamp=n,this.tickers[o].datetime=this.iso8601(n),e.resolve(this.tickers[o],"ticker."+o)}e.resolve(this.tickers,"tickers")}parseWSTicker(e,t){let i=this.safeString(e,"instrument");return this.safeTicker({symbol:this.safeSymbol(i,t),timestamp:void 0,datetime:void 0,high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:void 0,close:this.safeString(e,"last_price"),last:this.safeString(e,"last_price"),previousClose:void 0,change:this.safeString(e,"price_change"),percentage:this.safeString(e,"price_change_percentage"),average:void 0,baseVolume:void 0,quoteVolume:this.safeNumber(e,"volume"),info:e},t)}async watchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a="myTrades";if(void 0!==e){let t=this.market(e);a+=":"+(r=this.safeString(t,"symbol"))}await this.authenticate(s);let o=this.urls.api.ws,n=this.safeInteger(this.options,"bp_remaining_quota",200),d=this.deepExtend({type:"SUBSCRIBE",bp_remaining_quota:n,channels:[{name:"ACCOUNT_HISTORY"}]},s),h=await this.watch(o,a,d,"ACCOUNT_HISTORY",d),c=i;return(this.newUpdates&&(c=h.getLimit(r,i)),0===(h=this.filterBySymbolSinceLimit(h,r,t,c)).length)?await this.watchMyTrades(r,t,c,s):h}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e).symbol,r=0;void 0!==t&&(r=t);let a={type:"SUBSCRIBE",channels:[{name:"ORDER_BOOK",depth:r}]};return(await this.watchMany("book:"+s,a,"ORDER_BOOK",[s],i)).limit()}handleOrderBook(e,t){let i=this.safeString(t,"type"),s=this.safeString(t,"instrument_code"),a=this.safeSymbol(s),o=this.safeString(t,"time"),n=this.parse8601(o),d="book:"+a,h=this.safeValue(this.orderbooks,a);if(void 0===h&&(h=this.orderBook({})),"ORDER_BOOK_SNAPSHOT"===i){let e=this.parseOrderBook(t,a,n,"bids","asks");h.reset(e)}else if("ORDER_BOOK_UPDATE"===i){let e=this.safeList(t,"changes",[]);this.handleBookDeltas(h,e)}else throw new r.NotSupported(this.id+" watchOrderBook() did not recognize message type "+i);h.nonce=n,h.timestamp=n,h.datetime=this.iso8601(n),this.orderbooks[a]=h,e.resolve(h,d)}handleBookDelta(e,t){let i=this.parseOrderBookBidAsk(t,1,2),s=this.safeString(t,0);if("BUY"===s)e.bids.storeArray(i);else if("SELL"===s)e.asks.storeArray(i);else throw new r.NotSupported(this.id+" watchOrderBook () received unknown change type "+this.json(t))}handleBookDeltas(e,t){for(let i=0;i<t.length;i++)this.handleBookDelta(e,t[i])}async watchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a="orders";if(void 0!==e){let t=this.market(e);a+=":"+(r=this.safeString(t,"symbol"))}await this.authenticate(s);let o=this.urls.api.ws,n=this.safeString(s,"channel","ACCOUNT_HISTORY"),d=this.safeInteger(this.options,"bp_remaining_quota",200),h=this.deepExtend({type:"SUBSCRIBE",bp_remaining_quota:d,channels:[{name:n}]},s),c=await this.watch(o,a,h,n,h),l=i;return(this.newUpdates&&(l=c.getLimit(r,i)),0===(c=this.filterBySymbolSinceLimit(c,r,t,l)).length)?await this.watchOrders(r,t,l,s):c}handleTrading(e,t){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}let i=this.parseTradingOrder(t);this.orders.append(i),e.resolve(this.orders,"orders:"+i.symbol),e.resolve(this.orders,"orders")}parseTradingOrder(e,t){let i=this.safeString(e,"time"),s=this.safeString(e,"instrument_code"),r=this.safeSymbol(s,t,"_");return this.safeOrder({id:this.safeString(e,"order_id"),clientOrderId:this.safeString(e,"client_id"),info:e,timestamp:this.parse8601(i),datetime:i,lastTradeTimestamp:void 0,symbol:r,type:void 0,timeInForce:void 0,postOnly:void 0,side:this.safeStringLower(e,"side"),price:this.safeNumber2(e,"price","matched_price"),stopPrice:this.safeNumber(e,"trigger_price"),amount:this.safeNumber(e,"amount"),cost:void 0,average:void 0,filled:void 0,remaining:this.safeString(e,"remaining"),status:this.parseTradingOrderStatus(this.safeString(e,"status")),fee:void 0,trades:void 0},t)}parseTradingOrderStatus(e){return this.safeString({CANCELLED:"canceled",SELF_TRADE:"rejected",FILLED_FULLY:"closed",INSUFFICIENT_FUNDS:"rejected",INSUFFICIENT_LIQUIDITY:"rejected",TIME_TO_MARKET_EXCEEDED:"rejected",LAST_PRICE_UNKNOWN:"rejected"},e,e)}handleOrders(e,t){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new a.Pt(e)}let i=this.safeList(t,"orders",[]);if(0===i.length)return;let s=this.orders;for(let t=0;t<i.length;t++){let r=this.parseOrder(i[t]),a=this.safeString(r,"symbol","");s.append(r),e.resolve(this.orders,"orders:"+a);let o=this.safeList(i[t],"trades",[]);for(let t=0;t<o.length;t++){let i=this.parseTrade(o[t]);a=this.safeString(i,"symbol",a),this.myTrades.append(i),e.resolve(this.myTrades,"myTrades:"+a)}}e.resolve(this.orders,"orders"),e.resolve(this.myTrades,"myTrades")}handleAccountUpdate(e,t){let i;if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new a.Pt(e)}let s=this.orders,r=this.safeDict(t,"update",{}),n=this.safeString(r,"type");if("ORDER_REJECTED"===n||"ORDER_CLOSED"===n||"STOP_ORDER_TRIGGERED"===n){let e=this.safeString(r,"order_id"),t=this.safeString2(r,"time","timestamp"),a=this.filterByArray(this.orders,"id",e,!1),d=this.safeDict(a,0,{});i=this.safeString(d,"symbol");let h=this.safeString(r,"filled_amount"),c=this.parseWsOrderStatus(n);"ORDER_CLOSED"===n&&o.Y.stringEq(h,"0")&&(c="canceled");let l={id:e,symbol:i,status:c,timestamp:this.parse8601(t),datetime:t};s.append(l)}else{let e=this.parseOrder(r);i=this.safeString(e,"symbol",""),s.append(e)}e.resolve(this.orders,"orders:"+i),e.resolve(this.orders,"orders");let d=["locked","unlocked","spent","spent_on_fees","credited","deducted"];for(let e=0;e<d.length;e++){let t=this.safeDict(r,d[e]);void 0!==t&&this.updateBalance(t)}if(e.resolve(this.balance,"balance"),"TRADE_SETTLED"===n){let t=this.parseTrade(r);i=this.safeString(t,"symbol",""),this.myTrades.append(t),e.resolve(this.myTrades,"myTrades:"+i),e.resolve(this.myTrades,"myTrades")}}parseWsOrderStatus(e){return this.safeString({ORDER_REJECTED:"rejected",ORDER_CLOSED:"closed",STOP_ORDER_TRIGGERED:"triggered"},e,e)}updateBalance(e){let t=this.safeString(e,"currency_code"),i=this.safeCurrencyCode(t),s=this.account();s.free=this.safeString(e,"new_available"),s.used=this.safeString(e,"new_locked"),void 0!==i&&(this.balance[i]=s),this.balance=this.safeBalance(this.balance)}async watchOHLCV(e,t="1m",i,s,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=o.symbol,d=o.id,h=this.urls.api.ws,c=this.safeDict(this.options,"timeframes",{});if(void 0===this.safeDict(c,t))throw new r.NotSupported(this.id+" this interval is not supported, please provide one of the supported timeframes");let l="CANDLESTICKS",u=this.safeValue(this.clients,h),f="SUBSCRIBE",p={};if(void 0!==u)if(void 0!==(p=this.safeDict(u.subscriptions,l))){let e=this.safeDict(p,d,{});!0!==this.safeBool(e,t,!1)&&(f="UPDATE_SUBSCRIPTION",u.subscriptions[l]=void 0)}else p={};void 0===this.safeDict(p,d)&&void 0!==d&&(p[d]={}),void 0!==d&&void 0!==t&&(p[d][t]=!0);let m=[],g=Object.keys(p);for(let e=0;e<g.length;e++){let i=Object.keys(p[g[e]]);for(let s=0;s<i.length;s++){let i=this.safeDict(c,t),s={instrument_code:g[e],time_granularity:i};m.push(s)}}let v={type:f,channels:[{name:"CANDLESTICKS",properties:m}]},y=await this.watch(h,"ohlcv."+n+"."+t,this.deepExtend(v,a),l,p),b=s;return this.newUpdates&&(b=y.getLimit(n,s)),this.filterBySinceLimit(y,i,b,0,!0)}handleOHLCV(e,t){let i=this.safeString(t,"instrument_code"),s=this.safeSymbol(i),r=this.safeString(t,"time"),o=this.safeDict(t,"granularity"),n=this.safeDict(this.options,"timeframes",{}),d=this.findTimeframe(o,n),h="ohlcv."+s+"."+d,c=[this.parse8601(r),this.safeNumber(t,"open"),this.safeNumber(t,"high"),this.safeNumber(t,"low"),this.safeNumber(t,"close"),this.safeNumber(t,"volume")];this.ohlcvs[s]=this.safeDict(this.ohlcvs,s,{});let l=this.safeValue(this.safeDict(this.ohlcvs,s),d);if(void 0===l){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);l=new a.TG(e)}l.append(c),void 0!==s&&void 0!==d&&(this.ohlcvs[s][d]=l),e.resolve(l,h)}findTimeframe(e,t){let i=void 0===t?this.timeframes:t;if(void 0===i)throw new r.ArgumentsRequired(this.id+" findTimeframe() timeframes is required");let s=Object.keys(i);for(let t=0;t<s.length;t++){let r=s[t];if(i[r].unit===e.unit&&i[r].period===e.period)return r}}handleSubscriptions(e,t){return t}handleHeartbeat(e,t){return t}handleErrorMessage(e,t){throw new r.ExchangeError(this.id+" "+this.json(t))}handleMessage(e,t){if(void 0!==this.safeString(t,"error"))return void this.handleErrorMessage(e,t);let i=this.safeString(t,"type"),s={ORDER_BOOK_UPDATE:this.handleOrderBook,ORDER_BOOK_SNAPSHOT:this.handleOrderBook,ACTIVE_ORDERS_SNAPSHOT:this.handleOrders,INACTIVE_ORDERS_SNAPSHOT:this.handleOrders,ACCOUNT_UPDATE:this.handleAccountUpdate,BALANCES_SNAPSHOT:this.handleBalanceSnapshot,SUBSCRIPTIONS:this.handleSubscriptions,SUBSCRIPTION_UPDATED:this.handleSubscriptions,PRICE_TICK:this.handleTicker,PRICE_TICK_HISTORY:this.handleSubscriptions,HEARTBEAT:this.handleHeartbeat,MARKET_TICKER_UPDATES:this.handleTicker,PRICE_POINT_UPDATES:this.handlePricePointUpdates,CANDLESTICK_SNAPSHOT:this.handleOHLCV,CANDLESTICK:this.handleOHLCV,AUTHENTICATED:this.handleAuthenticationMessage,FILL:this.handleTrading,DONE:this.handleTrading,BOOKED:this.handleTrading,UPDATE:this.handleTrading,TRACKED:this.handleTrading,TRIGGERED:this.handleTrading,STOP_TRACKED:this.handleTrading,STOP_TRIGGERED:this.handleTrading},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}handlePricePointUpdates(e,t){return t}handleAuthenticationMessage(e,t){let i=this.safeValue(e.futures,"authenticated");return void 0!==i&&i.resolve(!0),t}async watchMany(e,t,i,s=[],r={}){let a=[];if(0===s.length){let e=this.markets_by_id;if(void 0===e)return[];a=Object.keys(e)}else a=this.marketIds(s);let o=this.urls.api.ws,n=this.safeValue(this.clients,o),d="SUBSCRIBE",h={};if(void 0!==n)if(void 0!==(h=this.safeDict(n.subscriptions,i)))for(let e=0;e<a.length;e++){let t=a[e];!0!==this.safeBool(h,t,!1)&&(d="UPDATE_SUBSCRIPTION",n.subscriptions[i]=void 0)}else h={};for(let e=0;e<a.length;e++)h[a[e]]=!0;return t.type=d,t.channels[0].instrument_codes=Object.keys(h),await this.watch(o,e,this.deepExtend(t,r),i,h)}async authenticate(e={}){let t=this.urls.api.ws,i=this.client(t),s="authenticated",r=i.reusableFuture("authenticated");if(void 0===this.safeDict(i.subscriptions,s)){this.checkRequiredCredentials();let i={type:"AUTHENTICATE",api_token:this.apiKey};this.watch(t,s,this.extend(i,e),s)}return await r}}i.d(t,{A:()=>n})},9304(e,t,i){"use strict";var s=i(356),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,cancelAllOrdersWs:!1,cancelOrdersWs:!1,cancelOrderWs:!1,createOrderWs:!1,editOrderWs:!1,fetchBalanceWs:!1,fetchOpenOrdersWs:!1,fetchOrderWs:!1,fetchTradesWs:!1,watchBalance:!1,watchMyTrades:!1,watchOHLCV:!0,watchOrderBook:!0,watchOrders:!1,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!0},urls:{api:{ws:"wss://apiws.p2pb2b.com/"}},options:{OHLCVLimit:1e3,tradesLimit:1e3,timeframes:{"15m":900,"30m":1800,"1h":3600,"1d":86400},watchTicker:{name:"state"},watchTickers:{name:"state"},tickerSubs:this.createSafeDictionary()},streaming:{ping:this.ping}})}async subscribe(e,t,i,s={}){let r=this.urls.api.ws,a={method:e,params:i,id:this.milliseconds()},o=this.extend(a,s);return await this.watch(r,t,o,t)}async watchOHLCV(e,t="15m",i,s,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.safeDict(this.options,"timeframes",{}),n=this.safeInteger(o,t);if(void 0===n)throw new r.BadRequest(this.id+" watchOHLCV cannot take a timeframe of "+t);let d=this.market(e),h=[d.id,n],c="kline::"+d.symbol,l=await this.subscribe("kline.subscribe",c,h,a),u=s;return this.newUpdates&&(u=l.getLimit(e,s)),this.filterBySinceLimit(l,i,u,0,!0)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeDict(this.options,"watchTicker"),s=this.safeString(i,"name","state"),[r,a]=this.handleOptionStringAndParams(t,"watchTicker","name",s),o=this.market(e);this.options.tickerSubs[o.id]=!0;let n=Object.keys(this.options.tickerSubs),d=r+"::"+o.symbol;return await this.subscribe(r+".subscribe",d,n,a)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=this.safeDict(this.options,"watchTicker"),r=this.safeString(s,"name","state"),[a,o]=this.handleOptionStringAndParams(t,"watchTickers","name",r),n=[],d=[];for(let e=0;e<i.length;e++){let t=this.market(i[e]);n.push(a+"::"+t.symbol),d.push(t.id)}let h=this.urls.api.ws,c={method:a+".subscribe",params:d,id:this.milliseconds()};return await this.watchMultiple(h,n,this.extend(c,o),n),this.filterByArray(this.tickers,"symbol",i)}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!1,!0,!0),a=[];if(void 0!==r)for(let e=0;e<r.length;e++)a.push("deals::"+r[e]);let o=this.marketIds(r),n=this.urls.api.ws,d={method:"deals.subscribe",params:o,id:this.milliseconds()},h=this.extend(d,s),c=await this.watchMultiple(n,a,h,a),l=this.safeDict(c,0),u=this.safeString(l,"symbol"),f=i;return this.newUpdates&&(f=c.getLimit(u,i)),this.filterBySinceLimit(c,t,f,"timestamp",!0)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="orderbook::"+s.symbol,a=this.safeString(i,"interval","0.001"),o=[s.id,void 0===t?100:t,a];return(await this.subscribe("depth.subscribe",r,o,i)).limit()}handleOHLCV(e,t){let i=this.safeList(t,"params");i=this.safeList(i,0);let s=this.safeString(t,"method").split("."),r=this.safeString(s,0),o=this.safeString(i,7),n=this.safeMarket(o),d=this.safeDict(this.options,"timeframes",{}),h=this.findTimeframe(r,d),c=this.safeString(n,"symbol"),l=this.parseOHLCV(i,n);this.ohlcvs[c]=this.safeValue(this.ohlcvs,c,{});let u=this.safeValue(this.ohlcvs[c],h);if(void 0!==c){if(void 0===u){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);u=new a.TG(e),this.ohlcvs[c][h]=u}if(u.append(l),void 0!==r){let t=r+"::"+c;e.resolve(u,t)}}return t}handleTrade(e,t){let i=this.safeList(t,"params",[]),s=this.safeList(i,1),r=this.safeString(i,0),o=this.safeMarket(r),n=this.safeString(o,"symbol"),d=this.safeValue(this.trades,n);if(void 0===d){let e=this.safeInteger(this.options,"tradesLimit",1e3);d=new a.I3(e),this.trades[n]=d}for(let e=0;e<s.length;e++){let t=s[e],i=this.parseTrade(t,o);d.append(i)}let h="deals::"+n;return e.resolve(d,h),t}handleTicker(e,t){let i,s=this.safeList(t,"params",[]),r=this.safeString(s,0),a=this.safeMarket(r),o=this.safeString(t,"method"),n=o.split("."),d=this.safeString(n,0),h=this.safeDict(s,1);if("price.update"===o){let e=this.safeString(s,1);i=this.safeTicker({last:e,close:e,symbol:a.symbol})}else i=this.parseTicker(h,a);let c=i.symbol;return this.tickers[c]=i,void 0!==d&&e.resolve(i,d+"::"+c),t}handleOrderBook(e,t){let i=this.safeList(t,"params",[]),s=this.safeBool(i,0,!1),r=this.safeDict(i,1),a=this.safeList(r,"asks"),o=this.safeList(r,"bids"),n=this.safeString(i,2),d=this.safeMarket(n),h=d.symbol,c="orderbook::"+d.symbol,l=this.safeDict(e.subscriptions,c,{}),u=this.safeInteger(l,"limit"),f=this.safeValue(this.orderbooks,h);if(void 0===f&&(this.orderbooks[h]=this.orderBook({},u),f=this.orderbooks[h]),!0===s&&f.reset({}),void 0!==o)for(let e=0;e<o.length;e++){let t=this.safeList(o,e),i=this.safeNumber(t,0),s=this.safeNumber(t,1);f.bids.store(i,s)}if(void 0!==a)for(let e=0;e<a.length;e++){let t=this.safeList(a,e),i=this.safeNumber(t,0),s=this.safeNumber(t,1);f.asks.store(i,s)}f.symbol=h,e.resolve(f,c)}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;if("pong"===this.safeString(t,"result"))return void this.handlePong(e,t);let i=this.safeString(t,"method"),s={"depth.update":this.handleOrderBook,"price.update":this.handleTicker,"kline.update":this.handleOHLCV,"state.update":this.handleTicker,"deals.update":this.handleTrade},r=this.safeValue(s,i);void 0!==r&&r.call(this,e,t)}handleErrorMessage(e,t){let i=this.safeString(t,"error");if(void 0!==i)throw new r.ExchangeError(this.id+" error: "+this.json(i));return!1}ping(e){return{method:"server.ping",params:[],id:this.milliseconds()}}handlePong(e,t){return e.lastPong=this.safeInteger(t,"id",this.milliseconds()),t}onError(e,t){this.options.tickerSubs=this.createSafeDictionary(),super.onError(e,t)}onClose(e,t){this.options.tickerSubs=this.createSafeDictionary(),super.onClose(e,t)}}i.d(t,{A:()=>o})},3100(e,t,i){"use strict";var s=i(5016),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,cancelOrderWs:!0,cancelOrdersWs:!0,cancelAllOrdersWs:!0,createOrderWs:!0,createOrdersWs:!1,editOrderWs:!0,watchBalance:!1,watchMyTrades:!0,watchOHLCV:!0,watchOrderBook:!0,watchOrders:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!1,watchPosition:!1,unWatchOrderBook:!0,unWatchTickers:!0,unWatchTrades:!0,unWatchOHLCV:!0,unWatchMyTrades:!0,unWatchOrders:!0},urls:{api:{ws:{public:"wss://ws.pacifica.fi/ws"}},test:{ws:{public:"wss://test-ws.pacifica.fi/ws"}}},options:{ws:{options:{headers:{}}}},streaming:{ping:this.ping,keepAlive:2e4},exceptions:{ws:{exact:{}}}})}setupApiKeyHeaders(e){let t={};void 0!==e?t["PF-API-KEY"]=e:void 0!==this.handleOption("setupApiKeyHeaders","apiKey")&&(t["PF-API-KEY"]=this.options.apiKey),this.options.ws.options.headers=t}async createOrderWs(e,t,i,s,a,o={}){let n;void 0===this.markets&&await this.loadMarkets();let[d,h]=this.createOrderRequest(e,t,i,s,a,o),c=this.isSandboxModeEnabled,l="api";c&&(l="test");let u=this.safeString(this.urls[l].ws,"public");if(void 0===u)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let f=this.wrapAsPostAction(h,d),p=this.safeString(f,"id");if("create_stop_order"===h)throw new r.NotSupported(this.id+" createOrderWs() do not support stop order type of order. Check provided arguments correctly!");if("set_position_tpsl"===h)throw new r.NotSupported(this.id+" createOrderWs() do not support set position tpsl type of order. Check provided arguments correctly!");let m=await this.watch(u,p,f,p),g=this.safeInteger(m,"code"),v=!1;200===g&&(v=!0),n=v?"open":"rejected";let y=this.safeDict(m,"data",{}),b=this.safeString(y,"i"),w=this.safeString(y,"I");return this.safeOrder({id:b,clientOrderId:w,status:n,info:m,symbol:e})}async editOrderWs(e,t,i,s,a,o,n={}){let d;void 0===this.markets&&await this.loadMarkets();let h=this.market(t),c=this.editOrderRequest(e,t,i,s,a,o,h,n),l=this.isSandboxModeEnabled,u="api";l&&(u="test");let f=this.safeString(this.urls[u].ws,"public");if(void 0===f)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let p=this.wrapAsPostAction("edit_order",c),m=this.safeString(p,"id"),g=await this.watch(f,m,p,m),v=this.safeInteger(g,"code"),y=!1;200===v&&(y=!0),d=y?"open":"rejected";let b=this.safeDict(g,"data",{}),w=this.safeString(b,"i"),k=this.safeString(b,"I");return this.safeOrder({id:w,clientOrderId:k,status:d,info:g,symbol:t})}async cancelOrdersWs(e,t,i={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===t)throw new r.ArgumentsRequired(this.id+'cancelOrders() requires a "symbol" argument!');let s=this.cancelOrdersRequest(e,t,i),a=this.isSandboxModeEnabled,o="api";a&&(o="test");let n=this.safeString(this.urls[o].ws,"public");if(void 0===n)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let d=this.wrapAsPostAction("batch_orders",s),h=this.safeString(d,"id"),c=await this.watch(n,h,d,h),l=this.safeDict(c,"data",{}),u=this.safeList(l,"results",[]),f=[];for(let e=0;e<u.length;e++){let t,i=this.safeDict(u,e),s=this.safeString(i,"error"),r=this.safeBool(i,"success",!1),a=this.safeString(i,"symbol"),o=this.safeMarket(a),n=this.safeString(i,"i"),d=this.safeString(i,"I");t=void 0!==s||!0!==r?"closed":"canceled",f.push(this.safeOrder({id:n,clientOrderId:d,status:t,info:c,symbol:o.symbol}))}return f}async cancelOrderWs(e,t,i={}){let s;if(void 0===this.markets&&await this.loadMarkets(),void 0===t)throw new r.ArgumentsRequired(this.id+" cancelOrderWs() requires a symbol argument");let a=this.cancelOrderRequest(e,t,i),o=this.isSandboxModeEnabled,n="api";o&&(n="test");let d=this.safeString(this.urls[n].ws,"public");if(void 0===d)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let h=this.wrapAsPostAction("cancel_order",a),c=this.safeString(h,"id"),l=await this.watch(d,c,h,c),u=this.safeInteger(l,"code"),f=!1;200===u&&(f=!0),s=f?"open":"rejected";let p=this.safeDict(l,"data",{}),m=this.safeString(p,"i"),g=this.safeString(p,"I");return this.safeOrder({id:m,clientOrderId:g,status:s,info:l,symbol:t})}async cancelAllOrdersWs(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.cancelAllOrdersRequest(e,t),s=this.isSandboxModeEnabled,a="api";s&&(a="test");let o=this.safeString(this.urls[a].ws,"public");if(void 0===o)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let n=this.wrapAsPostAction("cancel_all_orders",i),d=this.safeString(n,"id"),h=await this.watch(o,d,n,d);return[this.safeOrder({info:h})]}async watchOrderBook(e,t,i={}){this.setupApiKeyHeaders(),void 0===this.markets&&await this.loadMarkets();let s=this.market(e),[a,o]=this.handleOptionIntegerAndParams(i,"watchOrderBook","aggLevel",1),n="orderbook:"+e,d=this.isSandboxModeEnabled,h="api";d&&(h="test");let c=this.safeString(this.urls[h].ws,"public");if(void 0===c)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let l={method:"subscribe",params:{source:"book",symbol:s.id,agg_level:a}},u=this.extend(l,o);return(await this.watch(c,n,u,n)).limit()}async unWatchOrderBook(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),[s,a]=this.handleOptionIntegerAndParams(t,"watchOrderBook","aggLevel",1),o="unsubscribe:orderbook:"+e,n=this.isSandboxModeEnabled,d="api";n&&(d="test");let h=this.safeString(this.urls[d].ws,"public");if(void 0===h)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let c={method:"unsubscribe",params:{source:"book",symbol:i.id,agg_level:s}},l=this.extend(c,a);return await this.watch(h,o,l,o)}handleOrderBook(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"s"),r=this.safeMarket(s).symbol,a=this.safeList(i,"l",[]),o={bids:this.safeList(a,0,[]),asks:this.safeList(a,1,[])},n=this.safeInteger(i,"t"),d=this.parseOrderBook(o,r,n,"bids","asks","p","a"),h=this.safeInteger(i,"li");if(void 0!==h&&0!==h&&(d.nonce=h),!(r in this.orderbooks)){let e=this.orderBook(d);this.orderbooks[r]=e}let c=this.orderbooks[r];c.reset(d);let l="orderbook:"+r;e.resolve(c,l)}async watchTicker(e,t={}){return(await this.watchTickers([e],t))[e]}async watchTickers(e,t={}){this.setupApiKeyHeaders(),void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!0),s="tickers",a=this.isSandboxModeEnabled,o="api";a&&(o="test");let n=this.safeString(this.urls[o].ws,"public");if(void 0===n)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let d=await this.watch(n,s,this.extend({method:"subscribe",params:{source:"prices"}},t),s);return this.newUpdates?this.filterByArrayTickers(d,"symbol",i):this.tickers}async unWatchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets(),this.marketSymbols(e,void 0,!0);let i="unsubscribe:tickers",s=this.isSandboxModeEnabled,a="api";s&&(a="test");let o=this.safeString(this.urls[a].ws,"public");if(void 0===o)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");return await this.watch(o,i,this.extend({method:"unsubscribe",params:{source:"prices"}},t),i)}async watchMyTrades(e,t,i,s={}){let a,[o,n]=this.handleOriginAndSingleAddress("watchMyTrades",s);void 0===this.markets&&await this.loadMarkets();let d="myTrades";void 0!==e&&(d+=":"+(a=this.symbol(e)));let h=this.isSandboxModeEnabled,c="api";h&&(c="test");let l=this.safeString(this.urls[c].ws,"public");if(void 0===l)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let u=this.extend({method:"subscribe",params:{source:"account_trades",account:o}},n),f=await this.watch(l,d,u,d),p=i;return this.newUpdates&&(p=f.getLimit(a,i)),this.filterBySymbolSinceLimit(f,a,t,p,!0)}async unWatchMyTrades(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0!==e)throw new r.NotSupported(this.id+" unWatchMyTrades does not support a symbol argument, unWatch from all markets only");let[i,s]=this.handleOriginAndSingleAddress("unWatchMyTrades",t),a="unsubscribe:myTrades",o=this.isSandboxModeEnabled,n="api";o&&(n="test");let d=this.safeString(this.urls[n].ws,"public");if(void 0===d)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let h=this.extend({method:"unsubscribe",params:{source:"account_trades",account:i}},s);return await this.watch(d,a,h,a)}handleWsTickers(e,t){let i=[],s=this.safeList(t,"data",[]);for(let e=0;e<s.length;e++){let t=s[e],r=this.safeString(t,"symbol"),a=this.safeMarket(r),o=a.symbol,n=this.parseWsTicker(t,a);this.tickers[o]=n,i.push(n)}let r=this.indexBy(i,"symbol");return e.resolve(r,"tickers"),!0}parseWsTicker(e,t){return this.parseTicker(e,t)}handleMyTrades(e,t){if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new a.Pt(e)}let i=this.myTrades,s={},r=this.safeList(t,"data",[]);if(0===r.length)return;for(let e=0;e<r.length;e++){let t=r[e],a=this.parseWsTrade(t),o=a.symbol;void 0!==o&&(s[o]=!0),i.append(a)}let o=Object.keys(s);for(let t=0;t<o.length;t++){let s="myTrades:"+o[t];e.resolve(i,s)}e.resolve(i,"myTrades")}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n="trade:"+o,d=this.isSandboxModeEnabled,h="api";d&&(h="test");let c=this.safeString(this.urls[h].ws,"public");if(void 0===c)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let l={method:"subscribe",params:{source:"trades",symbol:a.id}},u=this.extend(l,s),f=await this.watch(c,n,u,n),p=i;return this.newUpdates&&(p=f.getLimit(o,i)),this.filterBySinceLimit(f,t,p,"timestamp",!0)}async unWatchTrades(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="unsubscribe:trade:"+i.symbol,a=this.isSandboxModeEnabled,o="api";a&&(o="test");let n=this.safeString(this.urls[o].ws,"public");if(void 0===n)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let d={method:"unsubscribe",params:{source:"trades",symbol:i.id}},h=this.extend(d,t);return await this.watch(n,s,h,s)}handleTrades(e,t){let i=this.safeList(t,"data",[]),s=this.safeDict(i,0,{}),r=this.safeString(s,"s"),o=this.safeMarket(r).symbol;if(!(o in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3),t=new a.I3(e);this.trades[o]=t}let n=this.trades[o];for(let e=0;e<i.length;e++){let t=this.safeDict(i,e,{}),s=this.parseWsTrade(t);n.append(s)}e.resolve(n,"trade:"+o)}parseWsTrade(e,t){let i,s=this.safeInteger(e,"t"),r=this.safeString(e,"p"),a=this.safeString(e,"a"),o=this.safeString(e,"s"),n=this.safeMarket(o,t),d=n.symbol,h=this.safeString(e,"h"),c=this.safeString(e,"f"),l=this.safeString2(e,"ts","d");"open_long"===l?l="buy":"close_long"===l||"open_short"===l?l="sell":"close_short"===l&&(l="buy");let u=this.safeString(e,"te");return void 0!==u&&(i="fulfill_maker"===u?"maker":"taker"),void 0===this.safeString(e,"i")&&(i=void 0),this.safeTrade({info:e,timestamp:s,datetime:this.iso8601(s),symbol:d,id:h,order:this.safeString(e,"i"),type:void 0,side:l,takerOrMaker:i,price:r,amount:a,cost:void 0,fee:{cost:c,currency:"USDC"}},n)}async watchOHLCV(e,t="1m",i,s,a={}){void 0===this.markets&&await this.loadMarkets();let o=this.market(e),n=o.symbol,d=this.isSandboxModeEnabled,h=this.safeString(this.timeframes,t,t),c="api";d&&(c="test");let l=this.safeString(this.urls[c].ws,"public");if(void 0===l)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let u={method:"subscribe",params:{source:"candle",symbol:o.id,interval:h}},f="candles:"+h+":"+n,p=this.extend(u,a),m=await this.watch(l,f,p,f),g=s;return this.newUpdates&&(g=m.getLimit(n,s)),this.filterBySinceLimit(m,i,g,0,!0)}async unWatchOHLCV(e,t="1m",i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),a=s.symbol,o=this.isSandboxModeEnabled,n="api";o&&(n="test");let d=this.safeString(this.urls[n].ws,"public");if(void 0===d)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let h={method:"unsubscribe",params:{source:"candle",symbol:s.id,interval:t}},c="unsubscribe:"+("candles:"+t+":")+a,l=this.extend(h,i);return await this.watch(d,c,l,c)}handleOHLCV(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"s"),r=this.safeMarket(s).symbol,o=this.safeString(i,"i");if(void 0===o)return;r in this.ohlcvs||(this.ohlcvs[r]={});let n=this.safeDict(this.ohlcvs,r,{}),d=this.safeValue(n,o);if(void 0===d){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);d=new a.TG(e),n[o]=d}let h=this.parseOHLCV(i);d.append(h);let c="candles:"+o+":"+r;e.resolve(d,c)}async watchOrders(e,t,i,s={}){let a,o;void 0===this.markets&&await this.loadMarkets();let[n,d]=this.handleOriginAndSingleAddress("watchOrders",s),h="order";void 0!==e&&(a=this.market(e),h=h+":"+(o=this.safeString(a,"symbol")));let c=this.isSandboxModeEnabled,l="api";c&&(l="test");let u=this.safeString(this.urls[l].ws,"public");if(void 0===u)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let f=this.extend({method:"subscribe",params:{source:"account_order_updates",account:n}},d),p=await this.watch(u,h,f,h),m=i;return this.newUpdates&&(m=p.getLimit(o,i)),this.filterBySymbolSinceLimit(p,o,t,m,!0)}async unWatchOrders(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0!==e)throw new r.NotSupported(this.id+" unWatchOrders() does not support a symbol argument, unWatch from all markets only");let i="unsubscribe:order",s=this.isSandboxModeEnabled,a="api";s&&(a="test");let o=this.safeString(this.urls[a].ws,"public");if(void 0===o)throw new r.ExchangeError(this.id+" has no websocket url for this endpoint");let[n,d]=this.handleOriginAndSingleAddress("unWatchOrders",t),h=this.extend({method:"unsubscribe",params:{source:"account_order_updates",account:n}},d);return await this.watch(o,i,h,i)}handleOrder(e,t){let i=this.safeList(t,"data",[]);if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}if(0===i.length)return;let s=this.orders,r="order",o={};for(let e=0;e<i.length;e++){let t=i[e],r=this.parseOrder(t);s.append(r);let a=this.safeString(r,"symbol");void 0!==a&&(o[a]=!0)}let n=Object.keys(o);for(let t=0;t<n.length;t++){let i=r+":"+n[t];e.resolve(s,i)}e.resolve(s,r)}handleErrorMessage(e,t){let i=this.safeString(t,"err",""),s=this.safeString(t,"type",""),r=this.safeDict(t,"data",{}),a=this.safeString(t,"id");void 0===a&&(a=this.safeString(r,"id"));try{this.handleErrors(0,i,"",s,this.options.ws.options.headers,this.json(r),t,{},{})}catch(t){return e.reject(t,a),!0}return!1}handleOrderBookUnsubscription(e,t){let i=this.safeString2(t,"symbol","s"),s=this.safeMarket(i).symbol,r="orderbook:"+s;this.cleanUnsubscription(e,r,"unsubscribe:"+r),s in this.orderbooks&&delete this.orderbooks[s]}handleTradesUnsubscription(e,t){let i=this.safeString2(t,"symbol","s"),s=this.safeMarket(i).symbol,r="trade:"+s;this.cleanUnsubscription(e,r,"unsubscribe:"+r),s in this.trades&&delete this.trades[s]}handleTickersUnsubscription(e,t){let i="tickers";this.cleanUnsubscription(e,i,"unsubscribe:"+i);let s=Object.keys(this.tickers);for(let e=0;e<s.length;e++)delete this.tickers[s[e]]}handleOHLCVUnsubscription(e,t){let i=this.safeString2(t,"symbol","s"),s=this.safeMarket(i).symbol,r=this.safeString(t,"interval"),a=this.findTimeframe(r);if(void 0===a)return;let o="candles:"+a+":"+s;this.cleanUnsubscription(e,o,"unsubscribe:"+o),void 0!==s&&s in this.ohlcvs&&void 0!==a&&a in this.ohlcvs[s]&&delete this.ohlcvs[s][a]}handleOrderUnsubscription(e,t){let i="order";this.cleanUnsubscription(e,i,"unsubscribe:"+i,!0),this.cleanCache({topic:"orders"})}handleMyTradesUnsubscription(e,t){let i="myTrades";this.cleanUnsubscription(e,i,"unsubscribe:"+i,!0),this.cleanCache({topic:"myTrades"})}handleSubscriptionResponse(e,t){let i=this.safeDict(t,"data",{});if("unsubscribe"===this.safeString(t,"channel")){let t=this.safeDict(i,"data",{}),s=this.safeString(t,"source");"book"===s?this.handleOrderBookUnsubscription(e,t):"trades"===s?this.handleTradesUnsubscription(e,t):"prices"===s?this.handleTickersUnsubscription(e,t):"candle"===s?this.handleOHLCVUnsubscription(e,t):"account_order_updates"===s?this.handleOrderUnsubscription(e,t):"account_trades"===s&&this.handleMyTradesUnsubscription(e,t)}}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;let i=this.safeString(t,"type"),s=this.safeString(t,"channel",""),r={pong:this.handlePong,trades:this.handleTrades,book:this.handleOrderBook,candle:this.handleOHLCV,account_order_updates:this.handleOrder,account_trades:this.handleMyTrades,prices:this.handleWsTickers,subscribe:this.handleSubscriptionResponse,unsubscribe:this.handleSubscriptionResponse},a=this.safeValue(r,s);if(void 0!==a)return void a.call(this,e,t);if(void 0!==i)return void this.handleWsPost(e,t);let o=Object.keys(r);for(let i=0;i<o.length;i++){let a=o[i];if(s.indexOf(o[i])>=0)return void r[a].call(this,e,t)}}ping(e){return{method:"ping"}}handlePong(e,t){return e.lastPong=this.safeInteger(t,"pong",this.milliseconds()),t}requestId(){return this.uuid()}wrapAsPostAction(e,t){if(void 0===e)throw new r.ArgumentsRequired(this.id+'postAction() requires a "operationType" argument!');let i={id:this.requestId(),params:{}};return i.params[e]=t,i}handleWsPost(e,t){let i=this.safeString(t,"id");e.resolve(t,i)}}i.d(t,{A:()=>o})},2935(e,t,i){"use strict";var s=i(3651),r=i(1697);class a extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchFundingRate:!0,watchFundingRates:!0,watchTicker:!0,watchTickers:!0,watchOrderBook:!0,watchOrders:!0,watchTrades:!0,watchTradesForSymbols:!1,watchBalance:!1,watchOHLCV:!1},urls:{logo:"https://x.com/tradeparadex/photo",api:{ws:"wss://ws.api.prod.paradex.trade/v1"},test:{ws:"wss://ws.api.testnet.paradex.trade/v1"},www:"https://www.paradex.trade/",doc:"https://docs.api.testnet.paradex.trade/",fees:"https://docs.paradex.trade/getting-started/trading-fees",referral:""},options:{},streaming:{}})}requestId(){let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,e}async authenticate(e={}){let t=this.urls.api.ws,i=this.client(t),s="authenticated",r=i.reusableFuture("authenticated");if(void 0===this.safeValue(i.subscriptions,s)){let i=await this.authenticateRest(),r={jsonrpc:"2.0",id:this.requestId(),method:"auth",params:{bearer:i}};this.watch(t,s,this.deepExtend(r,e),s)}return await r}handleAuthenticationMessage(e,t){if(void 0!==this.safeDict(t,"result")){let t=this.safeValue(e.futures,"authenticated");void 0!==t&&t.resolve(!0)}}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r="trades.";void 0!==e?r+=this.market(e).id:r+="ALL";let a=this.urls.api.ws,o={jsonrpc:"2.0",method:"subscribe",params:{channel:r}},n=await this.watch(a,r,this.deepExtend(o,s),r),d=i;return this.newUpdates&&(d=n.getLimit(e,i)),this.filterBySinceLimit(n,t,d,"timestamp",!0)}handleTrade(e,t){let i=this.safeDict(t,"params",{}),s=this.safeDict(i,"data",{}),a=this.parseTrade(s),o=a.symbol,n=this.safeString(i,"channel"),d=this.safeValue(this.trades,o);return void 0===d&&(d=new r.I3(this.safeInteger(this.options,"tradesLimit",1e3)),this.trades[o]=d),d.append(a),e.resolve(d,n),t}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s="order_book."+this.market(e).id+".snapshot@15@100ms",r=this.urls.api.ws;return(await this.watch(r,s,this.deepExtend({jsonrpc:"2.0",method:"subscribe",params:{channel:s}},i),s)).limit()}handleOrderBook(e,t){let i=this.safeDict(t,"params",{}),s=this.safeDict(i,"data",{}),r=this.safeString(s,"market"),a=this.safeMarket(r),o=this.safeInteger(s,"last_updated_at"),n=a.symbol;n in this.orderbooks||(this.orderbooks[n]=this.orderBook());let d={bids:[],asks:[]},h=this.safeList(s,"inserts");for(let e=0;e<h.length;e++){let t=this.safeDict(h,e),i=this.safeString(t,"side"),s=this.safeString(t,"price"),r=this.safeString(t,"size");"BUY"===i?d.bids.push([s,r]):d.asks.push([s,r])}let c=this.orderbooks[n],l=this.parseOrderBook(d,n,o,"bids","asks");l.nonce=this.safeInteger(s,"seq_no"),c.reset(l);let u=this.safeString(i,"channel");e.resolve(c,u)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.symbol(e),s="markets_summary",r=this.urls.api.ws,a=s+"."+i;return await this.watch(r,a,this.deepExtend({jsonrpc:"2.0",method:"subscribe",params:{channel:s}},t),a)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s="markets_summary",r=this.urls.api.ws,a=[];if(void 0!==i&&Array.isArray(i))for(let e=0;e<i.length;e++){let t=s+"."+i[e];a.push(t)}else a.push(s);let o=await this.watchMultiple(r,a,this.deepExtend({jsonrpc:"2.0",method:"subscribe",params:{channel:s}},t),a);if(this.newUpdates){let e={},t=this.safeString(o,"symbol");return void 0!==t&&(e[t]=o),e}return this.filterByArray(this.tickers,"symbol",i)}async watchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r="orders",a="orders.",o=void 0!==e?this.symbol(e):e;void 0!==e?(a+=this.market(e).id,r+=":"+o):a+="ALL";let n=this.urls.api.ws,d={jsonrpc:"2.0",method:"subscribe",params:{channel:a}},h=await this.watch(n,r,this.deepExtend(d,s),a),c=i;return this.newUpdates&&(c=h.getLimit(o,i)),this.filterBySymbolSinceLimit(h,o,t,c,!0)}handleOrder(e,t){let i=this.safeDict(t,"params",{}),s=this.safeDict(i,"data",{}),a=this.parseOrder(s),o=this.safeString(a,"symbol");if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new r.Pt(e)}this.orders.append(a);let n="orders";e.resolve(this.orders,n),void 0!==o&&e.resolve(this.orders,n+":"+o)}handleTicker(e,t){let i=this.safeDict(t,"params",{}),s=this.safeDict(i,"data",{}),r=this.safeString(s,"symbol"),a=this.safeMarket(r),o=a.symbol,n=this.safeString(i,"channel"),d=this.parseTicker(s,a);return this.tickers[o]=d,e.resolve(d,n),void 0!==n&&e.resolve(d,n+"."+o),t}async watchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.symbol(e),s="funding_data",r=this.urls.api.ws,a=s+"."+i;return await this.watch(r,a,this.deepExtend({jsonrpc:"2.0",method:"subscribe",params:{channel:s}},t),a)}async watchFundingRates(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s="funding_data",r=this.urls.api.ws,a=[];if(void 0!==i)if(i.length>0)for(let e=0;e<i.length;e++){let t=s+"."+i[e];a.push(t)}else a.push(s);else a.push(s);let o=await this.watchMultiple(r,a,this.deepExtend({jsonrpc:"2.0",method:"subscribe",params:{channel:s}},t),a);if(this.newUpdates){let e={},t=this.safeString(o,"symbol");return void 0!==t&&(e[t]=o),e}return this.filterByArray(this.fundingRates,"symbol",i)}handleFundingRate(e,t){let i=this.safeDict(t,"params",{}),s=this.safeDict(i,"data",{}),r=this.parseFundingRateWs(s),a=r.symbol;this.fundingRates[a]=r;let o=this.safeString(i,"channel");void 0!==o&&e.resolve(r,o+"."+a)}parseFundingRateWs(e,t){let i,s=this.safeString(e,"market"),r=this.safeSymbol(s,t),a=this.safeInteger(e,"created_at"),o=this.safeString(e,"funding_period_hours");return void 0!==o&&(i=o+"h"),{info:e,symbol:r,markPrice:void 0,indexPrice:void 0,interestRate:this.parseNumber("0"),estimatedSettlePrice:void 0,timestamp:a,datetime:this.iso8601(a),fundingRate:this.safeNumber(e,"funding_rate"),fundingTimestamp:void 0,fundingDatetime:void 0,nextFundingRate:void 0,nextFundingTimestamp:void 0,nextFundingDatetime:void 0,previousFundingRate:void 0,previousFundingTimestamp:void 0,previousFundingDatetime:void 0,interval:i}}handleErrorMessage(e,t){let i=this.safeDict(t,"error");if(void 0===i)return!0;if(void 0!==this.safeString(i,"code")){let e=this.id+" "+this.json(i);this.throwExactlyMatchedException(this.exceptions.exact,"-32600",e);let t=this.safeString(i,"message");void 0!==t&&this.throwBroadlyMatchedException(this.exceptions.broad,t,e)}return!1}handleMessage(e,t){if(!0!==this.handleErrorMessage(e,t))return;if(void 0!==this.safeDict(t,"result"))return void this.handleAuthenticationMessage(e,t);let i=this.safeDict(t,"params");if(void 0!==i){let s=this.safeString(i,"channel").split("."),r=this.safeString(s,0),a={trades:this.handleTrade,order_book:this.handleOrderBook,markets_summary:this.handleTicker,orders:this.handleOrder,funding_data:this.handleFundingRate},o=this.safeValue(a,r);void 0!==o&&o.call(this,e,t)}}}i.d(t,{A:()=>a})},8009(e,t,i){"use strict";var s=i(4721),r=i(5653),a=i(7749),o=i(1697),n=i(1453);class d extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchMyTrades:!0,watchOrders:!0,watchOrderBook:!0,watchOHLCV:!0,watchPositions:void 0,watchOrderBookForSymbols:!1,watchTradesForSymbols:!1,watchOHLCVForSymbols:!1,watchBalance:!0},urls:{test:{ws:"wss://testnet-api.phemex.com/ws"},api:{ws:"wss://ws.phemex.com"}},options:{tradesLimit:1e3,OHLCVLimit:1e3},streaming:{keepAlive:9e3}})}fromEn(e,t){if(void 0===e)return;let i=new a.Y(e);return i.decimals=this.sum(i.decimals,t),i.reduce(),i.toString()}fromEp(e,t){return void 0===e||void 0===t?e:this.fromEn(e,this.safeInteger(t,"priceScale"))}fromEv(e,t){return void 0===e||void 0===t?e:this.fromEn(e,this.safeInteger(t,"valueScale"))}fromEr(e,t){return void 0===e||void 0===t?e:this.fromEn(e,this.safeInteger(t,"ratioScale"))}requestId(){this.lockId();let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,this.unlockId(),e}parseSwapTicker(e,t){let i,s,r,o=this.safeString(e,"symbol"),n=this.safeMarket(o,t),d=n.symbol,h=this.safeIntegerProduct(e,"timestamp",1e-6),c=this.fromEp(this.safeString(e,"close"),n),l=this.parseNumber(c),u=this.parseNumber(this.fromEv(this.safeString(e,"turnover"),n)),f=this.parseNumber(this.fromEv(this.safeString(e,"volume"),n)),p=this.omitZero(this.fromEp(this.safeString(e,"open"),n)),m=this.parseNumber(p);return void 0!==p&&void 0!==c&&(i=this.parseNumber(a.Y.stringSub(c,p)),r=this.parseNumber(a.Y.stringDiv(a.Y.stringAdd(c,p),"2")),s=this.parseNumber(a.Y.stringMul(a.Y.stringSub(a.Y.stringDiv(c,p),"1"),"100"))),this.safeTicker({symbol:d,timestamp:h,datetime:this.iso8601(h),high:this.parseNumber(this.fromEp(this.safeString(e,"high"),n)),low:this.parseNumber(this.fromEp(this.safeString(e,"low"),n)),bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:m,close:l,last:l,previousClose:void 0,change:i,percentage:s,average:r,baseVolume:f,quoteVolume:u,markPrice:this.parseNumber(this.fromEp(this.safeString(e,"markPrice"),n)),indexPrice:this.parseNumber(this.fromEp(this.safeString(e,"indexPrice"),n)),info:e})}parsePerpetualTicker(e,t){let i,s,r,o=this.safeString(e,0),n=this.safeMarket(o,t),d=n.symbol,h=this.fromEp(this.safeString(e,4),n),c=this.parseNumber(h),l=this.parseNumber(this.fromEv(this.safeString(e,6),n)),u=this.parseNumber(this.fromEv(this.safeString(e,5),n)),f=this.omitZero(this.fromEp(this.safeString(e,1),n)),p=this.parseNumber(f);return void 0!==f&&void 0!==h&&(i=this.parseNumber(a.Y.stringSub(h,f)),r=this.parseNumber(a.Y.stringDiv(a.Y.stringAdd(h,f),"2")),s=this.parseNumber(a.Y.stringMul(a.Y.stringSub(a.Y.stringDiv(h,f),"1"),"100"))),this.safeTicker({symbol:d,timestamp:void 0,datetime:void 0,high:this.parseNumber(this.fromEp(this.safeString(e,2),n)),low:this.parseNumber(this.fromEp(this.safeString(e,3),n)),bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:p,close:c,last:c,previousClose:void 0,change:i,percentage:s,average:r,baseVolume:u,quoteVolume:l,info:e})}handleTicker(e,t){let i=[];if("market24h"in t){let e=this.safeValue(t,"market24h");i.push(this.parseSwapTicker(e))}else if("spot_market24h"in t){let e=this.safeValue(t,"spot_market24h");i.push(this.parseTicker(e))}else if("data"in t){let e=this.safeList(t,"data",[]);for(let t=0;t<e.length;t++)i.push(this.parsePerpetualTicker(e[t]))}for(let s=0;s<i.length;s++){let r=i[s],a=r.symbol,o="ticker:"+a,n=this.safeIntegerProduct(t,"timestamp",1e-6);r.timestamp=n,r.datetime=this.iso8601(n),this.tickers[a]=r,e.resolve(r,o)}}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleMarketTypeAndParams("watchBalance",void 0,e),s="USDT"===this.safeString(i,"settle"),r=":balance";return r=s?"perpetual"+r:t+r,await this.subscribePrivate(t,r,i)}handleBalance(e,t,i){this.balance.info=i;for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),s=this.safeString(t,"currency"),r=this.safeCurrencyCode(s),o=this.safeDict(this.currencies,r,{}),n=this.safeInteger(o,"valueScale",8),d=this.account(),h=this.safeString(t,"totalUsedBalanceRv");if(void 0===h){let e=this.safeString(t,"totalUsedBalanceEv");if(void 0===e){let i=this.safeString(t,"lockedTradingBalanceEv"),s=this.safeString2(t,"lockedWithdrawEv","lockedWithdrawRv");e=a.Y.stringAdd(i,s)}h=this.fromEn(e,n)}let c=this.safeString(t,"accountBalanceRv");if(void 0===c){let e=this.safeString2(t,"accountBalanceEv","balanceEv");c=this.fromEn(e,n)}d.used=h,d.total=c,void 0!==r&&(this.balance[r]=d),this.balance=this.safeBalance(this.balance)}t.resolve(this.balance,e+":balance")}handleTrades(e,t){let i=this.safeString(t,"symbol"),s=this.safeMarket(i),r=s.symbol,a="trade:"+r,n=this.safeValue(this.trades,r);if(void 0===n){let e=this.safeInteger(this.options,"tradesLimit",1e3);n=new o.I3(e),this.trades[r]=n}let d=this.safeList2(t,"trades","trades_p",[]),h=this.parseTrades(d,s);for(let e=0;e<h.length;e++)n.append(h[e]);e.resolve(n,a)}handleOHLCV(e,t){let i=this.safeString(t,"symbol"),s=this.safeMarket(i),r=s.symbol,a=this.safeList2(t,"kline","kline_p",[]),n=this.safeList(a,0,[]),d=this.safeString(n,1),h=this.findTimeframe(d);if(void 0!==h){let t="kline:"+h+":"+r,i=this.parseOHLCVs(a,s);this.ohlcvs[r]=this.safeDict(this.ohlcvs,r,{});let n=this.safeValue(this.safeDict(this.ohlcvs,r),h);if(void 0===n){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);n=new o.TG(e),this.ohlcvs[r][h]=n}for(let e=0;e<i.length;e++){let t=i[e];n.append(t)}e.resolve(n,t)}}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.symbol,r=i.swap,a="USDT"===i.settle,o="spot_market24h";!0===r&&(o=a?"perp_market24h_pack_p":"market24h");let n=this.urls.api.ws,d=this.requestId(),h=o+".subscribe",c=this.deepExtend({method:h,id:d,params:[]},t);return await this.watch(n,"ticker:"+s,c,h)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=i[0],r=this.market(s),a=r.swap,o="USDT"===r.settle,n="spot_market24h";!0===a&&(n=o?"perp_market24h_pack_p":"market24h");let d=this.urls.api.ws,h=this.requestId(),c=n+".subscribe",l=[];for(let e=0;e<i.length;e++)l.push("ticker:"+i[e]);let u=this.deepExtend({method:c,id:h,params:[]},t),f=await this.watchMultiple(d,l,u,l);if(this.newUpdates){let e={},t=this.safeString(f,"symbol");return void 0!==t&&(e[t]=f),e}return this.filterByArray(this.tickers,"symbol",i)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o=this.urls.api.ws,n=this.requestId(),d=r.swap,h="USDT"===r.settle,c="trade";!0===d&&h&&(c="trade_p");let l="trade:"+a,u={method:c+".subscribe",id:n,params:[r.id]},f=this.deepExtend(u,s),p=await this.watch(o,l,f,l),m=i;return this.newUpdates&&(m=p.getLimit(a,i)),this.filterBySinceLimit(p,t,m,"timestamp",!0)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=s.symbol,a=this.urls.api.ws,o=this.requestId(),n=s.swap,d="USDT"===s.settle,h="orderbook";!0===n&&d&&(h="orderbook_p");let c="orderbook:"+r,l={method:h+".subscribe",id:o,params:[s.id]},u=this.deepExtend(l,i);return(await this.watch(a,c,u,c)).limit()}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n=this.urls.api.ws,d=this.requestId(),h=a.swap,c="USDT"===a.settle,l="kline";!0===h&&c&&(l="kline_p");let u="kline:"+t+":"+o,f={method:l+".subscribe",id:d,params:[a.id,this.safeInteger(this.timeframes,t)]},p=this.deepExtend(f,r),m=await this.watch(n,u,p,u),g=s;return this.newUpdates&&(g=m.getLimit(o,s)),this.filterBySinceLimit(m,i,g,0,!0)}customHandleDelta(e,t,i){let s=this.customParseBidAsk(t,0,1,i);e.storeArray(s)}customHandleDeltas(e,t,i){for(let s=0;s<t.length;s++)this.customHandleDelta(e,t[s],i)}handleOrderBook(e,t){let i=this.safeString(t,"symbol"),s=this.safeMarket(i),r=s.symbol,a=this.safeString(t,"type"),o=this.safeInteger(t,"depth"),n="orderbook:"+r,d=this.safeInteger(t,"sequence"),h=this.safeIntegerProduct(t,"timestamp",1e-6);if("snapshot"===a){let i=this.safeDict2(t,"book","orderbook_p",{}),a=this.customParseOrderBook(i,r,h,"bids","asks",0,1,s);a.nonce=d;let c=this.orderBook(a,o);this.orderbooks[r]=c,e.resolve(c,n)}else if(r in this.orderbooks){let i=this.orderbooks[r],a=this.safeDict2(t,"book","orderbook_p",{}),o=this.safeList(a,"asks",[]),c=this.safeList(a,"bids",[]);this.customHandleDeltas(i.asks,o,s),this.customHandleDeltas(i.bids,c,s),i.nonce=d,i.timestamp=h,i.datetime=this.iso8601(h),this.orderbooks[r]=i,e.resolve(i,n)}}async watchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a="trades:",o=void 0!==e?this.symbol(e):e;void 0!==e&&(a+=(r=this.market(e)).symbol);let n=void 0!==r&&"USDT"===r.settle,d={};n&&(d={settle:"USDT"});let[h,c]=this.handleMarketTypeAndParams("watchMyTrades",r,this.extend(s,d));void 0===o&&(a="USDT"===this.safeString(c,"settle")?a+"perpetual":a+h);let l=await this.subscribePrivate(h,a,c),u=i;return this.newUpdates&&(u=l.getLimit(o,i)),this.filterBySymbolSinceLimit(l,o,t,u,!0)}handleMyTrades(e,t){let i,s="trades";if(0===t.length)return;let r=this.myTrades;if(void 0===r){let e=this.safeInteger(this.options,"tradesLimit",1e3);r=new o.Pt(e)}let a={};for(let e=0;e<t.length;e++){let s=t[e],o=this.safeString(s,"symbol"),n=this.safeMarket(o),d=this.parseTrade(s);r.append(d);let h=d.symbol;void 0===i&&(i="USDT"===n.settle?"perpetual":n.type),void 0!==h&&(a[h]=!0)}let n=Object.keys(a);for(let t=0;t<n.length;t++){let i=s+":"+n[t];e.resolve(r,i)}let d=s+":"+i;e.resolve(r,d)}async watchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a="orders:",o=void 0!==e?this.symbol(e):e;void 0!==e&&(a+=(r=this.market(e)).symbol);let n=void 0!==r&&"USDT"===r.settle,d={};n&&(d={settle:"USDT"});let[h,c]=this.handleMarketTypeAndParams("watchOrders",r,this.extend(s,d)),l="USDT"===this.safeString(c,"settle");void 0===o&&(a=l?a+"perpetual":a+h);let u=await this.subscribePrivate(h,a,c),f=i;return this.newUpdates&&(f=u.getLimit(o,i)),this.filterBySymbolSinceLimit(u,o,t,f,!0)}handleOrders(e,t){let i,s=[],r=[];if("closed"in t||"fills"in t||"open"in t){let e=this.safeList(t,"closed",[]),i=this.safeList(t,"open",[]),a=this.arrayConcat(i,e);if(0===a.length)return;s=this.safeList(t,"fills",[]);for(let e=0;e<a.length;e++){let t=a[e],i=this.parseOrder(t);r.push(i)}}else{if(0===t.length)return;for(let e=0;e<t.length;e++){let i=t[e],a=this.safeString(i,"action");void 0!==a&&"Cancel"!==a&&s.push(i);let o=this.parseWSSwapOrder(i);r.push(o)}}this.handleMyTrades(e,s);let a=this.safeInteger(this.options,"ordersLimit",1e3),n={};void 0===this.orders&&(this.orders=new o.Pt(a));let d=this.orders;for(let e=0;e<r.length;e++){let t=r[e];d.append(t);let s=t.symbol,a=this.market(s);void 0===i&&(i="USDT"===a.settle?"perpetual":a.type),n[s]=!0}let h=Object.keys(n);for(let t=0;t<h.length;t++){let i="orders:"+h[t];e.resolve(this.orders,i)}let c="orders:"+i;e.resolve(this.orders,c)}parseWSSwapOrder(e,t){let i=this.safeString(e,"orderID"),s=this.safeString(e,"clOrdID");void 0!==s&&s.length<1&&(s=void 0);let r=this.safeString(e,"symbol"),a=this.safeMarket(r,t),o=a.symbol,n=this.parseOrderStatus(this.safeString(e,"ordStatus")),d=this.safeStringLower(e,"side"),h=this.parseOrderType(this.safeString(e,"ordType")),c=this.safeString(e,"priceRp",this.fromEp(this.safeString(e,"priceEp"),a)),l=this.safeString(e,"orderQty"),u=this.safeString(e,"cumQty"),f=this.safeString(e,"leavesQty"),p=this.safeIntegerProduct(e,"actionTimeNs",1e-6),m=this.safeString(e,"cumValueRv",this.fromEv(this.safeString(e,"cumValueEv"),a)),g=this.safeIntegerProduct(e,"transactTimeNs",1e-6);0===g&&(g=void 0);let v=this.parseTimeInForce(this.safeString(e,"timeInForce")),y=this.safeString(e,"stopPx");return this.safeOrder({info:e,id:i,clientOrderId:s,datetime:this.iso8601(p),timestamp:p,lastTradeTimestamp:g,symbol:o,type:h,timeInForce:v,postOnly:"PO"===v,side:d,price:c,stopPrice:y,triggerPrice:y,amount:l,filled:u,remaining:f,cost:m,average:void 0,status:n,fee:void 0,trades:void 0},a)}handleMessage(e,t){let i=this.safeString(t,"id","");if(i in e.subscriptions){let s=this.safeValue(e.subscriptions,i);if(delete e.subscriptions[i],!0!==s)return void s.call(this,e,t)}let s=this.safeString(t,"method","");if("market24h"in t||"spot_market24h"in t||s.indexOf("perp_market24h_pack_p")>=0)return void this.handleTicker(e,t);if("trades"in t||"trades_p"in t)return void this.handleTrades(e,t);if("kline"in t||"kline_p"in t)return void this.handleOHLCV(e,t);if("book"in t||"orderbook_p"in t)return void this.handleOrderBook(e,t);if("orders"in t||"orders_p"in t){let i=this.safeDict2(t,"orders","orders_p",{});this.handleOrders(e,i)}if("accounts"in t||"accounts_p"in t||"wallets"in t){let i="spot";"accounts"in t&&(i="swap"),"accounts_p"in t&&(i="perpetual");let s=this.safeListN(t,["accounts","accounts_p","wallets"],[]);this.handleBalance(i,e,s)}}handleAuthenticate(e,t){let i=this.safeDict(t,"result"),s=this.safeString(i,"status"),r="authenticated";if("success"===s)e.resolve(t,r);else{let i=new n.AuthenticationError(this.id+" "+this.json(t));e.reject(i,r),r in e.subscriptions&&delete e.subscriptions[r]}}async subscribePrivate(e,t,i={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let s=this.urls.api.ws,r=this.seconds(),a="USDT"===this.safeString(i,"settle",""),o=this.omit(i,"settle"),n="aop.subscribe";"spot"===e&&(n="wo.subscribe"),a&&(n="aop_p.subscribe");let d={id:r,method:n,params:[]};return d=this.extend(d,o),await this.watch(s,t,d,n)}async authenticate(e={}){this.checkRequiredCredentials();let t=this.urls.api.ws,i=this.client(t),r=this.requestId(),a="authenticated",o=this.safeValue(i.subscriptions,a);if(void 0===o){let n=this.safeInteger(this.options,"expires",120),d=this.seconds()+n,h=this.apiKey+d.toString(),c=this.hmac(this.encode(h),this.encode(this.secret),s.sc),l={method:"user.auth",params:["API",this.apiKey,c,d],id:r},u=r.toString(),f=this.extend(l,e);a in i.subscriptions||(i.subscriptions[u]=this.handleAuthenticate),o=await this.watch(t,a,f,a),i.subscriptions[a]=o}return o}}i.d(t,{A:()=>d})},1818(e,t,i){"use strict";var s=i(4721),r=i(2406),a=i(1453),o=i(1697),n=i(7749);class d extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchOHLCV:!0,watchOrderBook:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!0,watchBalance:!0,watchStatus:!1,watchOrders:!0,watchMyTrades:!0,createOrderWs:!0,editOrderWs:!1,fetchOpenOrdersWs:!1,fetchOrderWs:!1,cancelOrderWs:!0,cancelOrdersWs:!0,cancelAllOrdersWs:!0,fetchTradesWs:!1,fetchBalanceWs:!1},urls:{api:{ws:{public:"wss://ws.poloniex.com/ws/public",private:"wss://ws.poloniex.com/ws/private"}}},options:{createMarketBuyOrderRequiresPrice:!0,tradesLimit:1e3,ordersLimit:1e3,OHLCVLimit:1e3,watchOrderBook:{name:"book_lv2"},connectionsLimit:2e3,requestsLimit:500,timeframes:{"1m":"candles_minute_1","5m":"candles_minute_5","10m":"candles_minute_10","15m":"candles_minute_15","30m":"candles_minute_30","1h":"candles_hour_1","2h":"candles_hour_2","4h":"candles_hour_4","6h":"candles_hour_6","12h":"candles_hour_12","1d":"candles_day_1","3d":"candles_day_3","1w":"candles_week_1","1M":"candles_month_1"}},streaming:{keepAlive:15e3,ping:this.ping}})}async authenticate(e={}){this.checkRequiredCredentials();let t=this.numberToString(this.milliseconds()),i=this.urls.api.ws.private,r="authenticated",a=this.client(i),o=this.safeValue(a.subscriptions,r);if(void 0===o){let n=this.hmac(this.encode("GET\n/ws\nsignTimestamp="+t),this.encode(this.secret),s.sc,"base64"),d={event:"subscribe",channel:["auth"],params:{key:this.apiKey,signTimestamp:t,signature:n,signatureMethod:"HmacSHA256",signatureVersion:"2"}},h=this.extend(d,e);o=await this.watch(i,r,h,r),a.subscriptions[r]=o}return o}async subscribe(e,t,i,s,r={}){let o,n="public";i&&(n="private");let d=this.safeString(this.urls.api.ws,n);if(void 0===d)throw new a.ExchangeError(this.id+" has no websocket url for this endpoint");let h={event:"subscribe",channel:[e]},c=[];if(this.isEmpty(s))c.push("all");else{if(void 0===s)throw new a.ArgumentsRequired(this.id+" subscribe() symbols is required");let e=this.marketIds(s);c=void 0===e?[]:e}let l=void 0===s?"":s.join(",");o=this.isEmpty(s)?t:t+"::"+l,"balances"!==e&&(h.symbols=c);let u=this.extend(h,r);return await this.watch(d,o,u,o)}async tradeRequest(e,t={}){let i=this.urls.api.ws.private,s=this.nonce().toString();return await this.watch(i,s,{id:s,event:e,params:t},s)}async createOrderWs(e,t,i,s,r,o={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let d=this.market(e),h=t.toUpperCase();if(void 0===i)throw new a.ArgumentsRequired(this.id+" createOrderWs() side is required");let c=i.toUpperCase();this.isPostOnly("MARKET"===h,"LIMIT_MAKER"===h,o)&&(h="LIMIT_MAKER");let l={symbol:d.id,side:i.toUpperCase(),type:t.toUpperCase()},u=o;if("MARKET"===h&&"BUY"===c){let t,[i,d]=this.handleOptionBoolAndParams(o,"createOrder","createMarketBuyOrderRequiresPrice",!0),h=this.safeNumber(d,"cost");if(u=this.omit(d,"cost"),void 0!==h)t=this.costToPrecision(e,h);else if(i)if(void 0===r)throw new a.InvalidOrder(this.id+" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend (quote quantity) in the amount argument");else{let i=this.numberToString(s),a=this.numberToString(r),o=n.Y.stringMul(i,a);t=this.costToPrecision(e,o)}else t=this.costToPrecision(e,s);l.amount=t}else l.quantity=this.amountToPrecision(d.symbol,s),void 0!==r&&(l.price=this.priceToPrecision(e,r));let f=await this.tradeRequest("createOrder",this.extend(l,u));return this.safeDict(f,0)}async cancelOrderWs(e,t,i={}){let s=this.safeString(i,"clientOrderId");if(void 0!==s){let e=this.safeList(i,"clientOrderId",[]);i.clientOrderIds=this.arrayConcat(e,[s])}let r=await this.cancelOrdersWs([e],t,i);return this.safeDict(r,0)}async cancelOrdersWs(e,t,i={}){return void 0===this.markets&&await this.loadMarkets(),await this.authenticate(),await this.tradeRequest("cancelOrders",this.extend({orderIds:e},i))}async cancelAllOrdersWs(e,t={}){return void 0===this.markets&&await this.loadMarkets(),await this.authenticate(),await this.tradeRequest("cancelAllOrders",t)}handleOrderRequest(e,t){let i=this.safeString(t,"id"),s=this.safeList(t,"data",[]),r=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.parseWsOrder(t);r.push(i)}e.resolve(r,i)}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let o=this.safeDict(this.options,"timeframes",{}),n=this.safeString(o,t,t);if(void 0===n)throw new a.BadRequest(this.id+" watchOHLCV cannot take a timeframe of "+t);let d=await this.subscribe(n,n,!1,[e],r),h=s;return this.newUpdates&&(h=d.getLimit(e,s)),this.filterBySinceLimit(d,i,h,0,!0)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.symbol(e),s=await this.watchTickers([i],t);return this.safeValue(s,i)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i="ticker",s=this.marketSymbols(e),r=await this.subscribe(i,i,!1,s,t);return this.newUpdates?r:this.filterByArray(this.tickers,"symbol",s)}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!1,!0,!0),a="trades",o=this.urls.api.ws.public,n=this.marketIds(r),d=this.extend({event:"subscribe",channel:[a],symbols:n},s),h=[];if(void 0!==r)for(let e=0;e<r.length;e++)h.push(a+"::"+r[e]);let c=await this.watchMultiple(o,h,d,h),l=this.safeDict(c,0),u=this.safeString(l,"symbol"),f=i;return this.newUpdates&&(f=c.getLimit(u,i)),this.filterBySinceLimit(c,t,f,"timestamp",!0)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.safeDict(this.options,"watchOrderBook"),r=this.safeString(s,"name","book_lv2"),[a,o]=this.handleOptionStringAndParams(i,"watchOrderBook","name",r);return(await this.subscribe(a,a,!1,[e],o)).limit()}async watchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r="orders";await this.authenticate();let a=void 0===e?void 0:this.symbol(e),o=await this.subscribe(r,r,!0,void 0===a?void 0:[a],s),n=i;return this.newUpdates&&(n=o.getLimit(a,i)),this.filterBySinceLimit(o,t,n,"timestamp",!0)}async watchMyTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=void 0===e?void 0:this.symbol(e),a=await this.subscribe("orders","myTrades",!0,void 0===r?void 0:[r],s),o=i;return this.newUpdates&&(o=a.getLimit(r,i)),this.filterBySinceLimit(a,t,o,"timestamp",!0)}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t="balances";return await this.authenticate(),await this.subscribe(t,t,!0,void 0,e)}parseWsOHLCV(e,t){return[this.safeInteger(e,"startTime"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"quantity")]}handleOHLCV(e,t){let i=this.safeValue(t,"data");i=this.safeValue(i,0);let s=this.safeString(t,"channel"),r=this.safeString(i,"symbol"),a=this.safeSymbol(r),n=this.safeMarket(a),d=this.safeDict(this.options,"timeframes",{}),h=this.findTimeframe(s,d),c=this.parseWsOHLCV(i,n);this.ohlcvs[a]=this.safeDict(this.ohlcvs,a,{});let l=void 0===h?void 0:this.safeValue(this.safeDict(this.ohlcvs,a),h);if(void 0!==a){if(void 0===l){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);l=new o.TG(e),void 0!==a&&void 0!==h&&(this.ohlcvs[a][h]=l)}if(l.append(c),void 0!==s){let t=s+"::"+a;e.resolve(l,t)}}return t}handleTrade(e,t){let i=this.safeList(t,"data",[]);for(let t=0;t<i.length;t++){let s=this.safeDict(i,t);if(void 0!==this.safeString(s,"symbol")){let t=this.parseWsTrade(s),i=t.symbol,r="trades::"+i,a=void 0===i?void 0:this.safeValue(this.trades,i);if(void 0===a){let e=this.safeInteger(this.options,"tradesLimit",1e3);a=new o.I3(e),void 0!==i&&(this.trades[i]=a)}a.append(t),e.resolve(a,r)}}return t}parseWsTrade(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeInteger(e,"createTime"),a=this.safeStringLower2(e,"matchRole","taker");return this.safeTrade({info:e,id:this.safeString2(e,"id","tradeId"),symbol:this.safeString(s,"symbol"),timestamp:r,datetime:this.iso8601(r),order:this.safeString(e,"orderId"),type:this.safeStringLower(e,"type"),side:this.safeStringLower2(e,"takerSide","side"),takerOrMaker:a,price:this.omitZero(this.safeString2(e,"tradePrice","price")),amount:this.omitZero(this.safeString2(e,"filledQuantity","quantity")),cost:this.safeString2(e,"amount","filledAmount"),fee:{rate:void 0,cost:this.safeString(e,"tradeFee"),currency:this.safeString(e,"feeCurrency")}},s)}parseStatus(e){return this.safeString({NEW:"open",PARTIALLY_FILLED:"open",FILLED:"closed",PENDING_CANCEL:"open",PARTIALLY_CANCELED:"open",CANCELED:"canceled"},e,e)}parseWsOrderTrade(e,t){let i=this.safeInteger(e,"tradeTime"),s=this.safeString(e,"symbol");return this.safeTrade({info:e,id:this.safeString(e,"tradeId"),symbol:this.safeSymbol(s,t),timestamp:i,datetime:this.iso8601(i),order:this.safeString(e,"orderId"),type:this.safeStringLower(e,"type"),side:this.safeString(e,"side"),takerOrMaker:this.safeStringLower(e,"matchRole"),price:this.safeString(e,"price"),amount:this.safeString(e,"tradeAmount"),cost:void 0,fee:{rate:void 0,cost:this.safeString(e,"tradeFee"),currency:this.safeString(e,"feeCurrency")}},t)}handleOrder(e,t){let i=this.safeList(t,"data",[]),s=this.orders;if(void 0===s){let e=this.safeInteger(this.options,"ordersLimit");s=new o.Pt(e),this.orders=s}let r=[];for(let t=0;t<i.length;t++){let a=this.safeDict(i,t),o=this.safeString(a,"symbol"),d=this.safeString(a,"eventType");if(void 0!==o){let t=this.safeSymbol(o),i=this.safeString(a,"orderId",""),h=this.safeString(a,"clientOrderId","");if("place"===d||"canceled"===d){let e=this.parseWsOrder(a);s.append(e)}else{let d=this.safeDict(s.hashmap,t,{}),c=this.safeDict2(d,i,h),l=this.parseWsTrade(a);if(this.handleMyTrades(e,l),void 0===c){let e=this.parseWsOrder(a);s.append(e),r.push(o);continue}void 0===c.trades&&(c.trades=[]),c.trades.push(l),c.lastTradeTimestamp=l.timestamp;let u="0",f="0",p=c.trades;for(let e=0;e<p.length;e++){let t=p[e],i=this.numberToString(t.cost),s=this.numberToString(t.amount);u=n.Y.stringAdd(u,i),f=n.Y.stringAdd(f,s)}if(n.Y.stringGt(f,"0")&&(c.average=this.parseNumber(n.Y.stringDiv(u,f))),c.cost=this.parseNumber(u),void 0!==c.filled){let e=this.numberToString(l.amount),t=this.numberToString(c.filled);if(c.filled=t=n.Y.stringAdd(t,e),void 0!==c.amount){let e=this.numberToString(c.amount);c.remaining=this.parseNumber(n.Y.stringSub(e,t))}}if(void 0===c.fee&&(c.fee={rate:void 0,cost:0,currency:this.safeString(l.fee,"currency")}),void 0!==c.fee.cost&&void 0!==this.safeNumber(l.fee,"cost")){let e=this.numberToString(c.fee.cost),t=this.numberToString(this.safeNumber(l.fee,"cost"));c.fee.cost=n.Y.stringAdd(e,t)}let m=this.safeString(a,"state");c.status=this.parseStatus(m),s.append(c)}r.push(o)}}for(let t=0;t<r.length;t++){let i=r[t],a="orders::"+this.market(i).symbol;e.resolve(s,a)}return e.resolve(s,"orders"),t}parseWsOrder(e,t){let i,s=this.safeString(e,"orderId"),r=this.safeString(e,"clientOrderId"),a=this.safeString(e,"symbol"),o=this.safeString(e,"ts"),d=this.safeString(e,"filledAmount"),h=this.safeString(e,"state");if(!n.Y.stringEq(d,"0")){i=[];let t=this.parseWsOrderTrade(e);i.push(t)}return this.safeOrder({info:e,symbol:this.safeSymbol(a,t),id:s,clientOrderId:r,timestamp:o,datetime:this.iso8601(o),lastTradeTimestamp:void 0,type:this.safeString(e,"type"),timeInForce:void 0,postOnly:void 0,side:this.safeString(e,"side"),price:this.safeString(e,"price"),stopPrice:void 0,triggerPrice:void 0,amount:this.safeString(e,"quantity"),cost:void 0,average:void 0,filled:d,remaining:this.safeString(e,"remaining_size"),status:this.parseStatus(h),fee:{rate:void 0,cost:this.safeString(e,"tradeFee"),currency:this.safeString(e,"feeCurrency")},trades:i})}handleTicker(e,t){let i=this.safeList(t,"data",[]),s={};for(let e=0;e<i.length;e++){let t=i[e];if(void 0!==this.safeString(t,"symbol")){let e=this.parseTicker(t),i=e.symbol;void 0!==i&&(this.tickers[i]=e),void 0!==i&&(s[i]=e)}}let r=this.findMessageHashes(e,"ticker::");for(let t=0;t<r.length;t++){let i=r[t],a=i.split("::")[1].split(","),o=this.filterByArray(s,"symbol",a);this.isEmpty(o)||e.resolve(o,i)}return e.resolve(s,"ticker"),t}handleOrderBook(e,t){let i=this.safeList(t,"data",[]),s=this.safeString(t,"action"),r="snapshot"===s,a="update"===s;for(let t=0;t<i.length;t++){let s=this.safeDict(i,t),o=this.safeString(s,"symbol"),n=this.safeMarket(o).symbol,d="book_lv2::"+n,h=this.safeDict(e.subscriptions,d,{}),c=this.safeInteger(h,"limit"),l=this.safeInteger(s,"ts"),u=this.safeList(s,"asks"),f=this.safeList(s,"bids");if(r||a){if(r&&(this.orderbooks[n]=this.orderBook({},c)),!(n in this.orderbooks))continue;let t=this.orderbooks[n];if(void 0!==f)for(let e=0;e<f.length;e++){let i=this.safeList(f,e),s=this.safeNumber(i,0),r=this.safeNumber(i,1);t.bids.store(s,r)}if(void 0!==u)for(let e=0;e<u.length;e++){let i=this.safeList(u,e),s=this.safeNumber(i,0),r=this.safeNumber(i,1);t.asks.store(s,r)}t.symbol=n,t.timestamp=l,t.datetime=this.iso8601(l),e.resolve(t,d)}}}handleBalance(e,t){let i=this.safeList(t,"data",[]);this.balance=this.parseWsBalance(i),e.resolve(this.balance,"balances")}parseWsBalance(e){let t=this.safeDict(e,0,{}),i=this.safeInteger(t,"ts"),s={info:e,timestamp:i,datetime:this.iso8601(i)};for(let t=0;t<e.length;t++){let i=this.safeDict(e,t),r=this.safeString(i,"currency"),a=this.safeCurrencyCode(r),o=this.account();o.free=this.safeString(i,"available"),o.used=this.safeString(i,"hold"),void 0!==a&&(s[a]=o)}return this.safeBalance(s)}handleMyTrades(e,t){let i="myTrades",s=t.symbol;if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new o.Pt(e)}let r=this.myTrades;r.append(t),e.resolve(r,i),e.resolve(r,i+":"+s)}handlePong(e){e.lastPong=this.milliseconds()}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;let i=this.safeString(t,"channel");"pong"===this.safeString(t,"event")&&(e.lastPong=this.milliseconds());let s={candles_minute_1:this.handleOHLCV,candles_minute_5:this.handleOHLCV,candles_minute_10:this.handleOHLCV,candles_minute_15:this.handleOHLCV,candles_minute_30:this.handleOHLCV,candles_hour_1:this.handleOHLCV,candles_hour_2:this.handleOHLCV,candles_hour_4:this.handleOHLCV,candles_hour_6:this.handleOHLCV,candles_hour_12:this.handleOHLCV,candles_day_1:this.handleOHLCV,candles_day_3:this.handleOHLCV,candles_week_1:this.handleOHLCV,candles_month_1:this.handleOHLCV,book:this.handleOrderBook,book_lv2:this.handleOrderBook,ticker:this.handleTicker,trades:this.handleTrade,orders:this.handleOrder,balances:this.handleBalance,createOrder:this.handleOrderRequest,cancelOrder:this.handleOrderRequest,cancelAllOrders:this.handleOrderRequest,auth:this.handleAuthenticate},r=void 0===i?void 0:this.safeValue(s,i);"auth"===i?this.handleAuthenticate(e,t):void 0===i?this.handleOrderRequest(e,t):this.safeList(t,"data",[]).length>0&&r.call(this,e,t)}handleErrorMessage(e,t){let i=this.safeString(t,"id"),s=this.safeString(t,"event"),r=this.safeList(t,"data"),o=this.safeDict(r,0),n=this.safeString(o,"orderId");if("error"===s||"0"===n)try{let e=this.safeString(o,"message"),i=this.safeString(o,"code"),s=this.id+" "+this.json(t);throw this.throwExactlyMatchedException(this.exceptions.exact,i,s),this.throwBroadlyMatchedException(this.exceptions.broad,e,s),new a.ExchangeError(s)}catch(t){if(t instanceof a.AuthenticationError){let i="authenticated";e.reject(t,i),i in e.subscriptions&&delete e.subscriptions[i]}else e.reject(t,i);return!0}return!1}handleAuthenticate(e,t){let i=this.safeDict(t,"data"),s=this.safeBool(i,"success"),r="authenticated";if(!0===s)e.resolve(t,r);else{let i=new a.AuthenticationError(this.id+" "+this.json(t));e.reject(i,r),r in e.subscriptions&&delete e.subscriptions[r]}return t}ping(e){return{event:"ping"}}}i.d(t,{A:()=>d})},3039(e,t,i){"use strict";var s=i(7939),r=i(1453),a=i(1697);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchMyTrades:!0,watchOHLCV:!0,watchOHLCVForSymbols:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOrders:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!0},urls:{api:{ws:{common:"wss://stream.toobit.com"}}},options:{ws:{timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","8h":"8h","12h":"12h","1d":"1d","1w":"1w","1M":"1M"},watchOrderBookForSymbols:{channel:"depth"},listenKeyRefreshRate:12e5}},streaming:{keepAlive:295e3,ping:this.ping},exceptions:{ws:{exact:{}}}})}ping(e){return{ping:this.milliseconds()}}handleMessage(e,t){let i=this.safeString(t,"topic");if(!0===this.handleErrorMessage(e,t))return;let s=this.safeInteger(t,"pong");if(void 0!==s)return void this.handleIncomingPong(e,s);let r={trade:this.handleTrades,kline:this.handleOHLCV,realtimes:this.handleTickers,depth:this.handleOrderBookPartialSnapshot,diffDepth:this.handleOrderBook,outboundAccountInfo:this.handleBalance,outboundContractAccountInfo:this.handleBalance,executionReport:this.handleOrder,contractExecutionReport:this.handleOrder,ticketInfo:this.handleMyTrade,outboundContractPositionInfo:this.handlePositions},a=void 0===i?void 0:this.safeValue(r,i);if(void 0!==a)a.call(this,e,t);else for(let i=0;i<t.length;i++){let s=t[i],a=this.safeString(s,"e"),o=void 0===a?void 0:this.safeValue(r,a);void 0!==o&&o.call(this,e,s)}}handleIncomingPong(e,t){e.lastPong=t}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!1),a=[],o=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.market(t);a.push("trade::"+t);let s=i.id;o.push(s)}let n=this.marketIds(r),d=this.safeString(this.urls.api.ws,"common")+"/quote/ws/v1",h={symbol:n.join(","),topic:"trade",event:"sub"},c=await this.watchMultiple(d,a,this.extend(h,s),a),l=this.safeDict(c,0),u=this.safeString(l,"symbol"),f=i;return this.newUpdates&&(f=c.getLimit(u,i)),this.filterBySinceLimit(c,t,f,"timestamp",!0)}handleTrades(e,t){let i=this.safeString(t,"symbol"),s=this.safeMarket(i),r=s.symbol;if(!(r in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.trades[r]=new a.I3(e)}let o=this.trades[r],n=this.safeList(t,"data",[]),d=this.parseWsTrades(n,s);for(let e=0;e<d.length;e++){let t=d[e];t.symbol=r,o.append(t)}e.resolve(o,"trade::"+r)}parseWsTrade(e,t){return this.parseTrade(e,t)}async watchOHLCV(e,t="1m",i,s,r={}){return r.callerMethodName="watchOHLCV",(await this.watchOHLCVForSymbols([[e,t]],i,s,r))[e][t]}async watchOHLCVForSymbols(e,t,i,s={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.safeString(this.urls.api.ws,"common")+"/quote/ws/v1",n=[],d=this.safeDict(this.options.ws,"timeframes",{}),h=[];for(let t=0;t<e.length;t++){let i=this.safeList(e,t),s=this.safeString(i,0),o=this.market(s).id,c=this.safeString(i,1,"1m"),l=this.safeString(d,c,c);if(void 0!==a&&a!==l)throw new r.NotSupported(this.id+" watchOHLCVForSymbols() only supports a single timeframe for all symbols");a=l,h.push(o),n.push("ohlcv::"+s+"::"+c)}let c={symbol:h.join(","),topic:"kline_"+a,event:"sub"},[l,u,f]=await this.watchMultiple(o,n,this.extend(c,s),n),p=i;this.newUpdates&&(p=f.getLimit(l,i));let m=this.filterBySinceLimit(f,t,p,0,!0);return this.createOHLCVObject(l,u,m)}handleOHLCV(e,t){let i=this.safeString(t,"symbol"),s=this.market(i),r=s.symbol,o=this.safeDict(t,"params",{}),n=this.safeString(o,"klineType"),d=this.findTimeframe(n);r in this.ohlcvs||(this.ohlcvs[r]={});let h=this.safeValue(this.ohlcvs[r],d);if(void 0===h){let e=this.safeInteger(this.options.ws,"OHLCVLimit",1e3);h=new a.TG(e),void 0!==d&&(this.ohlcvs[r][d]=h)}let c=this.safeList(t,"data",[]);for(let e=0;e<c.length;e++){let t=this.parseWsOHLCV(c[e],s);h.append(t)}let l="ohlcv::"+r+"::"+d,u=[r,d,h];e.resolve(u,l)}parseWsOHLCV(e,t){return this.parseOHLCV(e,t)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.symbol(e);return(await this.watchTickers([i],t))[i]}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=[],r=[];for(let e=0;e<i.length;e++){let t=i[e],a=this.market(t);s.push("ticker::"+t);let o=a.id;r.push(o)}let a=this.marketIds(i),o=this.safeString(this.urls.api.ws,"common")+"/quote/ws/v1",n={symbol:a.join(","),topic:"realtimes",event:"sub"},d=await this.watchMultiple(o,s,this.extend(n,t),s);if(this.newUpdates){let e={},t=this.safeString(d,"symbol");return void 0!==t&&(e[t]=d),e}return this.filterByArray(this.tickers,"symbol",i)}handleTickers(e,t){let i=this.safeList(t,"data");if(void 0===i)return;let s={};for(let t=0;t<i.length;t++){let r=i[t],a=this.parseWsTicker(r),o=a.symbol;void 0!==o&&(this.tickers[o]=a),void 0!==o&&(s[o]=a);let n="ticker::"+o;e.resolve(a,n)}e.resolve(s,"tickers")}parseWsTicker(e,t){return this.parseTicker(e,t)}watchOrderBook(e,t,i={}){return this.watchOrderBookForSymbols([e],t,i)}async watchOrderBookForSymbols(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!1),[r,a]=this.handleOptionStringAndParams(i,"watchOrderBookForSymbols","channel","depth"),o=[],n=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t);o.push("orderBook::"+t+"::"+r);let a=i.id;n.push(a)}let d=this.marketIds(s),h=this.safeString(this.urls.api.ws,"common")+"/quote/ws/v1",c={symbol:d.join(","),topic:r,event:"sub"};return(await this.watchMultiple(h,o,this.extend(c,a),o)).limit()}handleOrderBook(e,t){if(!0===this.safeBool(t,"f",!1))return void this.setOrderBookSnapshot(e,t,"diffDepth");let i=this.safeString(t,"symbol"),s=this.safeMarket(i).symbol,r=this.safeList(t,"data",[]);for(let t=0;t<r.length;t++){let i=this.safeDict(r,t),a="orderBook::"+s+"::diffDepth";if(!(s in this.orderbooks)){let e=this.safeInteger(this.options.ws,"orderBookLimit",1e3);this.orderbooks[s]=this.orderBook({},e)}let o=this.orderbooks[s],n=this.safeInteger(i,"t"),d=this.safeList(i,"b",[]),h=this.safeList(i,"a",[]);this.handleDeltas(o.asks,h),this.handleDeltas(o.bids,d),o.timestamp=n,this.orderbooks[s]=o,e.resolve(o,a)}}handleDelta(e,t){let i=this.parseOrderBookBidAsk(t);e.storeArray(i)}handleOrderBookPartialSnapshot(e,t){this.setOrderBookSnapshot(e,t,"depth")}setOrderBookSnapshot(e,t,i){let s=this.safeList(t,"data",[]),r=s.length;if(0!==r)for(let t=0;t<r;t++){let r=this.safeDict(s,t),a=this.safeString(r,"s"),o=this.safeSymbol(a),n="orderBook::"+o+"::"+i;if(!(o in this.orderbooks)){let e=this.safeInteger(this.options.ws,"orderBookLimit",1e3);this.orderbooks[o]=this.orderBook({},e)}let d=this.orderbooks[o],h=this.safeInteger(r,"t"),c=this.parseOrderBook(r,o,h,"b","a");d.reset(c),e.resolve(d,n)}}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let[t,i]=this.handleMarketTypeAndParams("watchBalance",void 0,e),s="spot"===t,r="contract";s&&(r="spot");let a="contract:balance";s&&(a="spot:balance");let o="contract:private";s&&(o="spot:balance");let n=this.getUserStreamUrl(),d=this.client(n);return this.setBalanceCache(d,t,o,i),d.future(r+":fetchBalanceSnapshot"),await this.watch(n,a,i,o)}setBalanceCache(e,t,i,s={}){if(void 0===i||i in e.subscriptions)return;let r="contract";"spot"===t&&(r="spot");let a=r+":fetchBalanceSnapshot";a in e.futures||(e.future(a),this.spawn(this.loadBalanceSnapshot,e,a,t))}handleBalance(e,t){let i=this.safeString(t,"e"),s=this.safeList(t,"B",[]),r=this.safeInteger(t,"E"),a="spot";"outboundContractAccountInfo"===i&&(a="contract"),a in this.balance||(this.balance[a]={}),this.balance[a].info=s,this.balance[a].timestamp=r,this.balance[a].datetime=this.iso8601(r);for(let e=0;e<s.length;e++){let t=s[e],i=this.safeString(t,"a"),r=this.safeCurrencyCode(i),o=this.account();o.info=t,o.used=this.safeString(t,"l"),o.free=this.safeString(t,"f"),void 0!==r&&(this.balance[a][r]=o)}this.balance[a]=this.safeBalance(this.balance[a]),e.resolve(this.balance[a],a+":balance")}async loadBalanceSnapshot(e,t,i){let s=await this.fetchBalance({type:i}),r="contract";"spot"===i&&(r="spot"),this.balance[r]=this.extend(s,this.safeDict(this.balance,r,{})),t in e.futures&&(e.futures[t].resolve(),e.resolve(this.balance[r],r+":fetchBalanceSnapshot"),e.resolve(this.balance[r],r+":balance"))}async watchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.marketOrNull(e),a=this.safeString(r,"symbol",e),o="orders";void 0!==a&&(o=o+":"+a);let n=this.getUserStreamUrl(),d=await this.watch(n,o,s,o),h=i;return this.newUpdates&&(h=d.getLimit(a,i)),this.filterBySymbolSinceLimit(d,a,t,h,!0)}handleOrder(e,t){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}let i=this.orders,s=this.parseWsOrder(t);i.append(s);let r="orders";e.resolve(i,r),r="orders:"+this.safeString(s,"symbol"),e.resolve(i,r)}parseWsOrder(e,t){let i,s=this.safeInteger(e,"O"),r=this.safeString(e,"s"),a=this.safeSymbol(r,t),o=this.safeStringLower(e,"pt"),n=this.safeStringLower(e,"o"),d=this.safeNumber(e,"n");return void 0!==d&&(i={cost:d,currency:void 0}),this.safeOrder({info:e,id:this.safeString(e,"i"),clientOrderId:this.safeString(e,"c"),timestamp:s,datetime:this.iso8601(s),lastUpdateTimestamp:this.safeInteger2(e,"U","E"),symbol:a,type:"market"===o?"market":n,timeInForce:this.safeStringUpper(e,"f"),postOnly:void 0,side:this.safeStringLower(e,"S"),price:this.safeString(e,"L"),stopPrice:void 0,triggerPrice:void 0,amount:this.safeString(e,"q"),cost:void 0,average:this.safeString(e,"p"),filled:this.safeString(e,"z"),remaining:void 0,status:this.parseOrderStatus(this.safeString(e,"X")),fee:i,trades:void 0},t)}async watchMyTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.marketOrNull(e),a=this.safeString(r,"symbol",e),o="myTrades";void 0!==a&&(o=o+":"+a);let n=this.getUserStreamUrl(),d=await this.watch(n,o,s,o),h=i;return this.newUpdates&&(h=d.getLimit(a,i)),this.filterBySinceLimit(d,t,h,"timestamp",!0)}handleMyTrade(e,t){let i=this.myTrades;if(void 0===i){let e=this.safeInteger(this.options,"tradesLimit",1e3);i=new a.Pt(e)}let s=this.parseMyTrade(t);i.append(s);let r="myTrades:"+s.symbol;e.resolve(i,r),r="myTrades",e.resolve(i,r)}parseMyTrade(e,t){let i=this.safeString(e,"s"),s=this.safeString(e,"t"),r=this.safeBool(e,"m",!1),a="taker";return r&&(a="maker"),this.safeTrade({info:e,id:this.safeString(e,"T"),timestamp:s,datetime:this.iso8601(s),symbol:this.safeSymbol(i,t),order:this.safeString(e,"o"),type:void 0,side:this.safeStringLower(e,"S"),takerOrMaker:a,price:this.safeString(e,"p"),amount:this.safeString(e,"q"),cost:void 0,fee:void 0},t)}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let a="swap",o="",n=e;if(this.isEmpty(e)||(n=this.marketSymbols(e)),!this.isEmpty(e)){if(void 0===n)throw new r.ArgumentsRequired(this.id+" watchPositions() symbols is required");o="::"+n.join(",")}o=a+":positions"+o;let d=this.getUserStreamUrl(),h=this.client(d);this.setPositionsCache(h,a,n);let c=this.safeValue(this.positions,a);if(void 0===c){let e=await h.future(a+":fetchPositionsSnapshot");return this.filterBySymbolsSinceLimit(e,n,t,i,!0)}let l=await this.watch(d,o,void 0,o);return this.newUpdates?l:this.filterBySymbolsSinceLimit(c,n,t,i,!0)}setPositionsCache(e,t,i){if(void 0===this.positions&&(this.positions={}),!(t in this.positions))if(!0===this.handleOption("watchPositions","fetchPositionsSnapshot",!1)){let i=t+":fetchPositionsSnapshot";i in e.futures||(e.future(i),this.spawn(this.loadPositionsSnapshot,e,i,t))}else this.positions[t]=new a.Hk}async loadPositionsSnapshot(e,t,i){let s=await this.fetchPositions(void 0,{type:i});this.positions[i]=new a.Hk;let r=this.positions[i];for(let e=0;e<s.length;e++){let t=s[e];r.append(t)}t in e.futures&&(e.futures[t].resolve(r),e.resolve(r,i+":positions"))}handlePositions(e,t){let i="swap";void 0===this.positions&&(this.positions={}),i in this.positions||(this.positions[i]=new a.Hk);let s=this.positions[i],r=t;Array.isArray(t)||(r=[t]);let o=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.parseWsPosition(t),a=this.safeInteger(t,"E");i.timestamp=a,i.datetime=this.iso8601(a),o.push(i),s.append(i)}let n=this.findMessageHashes(e,i+":positions::");for(let t=0;t<n.length;t++){let i=n[t],s=i.split("::")[1].split(","),r=this.filterByArray(o,"symbol",s,!1);this.isEmpty(r)||e.resolve(r,i)}e.resolve(o,i+":positions")}parseWsPosition(e,t){let i=this.safeString(e,"s");return this.safePosition({info:e,id:void 0,symbol:this.safeSymbol(i),notional:this.omitZero(this.safeString(e,"pv")),marginMode:this.safeStringLower(e,"mt"),liquidationPrice:this.safeString(e,"f"),entryPrice:this.safeString(e,"p"),unrealizedPnl:this.safeString(e,"up"),realizedPnl:this.safeNumber(e,"r"),percentage:void 0,contracts:void 0,contractSize:void 0,markPrice:this.safeString(e,"mp"),side:this.safeStringLower(e,"S"),hedged:void 0,timestamp:void 0,datetime:void 0,maintenanceMargin:this.safeString(e,"mm"),maintenanceMarginPercentage:void 0,collateral:void 0,initialMargin:this.omitZero(this.safeString(e,"m")),initialMarginPercentage:void 0,leverage:this.safeString(e,"v"),marginRatio:void 0})}async authenticate(e={}){let t=this.milliseconds(),i=this.safeInteger(this.options.ws,"lastAuthenticatedTime",0),s=this.safeInteger(this.options.ws,"listenKeyRefreshRate",12e5);if(t-i>s+1e4){this.checkRequiredCredentials();let i="authenticate",a=this.client("authenticationFlights");if(i in a.futures)return void await a.future(i);let o=a.reusableFuture(i);try{let o=await this.privatePostApiV1UserDataStream(e),n=this.safeString(o,"listenKey");if(void 0===n)throw new r.AuthenticationError(this.id+" authenticate() received an empty listenKey");this.options.ws.listenKey=n,this.options.ws.lastAuthenticatedTime=t,this.delay(s,this.keepAliveListenKey,e),a.resolve(n,i)}catch(t){let e=new r.AuthenticationError(this.id+" "+this.exceptionMessage(t));a.reject(e,i)}await o}}async keepAliveListenKey(e={}){let t=this.safeDict(this.options,"ws",{});if(void 0===this.safeString(t,"listenKey"))return;try{let t=await this.privatePostApiV1UserDataStream(e);this.options.ws.listenKey=this.safeString(t,"listenKey"),this.options.ws.lastAuthenticatedTime=this.milliseconds()}catch(s){let e=this.getUserStreamUrl(),t=this.client(e),i=Object.keys(t.futures);for(let e=0;e<i.length;e++){let r=i[e];t.reject(s,r)}this.options.ws.listenKey=void 0,this.options.ws.lastAuthenticatedTime=0;return}let i=this.safeInteger(this.options.ws,"listenKeyRefreshRate",12e5);this.delay(i,this.keepAliveListenKey,e)}getUserStreamUrl(){return this.safeString(this.urls.api.ws,"common")+"/api/v1/ws/"+this.safeString(this.options.ws,"listenKey")}handleErrorMessage(e,t){let i=this.safeString(t,"code");if(void 0!==i){let s=this.safeString(t,"desc"),a=this.id+" code: "+i+" message: "+s,o=new r.ExchangeError(a);return e.reject(o),!0}return!1}}i.d(t,{A:()=>o})},3296(e,t,i){"use strict";var s=i(4721),r=i(1692),a=i(1697),o=i(8748),n=i(1453);class d extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchOrderBook:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!0,watchOHLCV:!0,watchOrders:!0,watchMyTrades:!0,watchBalance:!0},urls:{api:{ws:"wss://{hostname}/websocket/v1"}},options:{tradesLimit:1e3}})}async watchPublicMultiple(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=e;void 0===e&&(s=this.symbols);let r=this.marketSymbols(s),a=void 0===r?[]:r,o=this.marketIds(a),n=this.implodeParams(this.urls.api.ws,{hostname:this.hostname}),d=this.client(n),h="upbitPublicSubscriptions";h in d.subscriptions||(d.subscriptions[h]=this.createSafeDictionary(!0));let c=d.subscriptions[h],l=[];for(let e=0;e<a.length;e++){let i=o[e],s=t+":"+a[e];l.push(s),s in c||(c[s]={type:t,codes:[i]})}let u=[{ticket:this.uuid()}],f=Object.keys(c);for(let e=0;e<f.length;e++){let t=f[e];u.push(c[t])}return await this.watchMultiple(n,l,u,l)}watchTicker(e,t={}){return this.watchPublicMultiple([e],"ticker")}async watchTickers(e,t={}){let i=await this.watchPublicMultiple(e,"ticker");if(this.newUpdates){let e={},t=this.safeString(i,"symbol");return void 0!==t&&(e[t]=i),e}return this.filterByArray(this.tickers,"symbol",e)}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){let r=await this.watchPublicMultiple(e,"trade"),a=this.safeDict(r,0),o=this.safeString(a,"symbol"),n=i;return this.newUpdates&&(n=r.getLimit(o,i)),this.filterBySinceLimit(r,t,n,"timestamp",!0)}async watchOrderBook(e,t,i={}){return(await this.watchPublicMultiple([e],"orderbook")).limit()}async watchOHLCV(e,t="1s",i,s,r={}){if("1s"!==t)throw new n.NotSupported(this.id+" watchOHLCV does not support"+t+" candle.");return await this.watchPublicMultiple([e],"candle."+t)}handleTicker(e,t){let i=this.parseTicker(t),s=i.symbol;void 0!==s&&(this.tickers[s]=i),e.resolve(i,"ticker:"+s)}handleOrderBook(e,t){let i=this.safeString(t,"code"),s=this.safeSymbol(i,void 0,"-"),r=this.safeString(t,"stream_type"),a=this.safeDict(this.options,"watchOrderBook",{}),o=this.safeInteger(a,"limit",15);"SNAPSHOT"===r&&(this.orderbooks[s]=this.orderBook({},o));let n=this.orderbooks[s];n.reset({}),n.symbol=s;let d=n.bids,h=n.asks,c=this.safeList(t,"orderbook_units",[]);for(let e=0;e<c.length;e++){let t=this.safeDict(c,e),i=this.safeFloat(t,"ask_price"),s=this.safeFloat(t,"ask_size"),r=this.safeFloat(t,"bid_price"),a=this.safeFloat(t,"bid_size");h.store(i,s),d.store(r,a)}let l=this.safeInteger(t,"timestamp"),u=this.iso8601(l);n.timestamp=l,n.datetime=u;let f="orderbook:"+s;e.resolve(n,f)}handleTrades(e,t){let i=this.parseTrade(t),s=i.symbol;if(void 0===s)return;let r=this.safeValue(this.trades,s);if(void 0===r){let e=this.safeInteger(this.options,"tradesLimit",1e3);r=new a.I3(e),this.trades[s]=r}r.append(i);let o="trade:"+s;e.resolve(r,o)}handleOHLCV(e,t){let i=this.safeString(t,"code"),s=this.safeSymbol(i),r=this.parseOHLCV(t);e.resolve(r,"candle.1s:"+s)}async authenticate(e={}){this.checkRequiredCredentials();let t=this.safeDict(this.options,"ws",{});if(void 0===this.safeString(t,"token")){let e={access_key:this.apiKey,nonce:this.uuid()},i=(0,o.a)(e,this.encode(this.secret),s.sc,!1);t.token=i,t.options={headers:{authorization:"Bearer "+i}},this.options.ws=t}let i=this.safeString(this.urls.api,"ws")+"/private";return this.client(i)}async watchPrivate(e,t,i,s={}){let r;await this.authenticate();let a={type:t};if(void 0!==e){await this.loadMarkets();let t=[r=this.market(e).symbol];a.codes=this.marketIds(t)}let o=i;void 0!==r&&(o=i+":"+r);let n=this.implodeParams(this.urls.api.ws,{hostname:this.hostname});n+="/private";let d=this.client(n),h="upbitPrivateSubscriptions";h in d.subscriptions||(d.subscriptions[h]=this.createSafeDictionary(!0));let c=t;void 0!==r&&(c=t+":"+r);let l=d.subscriptions[h];c in l||(l[c]=a);let u=[],f=Object.keys(l);for(let e=0;e<f.length;e++)u.push(l[f[e]]);let p=[{ticket:this.uuid()}];for(let e=0;e<u.length;e++)p.push(u[e]);return await this.watch(n,o,p,o)}async watchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.watchPrivate(e,"myOrder","myOrder"),a=i;return this.newUpdates&&(a=r.getLimit(e,i)),this.filterBySymbolSinceLimit(r,e,t,a,!0)}async watchMyTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=await this.watchPrivate(e,"myOrder","myTrades"),a=i;return this.newUpdates&&(a=r.getLimit(e,i)),this.filterBySymbolSinceLimit(r,e,t,a,!0)}parseWsOrderStatus(e){if(void 0!==e)return this.safeString({wait:"open",done:"closed",cancel:"canceled",watch:"open",trade:"open"},e,e)}parseWsOrder(e,t){let i,s=this.safeString(e,"uuid"),r=this.safeStringLower(e,"ask_bid");r="bid"===r?"buy":"sell";let a=this.parse8601(this.safeString(e,"order_timestamp")),o=this.parseWsOrderStatus(this.safeString(e,"state")),n=this.safeString(e,"code"),d=this.safeMarket(n,t),h=this.safeString(e,"paid_fee");return void 0!==h&&(i={currency:d.quote,cost:h}),this.safeOrder({info:e,id:s,clientOrderId:void 0,timestamp:a,datetime:this.iso8601(a),lastTradeTimestamp:this.safeString(e,"trade_timestamp"),symbol:d.symbol,type:this.safeString(e,"order_type"),timeInForce:this.safeString(e,"time_in_force"),postOnly:void 0,side:r,price:this.safeString(e,"price"),stopPrice:void 0,triggerPrice:void 0,cost:this.safeString(e,"executed_funds"),average:this.safeString(e,"avg_price"),amount:this.safeString(e,"volume"),filled:this.safeString(e,"executed_volume"),remaining:this.safeString(e,"remaining_volume"),status:o,fee:i,trades:void 0})}parseWsTrade(e,t){let i,s=this.safeStringLower(e,"ask_bid");s="bid"===s?"buy":"sell";let r=this.parse8601(this.safeString(e,"trade_timestamp")),a=this.safeString(e,"code"),o=this.safeMarket(a,t),n=this.safeString(e,"paid_fee");return void 0!==n&&(i={currency:o.quote,cost:n}),this.safeTrade({id:this.safeString(e,"trade_uuid"),timestamp:r,datetime:this.iso8601(r),symbol:o.symbol,side:s,price:this.safeString(e,"price"),amount:this.safeString(e,"volume"),cost:this.safeString(e,"executed_funds"),order:this.safeString(e,"uuid"),takerOrMaker:void 0,type:this.safeString(e,"order_type"),fee:i,info:e},o)}handleMyOrder(e,t){void 0!==this.safeString(t,"trade_uuid")&&this.handleMyTrade(e,t),this.handleOrder(e,t)}handleMyTrade(e,t){let i=this.myTrades;if(void 0===i){let e=this.safeInteger(this.options,"tradesLimit",1e3);i=new a.Pt(e)}let s=this.parseWsTrade(t);i.append(s);let r="myTrades";e.resolve(i,r),r="myTrades:"+s.symbol,e.resolve(i,r)}handleOrder(e,t){let i=this.parseWsOrder(t),s=this.safeString(i,"symbol"),r=this.safeString(i,"id");if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new a.Pt(e)}let o=this.orders,n=void 0===s?{}:this.safeDict(o.hashmap,s,{}),d=void 0===r?void 0:this.safeDict(n,r);if(void 0!==d){let e=this.safeValue(d,"fee");void 0!==e&&(i.fee=e);let t=this.safeList(d,"fees");void 0!==t&&(i.fees=t),i.trades=this.safeValue(d,"trades"),i.timestamp=this.safeInteger(d,"timestamp"),i.datetime=this.safeString(d,"datetime")}o.append(i);let h="myOrder";e.resolve(this.orders,h),h=h+":"+s,e.resolve(this.orders,h)}async watchBalance(e={}){return void 0===this.markets&&await this.loadMarkets(),await this.watchPrivate(void 0,"myAsset","myAsset")}handleBalance(e,t){let i=this.safeList(t,"assets",[]),s=this.safeInteger(t,"timestamp");this.balance.timestamp=s,this.balance.datetime=this.iso8601(s);for(let e=0;e<i.length;e++){let t=this.safeDict(i,e),s=this.safeString(t,"currency"),r=this.safeCurrencyCode(s),a=this.safeString(t,"balance"),o=this.safeString(t,"locked"),n=this.account();n.free=a,n.used=o,void 0!==r&&(this.balance[r]=n),this.balance=this.safeBalance(this.balance)}let r=this.safeString(t,"type");e.resolve(this.balance,r)}handleMessage(e,t){let i={ticker:this.handleTicker,orderbook:this.handleOrderBook,trade:this.handleTrades,myOrder:this.handleMyOrder,myAsset:this.handleBalance,"candle.1s":this.handleOHLCV},s=this.safeString(t,"type"),r=void 0===s?void 0:this.safeValue(i,s);void 0!==r&&r.call(this,e,t)}}i.d(t,{A:()=>d})},7095(e,t,i){"use strict";var s=i(4721),r=i(4691),a=i(1453),o=i(1697),n=i(7749);class d extends r.A{describe(){return this.deepExtend(super.describe(),{has:{watchBalance:!0,watchBidsAsks:!0,watchMyTrades:!0,watchOHLCV:!0,watchOHLCVForSymbols:!0,watchOrderBook:!0,watchOrderBookForSymbols:!0,watchOrders:!0,watchPositions:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!0,unWatchBidsAsks:!0,unWatchMyTrades:!0,unWatchOHLCV:!0,unWatchOHLCVForSymbols:!0,unWatchOrderBook:!0,unWatchOrderBookForSymbols:!0,unWatchOrders:!0,unWatchPositions:!0,unWatchTicker:!0,unWatchTickers:!0,unWatchTrades:!0,unWatchTradesForSymbols:!0},urls:{api:{ws:{spot:"wss://ws-spot.weex.com/v3/ws",contract:"wss://ws-contract.weex.com/v3/ws"}}},options:{ws:{options:{headers:{"User-Agent":"ccxt"}}},watchOHLCV:{priceType:"LAST_PRICE"},watchOHLCVForSymbols:{priceType:"LAST_PRICE"},watchOrderBook:{depth:"200"},watchOrderBookForSymbols:{depth:"200"},watchBalance:{fetchBalanceSnapshot:!0,awaitBalanceSnapshot:!0},watchPositions:{fetchPositionsSnapshot:!0,awaitPositionsSnapshot:!0}},streaming:{}})}requestId(){this.lockId();let e=this.sum(this.safeInteger(this.options,"requestId",0),1);return this.options.requestId=e,this.unlockId(),this.numberToString(e)}async subscribePublic(e,t,i=!1,s={},r={}){let a=this.requestId(),o="SUBSCRIBE";!0===this.safeBool(r,"unsubscribe",!1)&&(o="UNSUBSCRIBE");let n={id:a,method:o,params:t},d=this.extend(r,{id:a}),h="spot";i&&(h="contract");let c=this.safeString(this.urls.api.ws,h)+"/public";return await this.watchMultiple(c,e,this.deepExtend(n,s),e,d)}async subscribePrivate(e,t,i,s=!1,r={},a={}){let o="spot";s&&(o="contract");let n=this.safeString(this.urls.api.ws,o)+"/private";this.authenticate(n);let d="SUBSCRIBE";!0===this.safeBool(a,"unsubscribe",!1)&&(d="UNSUBSCRIBE");let h=this.requestId(),c={id:h,method:d,params:[i]},l=this.extend(a,{id:h});return await this.watch(n,e,this.deepExtend(c,r),t,l)}authenticate(e){if(this.checkRequiredCredentials(),void 0!==this.clients&&e in this.clients)return;let t=this.nonce(),i=t.toString()+"/v3/ws/private",r=this.hmac(this.encode(i),this.encode(this.secret),s.sc,"base64"),a=this.safeDict(this.options.ws.options,"headers"),o=this.safeString(a,"User-Agent","ccxt"),n={ws:{options:{headers:{"User-Agent":o,"ACCESS-KEY":this.apiKey,"ACCESS-SIGN":r,"ACCESS-PASSPHRASE":this.password,"ACCESS-TIMESTAMP":this.numberToString(t)}}}};this.extendExchangeOptions(n),this.client(e),this.extendExchangeOptions({ws:{options:{headers:{"User-Agent":o}}}})}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.symbol(e);return(await this.watchTickers([i],t))[i]}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1,!0),s=this.getMarketFromSymbols(i).contract,r="ticker",a=[],o=[];for(let e=0;e<i.length;e++){let t=i[e],s=this.market(t).id+"@"+r,n=r+"::"+t;a.push(n),o.push(s)}let n=await this.subscribePublic(a,o,s,t);if(this.newUpdates){let e={},t=this.safeString(n,"symbol");return void 0!==t&&(e[t]=n),e}return this.filterByArray(this.tickers,"symbol",i)}unWatchTicker(e,t={}){return this.unWatchTickers([e],t)}async unWatchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1,!0),s=this.getMarketFromSymbols(i).contract,r="ticker",a=[],o=[],n=[];for(let e=0;e<i.length;e++){let t=i[e],s=this.market(t).id+"@"+r,d=r+"::"+t,h="unsubscribe::"+d;a.push(d),o.push(s),n.push(h)}return await this.subscribePublic(n,o,s,t,{unsubscribe:!0,symbols:i,messageHashes:n,subMessageHashes:a,topic:r})}handleTicker(e,t){let i=this.getMarketFromClientAndMessage(e,t);if(void 0===i)return;let s=this.safeList(t,"d",[]),r=this.safeDict(s,0,{}),a=this.parseWsTicker(r,i),o=i.symbol;this.tickers[o]=a,e.resolve(this.tickers[o],"ticker::"+o)}parseWsTicker(e,t){let i,s=this.safeInteger(e,"C"),r=this.safeString(e,"c");return i=void 0===t?void 0:t.symbol,this.safeTicker({symbol:i,timestamp:s,datetime:this.iso8601(s),high:this.safeString(e,"h"),low:this.safeString(e,"l"),bid:this.safeString(e,"b"),bidVolume:this.safeString(e,"B"),ask:this.safeString(e,"a"),askVolume:this.safeString(e,"A"),vwap:this.safeString(e,"w"),open:this.safeString(e,"o"),close:r,last:r,previousClose:this.safeString(e,"x"),change:this.safeString(e,"p"),percentage:n.A.stringMul(this.safeString(e,"P"),"100"),average:this.safeString(e,"w"),baseVolume:this.safeString(e,"v"),quoteVolume:this.safeString(e,"q"),markPrice:this.safeString(e,"m"),indexPrice:this.safeString(e,"i"),info:e},t)}watchTrades(e,t,i,s={}){return this.watchTradesForSymbols([e],t,i,s)}async watchTradesForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.marketSymbols(e,void 0,!1,!0),a=this.getMarketFromSymbols(r).contract,o="trade",n=[],d=[];for(let e=0;e<r.length;e++){let t=r[e],i=this.market(t).id+"@"+o,s=o+"::"+t;n.push(s),d.push(i)}let h=await this.subscribePublic(n,d,a,s),c=this.safeDict(h,0),l=this.safeString(c,"symbol"),u=i;return this.newUpdates&&(u=h.getLimit(l,i)),this.filterBySinceLimit(h,t,u,"timestamp",!0)}unWatchTrades(e,t={}){return this.unWatchTradesForSymbols([e],t)}async unWatchTradesForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1,!0),s=this.getMarketFromSymbols(i).contract,r="trade",a=[],o=[],n=[];for(let e=0;e<i.length;e++){let t=i[e],s=this.market(t).id+"@"+r,d=r+"::"+t,h="unsubscribe::"+d;a.push(d),o.push(s),n.push(h)}return await this.subscribePublic(n,o,s,t,{unsubscribe:!0,symbols:i,messageHashes:n,subMessageHashes:a,topic:"trades"})}handleTrade(e,t){let i=this.getMarketFromClientAndMessage(e,t);if(void 0===i)return;let s=i.symbol;if(!(s in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.trades[s]=new o.I3(e)}let r=this.trades[s],a=this.safeList(t,"d",[]),n=[];for(let e=0;e<a.length;e++){let t=this.safeDict(a,e,{}),s=this.parseWsTrade(t,i);n.push(s)}let d=this.sortBy(n,"timestamp");for(let e=0;e<d.length;e++){let t=d[e];r.append(t)}this.trades[s]=r,e.resolve(r,"trade::"+s)}parseWsTrade(e,t){let i,s,r,a=this.safeInteger(e,"T");i=void 0===t?void 0:t.symbol;let o=this.safeBool(e,"m");return void 0!==o&&(s=o?"sell":"buy",r="taker"),this.safeTrade({info:e,id:this.safeString(e,"t"),timestamp:a,datetime:this.iso8601(a),symbol:i,order:void 0,type:void 0,side:s,takerOrMaker:r,price:this.safeString(e,"p"),amount:this.safeString(e,"q"),cost:this.safeString(e,"v"),fee:void 0},t)}async watchOHLCV(e,t="1m",i,s,r={}){let a=this.extend(r,{callerMethodName:"watchOHLCV"});return(await this.watchOHLCVForSymbols([[e,t]],i,s,a))[e][t]}async watchOHLCVForSymbols(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.safeString(s,"callerMethodName","watchOHLCVForSymbols"),o=this.omit(s,"callerMethodName"),n=[],d=[],h=this.safeList(e,0,[]),c=this.safeString(h,0),l=this.market(c),u=l.contract,f="LAST_PRICE",p=o;!0===u&&([f,p]=this.handleOptionStringAndParams2(o,r,"price","priceType",f));for(let t=0;t<e.length;t++){let i=this.safeList(e,t),s=this.safeString(i,0),o=this.market(s);if(o.type!==l.type)throw new a.BadRequest(this.id+" "+r+" market symbols must be of the same type");s=this.safeString(o,"symbol");let h=this.safeString(i,1,"1"),c=this.safeString(this.timeframes,h,h),u=o.id+"@kline_"+c+"_"+f,p="ohlcv::"+s+"::"+h;n.push(u),d.push(p)}let[m,g,v]=await this.subscribePublic(d,n,u,p),y=i;this.newUpdates&&(y=v.getLimit(m,i));let b=this.filterBySinceLimit(v,t,y,0,!0);return this.createOHLCVObject(m,g,b)}async unWatchOHLCV(e,t="1m",i={}){return i.callerMethodName="unWatchOHLCV",await this.unWatchOHLCVForSymbols([[e,t]],i)}async unWatchOHLCVForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeString(t,"callerMethodName","unWatchOHLCVForSymbols"),s=this.omit(t,"callerMethodName"),r=[],o=[],n=[],d=this.safeList(e,0,[]),h=this.safeString(d,0),c=this.market(h),l=c.contract,u="LAST_PRICE",f=s;!0===l&&([u,f]=this.handleOptionStringAndParams2(s,i,"price","priceType",u));for(let t=0;t<e.length;t++){let s=this.safeList(e,t),d=this.safeString(s,0),h=this.market(d);if(h.type!==c.type)throw new a.BadRequest(this.id+" "+i+" market symbols must be of the same type");d=this.safeString(h,"symbol");let l=this.safeString(s,1,"1"),f=this.safeString(this.timeframes,l,l),p=h.id+"@kline_"+f+"_"+u,m="ohlcv::"+d+"::"+l,g="unsubscribe::"+m;r.push(p),o.push(m),n.push(g)}return await this.subscribePublic(n,r,l,f,{unsubscribe:!0,symbolsAndTimeframes:e,messageHashes:n,subMessageHashes:o,topic:"ohlcv"})}handleOHLCV(e,t){let i=this.getMarketFromClientAndMessage(e,t);if(void 0===i)return;let s=i.symbol;s in this.ohlcvs||(this.ohlcvs[s]={});let r=this.safeList(t,"d",[]),a=this.safeDict(r,0,{}),n=this.safeString(a,"i"),d=this.findTimeframe(n),h=this.safeValue(this.safeDict(this.ohlcvs,s),d);if(void 0===h){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);h=new o.TG(e),void 0!==s&&void 0!==d&&(this.ohlcvs[s][d]=h)}for(let e=0;e<r.length;e++){let t=this.safeDict(r,e,{}),i=this.parseWsOHLCV(t);h.append(i)}let c="ohlcv::"+s+"::"+d,l=[s,d,h];e.resolve(l,c)}parseWsOHLCV(e,t){return[this.safeInteger(e,"t"),this.safeNumber(e,"o"),this.safeNumber(e,"h"),this.safeNumber(e,"l"),this.safeNumber(e,"c"),this.safeNumber(e,"v")]}async watchOrderBook(e,t,i={}){let s=this.extend(i,{callerMethodName:"watchOrderBook"});return await this.watchOrderBookForSymbols([e],t,s)}async watchOrderBookForSymbols(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.marketSymbols(e,void 0,!1,!0),r=this.getMarketFromSymbols(s).contract,a=this.safeString(i,"callerMethodName","watchOrderBookForSymbols"),o=this.omit(i,"callerMethodName"),[n,d]=this.handleOptionStringAndParams(o,a,"depth","200"),h=[],c=[];for(let e=0;e<s.length;e++){let t=s[e],i=this.market(t),r="orderbook::"+t,a=i.id+"@depth"+n;h.push(r),c.push(a)}return(await this.subscribePublic(h,c,r,d,{limit:t})).limit()}async unWatchOrderBook(e,t={}){let i=this.extend(t,{callerMethodName:"unWatchOrderBook"});return await this.unWatchOrderBookForSymbols([e],i)}async unWatchOrderBookForSymbols(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1,!0),s=this.getMarketFromSymbols(i).contract,r=this.safeString(t,"callerMethodName","unWatchOrderBookForSymbols"),a=this.omit(t,"callerMethodName"),[o,n]=this.handleOptionStringAndParams(a,r,"depth","200"),d=[],h=[],c=[];for(let e=0;e<i.length;e++){let t=i[e],s=this.market(t),r="orderbook::"+t,a=s.id+"@depth"+o,n="unsubscribe::"+r;d.push(r),h.push(a),c.push(n)}return await this.subscribePublic(c,h,s,n,{unsubscribe:!0,symbols:i,messageHashes:c,subMessageHashes:d,topic:"orderbook"})}handleOrderBook(e,t){let i=this.getMarketFromClientAndMessage(e,t);if(void 0===i)return;let s=i.symbol,r="orderbook::"+s;if(!(s in this.orderbooks)){let t=this.safeDict(e.subscriptions,r,{}),i=this.safeInteger(t,"limit");void 0!==i?this.orderbooks[s]=this.orderBook({},i):this.orderbooks[s]=this.orderBook({})}let a=this.orderbooks[s],o=this.safeInteger(t,"E"),n=this.safeString(t,"e"),d=this.safeInteger(t,"u");if("depthSnapshot"===n){let e=this.parseOrderBook(t,s,o,"b","a");e.nonce=d,a.reset(e)}else{let e=this.safeList(t,"a",[]),i=this.safeList(t,"b",[]);this.handleDeltas(a.asks,e),this.handleDeltas(a.bids,i),a.timestamp=o,a.datetime=this.iso8601(o),a.nonce=d}e.resolve(a,r)}handleDelta(e,t){let i=this.parseOrderBookBidAsk(t);e.storeArray(i)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1,!0);if(!0===this.getMarketFromSymbols(i).contract)throw new a.NotSupported(this.id+" watchBidsAsks is supported for spot markets only");let s=[],r=[];for(let e=0;e<i.length;e++){let t=i[e],a=this.market(t).id+"@bookTicker",o="bidask::"+t;s.push(o),r.push(a)}let o=await this.subscribePublic(s,r,!1,t);if(this.newUpdates){let e={},t=this.safeString(o,"symbol");return void 0!==t&&(e[t]=o),e}return this.filterByArray(this.bidsasks,"symbol",i)}async unWatchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1,!0);if(!0===this.getMarketFromSymbols(i).contract)throw new a.NotSupported(this.id+" unWatchBidsAsks is supported for spot markets only");let s=[],r=[],o=[];for(let e=0;e<i.length;e++){let t=i[e],a=this.market(t).id+"@bookTicker",n="bidask::"+t,d="unsubscribe::"+n;s.push(n),r.push(a),o.push(d)}return await this.subscribePublic(o,r,!1,t,{unsubscribe:!0,symbols:i,messageHashes:o,subMessageHashes:s,topic:"bidsasks"})}handleBidAsk(e,t){let i=this.getMarketFromClientAndMessage(e,t);if(void 0===i)return;let s=this.parseWsBidAsk(t,i),r=s.symbol;void 0!==r&&(this.bidsasks[r]=s),e.resolve(s,"bidask::"+r)}parseWsBidAsk(e,t){let i,s=this.safeInteger(e,"E");return i=void 0===t?void 0:t.symbol,this.safeTicker({symbol:i,timestamp:s,datetime:this.iso8601(s),ask:this.safeString(e,"a"),askVolume:this.safeString(e,"A"),bid:this.safeString(e,"b"),bidVolume:this.safeString(e,"B"),info:e},t)}async watchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a=this.safeString(r,"symbol"),[o,n]=this.handleMarketTypeAndParams("watchMyTrades",r,s),d="spot"!==o,h="myTrades";d&&(h="myContractTrades");let c=h;void 0!==a&&(h+="::"+a);let l=await this.subscribePrivate(h,c,"fill",d,n),u=i;return this.newUpdates&&(u=l.getLimit(a,i)),this.filterBySymbolSinceLimit(l,a,t,u,!0)}async unWatchMyTrades(e,t={}){if(void 0!==e)throw new a.NotSupported(this.id+" unWatchMyTrades does not support a symbol argument. Unsubscribing from myTrades is global for all symbols.");let[i,s]=this.handleMarketTypeAndParams("unWatchMyTrades",void 0,t),r="spot"!==i,o="myTrades";r&&(o="myContractTrades");let n="unsubscribe::"+o,d={unsubscribe:!0,messageHashes:[n],subMessageHashes:[o],topic:"myTrades",subHashIsPrefix:!0};return await this.subscribePrivate(n,n,"fill",r,s,d)}handleMyTrades(e,t){if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new o.Pt(e)}let i=this.myTrades,s=this.safeList(t,"d",[]),r={};for(let e=0;e<s.length;e++){let t=this.safeDict(s,e,{}),a=this.parseWsMyTrade(t),o=a.symbol;void 0!==o&&(r[o]=!0),i.append(a)}let a="myTrades",n=Object.keys(r);!0===this.getMarketFromSymbols(n).contract&&(a="myContractTrades");for(let t=0;t<n.length;t++){let s=a+"::"+n[t];e.resolve(i,s)}e.resolve(i,a)}parseWsMyTrade(e,t){let i,s=this.safeInteger(e,"createdTime"),r=this.safeString(e,"symbol"),a="spot";void 0!==this.safeString(e,"positionSide")&&(a="swap");let o=this.safeMarket(r,void 0,void 0,a),n=this.safeStringLower(e,"orderSide"),d=this.safeString(e,"fillFee");if(void 0!==d){let t=this.safeString(e,"coin"),s=this.safeCurrencyCode(t);"spot"===a&&(s="buy"===n?this.safeString(o,"base"):this.safeString(o,"quote")),i={cost:d,currency:s}}return this.safeTrade({info:e,id:this.safeString(e,"id"),timestamp:s,datetime:this.iso8601(s),symbol:o.symbol,order:this.safeString(e,"orderId"),type:this.safeString(e,"type"),side:n,takerOrMaker:this.safeStringLower(e,"direction"),price:void 0,amount:this.safeString(e,"fillSize"),cost:this.safeString(e,"fillValue"),fee:i})}async watchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a=this.safeString(r,"symbol"),[o,n]=this.handleMarketTypeAndParams("watchOrders",r,s),d="spot"!==o,h="orders";d&&(h="contractOrders");let c=h;void 0!==a&&(h+="::"+a);let l=await this.subscribePrivate(h,c,"orders",d,n),u=i;return this.newUpdates&&(u=l.getLimit(a,i)),this.filterBySymbolSinceLimit(l,a,t,u,!0)}async unWatchOrders(e,t={}){if(void 0!==e)throw new a.NotSupported(this.id+" unWatchOrders does not support a symbol argument. Unsubscribing from orders is global for all symbols.");let[i,s]=this.handleMarketTypeAndParams("unWatchOrders",void 0,t),r="spot"!==i,o="orders";r&&(o="contractOrders");let n="unsubscribe::"+o,d={unsubscribe:!0,messageHashes:[n],subMessageHashes:[o],topic:"orders",subHashIsPrefix:!0};return await this.subscribePrivate(n,n,"orders",r,s,d)}handleOrders(e,t){let i=this.safeList(t,"d",[]),s={};if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}let r=this.orders;for(let e=0;e<i.length;e++){let t=this.safeDict(i,e,{}),a=this.parseWsOrder(t);r.append(a);let o=a.symbol;void 0!==o&&(s[o]=!0)}let a="orders",n=Object.keys(s);!0===this.getMarketFromSymbols(n).contract&&(a="contractOrders");for(let t=0;t<n.length;t++){let i=a+"::"+n[t];e.resolve(r,i)}e.resolve(this.orders,a)}parseWsOrder(e,t){let i,s,r,a=this.safeInteger(e,"createdTime"),o=this.safeString(e,"symbol"),n="spot";void 0!==this.safeString(e,"positionSide")&&(n="swap");let d=this.safeMarket(o,void 0,void 0,n),h=this.safeStringLower(e,"orderSide"),c=this.safeString(e,"cumFillFee");if(void 0!==c){let t=this.safeString(e,"coin"),s=this.safeCurrencyCode(t);"spot"===n&&(s="buy"===h?this.safeString(d,"base"):this.safeString(d,"quote")),i={cost:c,currency:s}}let l=this.safeStringLower(e,"status"),u=this.safeString(e,"type"),f=this.omitZero(this.safeString(e,"triggerPrice"));return"TAKE_PROFIT_MARKET"===u||"TAKE_PROFIT"===u?r=f:("STOP_LOSS"===u||"STOP"===u||"STOP_MARKET"===u)&&(s=f),this.safeOrder({id:this.safeString(e,"id"),clientOrderId:this.safeString(e,"clientOrderId"),symbol:d.symbol,type:this.parseOrderType(u),timeInForce:this.safeString(e,"timeInForce"),postOnly:void 0,reduceOnly:this.safeBool(e,"reduceOnly"),side:h,amount:this.safeString(e,"size"),price:this.safeString(e,"price"),triggerPrice:f,cost:this.safeString(e,"cumFillValue"),filled:this.safeString(e,"cumFillSize"),remaining:void 0,timestamp:a,datetime:this.iso8601(a),fee:i,status:this.parseOrderStatus(l),lastTradeTimestamp:void 0,lastUpdateTimestamp:this.safeInteger(e,"updatedTime"),average:void 0,trades:void 0,stopLossPrice:s,takeProfitPrice:r,info:e},d)}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let[t,i]=this.handleMarketTypeAndParams("watchBalance",void 0,e),s="spot"!==t,r="spot";s&&(r="contract");let a=this.safeString(this.urls.api.ws,r)+"/private";this.authenticate(a);let o=this.client(a);this.setBalanceCache(o,t);let n=this.safeDict(this.options,"watchBalance"),d=this.safeBool(n,"fetchBalanceSnapshot",!1),h=this.safeBool(n,"awaitBalanceSnapshot",!0);!0===d&&!0===h&&await o.future(t+":fetchBalanceSnapshot");let c=t+":balance";return await this.subscribePrivate(c,t,"account",s,i)}setBalanceCache(e,t){if(t in e.subscriptions&&t in this.balance)return;let i=this.safeDict(this.options,"watchBalance");if(!0===this.safeBool(i,"fetchBalanceSnapshot",!1)){let i=t+":fetchBalanceSnapshot";i in e.futures||(e.future(i),this.spawn(this.loadBalanceSnapshot,e,i,t))}else this.balance[t]={}}async loadBalanceSnapshot(e,t,i){let s=await this.fetchBalance({type:i});this.balance[i]=this.extend(s,this.safeDict(this.balance,i,{})),t in e.futures&&(e.futures[t].resolve(),e.resolve(this.balance[i],i+":balance"))}handleBalance(e,t){let i=e.url,s="spot";i.indexOf("contract")>=0&&(s="swap");let r=s+":balance";void 0===this.balance[s]&&(this.balance[s]={}),this.balance[s].info=t;let a=this.safeList(t,"d",[]);for(let e=0;e<a.length;e++){let t=this.safeDict(a,e),i=this.safeString(t,"coin"),r=this.safeCurrencyCode(i),o=this.account();o.free=this.safeString2(t,"available","amount"),o.used=this.safeString(t,"frozen"),o.total=this.safeString2(t,"equity","legacyAmount"),void 0!==r&&(this.balance[s][r]=o)}let o=this.safeInteger(t,"E");this.balance[s].timestamp=o,this.balance[s].datetime=this.iso8601(o),this.balance[s]=this.safeBalance(this.balance[s]),e.resolve(this.balance[s],r)}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.safeString(this.urls.api.ws,"contract")+"/private";this.authenticate(r);let a=this.client(r),o=this.marketSymbols(e,"swap",!0),n="positions",d=n;void 0!==o&&(n+="::"+o.join(",")),this.setPositionsCache(a,s);let h=this.handleOption("watchPositions","fetchPositionsSnapshot",!0),c=this.handleOption("watchPositions","awaitPositionsSnapshot",!0);if(!0===h&&!0===c&&void 0===this.positions){let e=await a.future("fetchPositionsSnapshot");return this.filterBySymbolsSinceLimit(e,o,t,i,!0)}let l=await this.subscribePrivate(n,d,"positions",!0,s);return this.newUpdates?l:this.filterBySymbolsSinceLimit(this.positions,o,t,i,!0)}setPositionsCache(e,t={}){if(!0===this.handleOption("watchPositions","fetchPositionsSnapshot",!1)){let i="fetchPositionsSnapshot";i in e.futures||(e.future(i),this.spawn(this.loadPositionsSnapshot,e,i,t))}else this.positions=new o.Pt}async loadPositionsSnapshot(e,t,i){let s=await this.fetchPositions(void 0,i);this.positions=new o.Pt;let r=this.positions;for(let e=0;e<s.length;e++){let t=s[e];r.append(t)}e.futures[t].resolve(r),e.resolve(r,"positions")}async unWatchPositions(e,t={}){if(void 0!==e)throw new a.NotSupported(this.id+" unWatchPositions does not support a symbols argument. Unsubscribing from positions is global for all symbols.");let i="positions",s="unsubscribe::"+i;return await this.subscribePrivate(s,s,"positions",!0,t,{unsubscribe:!0,messageHashes:[s],subMessageHashes:[i],topic:"positions",subHashIsPrefix:!0})}handlePositions(e,t){void 0===this.positions&&(this.positions=new o.Pt);let i=this.positions,s=[],r=this.safeList(t,"d",[]);for(let e=0;e<r.length;e++){let t=this.safeDict(r,e,{}),a=this.parseWsPosition(t);i.append(a),s.push(a)}let a=this.findMessageHashes(e,"positions::");for(let t=0;t<a.length;t++){let i=a[t],r=i.split("::")[1].split(","),o=this.filterByArray(s,"symbol",r,!1);this.isEmpty(o)||e.resolve(o,i)}e.resolve(s,"positions")}parseWsPosition(e,t){return this.parsePosition(e,t)}getMarketFromClientAndMessage(e,t){let i=e.url,s="spot";i.indexOf("contract")>=0&&(s="swap");let r=this.safeString(t,"s");return this.safeMarket(r,void 0,void 0,s)}async pong(e,t){let i={id:this.requestId(),method:"PONG"};await e.send(i)}handlePing(e,t){this.spawn(this.pong,e,t)}handleSubscriptionStatus(e,t){let i=this.safeString(t,"id"),s=this.indexBy(e.subscriptions,"id"),r=this.safeDict(s,i,{});if(!0===this.safeBool(r,"unsubscribe",!1)){let t=this.safeBool(r,"subHashIsPrefix",!1),i=this.safeList(r,"messageHashes",[]),s=this.safeList(r,"subMessageHashes",[]);for(let r=0;r<i.length;r++){let a=this.safeString(i,r),o=this.safeString(s,r);this.cleanUnsubscription(e,o,a,t)}this.cleanCache(r)}return t}handleErrorMessage(e,t){if(!0!==this.safeBool(t,"result",!0)){let i=this.safeString(t,"msg",""),s=this.id+" "+this.json(t);try{throw this.throwExactlyMatchedException(this.exceptions.exact,i,s),this.throwBroadlyMatchedException(this.exceptions.broad,i,s),new a.ExchangeError(s)}catch(t){return e.reject(t),!0}}return!1}handleMessage(e,t){if(this.handleErrorMessage(e,t))return;if(void 0!==this.safeString(t,"id"))return void this.handleSubscriptionStatus(e,t);let i=this.safeStringN(t,["e","event","type"]);"ping"===i?this.handlePing(e,t):"ticker"===i?this.handleTicker(e,t):"trade"===i||"tradeSnapshot"===i?this.handleTrade(e,t):"kline"===i||"klineSnapshot"===i?this.handleOHLCV(e,t):"depth"===i||"depthSnapshot"===i?this.handleOrderBook(e,t):"bookTicker"===i?this.handleBidAsk(e,t):"fill"===i?this.handleMyTrades(e,t):"orders"===i?this.handleOrders(e,t):"account"===i?this.handleBalance(e,t):"positions"===i&&this.handlePositions(e,t)}}i.d(t,{A:()=>d})},3990(e,t,i){"use strict";var s=i(410),r=i(7749),a=i(1453),o=i(1697);class n extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchMyTrades:!0,watchOHLCV:!0,watchOrderBook:!0,watchOrders:!0,watchTicker:!0,watchTickers:!0,watchTrades:!0,watchTradesForSymbols:!1},urls:{api:{ws:"wss://api.whitebit.com/ws"}},options:{timeframes:{"1m":"60","5m":"300","15m":"900","30m":"1800","1h":"3600","4h":"14400","8h":"28800","1d":"86400","1w":"604800"},watchOrderBook:{priceInterval:0}},streaming:{ping:this.ping},exceptions:{ws:{exact:{1:a.BadRequest,2:a.BadRequest,4:a.BadRequest,6:a.AuthenticationError}}}})}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o=a.symbol,n=this.safeDict(this.options,"timeframes",{}),d=this.safeInteger(n,t),h=a.id,c=await this.watchPublic("candles:"+o,"candles_subscribe",[h,d],r),l=s;return this.newUpdates&&(l=c.getLimit(o,s)),this.filterBySinceLimit(c,i,l,0,!0)}handleOHLCV(e,t){let i=this.safeList(t,"params",[]);for(let t=0;t<i.length;t++){let s=i[t],r=this.safeString(s,7),a=this.safeMarket(r),n=a.symbol,d="candles:"+n,h=this.parseOHLCV(s,a);if(n in this.ohlcvs||(this.ohlcvs[n]={}),!("unknown"in this.ohlcvs[n])){let e=this.safeInteger(this.options,"OHLCVLimit",1e3),t=new o.TG(e);this.ohlcvs[n].unknown=t}let c=this.ohlcvs[n].unknown;c.append(h),e.resolve(c,d)}return t}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="orderbook:"+s.symbol,a=this.safeDict(this.options,"watchOrderBook",{}),o=this.safeString(a,"priceInterval","0"),n=this.safeString(i,"priceInterval",o),d=this.omit(i,"priceInterval"),h=[s.id,void 0===t?10:t,n,!0];return(await this.watchPublic(r,"depth_subscribe",h,d)).limit()}handleOrderBook(e,t){let i=this.safeList(t,"params",[]),s=this.safeBool(i,0),r=this.safeString(i,2),a=this.safeMarket(r).symbol,o=this.safeDict(i,1),n=this.safeTimestamp(o,"timestamp");if(!(a in this.orderbooks)){let e=this.orderBook();this.orderbooks[a]=e}let d=this.orderbooks[a];if(d.timestamp=n,d.datetime=this.iso8601(n),!0===s){let e=this.parseOrderBook(o,a);d.reset(e)}else{let e=this.safeList(o,"asks",[]),t=this.safeList(o,"bids",[]);this.handleDeltas(d.asks,e),this.handleDeltas(d.bids,t)}let h="orderbook:"+a;e.resolve(d,h)}handleDelta(e,t){let i=this.safeFloat(t,0),s=this.safeFloat(t,1);e.store(i,s)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e).symbol;return await this.watchMultipleSubscription("ticker:"+i,"market_subscribe",i,!1,t)}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e,void 0,!1),s=this.urls.api.ws,r=this.incrementingNonce(),a=[],o=[];for(let e=0;e<i.length;e++){let t=this.market(i[e]);a.push("ticker:"+t.symbol),o.push(t.id)}return await this.watchMultiple(s,a,this.extend({id:r,method:"market_subscribe",params:o},t),a),this.filterByArray(this.tickers,"symbol",i)}handleTicker(e,t){let i=this.safeList(t,"params",[]),s=this.safeString(i,0),r=this.safeMarket(s),a=r.symbol,o=this.safeDict(i,1,{}),n=this.parseTicker(o,r);this.tickers[a]=n,e.resolve(n,"ticker:"+a);let d=Object.keys(e.futures);for(let t=0;t<d.length;t++){let i=d[t];i.indexOf("tickers")>=0&&i.indexOf(a)>=0&&e.resolve(n,i)}return t}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e).symbol,a="trades:"+r,o=await this.watchMultipleSubscription(a,"trades_subscribe",r,!1,s),n=i;return this.newUpdates&&(n=o.getLimit(r,i)),this.filterBySinceLimit(o,t,n,"timestamp",!0)}handleTrades(e,t){let i=this.safeList(t,"params",[]),s=this.safeString(i,0),r=this.safeMarket(s),a=r.symbol,n=this.safeValue(this.trades,a);if(void 0===n){let e=this.safeInteger(this.options,"tradesLimit",1e3);n=new o.I3(e),this.trades[a]=n}let d=this.safeList(i,1,[]),h=this.parseTrades(d,r);for(let e=0;e<h.length;e++)n.append(h[e]);let c="trades:"+r.symbol;e.resolve(n,c)}async watchMyTrades(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" watchMyTrades() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.market(e).symbol,o="myTrades:"+r,n=await this.watchMultipleSubscription(o,"deals_subscribe",r,!0,s),d=i;return this.newUpdates&&(d=n.getLimit(r,i)),this.filterBySymbolSinceLimit(n,r,t,d,!0)}handleMyTrades(e,t,i){let s=this.safeValue(t,"params");if(void 0===this.myTrades){let e=this.safeInteger(this.options,"tradesLimit",1e3);this.myTrades=new o.I3(e)}let r=this.myTrades,a=this.parseWsTrade(s);r.append(a);let n=a.symbol;e.resolve(r,"myTrades:"+n)}parseWsTrade(e,t){let i,s,r,a=this.safeString(e,3),o=this.safeTimestamp(e,1),n=this.safeString(e,0),d=this.safeString(e,4),h=this.safeString(e,5),c=this.safeString(e,2),l=this.safeMarket(c,t),u=this.safeString(e,6);if(void 0!==u){let t=this.safeString(e,10);i={cost:u,currency:void 0!==t?this.safeCurrencyCode(t):l.quote}}let f=this.safeInteger(e,8);1===f?s="sell":2===f&&(s="buy");let p=this.safeInteger(e,9);return 1===p?r="maker":2===p&&(r="taker"),this.safeTrade({id:n,info:e,timestamp:o,datetime:this.iso8601(o),symbol:l.symbol,order:a,type:void 0,side:s,takerOrMaker:r,price:d,amount:h,cost:void 0,fee:i},l)}async watchOrders(e,t,i,s={}){if(void 0===e)throw new a.ArgumentsRequired(this.id+" watchOrders() requires a symbol argument");void 0===this.markets&&await this.loadMarkets(),await this.authenticate();let r=this.market(e).symbol,o="orders:"+r,n=await this.watchMultipleSubscription(o,"ordersPending_subscribe",r,!1,s),d=i;return this.newUpdates&&(d=n.getLimit(r,i)),this.filterBySymbolSinceLimit(n,r,t,d,!0)}handleOrder(e,t,i){let s=this.safeList(t,"params",[]),r=this.safeDict(s,1);if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}let a=this.orders,n=this.safeInteger(s,0),d=this.parseWsOrder(this.extend(r,{status:n}));a.append(d);let h=d.symbol;e.resolve(this.orders,"orders:"+h)}parseWsOrder(e,t){let i,s,a,o,n=this.safeInteger(e,"status"),d=this.safeString(e,"market"),h=this.safeMarket(d,t),c=this.safeString(e,"id"),l=this.omitZero(this.safeString(e,"client_order_id")),u=this.safeString(e,"price"),f=this.safeString(e,"deal_stock"),p=this.safeString(e,"deal_money"),m=this.safeString(e,"activation_price"),g=this.safeString(e,"type"),v=this.parseWsOrderType(g);"market"===v?(i=this.safeString(e,"deal_stock"),s="0"):(s=this.safeString(e,"left"),i=this.safeString(e,"amount"));let y=this.safeTimestamp(e,"ctime"),b=this.safeTimestamp(e,"mtime"),w=h.symbol,k=this.safeInteger(e,"side"),S="buy";1===k&&(S="sell");let O=this.safeString(e,"deal_fee");return void 0!==O&&(a={cost:this.parseNumber(O),currency:h.quote}),o=1===n||2===n?"open":r.Y.stringEquals(s,"0")?"closed":"canceled",this.safeOrder({info:e,symbol:w,id:c,clientOrderId:l,timestamp:y,datetime:this.iso8601(y),lastTradeTimestamp:b,type:v,timeInForce:void 0,postOnly:void 0,side:S,price:u,stopPrice:m,triggerPrice:m,amount:i,cost:p,average:void 0,filled:f,remaining:s,status:o,fee:a,trades:void 0},h)}parseWsOrderType(e){return this.safeString({1:"limit",2:"market",202:"market",3:"limit",4:"market",5:"limit",6:"market",8:"limit",10:"market"},e,e)}async watchBalance(e={}){let t;void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleMarketTypeAndParams("watchBalance",void 0,e),r="wallet:";"spot"===i?(t="balanceSpot_subscribe",r+="spot"):(t="balanceMargin_subscribe",r+="margin");let a=this.urls.api.ws,o=this.client(a);this.setBalanceCache(o,i,r);let[n,d]=this.handleOptionBoolAndParams(s,"watchBalance","fetchBalanceSnapshot",!0),[h,c]=this.handleOptionBoolAndParams(d,"watchBalance","awaitBalanceSnapshot",!0);return n&&h&&await o.future(i+":fetchBalanceSnapshot"),await this.watchPrivate(r,t,[],c)}setBalanceCache(e,t,i){if(!(i in e.subscriptions)&&!0===this.handleOption("watchBalance","fetchBalanceSnapshot",!0)){let s=t+":fetchBalanceSnapshot";s in e.futures||(e.future(s),this.spawn(this.loadBalanceSnapshot,e,s,t,i))}}async loadBalanceSnapshot(e,t,i,s){let r=await this.fetchBalance({type:i});this.balance=this.extend(r,this.balance),t in e.futures&&(e.futures[t].resolve(),e.resolve(this.balance,s))}handleBalance(e,t){let i=this.safeString(t,"method");if(void 0===i)return;let s=i.indexOf("Margin")>=0,r=this.safeList(t,"params",[]);for(let e=0;e<r.length;e++){let t=this.safeDict(r,e,{});if(this.balance.info=t,s){let e=this.safeString(t,"a"),i=this.safeCurrencyCode(e),s=this.account();s.free=this.safeString(t,"av"),s.total=this.safeString(t,"B"),s.debt=this.safeString(t,"b"),void 0!==i&&(this.balance[i]=s)}else{let e=Object.keys(t);for(let i=0;i<e.length;i++){let s=e[i],r=this.safeDict(t,s,{}),a=this.safeCurrencyCode(s),o=this.account();o.free=this.safeString(r,"available"),o.used=this.safeString(r,"freeze"),void 0!==a&&(this.balance[a]=o)}}}this.balance=this.safeBalance(this.balance);let a="wallet:";i.indexOf("Spot")>=0?a+="spot":a+="margin",e.resolve(this.balance,a)}async watchPublic(e,t,i=[],s={}){let r=this.urls.api.ws,a=this.incrementingNonce(),o=this.extend({id:a,method:t,params:i},s);return await this.watch(r,e,o,e)}async watchMultipleSubscription(e,t,i,s=!1,r={}){let a;void 0===this.markets&&await this.loadMarkets();let o=this.urls.api.ws,n=this.incrementingNonce(),d=this.safeValue(this.clients,o),h=[];if(void 0===d){let d={},c=this.market(i).id;void 0!==c&&(d[c]=!0),h=[c],s&&(h=[h]),a={id:n,method:t,params:h};let l=this.extend(a,r);return await this.watch(o,e,l,t,d)}{let r=this.safeDict(d.subscriptions,t,{}),h=!0,c=this.market(i).id;if(!0!==this.safeBool(r,c,!1)&&(void 0!==c&&(r[c]=!0),h=!1),h)return await this.watch(o,e,a,t,r);{let i=[];i=Object.keys(r),s&&(i=[i]);let a={id:n,method:t,params:i};return t in d.subscriptions&&delete d.subscriptions[t],await this.watch(o,e,a,t,r)}}}async watchPrivate(e,t,i=[],s={}){this.checkRequiredCredentials(),await this.authenticate();let r=this.urls.api.ws,a=this.incrementingNonce(),o=this.extend({id:a,method:t,params:i},s);return await this.watch(r,e,o,e)}async authenticate(e={}){this.checkRequiredCredentials();let t=this.urls.api.ws,i=this.client(t),s="authenticated",r="authenticateFlight";if(r in i.futures)return await i.future(r),1;if(void 0!==this.safeValue(i.subscriptions,s))return 1;let o=i.reusableFuture(r);try{let e=await this.v4PrivatePostProfileWebsocketToken(),o=this.safeString(e,"websocket_token");if(void 0===o)throw new a.AuthenticationError(this.id+" authenticate() received an empty websocket_token");let n=this.incrementingNonce(),d={id:n,method:this.handleAuthenticate};await this.watch(t,s,{id:n,method:"authorize",params:[o,"public"]},s,d),i.resolve(1,r)}catch(e){s in i.subscriptions&&delete i.subscriptions[s],s in i.futures&&i.reject(e,s),i.reject(e,r)}return await o,1}handleAuthenticate(e,t){return e.futures.authenticated.resolve(1),t}handleErrorMessage(e,t){let i=this.safeDict(t,"error");try{if(void 0!==i){let e=this.safeString(t,"code"),i=this.id+" "+this.json(t);this.throwExactlyMatchedException(this.exceptions.ws.exact,e,i)}}catch(t){if(t instanceof a.AuthenticationError)return e.reject(t,"authenticated"),"authenticated"in e.subscriptions&&delete e.subscriptions.authenticated,!1}return!0}handleMessage(e,t){if(!0!==this.handleErrorMessage(e,t))return;if("pong"===this.safeString(t,"result"))return void this.handlePong(e,t);let i=this.safeInteger(t,"id");if(void 0!==i)return void this.handleSubscriptionStatus(e,t,i);let s={market_update:this.handleTicker,trades_update:this.handleTrades,depth_update:this.handleOrderBook,candles_update:this.handleOHLCV,ordersPending_update:this.handleOrder,ordersExecuted_update:this.handleOrder,balanceSpot_update:this.handleBalance,balanceMargin_update:this.handleBalance,deals_update:this.handleMyTrades},r=this.safeString(t,"method"),a=this.safeValue(s,r);void 0!==a&&a.call(this,e,t)}handleSubscriptionStatus(e,t,i){let s=Object.values(e.subscriptions);for(let r=0;r<s.length;r++){let a=s[r];if(!0!==a){let s=this.safeInteger(a,"id");if(void 0!==s&&s===i){let i=this.safeValue(a,"method");if(void 0!==i)return void i.call(this,e,t)}}}}handlePong(e,t){return e.lastPong=this.milliseconds(),t}ping(e){return{id:0,method:"ping",params:[]}}}i.d(t,{A:()=>n})},3363(e,t,i){"use strict";var s=i(4721),r=i(4615),a=i(1453),o=i(1697),n=i(7749);class d extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchFundingRate:!0,watchFundingRates:!1,watchMyTrades:!0,watchOHLCV:!0,watchOrderBook:!0,watchOrders:!0,watchTicker:!0,watchTickers:!0,watchBidsAsks:!0,watchTrades:!0,watchTradesForSymbols:!1,watchPositions:!0,unWatchTicker:!0,unWatchTickers:!0,unWatchOrderBook:!0,unWatchOHLCV:!0,unWatchTrades:!0},urls:{api:{ws:{public:"wss://wss.woox.io/ws/stream",private:"wss://wss.woox.io/v2/ws/private/stream"}},test:{ws:{public:"wss://wss.staging.woox.io/ws/stream",private:"wss://wss.staging.woox.io/v2/ws/private/stream"}}},requiredCredentials:{apiKey:!0,secret:!0,uid:!0},options:{tradesLimit:1e3,ordersLimit:1e3,requestId:{},watchPositions:{fetchPositionsSnapshot:!0,awaitPositionsSnapshot:!0}},streaming:{ping:this.ping,keepAlive:9e3},exceptions:{ws:{exact:{"Auth is needed.":a.AuthenticationError}}}})}requestId(e){let t=this.safeDict(this.options,"requestId",{}),i=this.safeInteger(t,e,0),s=this.sum(i,1);return this.options.requestId[e]=s,s}async watchPublic(e,t){let i="";""!==this.uid&&(i="/"+this.uid);let s=this.safeString(this.urls.api.ws,"public")+i,r={id:this.requestId(s)},a=this.extend(r,t);return await this.watch(s,e,a,e,r)}async unwatchPublic(e,t,i,s={}){let r="";""!==this.uid&&(r="/"+this.uid);let a=this.safeString(this.urls.api.ws,"public")+r,o=this.requestId(a),n="unsubscribe::"+e,d={id:o.toString(),unsubscribe:!0,symbols:[t],topic:i,subMessageHashes:[e],unsubMessageHashes:[n]},h=this.safeList(s,"symbolsAndTimeframes"),c=void 0!==h?this.omit(s,"symbolsAndTimeframes"):s;return void 0!==h&&(d.symbolsAndTimeframes=h),await this.watch(a,n,this.extend({id:o,event:"unsubscribe",topic:e},c),n,d)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let[s,r]=this.handleOptionStringAndParams(i,"watchOrderBook","method","orderbook"),a=this.market(e),o=a.id+"@"+s,n="";""!==this.uid&&(n="/"+this.uid);let d=this.safeString(this.urls.api.ws,"public")+n,h=this.requestId(d),c={id:h.toString(),name:s,symbol:a.symbol,limit:t,params:r};return"orderbookupdate"===s&&(c.method=this.handleOrderBookSubscription),(await this.watch(d,o,this.extend({event:"subscribe",topic:o,id:h},r),o,c)).limit()}async unWatchOrderBook(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionStringAndParams(t,"watchOrderBook","method","orderbook"),r=this.market(e),a=r.id+"@"+i;return await this.unwatchPublic(a,r.symbol,"orderbook",s)}handleOrderBook(e,t){let i=this.safeDict(t,"data"),s=this.safeString(i,"symbol"),r=this.safeMarket(s).symbol,a=this.safeString(t,"topic");if(void 0!==a)if("orderbookupdate"===this.safeString(a.split("@"),1)){if(!(r in this.orderbooks))return;let i=this.orderbooks[r],s=this.safeInteger(i,"timestamp");if(void 0===s)i.cache.push(t);else try{let r=this.safeInteger(t,"ts");if(void 0===r)return;r>s&&(this.handleOrderBookMessage(e,t,i),e.resolve(i,a))}catch(t){delete this.orderbooks[r],void 0!==a&&delete e.subscriptions[a],e.reject(t,a)}}else{if(!(r in this.orderbooks)){let t=this.safeInteger(this.options,"watchOrderBookLimit",1e3),i=this.safeDict(e.subscriptions,a),s=this.safeInteger(i,"limit",t);this.orderbooks[r]=this.orderBook({},s)}let s=this.orderbooks[r],o=this.safeInteger(t,"ts"),n=this.parseOrderBook(i,r,o,"bids","asks");s.reset(n),e.resolve(s,a)}}handleOrderBookSubscription(e,t,i){let s=this.safeInteger(this.options,"watchOrderBookLimit",1e3),r=this.safeInteger(i,"limit",s),a=this.safeString(i,"symbol");void 0!==a&&(a in this.orderbooks&&delete this.orderbooks[a],this.orderbooks[a]=this.orderBook({},r),this.spawn(this.fetchOrderBookSnapshot,e,t,i))}async fetchOrderBookSnapshot(e,t,i){let s=this.safeString(i,"symbol"),r=this.safeString(t,"topic");try{let t=this.safeInteger(this.options,"watchOrderBookLimit",1e3),a=this.safeInteger(i,"limit",t),o=this.safeDict(i,"params"),n=await this.fetchRestOrderBookSafe(s,a,o);if(void 0===this.safeDict(this.orderbooks,s))return;let d=this.safeValue(this.orderbooks,s);d.reset(n);let h=d.cache;for(let t=0;t<h.length;t++){let i=h[t],s=this.safeInteger(i,"ts");if(void 0!==s)if(s<d.timestamp)continue;else this.handleOrderBookMessage(e,i,d)}void 0!==s&&(this.orderbooks[s]=d),e.resolve(d,r)}catch(t){void 0!==r&&delete e.subscriptions[r],e.reject(t,r)}}handleOrderBookMessage(e,t,i){let s=this.safeDict(t,"data");this.handleDeltas(i.asks,this.safeList(s,"asks",[])),this.handleDeltas(i.bids,this.safeList(s,"bids",[]));let r=this.safeInteger(t,"ts");return i.timestamp=r,i.datetime=this.iso8601(r),i}handleDelta(e,t){let i=this.safeFloat2(t,"price",0),s=this.safeFloat2(t,"quantity",1);e.store(i,s)}handleDeltas(e,t){for(let i=0;i<t.length;i++)this.handleDelta(e,t[i])}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e).id+"@ticker",s=this.extend({event:"subscribe",topic:i},t);return await this.watchPublic(i,s)}async unWatchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let[i,s]=this.handleOptionStringAndParams(t,"watchTicker","method","ticker"),r=this.market(e),a=r.id+"@"+i;return await this.unwatchPublic(a,r.symbol,"ticker",s)}parseWsTicker(e,t){return this.safeTicker({symbol:this.safeSymbol(void 0,t),timestamp:void 0,datetime:void 0,high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:this.safeString(e,"open"),close:this.safeString(e,"close"),last:void 0,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"volume"),quoteVolume:this.safeString(e,"amount"),info:e},t)}handleTicker(e,t){let i=this.safeValue(t,"data"),s=this.safeString(t,"topic"),r=this.safeString(i,"symbol"),a=this.safeMarket(r);i.date=this.safeInteger(t,"ts");let o=this.parseWsTicker(i,a);return o.symbol=a.symbol,this.tickers[a.symbol]=o,e.resolve(o,s),t}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s="tickers",r=this.extend({event:"subscribe",topic:s},t),a=await this.watchPublic(s,r);return this.filterByArray(a,"symbol",i)}async unWatchTickers(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0!==e)throw new a.NotSupported(this.id+" unWatchTickers() does not support a symbols argument. Only unwatch all tickers at once");return await this.unwatchPublic("tickers",void 0,"ticker",t)}handleTickers(e,t){let i=this.safeString(t,"topic"),s=this.safeValue(t,"data"),r=this.safeInteger(t,"ts"),a=[];for(let e=0;e<s.length;e++){let t=this.safeString(s[e],"symbol"),i=this.safeMarket(t),o=this.parseWsTicker(this.extend(s[e],{date:r}),i);this.tickers[i.symbol]=o,a.push(o)}e.resolve(a,i)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s="bbos",r=this.extend({event:"subscribe",topic:s},t),a=await this.watchPublic(s,r);return this.newUpdates?a:this.filterByArray(this.bidsasks,"symbol",i)}async unWatchBidsAsks(e,t={}){if(void 0===this.markets&&await this.loadMarkets(),void 0!==e)throw new a.NotSupported(this.id+" unWatchBidsAsks() does not support a symbols argument. Only unwatch all bidsAsks at once");return await this.unwatchPublic("bbos",void 0,"bidsasks",t)}handleBidAsk(e,t){let i=this.safeString(t,"topic"),s=this.safeList(t,"data",[]),r=this.safeInteger(t,"ts"),a={};for(let e=0;e<s.length;e++){let t=this.safeDict(s,e);if(void 0===t)continue;t.ts=r;let i=this.parseWsBidAsk(t),o=i.symbol;void 0!==o&&(this.bidsasks[o]=i),void 0!==o&&(a[o]=i)}e.resolve(a,i)}parseWsBidAsk(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeString(s,"symbol"),a=this.safeInteger(e,"ts");return this.safeTicker({symbol:r,timestamp:a,datetime:this.iso8601(a),ask:this.safeString(e,"ask"),askVolume:this.safeString(e,"askSize"),bid:this.safeString(e,"bid"),bidVolume:this.safeString(e,"bidSize"),info:e},s)}async watchOHLCV(e,t="1m",i,s,r={}){if(void 0===this.markets&&await this.loadMarkets(),"1m"!==t&&"5m"!==t&&"15m"!==t&&"30m"!==t&&"1h"!==t&&"1d"!==t&&"1w"!==t&&"1M"!==t)throw new a.ExchangeError(this.id+" watchOHLCV timeframe argument must be 1m, 5m, 15m, 30m, 1h, 1d, 1w, 1M");let o=this.market(e),n=this.safeString(this.timeframes,t,t),d=o.id+"@kline_"+n,h=this.extend({event:"subscribe",topic:d},r),c=await this.watchPublic(d,h),l=s;return this.newUpdates&&(l=c.getLimit(o.symbol,s)),this.filterBySinceLimit(c,i,l,0,!0)}async unWatchOHLCV(e,t="1m",i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=this.safeString(this.timeframes,t,t),a=s.id+"@kline_"+r;return i.symbolsAndTimeframes=[[s.symbol,t]],await this.unwatchPublic(a,s.symbol,"ohlcv",i)}handleOHLCV(e,t){let i=this.safeDict(t,"data"),s=this.safeString(t,"topic"),r=this.safeString(i,"symbol"),a=this.safeMarket(r).symbol,n=this.safeString(i,"type"),d=this.findTimeframe(n),h=[this.safeInteger(i,"startTime"),this.safeFloat(i,"open"),this.safeFloat(i,"high"),this.safeFloat(i,"low"),this.safeFloat(i,"close"),this.safeFloat(i,"volume")];this.ohlcvs[a]=this.safeDict(this.ohlcvs,a,{});let c=this.safeValue(this.safeDict(this.ohlcvs,a),d);if(void 0===c){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);c=new o.TG(e),void 0!==a&&void 0!==d&&(this.ohlcvs[a][d]=c)}c.append(h),e.resolve(c,s)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o=r.id+"@trade",n=this.extend({event:"subscribe",topic:o},s),d=await this.watchPublic(o,n),h=i;return this.newUpdates&&(h=d.getLimit(r.symbol,i)),this.filterBySymbolSinceLimit(d,a,t,h,!0)}async unWatchTrades(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=i.id+"@trade";return await this.unwatchPublic(s,i.symbol,"trades",t)}handleTrade(e,t){let i=this.safeString(t,"topic"),s=this.safeInteger(t,"ts"),r=this.safeDict(t,"data"),a=this.safeString(r,"symbol"),n=this.safeMarket(a),d=n.symbol,h=this.parseWsTrade(this.extend(r,{timestamp:s}),n),c=this.safeValue(this.trades,d);if(void 0===c){let e=this.safeInteger(this.options,"tradesLimit",1e3);c=new o.I3(e)}c.append(h),this.trades[d]=c,e.resolve(c,i)}parseWsTrade(e,t){let i,s,r=this.safeString(e,"symbol"),a=this.safeMarket(r,t),o=a.symbol,d=this.safeString2(e,"executedPrice","price"),h=this.safeString2(e,"executedQuantity","size"),c=n.Y.stringMul(d,h),l=this.safeStringLower(e,"side"),u=this.safeInteger(e,"timestamp"),f=this.safeBool(e,"maker");void 0!==f&&(i=f?"maker":"taker");let p=this.safeStringLower(e,"type"),m=this.safeNumber(e,"fee");return void 0!==m&&(s={cost:m,currency:this.safeCurrencyCode(this.safeString(e,"feeCurrency"))}),this.safeTrade({id:this.safeString(e,"tradeId"),timestamp:u,datetime:this.iso8601(u),symbol:o,side:l,price:d,amount:h,cost:c,order:this.safeString(e,"orderId"),takerOrMaker:i,type:p,fee:s,info:e},a)}checkRequiredUid(e=!0){if(void 0===this.uid||""===this.uid)if(!e)return!1;else throw new a.AuthenticationError(this.id+" requires `uid` credential (woox calls it `application_id`)");return!0}async authenticate(e={}){this.checkRequiredCredentials();let t=this.safeString(this.urls.api.ws,"private")+"/"+this.uid,i=this.client(t),r="authenticated",a=i.reusableFuture(r);if(void 0===this.safeValue(i.subscriptions,r)){let i=this.nonce().toString(),a=this.hmac(this.encode("|"+i),this.encode(this.secret),s.sc),o={event:"auth",params:{apikey:this.apiKey,sign:a,timestamp:i}},n=this.extend(o,e);this.watch(t,r,n,r,n)}return await a}async watchPrivate(e,t,i={}){await this.authenticate(i);let s=this.safeString(this.urls.api.ws,"private")+"/"+this.uid,r={id:this.requestId(s)},a=this.extend(r,t);return await this.watch(s,e,a,e,r)}async watchPrivateMultiple(e,t,i={}){await this.authenticate(i);let s=this.safeString(this.urls.api.ws,"private")+"/"+this.uid,r={id:this.requestId(s)},a=this.extend(r,t);return await this.watchMultiple(s,e,a,e,r)}async watchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.safeBool2(s,"stop","trigger",!1),a="executionreport";!0===r&&(a="algoexecutionreportv2");let o=this.omit(s,["stop","trigger"]),n=a,d=void 0!==e?this.symbol(e):e;void 0!==d&&(n+=":"+d);let h={event:"subscribe",topic:a},c=this.extend(h,o),l=await this.watchPrivate(n,c),u=i;return this.newUpdates&&(u=l.getLimit(d,i)),this.filterBySymbolSinceLimit(l,d,t,u,!0)}async watchMyTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.safeBool2(s,"stop","trigger",!1),a="executionreport";!0===r&&(a="algoexecutionreportv2");let o=this.omit(s,["stop","trigger"]),n="myTrades",d=void 0!==e?this.symbol(e):e;void 0!==d&&(n+=":"+d);let h={event:"subscribe",topic:a},c=this.extend(h,o),l=await this.watchPrivate(n,c),u=i;return this.newUpdates&&(u=l.getLimit(d,i)),this.filterBySymbolSinceLimit(l,d,t,u,!0)}parseWsOrder(e,t){let i=this.safeString2(e,"orderId","algoOrderId"),s=this.safeString(e,"symbol"),r=this.market(s).symbol,a=this.safeInteger(e,"timestamp"),o={cost:this.safeString(e,"totalFee"),currency:this.safeString(e,"feeAsset")},d=this.safeString(e,"price"),h=this.safeNumber(e,"price"),c=this.safeNumber(e,"avgPrice");n.Y.stringEq(d,"0")&&void 0!==c&&(h=c);let l=this.safeString(e,"quantity"),u=this.safeStringLower(e,"side"),f=this.safeStringLower(e,"type"),p=this.safeString2(e,"totalExecutedQuantity","executed"),m=this.safeString2(e,"status","algoStatus"),g=this.parseOrderStatus(m),v=this.safeString(e,"clientOrderId"),y=this.safeString(e,"triggerPrice");return this.safeOrder({info:e,symbol:r,id:i,clientOrderId:v,timestamp:a,datetime:this.iso8601(a),lastTradeTimestamp:a,type:f,timeInForce:void 0,postOnly:void 0,side:u,price:h,stopPrice:y,triggerPrice:y,reduceOnly:this.safeBool(e,"reduceOnly"),amount:l,cost:void 0,average:c,filled:p,remaining:void 0,status:g,fee:o,trades:void 0})}handleOrderUpdate(e,t){let i=this.safeString(t,"topic"),s=this.safeValue(t,"data");if(Array.isArray(s))for(let t=0;t<s.length;t++){let r=s[t];void 0!==this.omitZero(this.safeString(s,"tradeId"))&&this.handleMyTrade(e,r),this.handleOrder(e,r,i)}else void 0!==this.omitZero(this.safeString(s,"tradeId"))&&this.handleMyTrade(e,s),this.handleOrder(e,s,i)}handleOrder(e,t,i){let s=this.parseWsOrder(t),r=this.safeString(s,"symbol"),a=this.safeString(s,"id");if(void 0!==r){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}let t=this.orders,n=this.safeDict(t.hashmap,r,{}),d=this.safeDict(n,a);if(void 0!==d){let e=this.safeValue(d,"fee");void 0!==e&&(s.fee=e);let t=this.safeList(d,"fees");void 0!==t&&(s.fees=t),s.trades=this.safeValue(d,"trades"),s.timestamp=this.safeInteger(d,"timestamp"),s.datetime=this.safeString(d,"datetime")}t.append(s),e.resolve(this.orders,i);e.resolve(this.orders,i+":"+r)}}handleMyTrade(e,t){let i=this.myTrades;if(void 0===i){let e=this.safeInteger(this.options,"tradesLimit",1e3);i=new o.Pt(e)}let s=this.parseWsTrade(t);i.append(s);let r="myTrades:"+s.symbol;e.resolve(i,r),r="myTrades",e.resolve(i,r)}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=[],o=this.marketSymbols(e);if(this.isEmpty(o))r.push("positions");else{if(void 0===o)throw new a.ArgumentsRequired(this.id+" watchPositions() symbols is required");for(let e=0;e<o.length;e++){if(void 0===o)throw new a.ArgumentsRequired(this.id+" watchPositions() symbols is required");let t=o[e];r.push("positions::"+t)}}let n=this.safeString(this.urls.api.ws,"private")+"/"+this.uid,d=this.client(n);this.setPositionsCache(d,o);let h=this.handleOption("watchPositions","fetchPositionsSnapshot",!0),c=this.handleOption("watchPositions","awaitPositionsSnapshot",!0);if(!0===h&&!0===c&&void 0===this.positions){let e=await d.future("fetchPositionsSnapshot");return this.filterBySymbolsSinceLimit(e,o,t,i,!0)}let l=await this.watchPrivateMultiple(r,{event:"subscribe",topic:"position"},s);return this.newUpdates?l:this.filterBySymbolsSinceLimit(this.positions,o,t,i,!0)}setPositionsCache(e,t,i){if(!0===this.handleOption("watchPositions","fetchPositionsSnapshot",!1)){let t="fetchPositionsSnapshot";t in e.futures||(e.future(t),this.spawn(this.loadPositionsSnapshot,e,t))}else this.positions=new o.Hk}async loadPositionsSnapshot(e,t){let i=await this.fetchPositions();this.positions=new o.Hk;let s=this.positions;for(let e=0;e<i.length;e++){let t=i[e],r=this.safeNumber(t,"contracts",0);void 0!==r&&r>0&&s.append(t)}t in e.futures&&(e.futures[t].resolve(s),e.resolve(s,"positions"))}handlePositions(e,t){let i=this.safeDict(t,"data",{}),s=this.safeDict(i,"positions",{}),r=Object.keys(s);void 0===this.positions&&(this.positions=new o.Hk);let a=this.positions,n=[];for(let t=0;t<r.length;t++){let i=r[t],o=this.safeMarket(i),d=s[i],h=this.parsePosition(d,o);n.push(h),a.append(h);let c="positions::"+o.symbol;e.resolve(h,c)}e.resolve(n,"positions")}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t="balance",i=this.extend({event:"subscribe",topic:t},e);return await this.watchPrivate(t,i)}handleBalance(e,t){let i=this.safeDict(t,"data"),s=this.safeValue(i,"balances"),r=Object.keys(s),a=this.safeInteger(t,"ts");this.balance.info=i,this.balance.timestamp=a,this.balance.datetime=this.iso8601(a);for(let e=0;e<r.length;e++){let t=r[e],i=this.safeDict(s,t),a=this.safeCurrencyCode(t),o=this.account();void 0!==a&&a in this.balance&&(o=this.balance[a]);let d=this.safeString(i,"holding"),h=this.safeString(i,"frozen");o.total=d,o.used=h,o.free=n.Y.stringSub(d,h),void 0!==a&&(this.balance[a]=o)}this.balance=this.safeBalance(this.balance),e.resolve(this.balance,"balance")}async watchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e).id+"@estfundingrate",s=this.extend({event:"subscribe",topic:i},t);return await this.watchPublic(i,s)}handleFundingRate(e,t){let i=this.safeDict(t,"data",{}),s=this.parseFundingRate(i),r=s.symbol;void 0!==r&&(this.fundingRates[r]=s);let a=this.safeString(t,"topic");e.resolve(s,a)}handleErrorMessage(e,t){if(!("success"in t)||!0===this.safeBool(t,"success"))return!1;let i=this.safeString(t,"errorMsg");try{if(void 0!==i){let e=this.id+" "+this.json(t);this.throwExactlyMatchedException(this.exceptions.exact,i,e)}return!1}catch(t){if(t instanceof a.AuthenticationError){let i="authenticated";e.reject(t,i),i in e.subscriptions&&delete e.subscriptions[i]}else e.reject(t);return!0}}handleUnSubscription(e,t){let i=this.safeString(t,"data"),s=this.safeDict(e.subscriptions,"unsubscribe::"+i,{}),r=this.safeList(s,"subMessageHashes",[]),a=this.safeList(s,"unsubMessageHashes",[]);for(let t=0;t<r.length;t++){let i=r[t],s=a[t];this.cleanUnsubscription(e,i,s)}this.cleanCache(s)}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;let i={ping:this.handlePing,pong:this.handlePong,subscribe:this.handleSubscribe,unsubscribe:this.handleUnSubscription,orderbook:this.handleOrderBook,orderbookupdate:this.handleOrderBook,ticker:this.handleTicker,tickers:this.handleTickers,kline:this.handleOHLCV,auth:this.handleAuth,executionreport:this.handleOrderUpdate,algoexecutionreportv2:this.handleOrderUpdate,trade:this.handleTrade,balance:this.handleBalance,position:this.handlePositions,bbos:this.handleBidAsk,estfundingrate:this.handleFundingRate},s=this.safeString(t,"event"),r=this.safeValue(i,s);if(void 0!==r)return void r.call(this,e,t);let a=this.safeString(t,"topic");if(void 0!==a){if(void 0!==(r=this.safeValue(i,a)))return void r.call(this,e,t);let s=a.split("@");if(2===s.length){let a=this.safeString(s,1);if(void 0===a)return;if(void 0!==(r=this.safeValue(i,a)))return void r.call(this,e,t);let o=a.split("_");2===s.length&&void 0!==(r=this.safeValue(i,this.safeString(o,0)))&&r.call(this,e,t)}}}ping(e){return{event:"ping"}}async pong(e,t){await e.send({event:"pong"})}handlePing(e,t){this.spawn(this.pong,e,t)}handlePong(e,t){return e.lastPong=this.milliseconds(),t}handleSubscribe(e,t){let i=this.safeString(t,"id"),s=this.indexBy(e.subscriptions,"id"),r=this.safeDict(s,i,{}),a=this.safeValue(r,"method");return void 0!==a&&a.call(this,e,t,r),t}handleAuth(e,t){let i="authenticated";if(!0===this.safeBool(t,"success"))this.safeValue(e.futures,"authenticated").resolve(!0);else{let s=new a.AuthenticationError(this.json(t));e.reject(s,i),i in e.subscriptions&&delete e.subscriptions.authenticated}}}i.d(t,{A:()=>d})},5959(e,t,i){"use strict";var s=i(7468),r=i(6499),a=i(1453),o=i(1697),n=i(7749),d=i(1093);class h extends r.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchBalance:!0,watchMyTrades:!0,watchOHLCV:!0,watchOrderBook:!0,watchOrders:!0,watchTicker:!0,watchTickers:!0,watchBidsAsks:!0,watchTrades:!0,watchTradesForSymbols:!1,watchPositions:!0},urls:{api:{ws:{public:"wss://ws-evm.orderly.org/ws/stream",private:"wss://ws-private-evm.orderly.org/v2/ws/private/stream"}},test:{ws:{public:"wss://testnet-ws-evm.orderly.org/ws/stream",private:"wss://testnet-ws-private-evm.orderly.org/v2/ws/private/stream"}}},requiredCredentials:{apiKey:!0,secret:!0,accountId:!0},options:{tradesLimit:1e3,ordersLimit:1e3,requestId:{},watchPositions:{fetchPositionsSnapshot:!0,awaitPositionsSnapshot:!0}},streaming:{ping:this.ping,keepAlive:1e4},exceptions:{ws:{exact:{"Auth is needed.":a.AuthenticationError}}}})}requestId(e){let t=this.safeDict(this.options,"requestId",{}),i=this.safeInteger(t,e,0),s=this.sum(i,1);return this.options.requestId[e]=s,s}async watchPublic(e,t){let i="OqdphuyCtYWxwzhxyLLjOWNdFP7sQt8RPWzmb5xY";void 0!==this.accountId&&""!==this.accountId&&(i=this.accountId);let s=this.safeString(this.urls.api.ws,"public")+"/"+i,r={id:this.requestId(s)},a=this.extend(r,t);return await this.watch(s,e,a,e,r)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e).id+"@orderbook",r=this.extend({event:"subscribe",topic:s},i);return(await this.watchPublic(s,r)).limit()}handleOrderBook(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"symbol"),r=this.safeMarket(s).symbol,a=this.safeString(t,"topic");r in this.orderbooks||(this.orderbooks[r]=this.orderBook());let o=this.orderbooks[r],n=this.safeInteger(t,"ts"),d=this.parseOrderBook(i,r,n,"bids","asks");o.reset(d),e.resolve(o,a)}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e).id+"@ticker",s=this.extend({event:"subscribe",topic:i},t);return await this.watchPublic(i,s)}parseWsTicker(e,t){return this.safeTicker({symbol:this.safeSymbol(void 0,t),timestamp:void 0,datetime:void 0,high:this.safeString(e,"high"),low:this.safeString(e,"low"),bid:void 0,bidVolume:void 0,ask:void 0,askVolume:void 0,vwap:void 0,open:this.safeString(e,"open"),close:this.safeString(e,"close"),last:void 0,previousClose:void 0,change:void 0,percentage:void 0,average:void 0,baseVolume:this.safeString(e,"volume"),quoteVolume:this.safeString(e,"amount"),info:e},t)}handleTicker(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(t,"topic"),r=this.safeString(i,"symbol"),a=this.safeMarket(r);i.date=this.safeInteger(t,"ts");let o=this.parseWsTicker(i,a);return o.symbol=a.symbol,this.tickers[a.symbol]=o,e.resolve(o,s),t}async watchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s="tickers",r=this.extend({event:"subscribe",topic:s},t),a=await this.watchPublic(s,r);return this.filterByArray(a,"symbol",i)}handleTickers(e,t){let i=this.safeString(t,"topic"),s=this.safeList(t,"data",[]),r=this.safeInteger(t,"ts"),a=[];for(let e=0;e<s.length;e++){let t=this.safeString(s[e],"symbol"),i=this.safeMarket(t),o=this.parseWsTicker(this.extend(s[e],{date:r}),i);this.tickers[i.symbol]=o,a.push(o)}e.resolve(a,i)}async watchBidsAsks(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.marketSymbols(e),s="bbos",r=this.extend({event:"subscribe",topic:s},t),a=await this.watchPublic(s,r);return this.filterByArray(a,"symbol",i)}handleBidAsk(e,t){let i=this.safeString(t,"topic"),s=this.safeList(t,"data",[]),r=this.safeInteger(t,"ts"),a=[];for(let e=0;e<s.length;e++){let t=this.parseWsBidAsk(this.extend(s[e],{ts:r}));void 0!==t.symbol&&(this.tickers[t.symbol]=t),a.push(t)}e.resolve(a,i)}parseWsBidAsk(e,t){let i=this.safeString(e,"symbol"),s=this.safeMarket(i,t),r=this.safeString(s,"symbol"),a=this.safeInteger(e,"ts");return this.safeTicker({symbol:r,timestamp:a,datetime:this.iso8601(a),ask:this.safeString(e,"ask"),askVolume:this.safeString(e,"askSize"),bid:this.safeString(e,"bid"),bidVolume:this.safeString(e,"bidSize"),info:e},s)}async watchOHLCV(e,t="1m",i,s,r={}){if(void 0===this.markets&&await this.loadMarkets(),"1m"!==t&&"5m"!==t&&"15m"!==t&&"30m"!==t&&"1h"!==t&&"1d"!==t&&"1w"!==t&&"1M"!==t)throw new a.NotSupported(this.id+" watchOHLCV timeframe argument must be 1m, 5m, 15m, 30m, 1h, 1d, 1w, 1M");let o=this.market(e),n=this.safeString(this.timeframes,t,t),d=o.id+"@kline_"+n,h=this.extend({event:"subscribe",topic:d},r),c=await this.watchPublic(d,h),l=s;return this.newUpdates&&(l=c.getLimit(o.symbol,s)),this.filterBySinceLimit(c,i,l,0,!0)}handleOHLCV(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(t,"topic"),r=this.safeString(i,"symbol"),a=this.safeMarket(r).symbol,n=this.safeString(i,"type"),d=this.findTimeframe(n),h=[this.safeInteger(i,"startTime"),this.safeNumber(i,"open"),this.safeNumber(i,"high"),this.safeNumber(i,"low"),this.safeNumber(i,"close"),this.safeNumber(i,"volume")];this.ohlcvs[a]=this.safeDict(this.ohlcvs,a,{});let c=this.safeValue(this.safeDict(this.ohlcvs,a),d);if(void 0===c){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);c=new o.TG(e),void 0!==a&&void 0!==d&&(this.ohlcvs[a][d]=c)}c.append(h),e.resolve(c,s)}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a=r.symbol,o=r.id+"@trade",n=this.extend({event:"subscribe",topic:o},s),d=await this.watchPublic(o,n),h=i;return this.newUpdates&&(h=d.getLimit(r.symbol,i)),this.filterBySymbolSinceLimit(d,a,t,h,!0)}handleTrade(e,t){let i=this.safeString(t,"topic"),s=this.safeInteger(t,"ts"),r=this.safeDict(t,"data",{}),a=this.safeString(r,"symbol"),n=this.safeMarket(a),d=n.symbol,h=this.parseWsTrade(this.extend(r,{timestamp:s}),n);if(!(d in this.trades)){let e=this.safeInteger(this.options,"tradesLimit",1e3),t=new o.I3(e);this.trades[d]=t}let c=this.trades[d];c.append(h),this.trades[d]=c,e.resolve(c,i)}parseWsTrade(e,t){let i,s,r=this.safeString(e,"symbol"),a=this.safeMarket(r,t),o=a.symbol,d=this.safeString2(e,"executedPrice","price"),h=this.safeString2(e,"executedQuantity","size"),c=n.Y.stringMul(d,h),l=this.safeStringLower(e,"side"),u=this.safeInteger(e,"timestamp"),f=this.safeBool(e,"maker");void 0!==f&&(i=f?"maker":"taker");let p=this.safeString(e,"fee");return void 0!==p&&(s={cost:p,currency:this.safeCurrencyCode(this.safeString(e,"feeAsset"))}),this.safeTrade({id:this.safeString(e,"tradeId"),timestamp:u,datetime:this.iso8601(u),symbol:o,side:l,price:d,amount:h,cost:c,order:this.safeString(e,"orderId"),takerOrMaker:i,type:this.safeStringLower(e,"type"),fee:s,info:e},a)}handleAuth(e,t){let i="authenticated";if(!0===this.safeBool(t,"success"))this.safeValue(e.futures,"authenticated").resolve(!0);else{let s=new a.AuthenticationError(this.json(t));e.reject(s,i),i in e.subscriptions&&delete e.subscriptions.authenticated}}async authenticate(e={}){this.checkRequiredCredentials();let t=this.safeString(this.urls.api.ws,"private")+"/"+this.accountId,i=this.client(t),r="authenticated",a=i.reusableFuture(r);if(void 0===this.safeValue(i.subscriptions,r)){let i=this.nonce().toString(),a=this.secret;a.indexOf("ed25519:")>=0&&(a=a.split("ed25519:")[1]);let o=(0,d.q4)(this.encode(i),this.base58ToBinary(a),s.ev),n={event:"auth",params:{orderly_key:this.apiKey,sign:o,timestamp:i}},h=this.extend(n,e);this.watch(t,r,h,r)}return await a}async watchPrivate(e,t,i={}){await this.authenticate(i);let s=this.safeString(this.urls.api.ws,"private")+"/"+this.accountId,r={id:this.requestId(s)},a=this.extend(r,t);return await this.watch(s,e,a,e,r)}async watchPrivateMultiple(e,t,i={}){await this.authenticate(i);let s=this.safeString(this.urls.api.ws,"private")+"/"+this.accountId,r={id:this.requestId(s)},a=this.extend(r,t);return await this.watchMultiple(s,e,a,e,r)}async watchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.safeBool2(s,"stop","trigger",!1),o="executionreport";!0===a&&(o="algoexecutionreport");let n=this.omit(s,["stop","trigger"]),d=o;void 0!==e&&(r=this.market(e));let h=void 0!==r?this.safeString(r,"symbol"):void 0;void 0!==e&&(d+=":"+h);let c={event:"subscribe",topic:o},l=this.extend(c,n),u=await this.watchPrivate(d,l),f=i;return this.newUpdates&&(f=u.getLimit(h,i)),this.filterBySymbolSinceLimit(u,h,t,f,!0)}async watchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets();let a=this.safeBool2(s,"stop","trigger",!1),o="executionreport";!0===a&&(o="algoexecutionreport");let n=this.omit(s,"stop"),d="myTrades";void 0!==e&&(r=this.market(e));let h=void 0!==r?this.safeString(r,"symbol"):void 0;void 0!==e&&(d+=":"+h);let c={event:"subscribe",topic:o},l=this.extend(c,n),u=await this.watchPrivate(d,l),f=i;return this.newUpdates&&(f=u.getLimit(h,i)),this.filterBySymbolSinceLimit(u,h,t,f,!0)}parseWsOrder(e,t){let i=this.safeString(e,"orderId"),s=this.safeString(e,"symbol"),r=this.market(s).symbol,a=this.safeInteger(e,"timestamp"),o={cost:this.safeString(e,"totalFee"),currency:this.safeString(e,"feeAsset")},d=this.safeString(e,"price"),h=this.safeNumber(e,"price"),c=this.safeNumber(e,"avgPrice");n.Y.stringEq(d,"0")&&void 0!==c&&(h=c);let l=this.safeString(e,"quantity"),u=this.safeStringLower(e,"side"),f=this.safeStringLower(e,"type"),p=this.safeNumber(e,"totalExecutedQuantity"),m=this.safeString(e,"totalExecutedQuantity"),g=l;n.Y.stringGe(l,m)&&(g=n.Y.stringSub(g,m));let v=this.safeString(e,"status"),y=this.parseOrderStatus(v),b=this.safeString(e,"clientOrderId"),w=this.safeNumber(e,"triggerPrice");return this.safeOrder({info:e,symbol:r,id:i,clientOrderId:b,timestamp:a,datetime:this.iso8601(a),lastTradeTimestamp:a,type:f,timeInForce:void 0,postOnly:void 0,side:u,price:h,stopPrice:w,triggerPrice:w,amount:l,cost:void 0,average:void 0,filled:p,remaining:g,status:y,fee:o,trades:void 0})}handleOrderUpdate(e,t){let i=this.safeString(t,"topic"),s=this.safeValue(t,"data");if(Array.isArray(s))for(let t=0;t<s.length;t++){let r=s[t];void 0!==this.omitZero(this.safeString(s,"tradeId"))&&this.handleMyTrade(e,r),this.handleOrder(e,r,i)}else void 0!==this.omitZero(this.safeString(s,"tradeId"))&&this.handleMyTrade(e,s),this.handleOrder(e,s,i)}handleOrder(e,t,i){let s=this.parseWsOrder(t),r=this.safeString(s,"symbol"),a=this.safeString(s,"id");if(void 0!==r){if(void 0===this.orders){let e=this.safeInteger(this.options,"ordersLimit",1e3);this.orders=new o.Pt(e)}let t=this.orders,n=this.safeDict(t.hashmap,r,{}),d=this.safeDict(n,a);if(void 0!==d){let e=this.safeValue(d,"fee");void 0!==e&&(s.fee=e);let t=this.safeList(d,"fees");void 0!==t&&(s.fees=t),s.trades=this.safeList(d,"trades",[]),s.timestamp=this.safeInteger(d,"timestamp"),s.datetime=this.safeString(d,"datetime")}t.append(s),e.resolve(this.orders,i);e.resolve(this.orders,i+":"+r)}}handleMyTrade(e,t){let i="myTrades",s=this.safeString(t,"symbol"),r=this.safeMarket(s),a=r.symbol,n=this.parseWsTrade(t,r),d=this.myTrades;if(void 0===d){let e=this.safeInteger(this.options,"tradesLimit",1e3);d=new o.Pt(e),this.myTrades=d}d.append(n),e.resolve(d,i),e.resolve(d,i+":"+a)}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=[],o=this.marketSymbols(e);if(this.isEmpty(o))r.push("positions");else{if(void 0===o)throw new a.ArgumentsRequired(this.id+" watchPositions() symbols is required");for(let e=0;e<o.length;e++){if(void 0===o)throw new a.ArgumentsRequired(this.id+" watchPositions() symbols is required");let t=o[e];r.push("positions::"+t)}}let n=this.safeString(this.urls.api.ws,"private")+"/"+this.accountId,d=this.client(n);this.setPositionsCache(d,o);let h=this.handleOption("watchPositions","fetchPositionsSnapshot",!0),c=this.handleOption("watchPositions","awaitPositionsSnapshot",!0);if(!0===h&&!0===c&&void 0===this.positions){let e=await d.future("fetchPositionsSnapshot");return this.filterBySymbolsSinceLimit(e,o,t,i,!0)}let l=await this.watchPrivateMultiple(r,{event:"subscribe",topic:"position"},s);return this.newUpdates?l:this.filterBySymbolsSinceLimit(this.positions,o,t,i,!0)}setPositionsCache(e,t){if(!0===this.handleOption("watchPositions","fetchPositionsSnapshot",!1)){let t="fetchPositionsSnapshot";t in e.futures||(e.future(t),this.spawn(this.loadPositionsSnapshot,e,t))}else this.positions=new o.Hk}async loadPositionsSnapshot(e,t){let i=await this.fetchPositions();this.positions=new o.Hk;let s=this.positions;for(let e=0;e<i.length;e++){let t=i[e],r=this.safeString(t,"contracts","0");n.Y.stringGt(r,"0")&&s.append(t)}t in e.futures&&(e.futures[t].resolve(s),e.resolve(s,"positions"))}handlePositions(e,t){let i=this.safeDict(t,"data",{}),s=this.safeList(i,"positions",[]);void 0===this.positions&&(this.positions=new o.Hk);let r=this.positions,a=[];for(let t=0;t<s.length;t++){let i=s[t],o=this.safeString(i,"symbol"),n=this.safeMarket(o),d=this.parseWsPosition(i,n);a.push(d),r.append(d);let h="positions::"+n.symbol;e.resolve(d,h)}e.resolve(a,"positions")}parseWsPosition(e,t){let i,s=this.safeString(e,"symbol"),r=this.safeMarket(s,t),a=this.safeString(e,"positionQty");i=n.Y.stringGt(a,"0")?"long":"short";let o=this.safeString(r,"contractSize"),d=this.safeString(e,"markPrice"),h=this.safeInteger(e,"timestamp"),c=this.safeString(e,"averageOpenPrice"),l=this.safeString(e,"unsettledPnl");a=n.Y.stringAbs(a);let u=n.Y.stringMul(a,d);return this.safePosition({info:e,id:void 0,symbol:this.safeString(r,"symbol"),timestamp:h,datetime:this.iso8601(h),lastUpdateTimestamp:void 0,initialMargin:void 0,initialMarginPercentage:void 0,maintenanceMargin:void 0,maintenanceMarginPercentage:void 0,entryPrice:this.parseNumber(c),notional:this.parseNumber(u),leverage:void 0,unrealizedPnl:this.parseNumber(l),contracts:this.parseNumber(a),contractSize:this.parseNumber(o),marginRatio:void 0,liquidationPrice:this.safeNumber(e,"estLiqPrice"),markPrice:this.parseNumber(d),lastPrice:void 0,collateral:void 0,marginMode:"cross",marginType:void 0,side:i,percentage:void 0,hedged:void 0,stopLossPrice:void 0,takeProfitPrice:void 0})}async watchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t="balance",i=this.extend({event:"subscribe",topic:t},e);return await this.watchPrivate(t,i)}handleBalance(e,t){let i=this.safeDict(t,"data",{}),s=this.safeDict(i,"balances",{}),r=Object.keys(s),a=this.safeInteger(t,"ts");this.balance.info=i,this.balance.timestamp=a,this.balance.datetime=this.iso8601(a);for(let e=0;e<r.length;e++){let t=r[e],i=this.safeDict(s,t),a=this.safeCurrencyCode(t),o=this.account();void 0!==a&&a in this.balance&&(o=this.balance[a]);let d=this.safeString(i,"holding"),h=this.safeString(i,"frozen");o.total=d,o.used=h,o.free=n.Y.stringSub(d,h),void 0!==a&&(this.balance[a]=o)}this.balance=this.safeBalance(this.balance),e.resolve(this.balance,"balance")}handleErrorMessage(e,t){if(!("success"in t)||!0===this.safeBool(t,"success"))return!1;let i=this.safeString(t,"errorMsg");try{if(void 0!==i){let e=this.id+" "+this.json(t);this.throwExactlyMatchedException(this.exceptions.exact,i,e)}return!1}catch(t){if(t instanceof a.AuthenticationError){let i="authenticated";e.reject(t,i),i in e.subscriptions&&delete e.subscriptions[i]}else e.reject(t);return!0}}handleMessage(e,t){if(!0===this.handleErrorMessage(e,t))return;let i={ping:this.handlePing,pong:this.handlePong,subscribe:this.handleSubscribe,orderbook:this.handleOrderBook,ticker:this.handleTicker,tickers:this.handleTickers,kline:this.handleOHLCV,trade:this.handleTrade,auth:this.handleAuth,executionreport:this.handleOrderUpdate,algoexecutionreport:this.handleOrderUpdate,position:this.handlePositions,balance:this.handleBalance,bbos:this.handleBidAsk},s=this.safeString(t,"event"),r=this.safeValue(i,s);if(void 0!==r)return void r.call(this,e,t);let a=this.safeString(t,"topic");if(void 0!==a){if(void 0!==(r=this.safeValue(i,a)))return void r.call(this,e,t);let s=a.split("@");if(2===s.length){let a=this.safeString(s,1);if(void 0===a)return;if(void 0!==(r=this.safeValue(i,a)))return void r.call(this,e,t);let o=a.split("_");2===s.length&&void 0!==(r=this.safeValue(i,this.safeString(o,0)))&&r.call(this,e,t)}}}ping(e){return{event:"ping"}}async pong(e,t){await e.send({event:"pong"})}handlePing(e,t){this.spawn(this.pong,e,t)}handlePong(e,t){return e.lastPong=this.milliseconds(),t}handleSubscribe(e,t){return t}}i.d(t,{A:()=>h})},846(e,t,i){"use strict";var s=i(1434),r=i(1697),a=i(1453);class o extends s.A{describe(){return this.deepExtend(super.describe(),{has:{ws:!0,watchOHLCV:!0,unWatchOHLCV:!0,watchOrderBook:!0,unWatchOrderBook:!0,watchTicker:!0,unWatchTicker:!0,watchTickers:!0,unWatchTickers:!0,watchTrades:!0,unWatchTrades:!0,watchTradesForSymbols:!1,watchBalance:!0,watchOrders:!0,watchMyTrades:!0,watchPositions:!0,watchFundingRate:!0,unWatchFundingRate:!0},urls:{api:{ws:{spot:"wss://stream.xt.com",contract:"wss://fstream.xt.com/ws"}}},options:{tradesLimit:1e3,ordersLimit:1e3,OHLCVLimit:1e3,watchTicker:{method:"ticker"},watchTickers:{method:"tickers"},watchPositions:{type:"swap",fetchPositionsSnapshot:!0,awaitPositionsSnapshot:!0}},streaming:{keepAlive:2e4,ping:this.ping},token:void 0})}async getListenKey(e){this.checkRequiredCredentials();let t="spot";e&&(t="contract");let i=this.safeString(this.urls.api.ws,t);e||(i+="/private");let s=this.client(i);if(void 0===this.safeString(s.subscriptions,"token")){let i="authenticate:"+t;if(i in s.futures)return await s.future(i),s.subscriptions.token;let r=s.reusableFuture(i);try{let t;if(e){let e=await this.privateLinearGetFutureUserV1UserListenKey();t=this.safeString(e,"result")}else{let e=await this.privateSpotPostWsToken(),i=this.safeDict(e,"result");t=this.safeString(i,"accessToken")}if(void 0===t)throw new a.AuthenticationError(this.id+" getListenKey() received an empty listen key");s.subscriptions.token=t,s.resolve(t,i)}catch(e){s.reject(e,i)}await r}return s.subscriptions.token}getCacheIndex(e,t){let i=this.safeInteger(e,"nonce"),s=this.safeDict(t,0),r=this.safeInteger2(s,"i","u");if(void 0!==i&&void 0!==r&&i<r-1)return -1;for(let e=0;e<t.length;e++){let s=this.safeDict(t,e),r=this.safeInteger2(s,"i","u");if(void 0!==r&&void 0!==i&&r>=i)return e}return t.length}handleBookDelta(e,t){e.nonce=this.safeInteger2(t,"i","u");let i=this.safeList(t,"a",[]),s=this.safeList(t,"b",[]),r=e.bids,a=e.asks;for(let e=0;e<s.length;e++){let t=this.safeList(s,e),i=this.safeNumber(t,0),a=this.safeNumber(t,1);r.store(i,a)}for(let e=0;e<i.length;e++){let t=this.safeList(i,e),s=this.safeNumber(t,0),r=this.safeNumber(t,1);a.store(s,r)}}async subscribe(e,t,i,s,r,a={}){let o="private"===t,[n,d]=this.handleMarketTypeAndParams(i,s,a),h="spot"!==n,c=this.numberToString(this.milliseconds())+e,l={method:h?"SUBSCRIBE":"subscribe",id:c};o?h?l.params=[e+"@"+await this.getListenKey(h)]:(l.params=[e],l.listenKey=await this.getListenKey(h)):l.params=[e];let u="spot";h&&(u="contract");let f=e+"::"+u;void 0!==r&&(f=f+"::"+r.join(","));let p=this.extend(l,d),m=t;h&&(m=o?"user":"market");let g=this.safeString(this.urls.api.ws,u)+"/"+m;return await this.watch(g,f,p,f,{id:c})}async unSubscribe(e,t,i,s,r,a,o,n={},d={}){let h="private"===i,[c,l]=this.handleMarketTypeAndParams(s,a,n),u="spot"!==c,f=this.numberToString(this.milliseconds())+t,p={method:u?"UNSUBSCRIBE":"unsubscribe",id:f};h?u?p.params=[t+"@"+await this.getListenKey(u)]:(p.params=[t],p.listenKey=await this.getListenKey(u)):p.params=[t];let m="spot";u&&(m="contract");let g=t+"::"+m,v=this.extend(p,l),y=i;u&&(y=h?"user":"market");let b=this.safeString(this.urls.api.ws,m)+"/"+y,w={unsubscribe:!0,id:f,subMessageHashes:[g],messageHashes:[e],symbols:o,topic:r},k=this.safeList(d,"symbolsAndTimeframes");void 0!==k&&(w.symbolsAndTimeframes=k);let S=this.omit(d,"symbolsAndTimeframes");return await this.watch(b,e,this.extend(v,l),e,this.extend(w,S))}async watchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.safeDict(this.options,"watchTicker"),r=this.safeString(s,"method","ticker"),a=this.safeString(t,"method",r)+"@"+i.id;return await this.subscribe(a,"public","watchTicker",i,void 0,t)}async unWatchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.safeDict(this.options,"unWatchTicker"),r=this.safeString(s,"method","ticker"),a=this.safeString(t,"method",r)+"@"+i.id;return await this.unSubscribe("unsubscribe::"+a,a,"public","unWatchTicker",r,i,void 0,t)}async watchTickers(e,t={}){let i;void 0===this.markets&&await this.loadMarkets();let s=this.safeDict(this.options,"watchTickers"),r=this.safeString(s,"method","tickers"),a=this.safeString(t,"method",r);void 0!==e&&(i=this.market(e[0]));let o=await this.subscribe(a,"public","watchTickers",i,e,t);return this.newUpdates?o:this.filterByArray(this.tickers,"symbol",e)}async unWatchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.safeDict(this.options,"unWatchTickers"),s=this.safeString(i,"method","tickers"),r=this.safeString(t,"method",s);if(void 0!==e)throw new a.NotSupported(this.id+" unWatchTickers() does not support symbols argument, unsubscribtion is for all tickers at once only");let o=await this.unSubscribe("unsubscribe::"+r,r,"public","unWatchTickers","ticker",void 0,e,t);return this.newUpdates?o:this.filterByArray(this.tickers,"symbol",e)}async watchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o="kline@"+a.id+","+t,n=await this.subscribe(o,"public","watchOHLCV",a,void 0,r),d=s;return this.newUpdates&&(d=n.getLimit(e,s)),this.filterBySinceLimit(n,i,d,0,!0)}async unWatchOHLCV(e,t="1m",i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r="kline@"+s.id+","+t,a=[[s.symbol,t]];return await this.unSubscribe("unsubscribe::"+r,r,"public","unWatchOHLCV","ohlcv",s,[e],i,{symbolsAndTimeframes:a})}async watchTrades(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.market(e),a="trade@"+r.id,o=await this.subscribe(a,"public","watchTrades",r,void 0,s),n=i;return this.newUpdates&&(n=o.getLimit(e,i)),this.filterBySinceLimit(o,t,n,"timestamp")}async unWatchTrades(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s="trade@"+i.id;return await this.unSubscribe("unsubscribe::"+s,s,"public","unWatchTrades","trades",i,[e],t)}async watchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=this.market(e),r=this.safeString(i,"levels"),a=this.omit(i,"levels"),o="depth_update@"+s.id;return void 0!==r&&(o="depth@"+s.id+","+r),(await this.subscribe(o,"public","watchOrderBook",s,void 0,a)).limit()}async unWatchOrderBook(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e),s=this.safeString(t,"levels"),r=this.omit(t,"levels"),a="depth_update@"+i.id;void 0!==s&&(a="depth@"+i.id+","+s);let o="unsubscribe::"+a;return await this.unSubscribe(o,a,"public","unWatchOrderBook","orderbook",i,[e],r)}async watchOrders(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a=await this.subscribe("order","private","watchOrders",r,void 0,s),o=i;return this.newUpdates&&(o=a.getLimit(e,i)),this.filterBySinceLimit(a,t,o,"timestamp")}async watchMyTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a=await this.subscribe("trade","private","watchMyTrades",r,void 0,s),o=i;return this.newUpdates&&(o=a.getLimit(e,i)),this.filterBySinceLimit(a,t,o,"timestamp")}async watchBalance(e={}){return void 0===this.markets&&await this.loadMarkets(),await this.subscribe("balance","private","watchBalance",void 0,void 0,e)}async watchPositions(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r=this.safeString(this.urls.api.ws,"contract")+"/user",a=this.client(r);this.setPositionsCache(a);let o=this.handleOption("watchPositions","fetchPositionsSnapshot",!0),n=this.handleOption("watchPositions","awaitPositionsSnapshot",!0),d=this.positions;if(!0===o&&!0===n&&this.isEmpty(d)){let s=await a.future("fetchPositionsSnapshot");return this.filterBySymbolsSinceLimit(s,e,t,i,!0)}let h=await this.subscribe("position","private","watchPositions",void 0,void 0,s);return this.newUpdates?h:this.filterBySymbolsSinceLimit(d,e,t,i,!0)}async watchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new a.NotSupported(this.id+" watchFundingRate() supports swap contracts only");let s="fund_rate@"+i.id;return await this.subscribe(s,"public","watchFundingRate",i,void 0,t)}async unWatchFundingRate(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=this.market(e);if(!0!==i.swap)throw new a.NotSupported(this.id+" unWatchFundingRate() supports swap contracts only");let s="fund_rate@"+i.id;return await this.unSubscribe("unsubscribe::"+s,s,"public","unWatchFundingRate","fund_rate",i,void 0,t)}handleFundingRate(e,t){let i=this.safeDict(t,"data"),s=this.safeString(i,"s");if(void 0!==s){let r={symbol:s,fundingRate:this.safeString(i,"r")},a=this.parseFundingRate(r),o=this.safeInteger(i,"t");a.timestamp=o,a.datetime=this.iso8601(o);let n=a.symbol;this.fundingRates[n]=a;let d=this.safeString(t,"event");void 0!==d&&e.resolve(a,d+"::contract")}return t}setPositionsCache(e){if(void 0===this.positions&&(this.positions=new r.Hk),!0===this.handleOption("watchPositions","fetchPositionsSnapshot")){let t="fetchPositionsSnapshot";t in e.futures||(e.future(t),this.spawn(this.loadPositionsSnapshot,e,t))}}async loadPositionsSnapshot(e,t){let i=await this.fetchPositions();this.positions=new r.Hk;let s=this.positions;for(let e=0;e<i.length;e++){let t=i[e],r=this.safeNumber(t,"contracts",0);void 0!==r&&r>0&&s.append(t)}t in e.futures&&(e.futures[t].resolve(s),e.resolve(s,"position::contract"))}handlePosition(e,t){void 0===this.positions&&(this.positions=new r.Hk);let i=this.positions,s=this.safeDict(t,"data",{}),a=this.parsePosition(s);i.append(a);let o=this.findMessageHashes(e,"position::contract");for(let t=0;t<o.length;t++){let i=o[t],s=i.split("::")[1].split(","),r=this.filterByArray([a],"symbol",s,!1);this.isEmpty(r)||e.resolve(r,i)}e.resolve([a],"position::contract")}handleTicker(e,t){let i=this.safeDict(t,"data",{});if(void 0!==this.safeString(i,"s")){let s=this.safeString(i,"cv"),r=this.parseTicker(i),a=r.symbol;void 0!==a&&(this.tickers[a]=r);let o=this.safeString(t,"event"),n="contract";if(void 0!==s&&(n="spot"),void 0!==o){let t=o+"::"+n;e.resolve(r,t)}}return t}handleTickers(e,t){let i=this.safeList(t,"data",[]),s=this.safeDict(i,0),r=this.safeString2(s,"cv","aq"),a="contract";void 0!==r&&(a="spot");let o=[];for(let e=0;e<i.length;e++){let t=i[e],s=this.parseTicker(t),r=s.symbol;void 0!==r&&(this.tickers[r]=s),o.push(s)}let n=this.safeString(t,"topic")+"::"+a,d=this.findMessageHashes(e,n+"::");for(let t=0;t<d.length;t++){let i=d[t],s=i.split("::")[2].split(","),r=this.filterByArray(o,"symbol",s);Object.keys(r).length>0&&e.resolve(r,i)}return e.resolve(this.tickers,n),t}handleOHLCV(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString(i,"s");if(void 0!==s){let a=this.safeString(i,"i",""),o="contract";"q"in i&&(o="spot");let n=this.safeMarket(s,void 0,void 0,o),d=n.symbol,h=this.parseOHLCV(i,n);this.ohlcvs[d]=this.safeDict(this.ohlcvs,d,{});let c=this.safeValue(this.ohlcvs[d],a);if(void 0===c){let e=this.safeInteger(this.options,"OHLCVLimit",1e3);c=new r.TG(e),this.ohlcvs[d][a]=c}c.append(h);let l=this.safeString(t,"event");if(void 0!==l){let t=l+"::"+o;e.resolve(c,t)}}return t}handleTrade(e,t){let i=this.safeDict(t,"data",{}),s=this.safeStringLower(i,"s");if(void 0!==s){let a=this.parseTrade(i),o=this.safeString(i,"i"),n="contract";void 0!==o&&(n="spot");let d=this.safeMarket(s,void 0,void 0,n).symbol,h=this.safeString(t,"event"),c=this.safeValue(this.trades,d);if(void 0===c){let e=this.safeInteger(this.options,"tradesLimit",1e3);c=new r.I3(e),this.trades[d]=c}if(c.append(a),void 0!==h){let t=h+"::"+n;e.resolve(c,t)}}return t}handleOrderBook(e,t){let i=this.safeDict(t,"data"),s=this.safeString(i,"s");if(void 0!==s){let r=this.safeString(t,"event",""),a=r.split(",");r=this.safeString(a,0,"");let o="spot";void 0!==i&&"fu"in i&&(o="contract");let n=this.safeMarket(s,void 0,void 0,o).symbol,d=this.safeList(i,"a"),h=this.safeList(i,"b"),c=r+"::"+o;if(!(n in this.orderbooks)){let t=this.safeDict(e.subscriptions,c,{}),i=this.safeInteger(t,"limit");this.orderbooks[n]=this.orderBook({},i)}let l=this.orderbooks[n];if(void 0===this.safeInteger(l,"nonce")){l.cache.length===this.handleOption("watchOrderBook","snapshotDelay",25)&&this.spawn(this.loadOrderBook,e,c,n),l.cache.push(i);return}if(void 0!==d){let e=l.asks;for(let t=0;t<d.length;t++){let i=this.safeList(d,t),s=this.safeNumber(i,0),r=this.safeNumber(i,1);e.store(s,r)}}if(void 0!==h){let e=l.bids;for(let t=0;t<h.length;t++){let i=this.safeList(h,t),s=this.safeNumber(i,0),r=this.safeNumber(i,1);e.store(s,r)}}let u=this.safeInteger(i,"t");l.nonce=this.safeInteger2(i,"i","u"),l.timestamp=u,l.datetime=this.iso8601(u),l.symbol=n,e.resolve(l,c)}}parseWsOrderTrade(e,t){let i=this.safeString(e,"s"),s="spot";"symbol"in e&&(s="contract");let r=this.safeMarket(i,t,void 0,s),a=this.safeString(e,"t");return this.safeTrade({info:e,id:void 0,timestamp:a,datetime:this.iso8601(a),symbol:r.symbol,order:this.safeString(e,"i","orderId"),type:this.parseOrderStatus(this.safeString(e,"st","state")),side:this.safeStringLower(e,"sd","orderSide"),takerOrMaker:void 0,price:this.safeNumber(e,"price"),amount:this.safeString(e,"origQty"),cost:void 0,fee:{currency:void 0,cost:this.safeNumber(e,"f"),rate:void 0}},r)}parseWsOrder(e,t){let i=this.safeString2(e,"s","symbol"),s="spot";"symbol"in e&&(s="contract");let r=this.safeMarket(i,t,void 0,s),a=this.safeInteger2(e,"ct","createTime");return this.safeOrder({info:e,id:this.safeString2(e,"i","orderId"),clientOrderId:this.safeString2(e,"ci","clientOrderId"),timestamp:a,datetime:this.iso8601(a),lastTradeTimestamp:void 0,symbol:r.symbol,type:r.type,timeInForce:void 0,postOnly:void 0,side:this.safeStringLower2(e,"sd","orderSide"),price:this.safeNumber2(e,"p","price"),stopPrice:void 0,stopLossPrice:void 0,takeProfitPrice:void 0,amount:this.safeString2(e,"oq","origQty"),filled:this.safeString2(e,"eq","executedQty"),remaining:this.safeString(e,"lq"),cost:void 0,average:this.safeString2(e,"ap","avgPrice"),status:this.parseOrderStatus(this.safeString(e,"st","state")),fee:{currency:void 0,cost:this.safeNumber(e,"f")},trades:void 0},r)}handleOrder(e,t){let i=this.orders;if(void 0===i){let e=this.safeInteger(this.options,"ordersLimit");i=new r.Pt(e),this.orders=i}let s=this.safeDict(t,"data",{}),a=this.safeString2(s,"s","symbol");if(void 0!==a){let t="spot";"symbol"in s&&(t="contract");let r=this.safeMarket(a,void 0,void 0,t),o=this.parseWsOrder(s,r);i.append(o),e.resolve(i,"order::"+t)}return t}handleBalance(e,t){let i=this.safeDict(t,"data",{}),s=this.safeString2(i,"c","coin"),r=this.safeCurrencyCode(s),a=this.account();a.free=this.safeString(i,"availableBalance"),a.used=this.safeString(i,"f"),a.total=this.safeString2(i,"b","walletBalance"),void 0!==r&&(this.balance[r]=a),this.balance=this.safeBalance(this.balance);let o="spot";"coin"in i&&(o="contract"),e.resolve(this.balance,"balance::"+o)}handleMyTrades(e,t){let i=this.safeDict(t,"data",{}),s=this.myTrades;if(void 0===s){let e=this.safeInteger(this.options,"tradesLimit",1e3);s=new r.Pt(e),this.myTrades=s}let a=this.parseTrade(i),o=a.symbol;if(void 0===o)return;let n=this.market(o);s.append(a);let d="spot";!0===n.contract&&(d="contract"),e.resolve(s,"trade::"+d)}handleMessage(e,t){let i=this.safeString(t,"event");if("pong"===i)e.onPong();else if(void 0!==i){let i=this.safeString(t,"topic"),s={kline:this.handleOHLCV,depth:this.handleOrderBook,depth_update:this.handleOrderBook,ticker:this.handleTicker,agg_ticker:this.handleTicker,tickers:this.handleTickers,agg_tickers:this.handleTickers,balance:this.handleBalance,order:this.handleOrder,position:this.handlePosition,fund_rate:this.handleFundingRate},r=void 0===i?void 0:this.safeValue(s,i);if("trade"===i){let e=this.safeDict(t,"data");r=void 0!==e&&("oi"in e||"orderId"in e)?this.handleMyTrades:this.handleTrade}void 0!==r&&r.call(this,e,t)}else this.handleSubscriptionStatus(e,t)}ping(e){return e.lastPong=this.milliseconds(),"ping"}handleSubscriptionStatus(e,t){let i=this.safeString(t,"id"),s=this.indexBy(e.subscriptions,"id");if(void 0!==i){let t=this.safeDict(s,i,{});!0===this.safeBool(t,"unsubscribe",!1)&&this.handleUnSubscription(e,t)}return t}handleUnSubscription(e,t){let i=this.safeList(t,"messageHashes",[]),s=this.safeList(t,"subMessageHashes",[]);for(let t=0;t<i.length;t++){let r=i[t],a=s[t];this.cleanUnsubscription(e,a,r)}this.cleanCache(t)}handleErrorMessage(e,t){let i=this.safeString(t,"msg");if("invalid_listen_key"===i||"token expire"===i){"token"in e.subscriptions&&delete e.subscriptions.token,this.getListenKey(!0);return}let s=new a.ExchangeError(this.id+" "+this.json(t));e.reject(s)}}i.d(t,{A:()=>o})},6711(e,t,i){"use strict";var s=i(7468),r=i(7838),a=i(1453),o=i(7749),n=i(1093);class d extends r.A{describe(){return this.deepExtend(super.describe(),{id:"revolutx",name:"Revolut X",countries:["GB"],rateLimit:1e3,certified:!1,pro:!1,has:{CORS:void 0,spot:!0,margin:!1,swap:!1,future:!1,option:!1,cancelAllOrders:!0,cancelOrder:!0,createOrder:!0,editOrder:!0,fetchBalance:!0,fetchClosedOrders:!0,fetchCurrencies:!0,fetchMarkets:!0,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenOrders:!0,fetchOrder:!0,fetchOrderBook:!0,fetchOrders:!0,fetchTicker:!0,fetchTickers:!0,fetchTrades:!0},timeframes:{"1m":1,"5m":5,"15m":15,"30m":30,"1h":60,"4h":240,"1d":1440,"2d":2880,"4d":5760,"1w":10080,"2w":20160,"4w":40320},urls:{logo:"https://github.com/user-attachments/assets/594ab1a5-3985-4f79-89f4-c40ef7c33867",api:{public:"https://revx.revolut.com/api",private:"https://revx.revolut.com/api"},www:"https://exchange.revolut.com",doc:"https://developer.revolut.com/docs/api/revolut-x-crypto-exchange",fees:"https://exchange.revolut.com/fees"},api:{public:{get:{"2.0/public/order-book/{symbol}":{cost:1},"1.0/public/tickers":{cost:1},"1.0/public/candles/{symbol}":{cost:1},"1.0/public/trades/all":{cost:1},"1.0/public/configuration/currencies":{cost:1},"1.0/public/configuration/pairs":{cost:1}}},private:{get:{"1.0/balances":1,"1.0/orders/active":{cost:1},"1.0/orders/historical":{cost:1},"1.0/orders/{venue_order_id}":{cost:1},"1.0/orders/fills/{venue_order_id}":1,"1.0/trades/private/{symbol}":{cost:1},"1.0/transactions":1},post:{"1.0/orders":{cost:1}},put:{"1.0/orders/{venue_order_id}":{cost:1}},delete:{"1.0/orders":1,"1.0/orders/{venue_order_id}":{cost:1}}}},requiredCredentials:{apiKey:!0,secret:!1,privateKey:!0},fees:{trading:{tierBased:!1,percentage:!0,taker:this.parseNumber("0.0009"),maker:this.parseNumber("0")}},options:{region:void 0},precisionMode:4,features:{spot:{sandbox:!1,createOrder:{marginMode:!1,triggerPrice:!1,triggerPriceType:void 0,triggerDirection:!1,stopLossPrice:!1,takeProfitPrice:!1,attachedStopLossTakeProfit:void 0,timeInForce:{GTC:!0,IOC:!0,FOK:!1,PO:!1,GTD:!1},hedged:!1,trailing:!1,leverage:!1,marketBuyByCost:!0,marketBuyRequiresPrice:!1,selfTradePrevention:!1,iceberg:!1},createOrders:void 0,fetchMyTrades:{marginMode:!1,limit:1900,daysBack:30,untilDays:void 0,symbolRequired:!0},fetchOrder:{marginMode:!1,trigger:!1,trailing:!1,symbolRequired:!1},fetchOpenOrders:{marginMode:!1,limit:300,trigger:!1,trailing:!1,symbolRequired:!1},fetchOrders:{marginMode:!1,limit:1900,daysBack:30,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchClosedOrders:{marginMode:!1,limit:1900,daysBack:30,daysBackCanceled:void 0,untilDays:void 0,trigger:!1,trailing:!1,symbolRequired:!1},fetchOHLCV:{limit:5e4}}},httpExceptions:{400:a.BadRequest,403:a.PermissionDenied,404:a.OrderNotFound,409:a.ExchangeError,429:a.RateLimitExceeded},exceptions:{exact:{},broad:{insufficient:a.InsufficientFunds,"invalid order":a.InvalidOrder,"not found":a.OrderNotFound,"timestamp is in the future":a.InvalidNonce}}})}sign(e,t="public",i="GET",r={},o,d){let h,c,l=this.implodeParams(e,r),u=this.omit(r,this.extractParams(e)),f=Object.keys(u).length,p=this.safeString(this.urls.api,t);if(void 0===p)throw new a.ExchangeError(this.id+" sign() has no API URL for this endpoint");let m=p+"/"+l,g="";if("private"===t){this.checkRequiredCredentials();let e=this.milliseconds().toString();"GET"===i||"DELETE"===i?f>0&&(m+="?"+(g=this.urlencode(u))):c=this.json(u);let t=void 0!==c?c:d,r=e+i.toUpperCase()+"/api/"+l+g+(void 0!==t?t:""),a=(0,n.q4)(this.encode(r),this.privateKey,s.ev);h={"X-Revx-API-Key":this.apiKey,"X-Revx-Timestamp":e,"X-Revx-Signature":a},("POST"===i||"PUT"===i)&&(h["Content-Type"]="application/json")}else"GET"===i?f>0&&(m+="?"+(g=this.urlencode(u))):(c=this.json(u),h={"Content-Type":"application/json"});return{url:m,method:i,body:void 0!==c?c:d,headers:void 0!==h?h:o}}parseMarket(e){let t=this.safeString(e,"id"),i=this.safeString(e,"base",""),s=this.safeString(e,"quote",""),r=this.safeString(e,"base_step"),a=this.safeString(e,"quote_step"),o=this.safeString(e,"min_order_size"),n=this.safeString(e,"max_order_size"),d=this.safeString(e,"min_order_size_quote");return{id:t,symbol:i+"/"+s,base:i,quote:s,baseId:i,quoteId:s,active:"active"===this.safeString(e,"status"),type:"spot",spot:!0,margin:!1,swap:!1,future:!1,option:!1,contract:!1,settle:void 0,settleId:void 0,contractSize:void 0,linear:void 0,inverse:void 0,expiry:void 0,expiryDatetime:void 0,strike:void 0,optionType:void 0,taker:this.parseNumber("0.0009"),maker:this.parseNumber("0"),percentage:!0,tierBased:!1,feeSide:"get",precision:{amount:this.parseNumber(r),price:this.parseNumber(a)},limits:{amount:{min:this.parseNumber(o),max:this.parseNumber(n)},price:{min:void 0,max:void 0},cost:{min:this.parseNumber(d),max:void 0},leverage:{min:void 0,max:void 0},market:void 0},created:void 0,info:e}}async fetchMarkets(e={}){let t={},i=this.safeString2(e,"region","region",this.options.region);void 0!==i&&(t.region=i);let s=await this.publicGet10PublicConfigurationPairs(this.extend(t,e)),r=this.safeDict(s,"data",s),a=Object.keys(r),o=[];for(let e=0;e<a.length;e++){let t=a[e],i=this.safeDict(r,t,{}),s=this.safeString(i,"base"),n=this.safeString(i,"quote");if(void 0===s||void 0===n)continue;let d=s+"-"+n,h=this.extend(i,{id:d});o.push(this.parseMarket(h))}return o}parseCurrency(e){let t=this.safeString2(e,"id","symbol",""),i=this.safeCurrencyCode(t),s=this.safeString(e,"name"),r=this.safeInteger(e,"scale"),a=this.safeString(e,"status"),o=this.safeString(e,"asset_type"),n=void 0!==r?Math.pow(10,-r):void 0;return{info:e,id:t,code:i,name:s,active:"active"===a,type:"crypto"===o?"crypto":"fiat",deposit:void 0,withdraw:void 0,precision:this.parseNumber(n),fee:void 0,limits:{amount:{min:void 0,max:void 0},withdraw:{min:void 0,max:void 0},deposit:{min:void 0,max:void 0}},networks:{}}}async fetchCurrencies(e={}){let t={},i=this.safeString2(e,"region","region",this.options.region);void 0!==i&&(t.region=i);let s=await this.publicGet10PublicConfigurationCurrencies(this.extend(t,e)),r=this.safeDict(s,"data",s),a=Object.keys(r),o={};for(let e=0;e<a.length;e++){let t=a[e],i=this.safeDict(r,t,{}),s=this.extend(i,{id:t}),n=this.parseCurrency(s),d=this.safeString(n,"code","");""!==d&&(o[d]=n)}return o}parseTicker(e,t){let i,s,r=this.safeString(e,"symbol"),a=this.safeSymbol(r,t,"/"),n=this.safeString(e,"bid"),d=this.safeString(e,"ask"),h=this.safeString(e,"last_price"),c=this.safeString(e,"high_24h"),l=this.safeString(e,"low_24h"),u=this.safeString(e,"price_change_24h"),f=this.safeString(e,"volume_24h"),p=this.safeInteger(e,"timestamp");if(void 0!==h&&void 0!==u&&(i=o.Y.stringSub(h,u)),void 0!==i&&void 0!==u){let e=o.Y.stringDiv(u,i,8);s=this.parseNumber(o.Y.stringMul(e,"100"))}return this.safeTicker({symbol:a,timestamp:p,datetime:this.iso8601(p),high:c,low:l,bid:n,bidVolume:void 0,ask:d,askVolume:void 0,vwap:void 0,open:i,close:h,last:h,previousClose:void 0,change:u,percentage:s,average:void 0,baseVolume:f,quoteVolume:void 0,info:e},t)}async fetchTickers(e,t={}){void 0===this.markets&&await this.loadMarkets();let i={};if(void 0!==e){let t=[];for(let i=0;i<e.length;i++){let s=e[i],r=this.market(s);t.push(r.id)}i.symbols=t.join(",")}let s=this.safeString2(t,"region","region",this.options.region);void 0!==s&&(i.region=s);let r=await this.publicGet10PublicTickers(this.extend(i,t)),a=this.safeList(r,"data",[]),o=this.safeDict(r,"metadata",{}),n=this.safeInteger(o,"timestamp"),d={};for(let e=0;e<a.length;e++){let t=this.safeDict(a,e,{});t.timestamp=n;let i=this.parseTicker(t),s=this.safeString(i,"symbol","");""!==s&&(d[s]=i)}if(void 0!==e){let t={};for(let i=0;i<e.length;i++){let s=e[i];s in d&&(t[s]=d[s])}return t}return d}async fetchTicker(e,t={}){void 0===this.markets&&await this.loadMarkets();let i=await this.fetchTickers([e],t),s=this.safeDict(i,e);if(void 0===s)throw new a.ExchangeError(this.id+" fetchTicker() could not find ticker for symbol "+e);return s}async fetchOrderBook(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s={symbol:this.market(e).id};void 0!==t&&(s.limit=t);let r=this.safeString2(i,"region","region",this.options.region);void 0!==r&&(s.region=r);let a=await this.publicGet20PublicOrderBookSymbol(this.extend(s,i)),o=this.safeDict(a,"data",{}),n=this.safeDict(a,"metadata",{}),d=this.safeInteger(n,"timestamp");return this.parseOrderBook(o,e,d,"bids","asks","price","quantity")}parseOHLCV(e,t){return[this.safeInteger(e,"start"),this.safeNumber(e,"open"),this.safeNumber(e,"high"),this.safeNumber(e,"low"),this.safeNumber(e,"close"),this.safeNumber(e,"volume")]}async fetchOHLCV(e,t="1m",i,s,r={}){void 0===this.markets&&await this.loadMarkets();let a=this.market(e),o={symbol:a.id,interval:this.safeInteger(this.timeframes,t,5)};void 0!==i&&(o.since=i);let n=this.safeInteger2(r,"until","until");void 0!==n?o.until=n:o.until=this.milliseconds();let d=this.safeString2(r,"region","region",this.options.region);void 0!==d&&(o.region=d);let h=await this.publicGet10PublicCandlesSymbol(this.extend(o,r)),c=this.safeList(h,"data",[]);return this.parseOHLCVs(c,a,t,i,s)}parseTrade(e,t){let i,s=this.safeString(e,"id"),r=this.safeString(e,"symbol"),a=this.safeSymbol(r,t,"/"),o=this.safeNumber(e,"price"),n=this.safeNumber(e,"quantity"),d=this.safeStringLower(e,"side"),h=this.safeInteger(e,"timestamp");return void 0!==o&&void 0!==n&&(i=o*n),{info:e,id:s,order:void 0,symbol:a,side:d,type:void 0,takerOrMaker:void 0,price:o,amount:n,cost:i,timestamp:h,datetime:this.iso8601(h),fee:void 0,fees:[]}}async fetchTrades(e,t,i,s={}){let r;void 0===this.markets&&await this.loadMarkets(),void 0!==e&&(r=this.market(e));let a={};void 0!==r&&(a.symbol=r.id),void 0!==t&&(a.start_date=t);let o=this.safeInteger2(s,"until","until");void 0!==o?a.end_date=o:void 0!==t&&(a.end_date=this.milliseconds()),void 0!==i&&(a.limit=Math.min(i,1900));let n=this.safeString(s,"cursor");void 0!==n&&(a.cursor=n);let d=await this.publicGet10PublicTradesAll(this.extend(a,s)),h=this.safeList(d,"data",[]),c=[];for(let e=0;e<h.length;e++){let t=this.safeDict(h,e,{});c.push(this.parseTrade(t,r))}return this.filterBySymbolSinceLimit(this.sortBy(c,"timestamp"),e,t,i)}async fetchBalance(e={}){void 0===this.markets&&await this.loadMarkets();let t=await this.privateGet10Balances(e),i=Array.isArray(t)?t:this.safeList(t,"data",[]),s={info:t};for(let e=0;e<i.length;e++){let t=this.safeDict(i,e,{}),r=this.safeString(t,"currency"),a=this.safeCurrencyCode(r);if(void 0===a)continue;let n=this.account();n.free=this.safeString(t,"available");let d=this.safeString(t,"reserved"),h=this.safeString(t,"staked"),c=d;void 0!==h&&(c=void 0===d?h:o.Y.stringAdd(d,h)),n.used=c,n.total=this.safeString(t,"total"),s[a]=n}return this.safeBalance(s)}parseOrderStatus(e){return this.safeString({pending_new:"open",new:"open",partially_filled:"open",filled:"closed",cancelled:"canceled",canceled:"canceled",rejected:"rejected",replaced:"open"},e,e)}parseOrder(e,t){let i,s,r,a,o=this.safeString2(e,"id","venue_order_id"),n=this.safeString(e,"client_order_id"),d=this.safeString(e,"symbol"),h=this.safeSymbol(d,t,"/"),c=this.safeStringLower(e,"side"),l=this.safeStringLower(e,"type"),u=this.safeString(e,"quantity"),f=this.safeString(e,"filled_quantity"),p=this.safeString(e,"leaves_quantity"),m=this.safeString(e,"price"),g=this.safeString(e,"average_fill_price"),v=this.safeString(e,"amount"),y=this.safeString(e,"filled_amount"),b=this.safeString(e,"total_fee"),w=this.safeString(e,"fee_currency"),k=this.parseOrderStatus(this.safeString(e,"status")),S=this.safeStringUpper(e,"time_in_force"),O=this.safeInteger(e,"created_date"),T=this.safeInteger(e,"updated_date");return void 0!==b&&(i={cost:this.parseNumber(b),currency:w}),void 0!==u?s=u:void 0!==v&&(s=v),void 0!==f?r=f:void 0!==y&&(r=y),void 0!==p&&(a=p),this.safeOrder({id:o,clientOrderId:n,symbol:h,side:c,type:l,price:this.parseNumber(m),average:this.parseNumber(g),amount:this.parseNumber(s),filled:this.parseNumber(r),remaining:this.parseNumber(a),status:k,timeInForce:S,timestamp:O,datetime:this.iso8601(O),lastUpdateTimestamp:T,fee:i,info:e},t)}async createOrder(e,t,i,s,r,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(e),d=this.safeString2(o,"clientOrderId","client_order_id",this.uuid()),h=this.safeString2(o,"cost","quote_size"),c=this.safeStringLower2(o,"timeInForce","time_in_force"),l=this.safeList(o,"executionInstructions",this.safeList(o,"execution_instructions")),u={};if("limit"===t){let t={};void 0!==h?t.quote_size=this.costToPrecision(e,h):t.base_size=this.amountToPrecision(e,s),t.price=this.priceToPrecision(e,r),void 0!==c&&(t.time_in_force=c),void 0!==l&&(t.execution_instructions=l),u.limit=t}else if("market"===t){if(void 0!==c)throw new a.InvalidOrder(this.id+" createOrder() timeInForce is only supported for limit orders");if(void 0!==l)throw new a.InvalidOrder(this.id+" createOrder() executionInstructions are only supported for limit orders");let t={};void 0!==h?t.quote_size=this.costToPrecision(e,h):t.base_size=this.amountToPrecision(e,s),u.market=t}else throw new a.InvalidOrder(this.id+" createOrder() does not support order type "+t);let f={client_order_id:d,symbol:n.id,side:i,order_configuration:u},p=await this.privatePost10Orders(this.extend(f,this.omit(o,["cost","quote_size","clientOrderId","client_order_id","timeInForce","time_in_force","executionInstructions","execution_instructions"]))),m=this.safeValue(p,"data",{}),g=Array.isArray(m)?this.safeDict(m,0,{}):this.safeDict(p,"data",{}),v=this.safeString(g,"venue_order_id"),y=this.safeString(g,"state");return this.parseOrder(this.extend(g,{id:v,symbol:n.id,status:y,side:i,type:t}),n)}async cancelOrder(e,t,i={}){void 0===this.markets&&await this.loadMarkets();let s=await this.privateDelete10OrdersVenueOrderId(this.extend({venue_order_id:e},i));return this.safeOrder({info:s,id:e,status:"canceled"})}async cancelAllOrders(e,t={}){return void 0===this.markets&&await this.loadMarkets(),await this.privateDelete10Orders(t),[]}async fetchOrder(e,t,i={}){let s;void 0===this.markets&&await this.loadMarkets();let r=await this.privateGet10OrdersVenueOrderId(this.extend({venue_order_id:e},i)),a=this.safeDict(r,"data",{});return void 0!==t&&(s=this.market(t)),this.parseOrder(a,s)}async fetchOpenOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={};void 0!==e&&(r.symbols=this.market(e).id),void 0!==i&&(r.limit=i);let a=this.safeString(s,"cursor");void 0!==a&&(r.cursor=a);let o=this.safeList2(s,"orderStates","order_states");void 0!==o&&(r.order_states=o.join(","));let n=this.safeList2(s,"orderTypes","order_types");void 0!==n&&(r.order_types=n.join(","));let d=this.safeString(s,"side");void 0!==d&&(r.side=d);let h=await this.privateGet10OrdersActive(this.extend(r,this.omit(s,["cursor","orderStates","order_states","orderTypes","order_types","side"]))),c=this.safeList(h,"data",[]),l=[];for(let e=0;e<c.length;e++){let t=this.safeDict(c,e,{});l.push(this.parseOrder(t))}return this.filterBySymbolSinceLimit(l,e,t,i)}async fetchOrders(e,t,i,s={}){void 0===this.markets&&await this.loadMarkets();let r={};void 0!==e&&(r.symbols=this.market(e).id);let a=this.safeInteger2(s,"until","until");if(void 0!==t?r.start_date=t:void 0!==a&&(r.start_date=a-2592e6),void 0!==a)r.end_date=a;else if(void 0!==t){let e=this.milliseconds(),i=t+2592e6;r.end_date=i<e?i:e}void 0!==i&&(r.limit=i);let o=this.safeString(s,"cursor");void 0!==o&&(r.cursor=o);let n=this.safeList2(s,"orderStates","order_states");void 0!==n&&(r.order_states=n.join(","));let d=this.safeList2(s,"orderTypes","order_types");void 0!==d&&(r.order_types=d.join(","));let h=await this.privateGet10OrdersHistorical(this.extend(r,this.omit(s,["until","cursor","orderStates","order_states","orderTypes","order_types"]))),c=this.safeList(h,"data",[]),l=[];for(let e=0;e<c.length;e++){let t=this.safeDict(c,e,{});l.push(this.parseOrder(t))}return this.filterBySymbolSinceLimit(l,e,t,i)}async fetchClosedOrders(e,t,i,s={}){let r=this.safeList2(s,"orderStates","order_states",["filled","cancelled","rejected","replaced"]),a=this.extend(this.omit(s,["orderStates","order_states"]),{order_states:r});return await this.fetchOrders(e,t,i,a)}parseMyTrade(e,t){let i,s=this.safeString(e,"tid"),r=this.safeString(e,"oid"),a=this.safeNumber(e,"p"),o=this.safeNumber(e,"q"),n=this.safeStringLower(e,"s"),d=this.safeInteger2(e,"tdt","pdt"),h=this.safeBool(e,"im",!1);return void 0!==a&&void 0!==o&&(i=a*o),{info:e,id:s,order:r,symbol:this.safeSymbol(void 0,t),side:n,type:void 0,takerOrMaker:h?"maker":"taker",price:a,amount:o,cost:i,timestamp:d,datetime:this.iso8601(d),fee:void 0,fees:[]}}async fetchMyTrades(e,t,i,s={}){if(void 0===this.markets&&await this.loadMarkets(),void 0===e)throw new a.ArgumentsRequired(this.id+" fetchMyTrades() requires a symbol parameter");let r=this.market(e),o={symbol:r.id},n=this.safeInteger2(s,"until","until");if(void 0!==t?o.start_date=t:void 0!==n&&(o.start_date=n-2592e6),void 0!==n)o.end_date=n;else if(void 0!==t){let e=this.milliseconds(),i=t+2592e6;o.end_date=i<e?i:e}void 0!==i&&(o.limit=i);let d=this.safeString(s,"cursor");void 0!==d&&(o.cursor=d);let h=await this.privateGet10TradesPrivateSymbol(this.extend(o,this.omit(s,["until"]))),c=this.safeList(h,"data",[]),l=[];for(let e=0;e<c.length;e++){let t=this.safeDict(c,e,{});l.push(this.parseMyTrade(t,r))}return l}async editOrder(e,t,i,s,r,a,o={}){void 0===this.markets&&await this.loadMarkets();let n=this.market(t),d=this.safeString2(o,"clientOrderId","client_order_id",this.uuid()),h=this.safeString2(o,"cost","quote_size"),c=this.safeStringLower2(o,"timeInForce","time_in_force"),l=this.safeList(o,"executionInstructions",this.safeList(o,"execution_instructions")),u={client_order_id:d,venue_order_id:e};void 0!==h?u.quote_size=this.costToPrecision(t,h):void 0!==r&&(u.base_size=this.amountToPrecision(t,r)),void 0!==a&&(u.price=this.priceToPrecision(t,a)),void 0!==c&&(u.time_in_force=c),void 0!==l&&(u.execution_instructions=l);let f=await this.privatePut10OrdersVenueOrderId(this.extend(u,this.omit(o,["clientOrderId","client_order_id","cost","quote_size","timeInForce","time_in_force","executionInstructions","execution_instructions"]))),p=this.safeValue(f,"data",{}),m=Array.isArray(p)?this.safeDict(p,0,{}):this.safeDict(f,"data",{}),g=this.safeString(m,"venue_order_id"),v=this.safeString(m,"state");return this.parseOrder(this.extend(m,{id:g,symbol:n.id,status:v,side:s,type:i}),n)}handleErrors(e,t,i,s,r,a,o,n,d){if(e>=400){let e;if(void 0===o)return;let t=this.id+" "+a;"object"==typeof o&&(e=this.safeString2(o,"message","error")),void 0!==e&&this.throwBroadlyMatchedException(this.exceptions.broad,e,t)}}}i.d(t,{A:()=>d})},7735(e,t,i){"use strict";var s=i(6946),r=i.n(s);function a(){return{denom:"",amount:""}}i.d(t,{},{KO:{encode:(e,t=r().Writer.create())=>(""!==e.denom&&t.uint32(10).string(e.denom),""!==e.amount&&t.uint32(18).string(e.amount),t),decode(e,t){let i=e instanceof r().Reader?e:new(r()).Reader(e),s=void 0===t?i.len:i.pos+t,o=a();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:o.denom=i.string();break;case 2:o.amount=i.string();break;default:i.skipType(7&e)}}return o},fromPartial(e){let t=a();return t.denom=e.denom??"",t.amount=e.amount??"",t}}})},7251(e,t,i){"use strict";var s=i(6946),r=i.n(s);function a(){return{extraBitsStored:0,elems:new Uint8Array}}i.d(t,{},{s:{encode:(e,t=r().Writer.create())=>(0!==e.extraBitsStored&&t.uint32(8).uint32(e.extraBitsStored),0!==e.elems.length&&t.uint32(18).bytes(e.elems),t),decode(e,t){let i=e instanceof r().Reader?e:new(r()).Reader(e),s=void 0===t?i.len:i.pos+t,o=a();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:o.extraBitsStored=i.uint32();break;case 2:o.elems=i.bytes();break;default:i.skipType(7&e)}}return o},fromPartial(e){let t=a();return t.extraBitsStored=e.extraBitsStored??0,t.elems=e.elems??new Uint8Array,t}}})},7076(e,t,i){"use strict";var s=i(6946),r=i.n(s);function a(){return{key:new Uint8Array}}i.d(t,{},{r:{encode:(e,t=r().Writer.create())=>(0!==e.key.length&&t.uint32(10).bytes(e.key),t),decode(e,t){let i=e instanceof r().Reader?e:new(r()).Reader(e),s=void 0===t?i.len:i.pos+t,o=a();for(;i.pos<s;){let e=i.uint32();e>>>3==1?o.key=i.bytes():i.skipType(7&e)}return o},fromPartial(e){let t=a();return t.key=e.key??new Uint8Array,t}}})},5422(e,t,i){"use strict";i.r(t);var s,r=i(7251),a=i(7440),o=i(6946),n=i.n(o),d=i(1291),h=i.n(d),c=((s={})[s.SIGN_MODE_UNSPECIFIED=0]="SIGN_MODE_UNSPECIFIED",s[s.SIGN_MODE_DIRECT=1]="SIGN_MODE_DIRECT",s[s.SIGN_MODE_TEXTUAL=2]="SIGN_MODE_TEXTUAL",s[s.SIGN_MODE_DIRECT_AUX=3]="SIGN_MODE_DIRECT_AUX",s[s.SIGN_MODE_LEGACY_AMINO_JSON=127]="SIGN_MODE_LEGACY_AMINO_JSON",s[s.SIGN_MODE_EIP_191=191]="SIGN_MODE_EIP_191",s[s.UNRECOGNIZED=-1]="UNRECOGNIZED",s);function l(e){switch(e){case 0:case"SIGN_MODE_UNSPECIFIED":return 0;case 1:case"SIGN_MODE_DIRECT":return 1;case 2:case"SIGN_MODE_TEXTUAL":return 2;case 3:case"SIGN_MODE_DIRECT_AUX":return 3;case 127:case"SIGN_MODE_LEGACY_AMINO_JSON":return 127;case 191:case"SIGN_MODE_EIP_191":return 191;default:return -1}}function u(e){switch(e){case 0:return"SIGN_MODE_UNSPECIFIED";case 1:return"SIGN_MODE_DIRECT";case 2:return"SIGN_MODE_TEXTUAL";case 3:return"SIGN_MODE_DIRECT_AUX";case 127:return"SIGN_MODE_LEGACY_AMINO_JSON";case 191:return"SIGN_MODE_EIP_191";default:return"UNRECOGNIZED"}}function f(){return{signatures:[]}}function p(){return{publicKey:void 0,data:void 0,sequence:h().UZERO}}let m={encode:(e,t=n().Writer.create())=>(void 0!==e.publicKey&&a.F.encode(e.publicKey,t.uint32(10).fork()).ldelim(),void 0!==e.data&&v.encode(e.data,t.uint32(18).fork()).ldelim(),e.sequence.isZero()||t.uint32(24).uint64(e.sequence),t),decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,r=p();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.publicKey=a.F.decode(i,i.uint32());break;case 2:r.data=v.decode(i,i.uint32());break;case 3:r.sequence=i.uint64();break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=p();return t.publicKey=void 0!==e.publicKey&&null!==e.publicKey?a.F.fromPartial(e.publicKey):void 0,t.data=void 0!==e.data&&null!==e.data?v.fromPartial(e.data):void 0,t.sequence=void 0!==e.sequence&&null!==e.sequence?h().fromValue(e.sequence):h().UZERO,t}};function g(){return{single:void 0,multi:void 0}}let v={encode:(e,t=n().Writer.create())=>(void 0!==e.single&&b.encode(e.single,t.uint32(10).fork()).ldelim(),void 0!==e.multi&&k.encode(e.multi,t.uint32(18).fork()).ldelim(),t),decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,r=g();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.single=b.decode(i,i.uint32());break;case 2:r.multi=k.decode(i,i.uint32());break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=g();return t.single=void 0!==e.single&&null!==e.single?b.fromPartial(e.single):void 0,t.multi=void 0!==e.multi&&null!==e.multi?k.fromPartial(e.multi):void 0,t}};function y(){return{mode:0,signature:new Uint8Array}}let b={encode:(e,t=n().Writer.create())=>(0!==e.mode&&t.uint32(8).int32(e.mode),0!==e.signature.length&&t.uint32(18).bytes(e.signature),t),decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,r=y();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.mode=i.int32();break;case 2:r.signature=i.bytes();break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=y();return t.mode=e.mode??0,t.signature=e.signature??new Uint8Array,t}};function w(){return{bitarray:void 0,signatures:[]}}let k={encode(e,t=n().Writer.create()){for(let i of(void 0!==e.bitarray&&r.s.encode(e.bitarray,t.uint32(10).fork()).ldelim(),e.signatures))v.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,a=w();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:a.bitarray=r.s.decode(i,i.uint32());break;case 2:a.signatures.push(v.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return a},fromPartial(e){let t=w();return t.bitarray=void 0!==e.bitarray&&null!==e.bitarray?r.s.fromPartial(e.bitarray):void 0,t.signatures=e.signatures?.map(e=>v.fromPartial(e))||[],t}};i.d(t,{SignMode:()=>c,signModeFromJSON:()=>l,signModeToJSON:()=>u},{SignModeSDKType:c,SignatureDescriptor:m,SignatureDescriptor_Data:v,SignatureDescriptor_Data_Multi:k,SignatureDescriptor_Data_Single:b,SignatureDescriptors:{encode(e,t=n().Writer.create()){for(let i of e.signatures)m.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,r=f();for(;i.pos<s;){let e=i.uint32();e>>>3==1?r.signatures.push(m.decode(i,i.uint32())):i.skipType(7&e)}return r},fromPartial(e){let t=f();return t.signatures=e.signatures?.map(e=>m.fromPartial(e))||[],t}}})},5145(e,t,i){"use strict";i.r(t);var s=i(7440),r=i(7251),a=i(7735),o=i(6946),n=i.n(o),d=i(1291),h=i.n(d);function c(){return{body:void 0,authInfo:void 0,signatures:[]}}function l(){return{bodyBytes:new Uint8Array,authInfoBytes:new Uint8Array,signatures:[]}}function u(){return{bodyBytes:new Uint8Array,authInfoBytes:new Uint8Array,chainId:"",accountNumber:h().UZERO}}function f(){return{bodyBytes:new Uint8Array,publicKey:void 0,chainId:"",accountNumber:h().UZERO,sequence:h().UZERO,tip:void 0}}let p={encode:(e,t=n().Writer.create())=>(0!==e.bodyBytes.length&&t.uint32(10).bytes(e.bodyBytes),void 0!==e.publicKey&&s.F.encode(e.publicKey,t.uint32(18).fork()).ldelim(),""!==e.chainId&&t.uint32(26).string(e.chainId),e.accountNumber.isZero()||t.uint32(32).uint64(e.accountNumber),e.sequence.isZero()||t.uint32(40).uint64(e.sequence),void 0!==e.tip&&M.encode(e.tip,t.uint32(50).fork()).ldelim(),t),decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),r=void 0===t?i.len:i.pos+t,a=f();for(;i.pos<r;){let e=i.uint32();switch(e>>>3){case 1:a.bodyBytes=i.bytes();break;case 2:a.publicKey=s.F.decode(i,i.uint32());break;case 3:a.chainId=i.string();break;case 4:a.accountNumber=i.uint64();break;case 5:a.sequence=i.uint64();break;case 6:a.tip=M.decode(i,i.uint32());break;default:i.skipType(7&e)}}return a},fromPartial(e){let t=f();return t.bodyBytes=e.bodyBytes??new Uint8Array,t.publicKey=void 0!==e.publicKey&&null!==e.publicKey?s.F.fromPartial(e.publicKey):void 0,t.chainId=e.chainId??"",t.accountNumber=void 0!==e.accountNumber&&null!==e.accountNumber?h().fromValue(e.accountNumber):h().UZERO,t.sequence=void 0!==e.sequence&&null!==e.sequence?h().fromValue(e.sequence):h().UZERO,t.tip=void 0!==e.tip&&null!==e.tip?M.fromPartial(e.tip):void 0,t}};function m(){return{messages:[],memo:"",timeoutHeight:h().UZERO,extensionOptions:[],nonCriticalExtensionOptions:[]}}let g={encode(e,t=n().Writer.create()){for(let i of e.messages)s.F.encode(i,t.uint32(10).fork()).ldelim();for(let i of(""!==e.memo&&t.uint32(18).string(e.memo),e.timeoutHeight.isZero()||t.uint32(24).uint64(e.timeoutHeight),e.extensionOptions))s.F.encode(i,t.uint32(8186).fork()).ldelim();for(let i of e.nonCriticalExtensionOptions)s.F.encode(i,t.uint32(16378).fork()).ldelim();return t},decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),r=void 0===t?i.len:i.pos+t,a=m();for(;i.pos<r;){let e=i.uint32();switch(e>>>3){case 1:a.messages.push(s.F.decode(i,i.uint32()));break;case 2:a.memo=i.string();break;case 3:a.timeoutHeight=i.uint64();break;case 1023:a.extensionOptions.push(s.F.decode(i,i.uint32()));break;case 2047:a.nonCriticalExtensionOptions.push(s.F.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return a},fromPartial(e){let t=m();return t.messages=e.messages?.map(e=>s.F.fromPartial(e))||[],t.memo=e.memo??"",t.timeoutHeight=void 0!==e.timeoutHeight&&null!==e.timeoutHeight?h().fromValue(e.timeoutHeight):h().UZERO,t.extensionOptions=e.extensionOptions?.map(e=>s.F.fromPartial(e))||[],t.nonCriticalExtensionOptions=e.nonCriticalExtensionOptions?.map(e=>s.F.fromPartial(e))||[],t}};function v(){return{signerInfos:[],fee:void 0,tip:void 0}}let y={encode(e,t=n().Writer.create()){for(let i of e.signerInfos)w.encode(i,t.uint32(10).fork()).ldelim();return void 0!==e.fee&&A.encode(e.fee,t.uint32(18).fork()).ldelim(),void 0!==e.tip&&M.encode(e.tip,t.uint32(26).fork()).ldelim(),t},decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,r=v();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.signerInfos.push(w.decode(i,i.uint32()));break;case 2:r.fee=A.decode(i,i.uint32());break;case 3:r.tip=M.decode(i,i.uint32());break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=v();return t.signerInfos=e.signerInfos?.map(e=>w.fromPartial(e))||[],t.fee=void 0!==e.fee&&null!==e.fee?A.fromPartial(e.fee):void 0,t.tip=void 0!==e.tip&&null!==e.tip?M.fromPartial(e.tip):void 0,t}};function b(){return{publicKey:void 0,modeInfo:void 0,sequence:h().UZERO}}let w={encode:(e,t=n().Writer.create())=>(void 0!==e.publicKey&&s.F.encode(e.publicKey,t.uint32(10).fork()).ldelim(),void 0!==e.modeInfo&&S.encode(e.modeInfo,t.uint32(18).fork()).ldelim(),e.sequence.isZero()||t.uint32(24).uint64(e.sequence),t),decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),r=void 0===t?i.len:i.pos+t,a=b();for(;i.pos<r;){let e=i.uint32();switch(e>>>3){case 1:a.publicKey=s.F.decode(i,i.uint32());break;case 2:a.modeInfo=S.decode(i,i.uint32());break;case 3:a.sequence=i.uint64();break;default:i.skipType(7&e)}}return a},fromPartial(e){let t=b();return t.publicKey=void 0!==e.publicKey&&null!==e.publicKey?s.F.fromPartial(e.publicKey):void 0,t.modeInfo=void 0!==e.modeInfo&&null!==e.modeInfo?S.fromPartial(e.modeInfo):void 0,t.sequence=void 0!==e.sequence&&null!==e.sequence?h().fromValue(e.sequence):h().UZERO,t}};function k(){return{single:void 0,multi:void 0}}let S={encode:(e,t=n().Writer.create())=>(void 0!==e.single&&O.encode(e.single,t.uint32(10).fork()).ldelim(),void 0!==e.multi&&P.encode(e.multi,t.uint32(18).fork()).ldelim(),t),decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,r=k();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.single=O.decode(i,i.uint32());break;case 2:r.multi=P.decode(i,i.uint32());break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=k();return t.single=void 0!==e.single&&null!==e.single?O.fromPartial(e.single):void 0,t.multi=void 0!==e.multi&&null!==e.multi?P.fromPartial(e.multi):void 0,t}},O={encode:(e,t=n().Writer.create())=>(0!==e.mode&&t.uint32(8).int32(e.mode),t),decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,r={mode:0};for(;i.pos<s;){let e=i.uint32();e>>>3==1?r.mode=i.int32():i.skipType(7&e)}return r},fromPartial(e){let t={mode:0};return t.mode=e.mode??0,t}};function T(){return{bitarray:void 0,modeInfos:[]}}let P={encode(e,t=n().Writer.create()){for(let i of(void 0!==e.bitarray&&r.s.encode(e.bitarray,t.uint32(10).fork()).ldelim(),e.modeInfos))S.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,a=T();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:a.bitarray=r.s.decode(i,i.uint32());break;case 2:a.modeInfos.push(S.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return a},fromPartial(e){let t=T();return t.bitarray=void 0!==e.bitarray&&null!==e.bitarray?r.s.fromPartial(e.bitarray):void 0,t.modeInfos=e.modeInfos?.map(e=>S.fromPartial(e))||[],t}};function I(){return{amount:[],gasLimit:h().UZERO,payer:"",granter:""}}let A={encode(e,t=n().Writer.create()){for(let i of e.amount)a.KO.encode(i,t.uint32(10).fork()).ldelim();return e.gasLimit.isZero()||t.uint32(16).uint64(e.gasLimit),""!==e.payer&&t.uint32(26).string(e.payer),""!==e.granter&&t.uint32(34).string(e.granter),t},decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,r=I();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.amount.push(a.KO.decode(i,i.uint32()));break;case 2:r.gasLimit=i.uint64();break;case 3:r.payer=i.string();break;case 4:r.granter=i.string();break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=I();return t.amount=e.amount?.map(e=>a.KO.fromPartial(e))||[],t.gasLimit=void 0!==e.gasLimit&&null!==e.gasLimit?h().fromValue(e.gasLimit):h().UZERO,t.payer=e.payer??"",t.granter=e.granter??"",t}};function x(){return{amount:[],tipper:""}}let M={encode(e,t=n().Writer.create()){for(let i of e.amount)a.KO.encode(i,t.uint32(10).fork()).ldelim();return""!==e.tipper&&t.uint32(18).string(e.tipper),t},decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,r=x();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.amount.push(a.KO.decode(i,i.uint32()));break;case 2:r.tipper=i.string();break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=x();return t.amount=e.amount?.map(e=>a.KO.fromPartial(e))||[],t.tipper=e.tipper??"",t}};function _(){return{address:"",signDoc:void 0,mode:0,sig:new Uint8Array}}i.d(t,{},{AuthInfo:y,AuxSignerData:{encode:(e,t=n().Writer.create())=>(""!==e.address&&t.uint32(10).string(e.address),void 0!==e.signDoc&&p.encode(e.signDoc,t.uint32(18).fork()).ldelim(),0!==e.mode&&t.uint32(24).int32(e.mode),0!==e.sig.length&&t.uint32(34).bytes(e.sig),t),decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,r=_();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.address=i.string();break;case 2:r.signDoc=p.decode(i,i.uint32());break;case 3:r.mode=i.int32();break;case 4:r.sig=i.bytes();break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=_();return t.address=e.address??"",t.signDoc=void 0!==e.signDoc&&null!==e.signDoc?p.fromPartial(e.signDoc):void 0,t.mode=e.mode??0,t.sig=e.sig??new Uint8Array,t}},Fee:A,ModeInfo:S,ModeInfo_Multi:P,ModeInfo_Single:O,SignDoc:{encode:(e,t=n().Writer.create())=>(0!==e.bodyBytes.length&&t.uint32(10).bytes(e.bodyBytes),0!==e.authInfoBytes.length&&t.uint32(18).bytes(e.authInfoBytes),""!==e.chainId&&t.uint32(26).string(e.chainId),e.accountNumber.isZero()||t.uint32(32).uint64(e.accountNumber),t),decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,r=u();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.bodyBytes=i.bytes();break;case 2:r.authInfoBytes=i.bytes();break;case 3:r.chainId=i.string();break;case 4:r.accountNumber=i.uint64();break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=u();return t.bodyBytes=e.bodyBytes??new Uint8Array,t.authInfoBytes=e.authInfoBytes??new Uint8Array,t.chainId=e.chainId??"",t.accountNumber=void 0!==e.accountNumber&&null!==e.accountNumber?h().fromValue(e.accountNumber):h().UZERO,t}},SignDocDirectAux:p,SignerInfo:w,Tip:M,Tx:{encode(e,t=n().Writer.create()){for(let i of(void 0!==e.body&&g.encode(e.body,t.uint32(10).fork()).ldelim(),void 0!==e.authInfo&&y.encode(e.authInfo,t.uint32(18).fork()).ldelim(),e.signatures))t.uint32(26).bytes(i);return t},decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,r=c();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.body=g.decode(i,i.uint32());break;case 2:r.authInfo=y.decode(i,i.uint32());break;case 3:r.signatures.push(i.bytes());break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=c();return t.body=void 0!==e.body&&null!==e.body?g.fromPartial(e.body):void 0,t.authInfo=void 0!==e.authInfo&&null!==e.authInfo?y.fromPartial(e.authInfo):void 0,t.signatures=e.signatures?.map(e=>e)||[],t}},TxBody:g,TxRaw:{encode(e,t=n().Writer.create()){for(let i of(0!==e.bodyBytes.length&&t.uint32(10).bytes(e.bodyBytes),0!==e.authInfoBytes.length&&t.uint32(18).bytes(e.authInfoBytes),e.signatures))t.uint32(26).bytes(i);return t},decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),s=void 0===t?i.len:i.pos+t,r=l();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.bodyBytes=i.bytes();break;case 2:r.authInfoBytes=i.bytes();break;case 3:r.signatures.push(i.bytes());break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=l();return t.bodyBytes=e.bodyBytes??new Uint8Array,t.authInfoBytes=e.authInfoBytes??new Uint8Array,t.signatures=e.signatures?.map(e=>e)||[],t}}})},7378(e,t,i){"use strict";var s=i(6946),r=i.n(s),a=i(1291),o=i.n(a);function n(){return{selectedAuthenticators:[]}}i.d(t,{},{KX:{encode(e,t=r().Writer.create()){for(let i of(t.uint32(10).fork(),e.selectedAuthenticators))t.uint64(i);return t.ldelim(),t},decode(e,t){let i=e instanceof r().Reader?e:new(r()).Reader(e),s=void 0===t?i.len:i.pos+t,a=n();for(;i.pos<s;){let e=i.uint32();if(e>>>3==1)if((7&e)==2){let e=i.uint32()+i.pos;for(;i.pos<e;)a.selectedAuthenticators.push(i.uint64())}else a.selectedAuthenticators.push(i.uint64());else i.skipType(7&e)}return a},fromPartial(e){let t=n();return t.selectedAuthenticators=e.selectedAuthenticators?.map(e=>o().fromValue(e))||[],t}}})},7072(e,t,i){"use strict";var s=i(4784),r=i(6946),a=i.n(r),o=i(1291),n=i.n(o);function d(){return{subaccountId:void 0,clientId:0,orderFlags:0,clobPairId:0}}let h={encode:(e,t=a().Writer.create())=>(void 0!==e.subaccountId&&s.D.encode(e.subaccountId,t.uint32(10).fork()).ldelim(),0!==e.clientId&&t.uint32(21).fixed32(e.clientId),0!==e.orderFlags&&t.uint32(24).uint32(e.orderFlags),0!==e.clobPairId&&t.uint32(32).uint32(e.clobPairId),t),decode(e,t){let i=e instanceof a().Reader?e:new(a()).Reader(e),r=void 0===t?i.len:i.pos+t,o=d();for(;i.pos<r;){let e=i.uint32();switch(e>>>3){case 1:o.subaccountId=s.D.decode(i,i.uint32());break;case 2:o.clientId=i.fixed32();break;case 3:o.orderFlags=i.uint32();break;case 4:o.clobPairId=i.uint32();break;default:i.skipType(7&e)}}return o},fromPartial(e){let t=d();return t.subaccountId=void 0!==e.subaccountId&&null!==e.subaccountId?s.D.fromPartial(e.subaccountId):void 0,t.clientId=e.clientId??0,t.orderFlags=e.orderFlags??0,t.clobPairId=e.clobPairId??0,t}};function c(){return{orderId:void 0,side:0,quantums:n().UZERO,subticks:n().UZERO,goodTilBlock:void 0,goodTilBlockTime:void 0,timeInForce:0,reduceOnly:!1,clientMetadata:0,conditionType:0,conditionalOrderTriggerSubticks:n().UZERO,twapParameters:void 0,builderCodeParameters:void 0,orderRouterAddress:""}}function l(){return{duration:0,interval:0,priceTolerance:0}}let u={encode:(e,t=a().Writer.create())=>(0!==e.duration&&t.uint32(8).uint32(e.duration),0!==e.interval&&t.uint32(16).uint32(e.interval),0!==e.priceTolerance&&t.uint32(24).uint32(e.priceTolerance),t),decode(e,t){let i=e instanceof a().Reader?e:new(a()).Reader(e),s=void 0===t?i.len:i.pos+t,r=l();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.duration=i.uint32();break;case 2:r.interval=i.uint32();break;case 3:r.priceTolerance=i.uint32();break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=l();return t.duration=e.duration??0,t.interval=e.interval??0,t.priceTolerance=e.priceTolerance??0,t}};function f(){return{builderAddress:"",feePpm:0}}let p={encode:(e,t=a().Writer.create())=>(""!==e.builderAddress&&t.uint32(10).string(e.builderAddress),0!==e.feePpm&&t.uint32(16).uint32(e.feePpm),t),decode(e,t){let i=e instanceof a().Reader?e:new(a()).Reader(e),s=void 0===t?i.len:i.pos+t,r=f();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.builderAddress=i.string();break;case 2:r.feePpm=i.uint32();break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=f();return t.builderAddress=e.builderAddress??"",t.feePpm=e.feePpm??0,t}};i.d(t,{},{e3:h,pH:{encode:(e,t=a().Writer.create())=>(void 0!==e.orderId&&h.encode(e.orderId,t.uint32(10).fork()).ldelim(),0!==e.side&&t.uint32(16).int32(e.side),e.quantums.isZero()||t.uint32(24).uint64(e.quantums),e.subticks.isZero()||t.uint32(32).uint64(e.subticks),void 0!==e.goodTilBlock&&t.uint32(40).uint32(e.goodTilBlock),void 0!==e.goodTilBlockTime&&t.uint32(53).fixed32(e.goodTilBlockTime),0!==e.timeInForce&&t.uint32(56).int32(e.timeInForce),!0===e.reduceOnly&&t.uint32(64).bool(e.reduceOnly),0!==e.clientMetadata&&t.uint32(72).uint32(e.clientMetadata),0!==e.conditionType&&t.uint32(80).int32(e.conditionType),e.conditionalOrderTriggerSubticks.isZero()||t.uint32(88).uint64(e.conditionalOrderTriggerSubticks),void 0!==e.twapParameters&&u.encode(e.twapParameters,t.uint32(98).fork()).ldelim(),void 0!==e.builderCodeParameters&&p.encode(e.builderCodeParameters,t.uint32(106).fork()).ldelim(),""!==e.orderRouterAddress&&t.uint32(114).string(e.orderRouterAddress),t),decode(e,t){let i=e instanceof a().Reader?e:new(a()).Reader(e),s=void 0===t?i.len:i.pos+t,r=c();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.orderId=h.decode(i,i.uint32());break;case 2:r.side=i.int32();break;case 3:r.quantums=i.uint64();break;case 4:r.subticks=i.uint64();break;case 5:r.goodTilBlock=i.uint32();break;case 6:r.goodTilBlockTime=i.fixed32();break;case 7:r.timeInForce=i.int32();break;case 8:r.reduceOnly=i.bool();break;case 9:r.clientMetadata=i.uint32();break;case 10:r.conditionType=i.int32();break;case 11:r.conditionalOrderTriggerSubticks=i.uint64();break;case 12:r.twapParameters=u.decode(i,i.uint32());break;case 13:r.builderCodeParameters=p.decode(i,i.uint32());break;case 14:r.orderRouterAddress=i.string();break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=c();return t.orderId=void 0!==e.orderId&&null!==e.orderId?h.fromPartial(e.orderId):void 0,t.side=e.side??0,t.quantums=void 0!==e.quantums&&null!==e.quantums?n().fromValue(e.quantums):n().UZERO,t.subticks=void 0!==e.subticks&&null!==e.subticks?n().fromValue(e.subticks):n().UZERO,t.goodTilBlock=e.goodTilBlock??void 0,t.goodTilBlockTime=e.goodTilBlockTime??void 0,t.timeInForce=e.timeInForce??0,t.reduceOnly=e.reduceOnly??!1,t.clientMetadata=e.clientMetadata??0,t.conditionType=e.conditionType??0,t.conditionalOrderTriggerSubticks=void 0!==e.conditionalOrderTriggerSubticks&&null!==e.conditionalOrderTriggerSubticks?n().fromValue(e.conditionalOrderTriggerSubticks):n().UZERO,t.twapParameters=void 0!==e.twapParameters&&null!==e.twapParameters?u.fromPartial(e.twapParameters):void 0,t.builderCodeParameters=void 0!==e.builderCodeParameters&&null!==e.builderCodeParameters?p.fromPartial(e.builderCodeParameters):void 0,t.orderRouterAddress=e.orderRouterAddress??"",t}}})},5399(e,t,i){"use strict";var s=i(7072),r=i(4784),a=i(6946),o=i.n(a);function n(){return{order:void 0}}function d(){return{orderId:void 0,goodTilBlock:void 0,goodTilBlockTime:void 0}}function h(){return{subaccountId:void 0,shortTermCancels:[],goodTilBlock:0}}function c(){return{clobPairId:0,clientIds:[]}}let l={encode(e,t=o().Writer.create()){for(let i of(0!==e.clobPairId&&t.uint32(8).uint32(e.clobPairId),t.uint32(18).fork(),e.clientIds))t.uint32(i);return t.ldelim(),t},decode(e,t){let i=e instanceof o().Reader?e:new(o()).Reader(e),s=void 0===t?i.len:i.pos+t,r=c();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:r.clobPairId=i.uint32();break;case 2:if((7&e)==2){let e=i.uint32()+i.pos;for(;i.pos<e;)r.clientIds.push(i.uint32())}else r.clientIds.push(i.uint32());break;default:i.skipType(7&e)}}return r},fromPartial(e){let t=c();return t.clobPairId=e.clobPairId??0,t.clientIds=e.clientIds?.map(e=>e)||[],t}};i.d(t,{},{F9:{encode:(e,t=o().Writer.create())=>(void 0!==e.order&&s.pH.encode(e.order,t.uint32(10).fork()).ldelim(),t),decode(e,t){let i=e instanceof o().Reader?e:new(o()).Reader(e),r=void 0===t?i.len:i.pos+t,a=n();for(;i.pos<r;){let e=i.uint32();e>>>3==1?a.order=s.pH.decode(i,i.uint32()):i.skipType(7&e)}return a},fromPartial(e){let t=n();return t.order=void 0!==e.order&&null!==e.order?s.pH.fromPartial(e.order):void 0,t}},sb:{encode:(e,t=o().Writer.create())=>(void 0!==e.orderId&&s.e3.encode(e.orderId,t.uint32(10).fork()).ldelim(),void 0!==e.goodTilBlock&&t.uint32(16).uint32(e.goodTilBlock),void 0!==e.goodTilBlockTime&&t.uint32(29).fixed32(e.goodTilBlockTime),t),decode(e,t){let i=e instanceof o().Reader?e:new(o()).Reader(e),r=void 0===t?i.len:i.pos+t,a=d();for(;i.pos<r;){let e=i.uint32();switch(e>>>3){case 1:a.orderId=s.e3.decode(i,i.uint32());break;case 2:a.goodTilBlock=i.uint32();break;case 3:a.goodTilBlockTime=i.fixed32();break;default:i.skipType(7&e)}}return a},fromPartial(e){let t=d();return t.orderId=void 0!==e.orderId&&null!==e.orderId?s.e3.fromPartial(e.orderId):void 0,t.goodTilBlock=e.goodTilBlock??void 0,t.goodTilBlockTime=e.goodTilBlockTime??void 0,t}},um:{encode(e,t=o().Writer.create()){for(let i of(void 0!==e.subaccountId&&r.D.encode(e.subaccountId,t.uint32(10).fork()).ldelim(),e.shortTermCancels))l.encode(i,t.uint32(18).fork()).ldelim();return 0!==e.goodTilBlock&&t.uint32(24).uint32(e.goodTilBlock),t},decode(e,t){let i=e instanceof o().Reader?e:new(o()).Reader(e),s=void 0===t?i.len:i.pos+t,a=h();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:a.subaccountId=r.D.decode(i,i.uint32());break;case 2:a.shortTermCancels.push(l.decode(i,i.uint32()));break;case 3:a.goodTilBlock=i.uint32();break;default:i.skipType(7&e)}}return a},fromPartial(e){let t=h();return t.subaccountId=void 0!==e.subaccountId&&null!==e.subaccountId?r.D.fromPartial(e.subaccountId):void 0,t.shortTermCancels=e.shortTermCancels?.map(e=>l.fromPartial(e))||[],t.goodTilBlock=e.goodTilBlock??0,t}}})},9670(e,t,i){"use strict";var s=i(4784),r=i(1291),a=i.n(r),o=i(6946),n=i.n(o);function d(){return{sender:void 0,recipient:void 0,assetId:0,amount:a().UZERO}}function h(){return{sender:"",recipient:void 0,assetId:0,quantums:a().UZERO}}function c(){return{sender:void 0,recipient:"",assetId:0,quantums:a().UZERO}}i.d(t,{},{bT:{encode:(e,t=n().Writer.create())=>(void 0!==e.sender&&s.D.encode(e.sender,t.uint32(18).fork()).ldelim(),""!==e.recipient&&t.uint32(10).string(e.recipient),0!==e.assetId&&t.uint32(24).uint32(e.assetId),e.quantums.isZero()||t.uint32(32).uint64(e.quantums),t),decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),r=void 0===t?i.len:i.pos+t,a=c();for(;i.pos<r;){let e=i.uint32();switch(e>>>3){case 2:a.sender=s.D.decode(i,i.uint32());break;case 1:a.recipient=i.string();break;case 3:a.assetId=i.uint32();break;case 4:a.quantums=i.uint64();break;default:i.skipType(7&e)}}return a},fromPartial(e){let t=c();return t.sender=void 0!==e.sender&&null!==e.sender?s.D.fromPartial(e.sender):void 0,t.recipient=e.recipient??"",t.assetId=e.assetId??0,t.quantums=void 0!==e.quantums&&null!==e.quantums?a().fromValue(e.quantums):a().UZERO,t}},mr:{encode:(e,t=n().Writer.create())=>(void 0!==e.sender&&s.D.encode(e.sender,t.uint32(10).fork()).ldelim(),void 0!==e.recipient&&s.D.encode(e.recipient,t.uint32(18).fork()).ldelim(),0!==e.assetId&&t.uint32(24).uint32(e.assetId),e.amount.isZero()||t.uint32(32).uint64(e.amount),t),decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),r=void 0===t?i.len:i.pos+t,a=d();for(;i.pos<r;){let e=i.uint32();switch(e>>>3){case 1:a.sender=s.D.decode(i,i.uint32());break;case 2:a.recipient=s.D.decode(i,i.uint32());break;case 3:a.assetId=i.uint32();break;case 4:a.amount=i.uint64();break;default:i.skipType(7&e)}}return a},fromPartial(e){let t=d();return t.sender=void 0!==e.sender&&null!==e.sender?s.D.fromPartial(e.sender):void 0,t.recipient=void 0!==e.recipient&&null!==e.recipient?s.D.fromPartial(e.recipient):void 0,t.assetId=e.assetId??0,t.amount=void 0!==e.amount&&null!==e.amount?a().fromValue(e.amount):a().UZERO,t}},wD:{encode:(e,t=n().Writer.create())=>(""!==e.sender&&t.uint32(10).string(e.sender),void 0!==e.recipient&&s.D.encode(e.recipient,t.uint32(18).fork()).ldelim(),0!==e.assetId&&t.uint32(24).uint32(e.assetId),e.quantums.isZero()||t.uint32(32).uint64(e.quantums),t),decode(e,t){let i=e instanceof n().Reader?e:new(n()).Reader(e),r=void 0===t?i.len:i.pos+t,a=h();for(;i.pos<r;){let e=i.uint32();switch(e>>>3){case 1:a.sender=i.string();break;case 2:a.recipient=s.D.decode(i,i.uint32());break;case 3:a.assetId=i.uint32();break;case 4:a.quantums=i.uint64();break;default:i.skipType(7&e)}}return a},fromPartial(e){let t=h();return t.sender=e.sender??"",t.recipient=void 0!==e.recipient&&null!==e.recipient?s.D.fromPartial(e.recipient):void 0,t.assetId=e.assetId??0,t.quantums=void 0!==e.quantums&&null!==e.quantums?a().fromValue(e.quantums):a().UZERO,t}}})},5489(e,t,i){"use strict";var s=i(9670),r=i(6946),a=i.n(r);function o(){return{transfer:void 0}}i.d(t,{},{bX:{encode:(e,t=a().Writer.create())=>(void 0!==e.transfer&&s.mr.encode(e.transfer,t.uint32(10).fork()).ldelim(),t),decode(e,t){let i=e instanceof a().Reader?e:new(a()).Reader(e),r=void 0===t?i.len:i.pos+t,n=o();for(;i.pos<r;){let e=i.uint32();e>>>3==1?n.transfer=s.mr.decode(i,i.uint32()):i.skipType(7&e)}return n},fromPartial(e){let t=o();return t.transfer=void 0!==e.transfer&&null!==e.transfer?s.mr.fromPartial(e.transfer):void 0,t}}})},4784(e,t,i){"use strict";var s=i(6946),r=i.n(s);function a(){return{owner:"",number:0}}i.d(t,{},{D:{encode:(e,t=r().Writer.create())=>(""!==e.owner&&t.uint32(10).string(e.owner),0!==e.number&&t.uint32(16).uint32(e.number),t),decode(e,t){let i=e instanceof r().Reader?e:new(r()).Reader(e),s=void 0===t?i.len:i.pos+t,o=a();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:o.owner=i.string();break;case 2:o.number=i.uint32();break;default:i.skipType(7&e)}}return o},fromPartial(e){let t=a();return t.owner=e.owner??"",t.number=e.number??0,t}}})},7440(e,t,i){"use strict";var s=i(6946),r=i.n(s);function a(){return{typeUrl:"",value:new Uint8Array}}i.d(t,{},{F:{encode:(e,t=r().Writer.create())=>(""!==e.typeUrl&&t.uint32(10).string(e.typeUrl),0!==e.value.length&&t.uint32(18).bytes(e.value),t),decode(e,t){let i=e instanceof r().Reader?e:new(r()).Reader(e),s=void 0===t?i.len:i.pos+t,o=a();for(;i.pos<s;){let e=i.uint32();switch(e>>>3){case 1:o.typeUrl=i.string();break;case 2:o.value=i.bytes();break;default:i.skipType(7&e)}}return o},fromPartial(e){let t=a();return t.typeUrl=e.typeUrl??"",t.value=e.value??new Uint8Array,t}}})},9475(e,t,i){"use strict";i.r(t);var s=i(7076),r=i(7378),a=i(5399),o=i(9670),n=i(5489),d=i(7440);let h={"/dydxprotocol.clob.MsgPlaceOrder":a.F9,"/dydxprotocol.clob.MsgCancelOrder":a.sb,"/dydxprotocol.clob.MsgBatchCancel":a.um,"/dydxprotocol.sending.MsgCreateTransfer":n.bX,"/dydxprotocol.sending.MsgWithdrawFromSubaccount":o.bT,"/dydxprotocol.sending.MsgDepositToSubaccount":o.wD,"/dydxprotocol.accountplus.TxExtension":r.KX,"/cosmos.crypto.secp256k1.PubKey":s.r};function c(e){let{typeUrl:t,value:i}=e,s=h[t];if(!s)throw Error(`Unsupport type url: ${t}`);let r=s.encode(s.fromPartial(i)).finish();return d.F.fromPartial({typeUrl:t,value:r})}i.d(t,{encodeAsAny:()=>c},{registry:h})},9660(e,t,i){"use strict";var s=i(4721),r=i(273),a=i(1453),o=i(7749);class n extends r.A{describe(){return this.deepExtend(super.describe(),{id:"tokocrypto",name:"Tokocrypto",countries:["ID"],certified:!1,pro:!1,version:"v1",has:{CORS:void 0,spot:!0,margin:!0,swap:!1,future:!1,option:!1,addMargin:void 0,borrowMargin:void 0,cancelAllOrders:!1,cancelOrder:!0,cancelOrders:void 0,closeAllPositions:!1,closePosition:!1,createDepositAddress:!1,createMarketBuyOrderWithCost:!0,createMarketOrderWithCost:!1,createMarketSellOrderWithCost:!1,createOrder:!0,createReduceOnlyOrder:void 0,createStopLimitOrder:!0,createStopLossOrder:!1,createStopMarketOrder:!0,createStopOrder:!0,createTakeProfitOrder:!1,fetchAccounts:!1,fetchAllGreeks:!1,fetchBalance:!0,fetchBidsAsks:!0,fetchBorrowInterest:void 0,fetchBorrowRateHistories:void 0,fetchBorrowRateHistory:void 0,fetchCanceledOrders:!1,fetchClosedOrder:!1,fetchClosedOrders:"emulated",fetchCrossBorrowRate:!1,fetchCrossBorrowRates:!1,fetchCurrencies:!1,fetchDeposit:!1,fetchDepositAddress:!0,fetchDepositAddresses:!1,fetchDepositAddressesByNetwork:!1,fetchDeposits:!0,fetchDepositsWithdrawals:!1,fetchFundingHistory:!1,fetchFundingInterval:!1,fetchFundingIntervals:!1,fetchFundingRate:!1,fetchFundingRateHistory:!1,fetchFundingRates:!1,fetchGreeks:!1,fetchIndexOHLCV:!1,fetchIsolatedBorrowRate:!1,fetchIsolatedBorrowRates:!1,fetchL3OrderBook:!1,fetchLedger:void 0,fetchLeverage:!1,fetchLeverageTiers:!1,fetchLongShortRatio:!1,fetchLongShortRatioHistory:!1,fetchMarketLeverageTiers:"emulated",fetchMarkets:!0,fetchMarkOHLCV:!1,fetchMarkPrice:!1,fetchMarkPrices:!1,fetchMySettlementHistory:!1,fetchMyTrades:!0,fetchOHLCV:!0,fetchOpenInterestHistory:!1,fetchOpenInterests:!1,fetchOpenOrder:!1,fetchOpenOrders:!0,fetchOption:!1,fetchOptionChain:!1,fetchOrder:!0,fetchOrderBook:!0,fetchOrderBooks:!1,fetchOrders:!0,fetchOrderTrades:!1,fetchPosition:!1,fetchPositionHistory:!1,fetchPositionMode:!1,fetchPositions:!1,fetchPositionsForSymbol:!1,fetchPositionsHistory:!1,fetchPositionsRisk:!1,fetchPremiumIndexOHLCV:!1,fetchSettlementHistory:!1,fetchStatus:!1,fetchTicker:!0,fetchTickers:!0,fetchTime:!0,fetchTrades:!0,fetchTradingFee:!1,fetchTradingFees:!1,fetchTradingLimits:!1,fetchTransactionFee:!1,fetchTransactionFees:!1,fetchTransactions:!1,fetchTransfers:!1,fetchUnderlyingAssets:!1,fetchVolatilityHistory:!1,fetchWithdrawal:!1,fetchWithdrawals:!0,fetchWithdrawalWhitelist:!1,reduceMargin:!1,repayCrossMargin:!1,repayIsolatedMargin:!1,setLeverage:!1,setMargin:!1,setMarginMode:!1,setPositionMode:!1,signIn:!1,transfer:!1,withdraw:!0},timeframes:{"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1h":"1h","2h":"2h","4h":"4h","6h":"6h","8h":"8h","12h":"12h","1d":"1d","3d":"3d","1w":"1w","1M":"1M"},urls:{logo:"https://user-images.githubusercontent.com/1294454/183870484-d3398d0c-f6a1-4cce-91b8-d58792308716.jpg",api:{rest:{public:"https://www.tokocrypto.com",binance:"https://api.binance.com/api/v3",private:"https://www.tokocrypto.com"}},www:"https://tokocrypto.com",doc:"https://www.tokocrypto.com/apidocs/",fees:"https://www.tokocrypto.com/fees/newschedule"},api:{binance:{get:{ping:{cost:1},time:{cost:1},depth:{cost:1,byLimit:[[100,1],[500,5],[1e3,10],[5e3,50]]},trades:{cost:1},aggTrades:{cost:1},historicalTrades:{cost:5},klines:{cost:1},"ticker/24hr":{cost:1,noSymbol:40},"ticker/price":{cost:1,noSymbol:2},"ticker/bookTicker":{cost:1,noSymbol:2},exchangeInfo:{cost:10},executionRules:{cost:2,noSymbol:40}},put:{userDataStream:{cost:1}},post:{userDataStream:{cost:1}},delete:{userDataStream:{cost:1}}},public:{get:{"open/v1/common/time":{cost:1},"open/v1/common/symbols":{cost:1},"open/v1/market/depth":{cost:1},"open/v1/market/trades":{cost:1},"open/v1/market/agg-trades":{cost:1},"open/v1/market/klines":{cost:1}}},private:{get:{"open/v1/orders/detail":{cost:1},"open/v1/orders":{cost:1},"open/v1/account/spot":{cost:1},"open/v1/account/spot/asset":{cost:1},"open/v1/orders/trades":{cost:1},"open/v1/withdraws":{cost:1},"open/v1/deposits":{cost:1},"open/v1/deposits/address":{cost:1}},post:{"open/v1/orders":{cost:1},"open/v1/orders/cancel":{cost:1},"open/v1/orders/oco":{cost:1},"open/v1/withdraws":{cost:1},"open/v1/user-data-stream":{cost:1},"open/v1/user-listen-token":{cost:1}}}},fees:{trading:{tierBased:!0,percentage:!0,taker:this.parseNumber("0.0075"),maker:this.parseNumber("0.0075")}},precisionMode:4,options:{createMarketBuyOrderRequiresPrice:!0,defaultTimeInForce:"GTC",hasAlreadyAuthenticatedSuccessfully:!1,warnOnFetchOpenOrdersWithoutSymbol:!0,recvWindow:5e3,timeDifference:0,adjustForTimeDifference:!1,newOrderRespType:{market:"FULL",limit:"FULL"},quoteOrderQty:!1,networks:{ERC20:"ETH",TRC20:"TRX",BEP2:"BNB",BEP20:"BSC",OMNI:"OMNI",EOS:"EOS",SOL:"SOL"},reverseNetworks:{"t