
    E#iп                       S SK Jr  S SKJr  S SKrS SKrS SKrS SKJrJ	r	J
r
JrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJ r   S SK!J"r"  S SK#J$r$  S SK#J%r%  S SK#J&r&  S S	K#J'r'  S S
K#J(r(  S SK#J)r)  S SK#J*r*  S SK#J+r+  S SK#J,r,  S SK#J-r-  S SK#J.r.  S SK#J/r/  S SK#J0r0  S SK#J1r1  S SK2J3r3  S SK4J5r5   " S S\\5      r6g)    )Exchange)ImplicitAPIN)AnyBalances
Conversion
CurrenciesCurrencyDepositAddressIntLeverageTierLeverageTiersMarginModificationMarketNumOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersFundingRateTradeTransactionTransferEntry)List)ExchangeError)AuthenticationError)PermissionDenied)AccountSuspended)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidOrder)OrderNotFound)DuplicateOrderId)DDoSProtection)RateLimitExceeded)CancelPending)	TICK_SIZE)Precisec                   |  ^  \ rS rSrS\4U 4S jjrS|S jrS\4S jrS\4S jr	0 4S\
\   4S	 jjr0 4S\4S
 jjrS}S\4S jjrS~S\4S jjrS0 4S\S\S\4S jjrS rS|S\4S jjrS|S\4S jjrS rS|S\4S jjrS|S\4S jjrS|S\4S jjrS|S\S\4S jjrSSS0 4S\S\S\S\S\
\   4
S jjrS|S\S\S\4S jjr 0 4S\S\4S jjr!S0 4S\"S\#4S  jjr$SS0 4S\S\S\S\
\%   4S! jjr&S|S"\S\S\%4S# jjr'S$ r(S% r)0 4S\*4S& jjr+S'\,4S( jr-S)\,4S* jr.S+\,4S, jr/S|S-\S\4S. jjr0S/ r1S|S\4S0 jjr2S|S-\S\S\34S1 jjr4S0 4S\S)\5S2\6S3\7S4\84
S5 jjr9SS0 4S6\S\S)\5S2\6S3\8S4\84S7 jjr:S0 4S6\S\,4S8 jjr;S0 4S\,4S9 jjr<S0 4S6\S\,4S: jjr=SSS0 4S\,S\S\S\
\3   4S; jjr>SSS0 4S\,S\S\S\
\3   4S< jjr?SSS0 4S\,S\S\S\
\3   4S= jjr@SSS0 4S\,S\S\4S> jjrA0 4S?\S\B4S@ jjrCSSS0 4S?\,S\S\S\
\D   4SA jjrESSS0 4S?\,S\S\S\
\D   4SB jjrFS'\,4SC jrGS|SD\SE\HS\D4SF jjrIS0 4S\"S\
\J   4SG jjrKS|SH\S\4SI jjrLSSS0 4S\,S\S\4SJ jjrMSS\SK\,4SL jjrN0 4S\S\O4SM jjrPS|S\S\O4SN jjrQ0 4S\S3\7S\R4SO jjrSSP rTS|SQ\S\S\R4SR jjrUS0 4SS\S\,4ST jjrVS0 4SU\WS\,4SV jjrXS0 4S\"S\Y4SW jjrZS|S\S\
\[   4SX jjr\SYSZ0 SS4S[ jr]S0 4S\\^S\,4S] jjr_0 4S?\S3\7S^\S_\S\`4
S` jjraSSS0 4S?\,S\S\S\
\`   4Sa jjrbS|Sb\SE\HS\`4Sc jjrcS'\,S\,4Sd jrdSSS0 4S\,S\S\4Se jjreS0 4S?\S3\7Sf\Sg\,S\D4
Sh jjrf0 4S\4Si jjrgS|S\4Sj jjrhS0 4Sk\Sl\S3\8S\i4Sm jjrjS0 4S6\Sk\Sl\S3\8S\i4
Sn jjrkSSS0 4S?\,S\S\S\
\i   4So jjrlSSp\Sq\HSr\HS\i4Ss jjrmSt\^Su\Sv\Sw\Sx\Sy\4Sz jrnS{roU =rp$ )phemex   returnc                   > U R                  [        [        U ]  5       0 SS_SS_SS/_SS_S	S
_SS_SS_SS_S0 SS _SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_S S_S!S_S"S_0 S#S_S$S_S%S_S&S_S'S_S(S_S)S_S*S_S+S_S,S_S-S_S.S_S/S_S0S_S1S_S2S_S3S_E0 S4S_S5S_S6S_S7S_S8S_S9S_S:S_S;S<_S=S_S>S_S?S_S@S_SAS_SBS_SCS_SDS_SES_E0 SFS_SGS_SHS_SIS_SJS_SKS_SLS_SMS_SNS_SOS_SPS_SQS_SRS_SSS_STS_SUS_SVS_ESWS0E_SXSYSZS[S\S[S].S^S_S`S_S].SaSbScSdSeSf.Sg._Sh0 SiSj_SkSl_SmSn_SoSp_SqSr_SsSt_SuSv_SwSx_SySz_S{S|_S}S~_SS_SS_SS_SS_SS__SSSSSSSSSSSSSSS.0SSSSSSSSSSS.	0SSSSSSSSS.00 SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_0 SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_E0 SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_ESS0E0 SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SSSSSSSSSS.	SSSSSSSSS.S.S._S[        _SSSSU R                  S5      U R                  S5      S.0_SSSSSSSS.SSSS SSSSS.SSSSSSSS.S SSSSSS.SSSSS.SS SSSS.SS S S SSSS.SSSSSSSSS.SS0S.	SS0SSSSSS.SS.SS.SS0S.SS0SS0S.S S S.S._SSSS._S0 S[        _S[        _S[        _S[        _S[        _S[        _S[        _S[        _S[        _S[        _GS [        _GS[        _GS[        _GS[        _GS[        _GS[        _GS[        _0 GS[        _GS[        _GS	[        _GS
[        _GS[        _GS[        _GS[        _GS[        _GS[        _GS[        _GS[        _GS[        _GS[        _GS[        _GS[        _GS[        _GS[        _E0 GS[        _GS[        _GS[        _GS[        _GS[        _GS[         _GS[         _GS[        _GS [        _GS![        _GS"[        _GS#[        _GS$[        _GS%[        _GS&[        _GS'[        _GS([        _E0 GS)[        _GS*[        _GS+[        _GS,[        _GS-[        _GS.[        _GS/[        _GS0[        _GS1[        _GS2[        _GS3[        _GS4[        _GS5[        _GS6[        _GS7[        _GS8[        _GS9[        _E0 GS:[        _GS;[        _GS<[        _GS=[        _GS>[        _GS?[        _GS@[        _GSA[        _GSB[        _GSC[        _GSD[        _GSE[        _GSF[        _GSG[        _GSH[        _GSI[        _GSJ[        _E0 GSK[        _GSL[        _GSM[        _GSN[        _GSO[        _GSP[        _GSQ[        _GSR[        _GSS[        _GST[        _GSU[        _GSV[        _GSW[        _GSX[        _GSY[        _GSZ[        _GS[[        _E0 GS\[        _GS][        _GS^[        _GS_[        _GS`[        _GSa[        _GSb[        _GSc[        _GSd[        _GSe[        _GSf[        _GSg[        _GSh[        _GSi[        _GSj[        _GSk[        _GSl[        _E0 GSm[        _GSn[        _GSo[        _GSp[        _GSq[        _GSr[        _GSs[        _GSt[        _GSu[        _GSv[        _GSw[        _GSx[        _GSy[        _GSz[        _GS{[        _GS|[        _GS}[        _E[        [        [        [        [        [        [        [        ["        [        [$        ["        [        GS~.E["        ["        [        [        [        [        GS.GS._GSGSGSSGSGSGSGS.GSGSGS.GSSSGS./ GSQGSS0GSGSGSGSGSGS.GS.
0E5      $ (  Nidr0   namePhemex	countriesCN	rateLimitg      ^@versionv1	certifiedFproThostnamezapi.phemex.comhasCORSspotmarginswapfutureoption	addMargincancelAllOrderscancelOrderclosePositioncreateConvertTradecreateOrdercreateReduceOnlyOrdercreateStopLimitOrdercreateStopMarketOrdercreateStopOrder	editOrderfetchBalancefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchClosedOrdersfetchConvertQuotefetchConvertTradefetchConvertTradeHistoryfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsfetchFundingHistoryfetchFundingRatefetchFundingRateHistoriesfetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLeveragefetchLeverageTiersfetchMarketLeverageTiersemulatedfetchMarketsfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchPositionsfetchPositionsRiskfetchPremiumIndexOHLCVfetchTickerfetchTickersfetchTradesfetchTradingFeefetchTradingFeesfetchTransfersfetchWithdrawalsreduceMarginsandboxsetLeverage	setMarginsetMarginModesetPositionModetransferwithdrawurlszchttps://user-images.githubusercontent.com/1294454/85225056-221eb600-b3d7-11ea-930d-564d2690e3f6.jpgz!https://testnet-api.phemex.com/v1zhttps://testnet-api.phemex.comz.https://testnet-api.phemex.com/exchange/public)r;   v2publicprivatezhttps://{hostname}/v1zhttps://{hostname}z"https://{hostname}/exchange/publiczhttps://phemex.comz'https://phemex-docs.github.io/#overviewz"https://phemex.com/fees-conditionsz.https://phemex.com/register?referralCode=EDNVJg?)urldiscount)logotestapiwwwdocfeesreferral
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31104000r   get   )zcfg/v2/productszcfg/fundingRatesproductsznomics/tradeszmd/klinezmd/v2/kline/listzmd/v2/klinezmd/v2/kline/lastmd/orderbookmd/trademd/spot/ticker/24hrz"exchange/public/cfg/chain-settings)	zmd/fullbookr   r   zmd/ticker/24hrzmd/ticker/24hr/allr   zmd/spot/ticker/24hr/allzexchange/public/products)api-data/public/data/funding-rate-history)zpublic/productszpublic/products-pluszmd/v2/orderbookzmd/v2/tradezmd/v2/ticker/24hrzmd/v2/ticker/24hr/allr   zspot/orders/active   spot/orderszspot/walletszexchange/spot/orderzexchange/spot/order/tradeszexchange/order/v2/orderListzexchange/order/v2/tradingListzaccounts/accountPositionszg-accounts/accountPositionszg-accounts/positions   zg-accounts/risk-unitzapi-data/futures/funding-feeszapi-data/g-futures/funding-feeszapi-data/futures/orderszapi-data/g-futures/ordersz#api-data/futures/orders/by-order-idz%api-data/g-futures/orders/by-order-idzapi-data/futures/tradeszapi-data/g-futures/tradeszapi-data/futures/trading-feeszapi-data/g-futures/trading-feesz&api-data/futures/v2/tradeAccountDetailzg-orders/activeListzorders/activeListzexchange/order/listzexchange/orderzexchange/order/tradezphemex-user/users/childrenz%phemex-user/wallets/v2/depositAddressz&phemex-user/wallets/tradeAccountDetailz)phemex-deposit/wallets/api/depositAddressz&phemex-deposit/wallets/api/depositHistz#phemex-deposit/wallets/api/chainCfgz(phemex-withdraw/wallets/api/withdrawHistz&phemex-withdraw/wallets/api/asset/infoz$phemex-user/order/closedPositionListzexchange/margins/transferz!exchange/wallets/confirm/withdrawzexchange/wallets/withdrawListzexchange/wallets/depositListz"exchange/wallets/v2/depositAddresszapi-data/spots/fundszapi-data/spots/ordersz!api-data/spots/orders/by-order-idzapi-data/spots/pnlszapi-data/spots/tradesz!api-data/spots/trades/by-order-idzassets/convertzassets/transferz"assets/spots/sub-accounts/transferz$assets/futures/sub-accounts/transferzassets/quoteordersg-orderszpositions/assignzexchange/wallets/transferOutzexchange/wallets/transferInzexchange/marginszexchange/wallets/createWithdrawzexchange/wallets/cancelWithdrawz&exchange/wallets/createWithdrawAddresszassets/universal-transferz*phemex-withdraw/wallets/api/createWithdrawz*phemex-withdraw/wallets/api/cancelWithdraw)	zspot/orders/creater   zorders/replacezg-orders/replacezg-orders/createzpositions/leveragezg-positions/leveragez g-positions/switch-pos-mode-synczpositions/riskLimit      )r   zspot/orders/allzorders/cancelr   z
orders/allzg-orders/cancelr   zg-orders/all)r   postputdelete)r   r;   r   r   precisionModer   tradingz0.001)	tierBased
percentagetakermakerfeatures)marklastindex)IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedleveragemarketBuyByCostmarketBuyRequiresPriceselfTradePreventiontrailingiceberg   i )r   limitdaysBack	untilDayssymbolRequired)r   triggerr   r   )r   r   r   r   r   )r   r   r   r   r   r   r   )r   r   r   daysBackCanceledr   r   r   r   r     )	r   rK   createOrdersrm   rq   rp   rs   rT   rn   extendsdefault)r   price)r   r   r     )r   rK   rn   forDerivatives)linearinverse)r   rA   r   rC   rD   requiredCredentials)apiKeysecret
exceptions401412600119999100011000210003100041000511001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611128)11129111301113111132111331113430000300183400335104399953999639997)z401 Insufficient privilegez401 Request IP mismatchzFailed to find api-keyzMissing required parameterz!API Signature verification failedzApi key not found)exactbroadoptions
CCXT123456<   TRXETHBNB)TRC20ERC20BEP20)USDTMKRr   )rA   rC   )BUSDFEITUSDUSDUSDCUSDDUSDPr  fillResponseFromRequestByLastPriceByMarkPriceByIndexPrice
ByAskPrice
ByBidPrice)r   r   r   askbid)
brokerIdx-phemex-request-expirycreateOrderByQuoteRequiresPricenetworksdefaultNetworksdefaultSubTypeaccountsByTypestableCoinsr   triggerPriceTypesMap)deep_extendsuperr0   describer-   parse_numberr    r$   r)   r(   r,   r&   r'   r   r"   r%   r*   r!   r+   )self	__class__s    S/home/james-whalen/.local/lib/python3.13/site-packages/ccxt/async_support/phemex.pyr  phemex.describe!   sf   fd < > U	A
(U	A
HU	A
 $U	A
 	U	A

 tU	A
 U	A
 4U	A
 (U	A
  FFF %F 	F
 %F %F UF "4F tF  F %dF tF (F 'F (F  "4!F" T#F$ %F& +E'F( )%)F* $T+F, $T-F. $U/F0 +D1F2 '3F4 (5F6 "47F8 &t9F: (;F< 1%=F>  ?F@ &tAFB #DCFD ,UEFF *4GFH $UIFJ "5KFL *5MFN +EOFP  QFR %dSFT +JUFV WFX !%YFZ  [F\ d]F^ $T_F` "4aFb dcFd !$eFf tgFh !$iFj %ekFl )%mFn toFp qFr tsFt "5uFv #EwFx !$yFz #D{F| }F~ 4F@ tAFB TCFD  EFF "4GFH DIFJ DKFU	A
` }=:N?	 2.B3	 ,@<K ##aU	A
L  de e u	
 v f f g g g w g h i i  j!MU	A
p +,,-$%)*$%,-'(,-()$%/0>?" '(()$%*+.//03445EF
 +,01+,'(-.12EF
;,a; &q	;
 '; .q; 5a; 6q; 8; 4Q; 6q; /; /; 8;  :1!;" 21#;$ 4Q%;& >q';( @);* 21+;, 4Q-;. 8/;0 :11;2 A!3;4 .q5;6 ,Q7;8 .q9;: )!;;> /?;@ 5aA;B @C;D A!E;F DQG;H A!I;J >qK;L CAM;N A!O;P ?Q;R 4QS;T <QU;V 8W;X 7Y;Z =a[;\ /];^ 0_;` <Qa;b .qc;d 0e;f <Qg;h )!i;l *1m;n =ao;p ?q;r 's;x%q !!	
 #A +A 7 6q +A :1 :1 A! *1 =a  ?!" 4Q#$ )!%( Ea)* Ea+2 /0'(*+,-+,./01<=/0 ()+, *+"#&'+,$%()CnSXqU	A
b YcU	A
d !&"&!..w7!..w7	eU	A
t #&+(, %)$(%)-
 -2).+06:#'#'"&#(	( #($)+/27/4$)#(3$6 %)&+!$$*%&*/& ',#($)*.	# ',!%#($)*.( ',!%$(%)#($)*.$ ',!$$*,2%&#($)*/	*  #KHT y  ),0 )-(,)-1
 &*7 #'$  ##( "#3 "#3 	 ##OkuU	A
L "$MU	A
T Y.Y :Y J	Y ZY -Y ]Y ]Y ]Y ]Y .Y \Y .Y \Y  .!Y" ]#Y$ ]%Y& ]'Y( ])Y* .+Y, \-Y. \/Y0 \1Y2 \3Y4 \5Y6 Z7Y8 ]9Y: ];Y< ]=Y> ]?Y@ ]AYB -CYD ]EYF ]GYH ZIYJ ]KYL YMYN YOYP ]QYR ]SYT ^UYV ^WYX -YYZ \[Y\ \]Y^ \_Y` \aYb \cYd \eYf \gYh \iYj \kYl \mYn \oYp \qYr \sYt \uYv \wYx \yYz \{Y| \}Y~ \Y@ \AYB \CYD \EYF \GYH \IYJ \KYL \MYN \OYP ]QYR \SYT \UYV \WYX \YYZ \[Y\ \]Y^ \_Y` ]aYb YcYd \eYf \gYh \iYj \kYl \mYn \oYp \qYr \sYt \uYv \wYx \yYz .{Y| \}Y~ \Y@ -AYB \CYD \EYF \GYH \IYJ \KYL \MYN \OYP \QYR \SYT \UYV \WYX ZYYZ Z[Y\ ]]Y^ ._Y` .aYb ZcYd ZeYf ZgYh .iYj .kYl ]mYn \oYp \qYr \sYt \uYv \wYx ZyYz \{Y| \}Y~ \Y@ \AYB \CYD \EYF \GYH \IYJ \KYL \MYN \OYP \QYR \SYT \UYV *)))))''-..-&qYv 3C/?.A2<9L)<wcUU	A
\ (+-37""" " $ #+"$#	  .t *)+'')?&]U	A
 U	 U		    Nc                     Uc  U$ UR                  S5      nSR                  U5      nUR                  S5      nU R                  US5      $ )N,  r   )splitjoinsafe_number)r  valuepartss      r  parse_safe_numberphemex.parse_safe_numbery  sH    =LC C q))r  marketc                 0   U R                  US5      nU R                  US5      nU R                  USU5      nU R                  US5      nU R                  US5      nU R                  U5      nUR                  SS5      nU R                  U5      nU R                  U5      n	Sn
Xe:w  a  S	n
SU;  a  Xx:X  a  U	nU R                  US
5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  USS5      nS nU	S:X  a  U R	                  S5      nOMUR                  S5      (       a&  UR                  S5      nU R	                  US   5      nOU R	                  U5      nU R                  0 SU_SUS-   U-   S-   U	-   _SU_SU_SU	_SU_SU_SU_SS _S!S_S"S_S S	_S#S_S$S_S%US&:H  _S'S	_S(U
(       + _U
U R	                  U R                  UU5      5      U R	                  U R                  UU5      5      US S S S UUUU R                  US)S*5      U R                  US+5      S,.U R	                  S5      U R                  US-5      S..S S S..U R	                  U R                  X5      5      U R	                  U R                  X5      5      S..S U R	                  U R                  US/5      5      S..S0.S US1.E5      $ )2NsymbolcontractUnderlyingAssetsbaseCurrencyquoteCurrencysettleCurrencyr  r  FT
priceScale
ratioScale
valueScale
minPriceEp
maxPriceEpmakerFeeRateErtakerFeeRateErstatuscontractSizer  1r   r4   /:basequotesettlebaseIdquoteIdsettleIdtyperC   rA   rB   rD   rE   activeListedcontractr   lotSizeqtyStepSizetickSizeamountr   maxLeverageminmaxmaxOrderQtyr   r  r   costr   r   r   r  expiryexpiryDatetimestrike
optionTyper  r  r  	precisionlimitscreatedinfo)safe_stringsafe_currency_codereplacesafe_integerr  findr  safe_market_structurefrom_ensafe_number_2r  )r  r  r4   r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  contractSizeStringr  r  s                         r  parse_swap_marketphemex.parse_swap_market  s   d fh/#'#3#3F<V#W !!&.:RS""6?;##F,<=&&v.||C$''0((2G"f,$-&&v|<
&&v|<
&&v|<
%%fl;
%%fl;
))&2BC))&2BC!!&(3!--fncJ V,,S1L$$S)) ',,S1E,,U1X6L  ,,-?@L)) 5+
"5+
dSj5(3.75+
 D5+
 U	5+

 f5+
 f5+
 w5+
 5+
 F5+
 E5+
 e5+
 D5+
 e5+
 e5+
 f(5+
  !5+
" 'k#5+
$ &&t||NJ'OP&&t||NJ'OP("$$$,,VYN))&*=  ,,S1++FMB
  
  ,,T\\*-QR,,T\\*-QR
  ,,T-=-=fm-TU$ i5+
 5 5	r  c                    U R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  U5      nU R                  U5      nU R                  US5      nU R                  U R                  US5      5      n	U R                  U R                  US5      5      n
U R	                  0 SU_SUS	-   U-   _S
U_SU_SS _SU_SU_SS _SU_SS_SS_SS_SS_SS_SUS:H  _SS_SS _S U R                  US5      U R                  US5      S S S S S U R                  US5      U R                  US5      U R                  US5      U	U
S .S S S!.U	U R                  U R                  US"5      5      S!.U
S S!.U R                  U R                  US#5      5      U R                  U R                  US$5      5      S!.S%.U R                  US&5      US'.E5      $ )(Nr  r  r  r  r  baseTickSizequoteTickSizer4   r  r  r  r  r  r  r  rA   TrB   FrC   rD   rE   r  r  r  r   defaultTakerFeedefaultMakerFeer  r  r  r  r  maxBaseOrderSizeminOrderValuemaxOrderValuer  listTimer  )safe_string_lowerr  r  r  r  r  r  )r  r  r  r4   r  r  r  r  r  precisionAmountprecisionPrices              r  parse_spot_marketphemex.parse_spot_market  s   J %%ff5fh/""6?;!!&.9&&v.''0!!&(3001A1A&.1YZ//0@0@0YZ)) 5+
"5+
dSj5(5+
 D5+
 U	5+

 d5+
 f5+
 w5+
 5+
 D5+
 D5+
 e5+
 E5+
 e5+
 e5+
 f(5+
  !5+
" d#5+
$ %%f.?@%%f.?@ "++FLA++FLA++FLA)'  
 +11$2B2B6K]2^_
 *
  11$2B2B6?2[\11$2B2B6?2[\$ ((<i5+
 5 5	r  c                   #    U R                  U5      nU R                  U5      n[        R                  " X#/6 I Sh  vN u  pEU R	                  US/ 5      nU R                  US0 5      nU R                  US/ 5      nU R                  US/ 5      n	U R                  X5      nU R                  US/ 5      n
U R                  US/ 5      nU R                  X5      n
U R                  US/ 5      nU R                  U
S5      nU R                  US5      nU R                  US	5      n/ n[        S
[        U5      5       GH	  nUU   nU R                  US5      nUS:X  d  US:X  d  US:X  an  U R                  US5      nU R                  UU0 5      nU R                  UU5      nU R                  UU0 5      nU R                  UU5      nU R                  U5      nO]U R                  US5      nU R                  UU0 5      nU R                  USS5      nU R                  USU05      nU R                  U5      nUR!                  U5        GM     U$  GN7f)z
retrieves data on all markets for phemex

https://phemex-docs.github.io/#query-product-information-3

:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: an array of objects representing market data
Ndatar   perpProductsV2
riskLimitsriskLimitsV2
currenciesr  currencyr   r  	perpetualperpetualv2perpetualpilotr  r  8)v2GetPublicProductsv1GetExchangePublicProductsasynciogather
safe_value	safe_dict	safe_listarray_concatindex_byrangelenr
  r  extendr  r  append)r  paramsv2ProductsPromisev1ProductsPromise
v2Products
v1Productsv1ProductsDatav2ProductsDatar   perpetualProductsV2r  r  r  riskLimitsByIdv1ProductsByIdcurrenciesByCoderesultir  r  r4   riskLimitValuesv1ProductsValuesr  currencyValuesr  s                             r  fetch_marketsphemex.fetch_marketsr  sE     !44V<l !<<VD'.~~8I7]'^!^
VR@H 
FB?>>.*bA"nn^=MrR$$XC^^NL"E
~~nnbI&&z@
^^NL"E
z8<~x@==Z@q#h-(Aa[F))&&9D#)>DL\D\%%fh7"&..R"HV_=#'>>."b#I V-=>//7#//G!%0@,PR!S!--nlCP
VlJ-GH//7MM&!! )" E "_s   :I
IHI
c                 *  #    U R                  U5      I Sh  vN nU R                  US0 5      nU R                  US/ 5      n0 n[        S[        U5      5       GH0  nXF   nU R	                  US5      nU R                  U5      n	U R	                  US5      n
[        U
5      nU R	                  US5      nU R	                  US5      nSnSnSnUbn  U R                  U
5      nU R                  U5      nU R                  [        R                  " UU5      5      nU R                  [        R                  " UU5      5      nU R                  UUU	U R	                  US	5      U R	                  US
5      S:H  SSSUUUS.SSS.S.USSS.5      XY'   GM3     U$  GNy7f)z
fetches all available currencies on an exchange
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: an associative dictionary of currencies
Nr  r  r   r  r  
minValueEv
maxValueEvr5   r  r  r  )r  r   crypto)r4   r  coder5   r  depositr   feer  r  r  r  r  )r  r  r#  r$  r  r  intparse_precisionr  r.   
string_mulsafe_currency_structure)r  r'  responser  r  r2  r3  r  r4   r=  valueScaleStringr  r:  r;  	minAmount	maxAmountr  precisionStrings                     r  fetch_currenciesphemex.fetch_currenciesV  s     11&99 x4__T<<
q#j/*A!}H!!(J7B**2.D#//,G-.J))(LAJ))(LAJ!I!I!I%"&"6"67G"H --o>	 --g.@.@_.]^	 --g.@.@_.]^	77 ((6:**8X>(J &  )(
  $#!	 )  -9 FL! +P u :s   FFE9Fc                    Uc  [        U R                  S-   5      eU R                  X5      nUS   (       a  U R                  XT5      nU R	                  U R                  U R                  X5      U5      5      U R	                  U5      /$ )Nz/ customParseBidAsk() requires a market argumentrA   )r#   r4   r  from_evr  from_ep)r  bidaskpriceKey	amountKeyr  r  s         r  custom_parse_bid_askphemex.custom_parse_bid_ask  s}    >#DGG._$_``!!&4&>\\&1Fdll4+;+;F+MvVWf%
 	
r  c	           
         UUU R                  U5      S S.n	XE/n
[        S[        U
5      5       H^  nX   n/ nU R                  X5      n[        S[        U5      5       H'  nUR	                  U R                  X   XgU5      5        M)     XU'   M`     U R                  X   SS5      X'   U R                  X   S5      X'   U	$ )N)r  	timestampdatetimenoncer   T)iso8601r#  r$  r  r&  rQ  sort_by)r  	orderbookr  rT  bidsKeyasksKeyrO  rP  r  r2  sidesr3  sider   bidasksks                   r  custom_parse_order_bookphemex.custom_parse_order_book  s    "Y/	
 "q#e*%A8DFooi6G1c'l+d77
HY_`a ,!4L & ,,v4@,,v:r  r  r   c           
        #    U R                  5       I Sh  vN   U R                  U5      nSUS   0nSnUS   S:H  =(       d    US   S:H  nUS   (       a0  U(       a)  U R                  U R                  XS5      5      I Sh  vN nOZUb/  US::  a)  U R	                  U R                  XS5      5      I Sh  vN nO(U R                  U R                  XS5      5      I Sh  vN nU R                  US	0 5      nU R                  US
S0 5      n	U R                  USS5      n
U R                  XU
SSSSU5      nU R                  US5      US'   U$  GN2 N N Ns7f)a)  
fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#queryorderbook

:param str symbol: unified symbol of the market to fetch the order book for
:param int [limit]: the maximum amount of order book entries to return
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
Nr  r4   r  r  r  r      r2  bookorderbook_prT  ư>bidsasksr   r   sequencerV  )load_marketsr  v2GetMdV2Orderbookr%  v1GetMdOrderbookv1GetMdFullbookr  safe_value_2safe_integer_productr`  r  )r  r  r   r'  r  requestrD  isStableSettledr2  rd  rT  rY  s               r  fetch_order_bookphemex.fetch_order_book  sV     !!!V$fTl
 !(+v5V6(;Kv;U(!44T[[5QRRH!!%!6!6t{{77S!TT!%!5!5dkk'6R!SS4 8R8  C--fk8L	00y&RXZ[]^`fg	!..vzB	'[ 	" S USsG   EEA)E E1E2E3(EEA-EEEEc                     U R                  U5      n[        U5      nUR                  U-
  Ul        UR                  5         [	        U5      nU R                  U5      $ N)number_to_stringr.   decimalsreducestrparse_to_numeric)r  nscalestringNprecisepreciseStrings         r  to_enphemex.to_en  sS    ''*'""++e3G$$]33r  c                 :    Ub  Uc  U$ U R                  XS   5      $ Nr  r  )r  r  r  s      r  to_evphemex.to_ev  s$    NMzz&"677r  c                 :    Ub  Uc  U$ U R                  XS   5      $ Nr  r  )r  r   r  s      r  to_epphemex.to_ep  s$    Mv~Lzz%!566r  c                     Ub  Uc  g [        U5      nU R                  UR                  U5      Ul        UR                  5         [	        U5      $ ru  )r.   sumrw  rx  ry  )r  enr|  r~  s       r  r  phemex.from_en  sD    :"+88G$4$4e<7|r  c                 T    Ub  Uc  U$ U R                  XR                  US5      5      $ r  r  r  )r  epr  s      r  rM  phemex.from_ep
  ,    JFNI||B 1 1&, GHHr  c                 T    Ub  Uc  U$ U R                  XR                  US5      5      $ r  r  )r  evr  s      r  rL  phemex.from_ev  r  r  c                 T    Ub  Uc  U$ U R                  XR                  US5      5      $ )Nr  r  )r  err  s      r  from_erphemex.from_er  r  r  c                 L   Ub<  US   (       a2  U R                  U R                  U R                  US5      U5      5      nOU R                  US5      nU R	                  US5      U R                  U R                  U R                  US5      U5      5      U R                  U R                  U R                  US5      U5      5      U R                  U R                  U R                  US5      U5      5      U R                  U R                  U R                  US5      U5      5      U/$ )NrA      r   r      r      )r  rL  r  r  safe_timestamprM  )r  ohlcvr  
baseVolumes       r  parse_ohlcvphemex.parse_ohlcv  s    F6N**4<<8H8HPQ8RTZ+[\J))%3Jq)dll4+;+;E1+EvNOdll4+;+;E1+EvNOdll4+;+;E1+EvNOdll4+;+;E1+EvNO
 	
r  r   	timeframesincec                   #    U R                  5       I Sh  vN   U R                  U5      nUnUS   U R                  U R                  X"5      S.nU R	                  USS5      n	U R                  US/5      nUS   S:H  =(       d    US   S:H  n
US	   =(       d    U
=(       a    USL=(       d    U	SLnS
nU(       a  SnUc  Un[        XL5      US'   SnUS	   (       d  U
(       a  U	c  Ub  U R                  U5      nUb  [        [        US
-  5      5      nX8S'   O
U	S-  X-  -
  nU	b  [        [        U	S
-  5      5      US'   O#X<U-  -   nU R                  5       nUU:  a  UnXS'   U R                  U R                  X5      5      I Sh  vN nOU R                  U R                  X5      5      I Sh  vN nOfUb;  U R                  U5      S
-  nU R                  5       U-
  nU R                  UU-  5      nU R!                  U R                  X5      5      I Sh  vN nU R#                  US0 5      nU R%                  US/ 5      nU R'                  UXbX75      $  GN> N N ND7f)a{  
fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#querykline
https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md#query-kline

:param str symbol: unified symbol of the market to fetch OHLCV data for
:param str timeframe: the length of time each candle represents
:param int [since]: *only used for USDT settled contracts, otherwise is emulated and not supported by the exchange* timestamp in ms of the earliest candle to fetch
:param int [limit]: the maximum amount of candles to fetch
:param dict [params]: extra parameters specific to the exchange API endpoint
:param int [params.until]: *USDT settled/ linear swaps only* end time in ms
:returns int[][]: A list of candles ordered, open, high, low, close, volume
Nr4   )r  
resolutionuntiltor  r  r  r   r   r   r   fromd   r  rows)rj  r  r  r   safe_integer_2omitr  parse_timeframer@  roundsecondspublicGetMdV2KlineListr%  publicGetMdV2KlineLastmillisecondsparse_to_intpublicGetMdV2Kliner  r   parse_ohlcvs)r  r  r  r  r   r'  r  	userLimitrp  r  rq  usesSpecialFromToEndpointmaxLimitrD  candleDurationr  nowduration	timeDeltar  r  s                        r  fetch_ohlcvphemex.fetch_ohlcv5  ss     !!!V$	Tl**4??IQ
 ##FGT:6G9-!(+v5V6(;Kv;U&,X&6&I/$|RW_cRcQ{invziz!$H=Eu/(!u'8!%!5!5i!@$edl 34E&+FO #S[X-FGE$$'edl(;$<GDM ^";<B,,.CCx $&DM!%!<!<T[[=Y!ZZ!%!<!<T[[=Y!ZZ   //	:TA --/%7	)))h*>?!44T[[5QRRH x4~~dFB/  v%KK 	"H [Z SsG   IIE/II(I/I0A&II>IIIItickerc                 p   U R                  US5      nU R                  X25      nUS   nU R                  USS5      nU R                  U R	                  USS5      U5      nU R                  U R	                  USS5      U5      nU R                  US5      nUc#  U R                  U R	                  US	S
5      U5      nU R                  U R                  US5      U5      n	U R                  0 SU_SU_SU R                  U5      _SU R                  U R	                  USS5      U5      _SU R                  U R	                  USS5      U5      _SU R                  U R                  US5      U5      _SS _SU R                  U R                  US5      U5      _SS _SS _SU	_SU_SU_SS _SS _SS _S S _UUUS!.EU5      $ )"Nr  rT  rf  lastEpcloseRp
turnoverEv
turnoverRvvolumevolumeEvvolumeRqopenEprU  highhighEphighRplowlowEplowRpr  bidEp	bidVolumer  askEp	askVolumevwapopencloser   previousClosechanger   average)r  quoteVolumer  )	r  safe_marketro  rM  safe_string_2r  rL  safe_tickerrW  )
r  r  r  marketIdr  rT  r   r  r  r  s
             r  parse_tickerphemex.parse_ticker  s<   l ##FH5!!(3!--fk8L	||D..vxKVTll4#5#5flL#Y[ab%%fh7
d&8&8Z&XZ`aJ||D,,VX>G !
f!
!
 Y/!
 DLL!3!3FHh!OQWX	!

 4<< 2 267G LfU!
 4<< 0 0 A6J!
 !
 4<< 0 0 A6J!
 !
 D!
 D!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ %&)!
* + 	r  c                   #    U R                  5       I Sh  vN   U R                  U5      nSUS   0nSnUS   (       ae  US   (       d	  US   S:X  a)  U R                  U R                  XB5      5      I Sh  vN nOQU R	                  U R                  XB5      5      I Sh  vN nO(U R                  U R                  XB5      5      I Sh  vN nU R                  US0 5      nU R                  Xc5      $  N N| NU N.7f)	a  
fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#query24hrsticker

:param str symbol: unified symbol of the market to fetch the ticker for
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
Nr  r4   rC   r   r  r  r2  )rj  r  v1GetMdTicker24hrr%  v2GetMdV2Ticker24hrv1GetMdSpotTicker24hrr  r  r  r  r'  r  rp  rD  r2  s          r  fetch_tickerphemex.fetch_ticker  s      !!!V$fTl
 &>i F8$4$=!%!7!7G8T!UU!%!9!9$++g:V!WW!77G8TUUHZ (B7  00w 	" VWUsF   C8C0AC85C26(C8C4(C8C6)C82C84C86C8symbolsc                 @  #    U R                  5       I Sh  vN   SnUb#  U R                  US5      nU R                  U5      nSnU R                  SX25      u  pRSnU R	                  SX25      u  pbU R                  US5      nSnUS:X  a  U R                  U5      I Sh  vN nOOUS:X  d  U R                  US5      S:X  a  U R                  U5      I Sh  vN nOU R                  U5      I Sh  vN nU R                  US	/ 5      n	U R                  X5      $  N Nz NF N.7f)
a  
fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

https://phemex-docs.github.io/#query-24-hours-ticker-for-all-symbols-2     # spot
https://phemex-docs.github.io/#query-24-ticker-for-all-symbols             # linear
https://phemex-docs.github.io/#query-24-hours-ticker-for-all-symbols       # inverse

:param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
Nr   rx   r  rA   r   r  r  r2  )rj  r  r  handle_market_type_and_paramshandle_sub_type_and_paramsr  v1GetMdSpotTicker24hrAllr  v1GetMdTicker24hrAllv2GetMdV2Ticker24hrAllr   parse_tickers)
r  r  r'  r  firstr  subTypequeryrD  r2  s
             r  fetch_tickersphemex.fetch_tickers#  s     !!!OOGQ/E[['F99.&Y99.&Y		&&)6>!::5AAH	!T%5%5fh%G5%P!66u==H!88??H(B7!!&22% 	" B=?sF   DDBDD5DDD-D.)DDDDc                   #    U R                  5       I Sh  vN   U R                  U5      nSUS   0nSnUS   S:H  =(       d    US   S:H  nUS   (       a0  U(       a)  U R                  U R                  Xd5      5      I Sh  vN nO(U R	                  U R                  Xd5      5      I Sh  vN nU R                  US0 5      n	U R                  U	S	S
/ 5      n
U R                  XX#5      $  N Nh NA7f)a  
get the list of most recent trades for a particular symbol

https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#querytrades

:param str symbol: unified symbol of the market to fetch trades for
:param int [since]: timestamp in ms of the earliest trade to fetch
:param int [limit]: the maximum amount of trades to fetch
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
Nr  r4   r  r  r  r   r2  tradestrades_p)rj  r  v2GetMdV2Trader%  v1GetMdTrader  rn  parse_trades)r  r  r  r   r'  r  rp  rD  rq  r2  r  s              r  fetch_tradesphemex.fetch_tradesC  s      !!!V$fTl
 !(+v5V6(;Kv;U(!00W1MNNH!..t{{7/KLLH" 8R8""68ZD  >>= 	" OLs4   C-C'A)C- C)(C-)C+*>C-)C-+C-tradec                    S nS nS nS nS nS nS n	S n
U R                  US5      nU R                  X5      nUS   nS nS n[        U[        5      (       a  [	        U5      nU R                  USS5      nUS:  a  U R                  XS-
  5      nU R                  XS-
  5      nU R                  XS-
  5      nU R                  XS-
  5      n[        XS-
     [        R                  5      (       a$  U R                  UU5      nU R                  UU5      nGOU R                  USS5      nUc  U R                  US	5      nU R                  US
S5      nU R                  US5      nUS   S:X  d
  US   S:X  Ga  U R                  US5      nUS:X  d  US:X  a  UnOUb
  US:X  a  SOSnU R                  US5      nUS:X  a  SnOUS:X  a  SnU R                  US5      nU R                  US5      nU R                  US5      nU R                  U R                  US5      5      nU R                  US5      n	Ub%  U R                  US5      nU R                  U5      n
GOU R                  U R                  US5      5      nUb  UnSn
GOU R                  US5      nU R                  U R                  US5      5      nU R                  US 5      nUS!:X  a  S"nU R                  U R                  US#5      U5      nU R                  U R                  US$5      U5      nU R                  US%U5      nU R!                  U R                  US&S'5      U5      nU R!                  U R                  U R                  US(5      5      U5      nUb  U R!                  U R                  US)5      U5      n	US*   (       a"  U R                  U R                  US+5      5      n
OPU R#                  US,5      nUb#  U R                  US-5      nU R                  U5      n
OU R                  US5      nUb  Sn
UU	U
S..nU R%                  UUUUU R'                  U5      UUUUUUUUS/.U5      $ )0Nr  r   rf  r  r   r   r   transactTimeNs	createdAtexecIdexecIDorderIDr  r  r  r]  buysellr  ordTyper  2r   execPriceRp	execQtyRqexecValueRv	execFeeRv	feeRateRrr  ptFeeRvPT
execStatus	MakerFillr   execPriceEpexecBaseQtyEvexecQtyexecQuoteQtyEvexecValueEv	execFeeEv	feeRateErrA   feeCurrencyr  settlementCurrency)r  rater  )r  r4   r  rT  rU  orderr  r]  takerOrMakerr   r  r  r?  )r  r  
isinstancelistr$  ro  r
  numbersRealrM  rL  r  r  	omit_zeror  parse_order_typer  r  
safe_traderW  )r  r  r  r4   r]  
costStringr  r?  feeCostStringfeeRateStringfeeCurrencyCoder  r  orderIdr  tradeLengthrT  priceStringamountStringsideIdr  
currencyIdr  r  r  settlementCurrencyIds                             r  parse_tradephemex.parse_tradeo  s   r 
!!###E84!!(3! eT""e*K11%HEIQ%%e1_=))%qAD**5/BK++E?CL%a0',,??"ll;?#||L&A11%9I8TI  --e[A	##E8X>B&&ui8Gh6)VH-=-G//v>eO6)9!D'%+s]5D**5)<c>#D^"D"..umD#//{C!--e]C
 $t/?/?{/S T $ 0 0 D ,!%!1!1%!DJ&*&=&=j&IO"nnT-=-=eY-OPG*(/*.--eV<,,T-=-=eY-OP!--e\B
,#*L"ll4+;+;E=+QSYZ#||D,<,<UO,TV\]#//y,O!\\$*<*<UDTVc*dflm
 $T^^D<L<LUT_<`-aci j ,$(LL1A1A%1UW]$^Mf~*.*A*A$BRBRSXZgBh*i#vv>+373C3CDJ^3_0.2.E.EFZ.[O$($4$4UI$FM$0*.%%+C
 "Y/( " 
  	r  c                    S nSU0nU R                  US/ 5      n[        S[        U5      5       GH  nXE   nU R                  US5      nU R	                  U5      nU R                  U R
                  U0 5      n	U R                  U	SS5      n
U R                  5       nU R                  US5      nU R                  US5      nU R                  US	5      nU R                  X5      nU R                  X5      nU R                  X5      n[        R                  " UU5      nU R                  US
S5      nUc  UO[        UU5      nXS'   UUS'   XU'   GM     X#S'   U R                  U5      US'   U R                  U5      $ )Nr  r  r   r  r     	balanceEvlockedTradingBalanceEvlockedWithdrawEvlastUpdateTimeNsrf  totalusedrT  rU  )r  r#  r$  r  r  r  r  accountr  r.   
string_addro  r  rW  safe_balance)r  rD  rT  r2  r  r3  balancer.  r=  r  r|  r:  r4  r5  r6  r8  lockedTradingBalancelockedWithdrawr9  r7  s                       r  parse_spot_balancephemex.parse_spot_balance  s   2 	)x4q#d)$AgG))':>J**:6DtbAH%%ha@EllnG((+>I%)%5%5g?W%X"#//9KLLL2E#'<<0F#N !\\*:BN%%&:NKD#88BTV^_-6->(STdEeI$G"GFO"4L% %& ({!\\)4z  ((r  c                    SU0nU R                  US0 5      nU R                  US0 5      nU R                  US5      nU R                  U5      nU R                  U5      nU R	                  USS5      nU R                  5       n	U R                  USS5      n
U R                  US	S
5      nUS:g  nU(       a  U R                  X5      OU
U	S'   U(       a  U R                  X5      OUU	S'   XU'   U R                  U5      $ )Nr  r  r:  r  r  r3  accountBalanceEvaccountBalanceRvtotalUsedBalanceEvtotalUsedBalanceRvr  r8  r9  )	r  r  r  r  r  r:  r  r  r<  )r  rD  r2  r  r=  r.  r=  r  r  r:  rC  rE  needsConversions                r  parse_swap_balancephemex.parse_swap_balance  s   > )x4//$	26%%gz:
&&z2==&&&xqA
,,.--g7IK]^!//9MOcd6>IX4<<(8E^nJY$,,'9F_qt  ((r  c                   #    U R                  5       I Sh  vN   SnU R                  SSU5      u  p!U R                  US5      nU R                  US/5      nSn0 nUS:w  a$  US:w  a  [	        U R
                  S-   U-   S-   5      eUS:X  a  SnU R                  USSS	5      u  paUc  Ub~  SnUb  UnOUnU R                  U5      nUS
   US'   US
   S	:X  a)  U R                  U R                  XQ5      5      I Sh  vN nOU R                  U R                  XQ5      5      I Sh  vN nOU R                  US5      nUc  [        U R
                  S-   U-   S-   5      eU R                  U R                  XQ5      5      I Sh  vN nO(U R                  U R                  XQ5      5      I Sh  vN nUS:X  a  U R                  U5      $ U R                  U5      $  GN N N N\ N57f)at  
query for balance and get the amount of funds available for trading or funds locked in orders

https://phemex-docs.github.io/#query-wallets
https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#query-account-positions
https://phemex-docs.github.io/#query-trading-account-and-positions

:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.type]: spot or swap
:param str [params.code]: *swap only* currency code of the balance to query(USD, USDT, etc), default is USDT
:returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
NrQ   r=  rA   rC   z does not support z markets, only spot and swapr  r  r4   r  zP fetchBalance() requires a code parameter or a currency or settle parameter for z type)rj  r  r  r  r$   r4   handle_option_and_paramsr  #privateGetGAccountsAccountPositionsr%  "privateGetAccountsAccountPositionsr#   privateGetSpotWalletsrH  r@  )	r  r'  r  r=  rD  rp  r  coinr  s	            r  fetch_balancephemex.fetch_balance  s     !!!99.$PVW/6F8,FNTWW';;dBEccdd6>F!::6>S[]cdNF6#5#D!D==.&.tn
#D>V+%)%M%MdkkZaNj%kkH%)%L%LT[[Y`Mi%jjH++FJ?#+DGG  7I  -I  LP  -P  SZ  -Z  [  [!%!;!;DKK<X!YY!77G8TUUHl 6>**844&&x00m 	"*  lj
 ZUsY   GGC!G8G9(G!G"AG=G>(G&G'-GGGGGr  c                     0 SS_SS_SS_SS_SS_S	S_S
S_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS0EnU R                  X!U5      $ )NCreatedr  UntriggeredDeactivatedclosed	TriggeredRejectedrejectedNewPartiallyFilledFilledCanceledcanceled	Suspendedr  r  34567r  r  r  r  statusess      r  parse_order_statusphemex.parse_order_status  s    
v
6
 8
 	

 

 6
 v
 h
 

 
 
 
 
 
 
  !
" #
$ %
( &99r  r  c                 D    SSSSSSSSSSSSS.nU R                  X!U5      $ )Nr  r   stop	stopLimit)r  r  r`  ra  rb  rc  rd  r  910Limitr   re  )r  r  typess      r  r#  phemex.parse_order_type  sB    
 T22r  r   c                 4    SSSSS.nU R                  X!U5      $ )NGTCr   r   r   )GoodTillCancelPostOnlyImmediateOrCancel
FillOrKillre  )r  r   timeInForcess      r  parse_time_in_forcephemex.parse_time_in_force  s*    #!&	
 ;GGr  r  c           
      b   U R                  US5      nU R                  US5      nUb  [        U5      S:  a  S nU R                  US5      nU R                  XR5      nUS   nU R                  U R                  US5      U5      nU R	                  U R                  US5      U5      nU R                  U R	                  U R                  US5      U5      5      n	U R	                  U R                  USS	5      U5      n
U R                  U R                  US
S5      U5      nU R                  U R                  US5      U5      nU R                  U R                  US5      5      nU R                  US5      nU R                  U R                  US5      5      nU R                  USSS5      nS nU R	                  U R                  US5      U5      nUb$  UU R                  U R                  US5      5      S.nU R                  U R                  US5      5      nU R                  U R                  U R                  U R                  US5      5      5      5      nUS:H  nU R                  0 SU_SU_SU_SU_SU R!                  U5      _SS _SU_SU_SU_S U_SU_S!U_S"U_S#U_S$U_S%U_S&U
_U	UUS S'.EU5      $ )(Nr  clOrdIDr   r  priceEp	baseQtyEvleavesBaseQtyEvcumBaseQtyEvcumBaseValueEvcumQuoteValueEv
quoteQtyEv
avgPriceEp	ordStatusr]  r  actionTimeNscreateTimeNsrf  cumFeeEvr  r  r  r   stopPxEpr   r  r4   clientOrderIdrT  rU  lastTradeTimestampr  postOnlyr   r   r  r  r  filled)	remainingr  r?  r  )r  r$  r  rM  rL  r"  r  r  rh  r
  r#  safe_integer_product_2r  ry  r  
safe_orderrW  )r  r  r  r4   r  r  r  r   r  r  r  r  r  r  r]  r  rT  r?  feeCostr   r   r  s                         r  parse_spot_orderphemex.parse_spot_order  s6   r eY/((	:%C,>,B M##E84!!(3!T--eY?Hd..ukBFKNN4<<0@0@HY0Z\b#cd	d00HXY[ab||D..u6GVX^_,,t//|DfM(()9)9%)MN%%eV4$$T%5%5eY%GH//~~W_`	,,t//zBFK 33D4D4DUM4Z[C ..t/?/?}/UV((TEUEUV[]gEh8i)jk4'  
E 
" 
 ] 
 	 

 Y/ 
 !$ 
 f 
 D 
 ; 
  
 D 
 U 
 L 
 f 
 D 
  w! 
" f# 
$ #+ 
, - 	r  c                 0    SSS.nU R                  X!U5      $ )Nr  r  )r  r  re  )r  r]  r\  s      r  parse_order_sidephemex.parse_order_side/	  s$    
 T22r  c                    U R                  USS5      nU R                  USS5      nUb  [        U5      S:  a  S nU R                  US5      nU R                  XR5      nU R	                  XR5      nU R                  U R                  US5      5      nU R                  U R                  US5      5      nU R                  U R                  US	5      5      n	U R                  US
5      n
U
c"  U R                  U R                  US5      U5      n
U R                  USS5      nU R                  USS5      nU R                  USS5      nU R                  USS5      nUc  U R                  US5      nU R                  USS5      nU R                  USS5      nUS:X  a  S nU R                  U R                  US5      5      nU R                  U R                  USS5      5      nUS:H  nU R                  US5      nU R                  US5      nUS:X  a  S nU R                  US!5      nU R                  US"5      nU R                  U R                  US#5      5      nU R                  U R                  US$5      5      nS nUb	  UUS%   S&.nOUb  US'S&.nU R!                  0 S(U_S)U_S*U_S+U R#                  U5      _S,U_S-U_SU_S.U	_SU_S/U_SU_SU_S0U
_S1U_S2U_S3U_S4U_UUUS UUS S5.E5      $ )6Nr  r)  r|  clOrdIdr   r  r  r]  	orderTypepriceRpr}  orderQty
orderQtyRqcumQtycumQtyRq	leavesQtyleavesQtyRqr  rf  r  cumValue
cumValueRvr   r   r   stopPxstopPxRpr   
reduceOnlyexecInst
ReduceOnlyTtakeProfitRp
stopLossRpr  r  r  r  r  r  r4   r  rU  rT  r  r  r  r   r   r   r   r  )r  r  r  r  r  r?  r  )r  r$  r  safe_symbolr  rh  r  r
  r#  rM  r  ro  r  ry  r"  r  r  rW  )r  r  r  r4   r  r  r  r  r]  r  r   r  r  r  rT  r  r  r   r   r  r  r  
takeProfitstopLossfeeValuer  r?  s                              r  parse_swap_orderphemex.parse_swap_order6	  s   L y)<**5)YG%C,>,B M##E84!!(3!!(3(()9)9%)MN$$T%;%;E6%JK$$T%5%5e[%IJ  	2=LL!1!1%!CVLE##E:|D##E8Z@&&uk=I	--e^XN	))%=I!!%\B!66u>NPXY"!%..t/?/?}/UV~~d&8&8*&UV4'__UL9
##E:6|#J%%e^<
##E<8>>$"2"25+"FG..!1!1%!CD "7OC   C   
E 
" 
 ] 
 Y/	 

  
 !"4 
 f 
 D 
 ; 
  
 * 
 D 
 U 
 L 
 z 
  X! 
" f# 
$ "1 
  	r  c                     U R                  USS5      nSU;   =(       d    SU;   =(       d    SU;   nU(       d  U(       a  U R                  X5      $ U R                  X5      $ )NrC   F	closedPnlclosedPnlRv
totalPnlRv)	safe_boolr  r  )r  r  r  isSwaphasPnls        r  parse_orderphemex.parse_order	  sZ    6&^MU,B^X]H]V((77$$U33r  r]  r  r   c                 .  #    U R                  5       I Sh  vN   U R                  U5      nU R                  U5      nU R                  U5      nUS   UUS.n	U R                  USS5      n
U R	                  US5      nUSLnU R	                  US5      nUSLnUS   S	:H  =(       d    US   S
:H  nU
c7  U R                  U R                  SS5      nUb  UU R                  5       -   U	S'   OXS'   U R                  USS/5      nU R                  U/ SQ5      nUb2  U(       a  U R                  UU5      U	S'   OU R                  UU5      U	S'   U R                  U/ SQ5      nUS   (       GaR  U R	                  USS5      nUS:X  d  US:X  d  US:X  a  Ub  SnUb  US:X  a  SU	S'   OUS:X  a  SU	S'   SU	S'   UU	S'   US:X  a  U R                  US5      nU R                  US5      nU R                  S   (       ao  UbK  U R                  U5      nU R                  U5      n[        R                  " UU5      nU R!                  U5      nO!Uc  [#        U R$                  S-   U-   S -   5      eUc  UOUnU R                  U5      nU R'                  UU5      U	S!'   GOCU R                  U5      nU R'                  UU5      U	S"'   GOUS#   (       Ga  U R)                  US$S%5      nU R                  US$5      nU R+                  US&5      nUcI  U(       a@  U R)                  US'5      nU(       a  US(:X  a  S)OS(nU R                  US'5      nUS(:X  a  S*OS+nOS,nU R                  U5      nUU	S&'   U(       a  XIS-'   OU R-                  U5      U	S.'   Ub  U R                  US/S05      nUU	S/'   SnU R/                  US15      u  nnUc  [#        U R$                  S2-   5      eUS3:X  d  US4:X  a(  US):X  a  US:X  a  SOS5U	S'   OGUS(:X  a  US:X  a  SOSU	S'   O3US6:X  d  US7:X  a'  US):X  a  US:X  a  SOSU	S'   OUS(:X  a  US:X  a  SOS5U	S'   U(       d  U(       Ga  U(       a  U R1                  US8S95      nUc  [3        U R$                  S:-   5      eU(       a  U R                  UU5      U	S;'   OU R                  UU5      U	S<'   U R                  US=S>5      nUb#  U R                  U R                  S?   UU5      U	S>'   U R                  US@5      nUb  U R                  UU5      U	SA'   U(       a  U R1                  US8S95      n U c  [3        U R$                  SB-   5      eU(       a  U R                  UU 5      U	SC'   OU R                  U U5      U	SD'   U R                  US=SE5      n!U!b#  U R                  U R                  S?   U!U!5      U	SE'   U R                  US@5      n"U"b  U R                  UU"5      U	SF'   US:X  d  US:X  d  US5:X  aB  U(       a  U R                  X5      U	SG'   O&U R                  U5      nU R                  UU5      U	SH'   U R                  USI5      n#U#bD  U(       a  U R                  UU#5      U	SC'   OU R                  U#U5      U	SD'   U R                  USI5      nU R                  USJ5      n$U$bD  U(       a  U R                  UU$5      U	S;'   OU R                  U$U5      U	S<'   U R                  USJ5      nSn%U(       a)  U R5                  U R7                  X5      5      I Sh  vN n%O[USK   (       a)  U R9                  U R7                  X5      5      I Sh  vN n%O(U R;                  U R7                  X5      5      I Sh  vN n%U R=                  U%SL0 5      n&U R?                  U&U5      $  GNv N NW N07f)Ma  
create a trade order

https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#place-order
https://phemex-docs.github.io/#place-order-http-put-prefered-3

:param str symbol: unified symbol of the market to create an order in
:param str type: 'market' or 'limit'
:param str side: 'buy' or 'sell'
:param float amount: how much of currency you want to trade in units of base currency
:param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
:param dict [params]: extra parameters specific to the exchange API endpoint
:param float [params.trigger]: trigger price for conditional orders
:param dict [params.takeProfit]: *swap only* *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered(perpetual swap markets only)
:param float [params.takeProfit.triggerPrice]: take profit trigger price
:param dict [params.stopLoss]: *swap only* *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered(perpetual swap markets only)
:param float [params.stopLoss.triggerPrice]: stop loss trigger price
:param str [params.posSide]: *swap only* "Merged" for one way mode, "Long" for buy side of hedged mode, "Short" for sell side of hedged mode
:param bool [params.hedged]: *swap only* True for hedged mode, False for one way mode, default is False
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
Nr4   )r  r]  r  r|  r  r  r  r  r  r  r  r  )r  	stopPricer   r  r  )r  r  r  r  r   rA   qtyTypeByBaser   StopMarketIfTouchedByQuotero  	StopLimitr  r  r   r  r  z createOrder() z. requires a price argument or a cost parameterr  r~  rC   r   FposSider  r  r  LongShortMergedr  r  triggerTyper  r   zi createOrder() also requires a 'triggerDirection' parameter with either 'ascending' or 'descending' value	ascendingupLimitIfTouched
descendingdownr   r  zc createOrder() requires a trigger price in params["stopLoss"]["triggerPrice"] for a stop loss orderr  
stopLossEpr   	slTriggerr  r   slPxRpzg createOrder() requires a trigger price in params["takeProfit"]["triggerPrice"] for a take profit orderr  takeProfitEp	tpTriggertpPxRpr  r}  r   r   r  r  ) rj  r  
capitalizer  r  r  r  uuid16r  safe_string_nprice_to_precisionr  r  rv  r.   rB  r  r#   r4   r  r  r
  r  handle_param_stringrn  r'   privatePostGOrdersr%  privatePostOrdersprivatePostSpotOrdersr  r  )'r  r  r  r]  r  r   r'  r  requestSiderp  r  r  stopLossDefinedr  takeProfitDefinedrq  r  r   r  r  r,  r+  quoteAmountr%  r   r  r  r  r   stopLossTriggerPricestopLossTriggerPriceTypeslLimitPricetakeProfitTriggerPricetakeProfitTriggerPriceTypetpLimitPricer   r   rD  r  s'                                          r  create_orderphemex.create_order	  s'    , !!!V$ood+t$ Tl	
8 **69oN??6:6#4/__V\:
't3!(+v5V6(;Kv;U ''j,OH#%-%=	"!.IYYv	?'CDF))&2YZ#&*&=&=fl&S
#&*jjv&F
#6#de&>>oofiBG dfn$BS:S$'G'7?)4GI&X%)/GI&%2	"!(GI)#''7662<< AB('+'<'<V'D&*&;&;E&B&-&8&8{&S#00=/:K0Kg0U  YI  1I  J  J"&,vT!2248
(,

:v(F%#44V<'+zz,'G$F^^^^FHe<FYYvx0F,,VY?G!%!EJ!*.%-ve!%6<!@)-fWG&Goog.G!(GI(.%&*&7&7&?
#'"..v}mT)4&#' +/+C+CFL^+_( &#++DGG  7b  -b  c  c#{26F$6Nv~CG8CS->Zj	*8<8HV{	*%59IV9Sv~8<8HV{	*CG8CS->Zj	*"3"+/+<+<X~Wb+c(+3*477  6[  ,[  \  \&040G0GPd0e-04

;OQW0X-/3/A/A(L^`k/l,/;/3/?/?Mc@df~  AY  0Z,#'#3#3Hg#FL#/,0,C,CFL,Y)$-1->->z>[f-g*-5*477  6_  ,_  `  `&262I2I&Rh2i/26**=SU[2\/151C1CJPbdo1p.1=/3/?/?Mc@d  gA  C]  0^,#'#3#3J#HL#/,0,C,CFL,Y)GO!4$BR:R%)%<%<V%K	""33E:%)ZZV%D	"**63DE&*.*A*A&/*Z'*.**_f*M'YYv'89F((A$(,(?(?(V%(,

=&(I%YYv7F!44T[[5QRRHJ!33DKK4PQQH!77G8TUUHZ ~~h3f--y 	"T SQUsF   ^^[/^^2^9^:(^"^#*^^^^r4   c                   #    U R                  5       I Sh  vN   U R                  U5      nSUS   0n	U R                  USS5      n
U R                  USS/5      nUS   S:H  =(       d    US   S:H  nU
b  XS'   OXS	'   Ub4  U(       a  U R	                  US   U5      U	S
'   OU R                  Xh5      U	S'   U R                  US5      nU R                  US/5      nUb  XS'   O7Ub4  U(       a  U R                  US   U5      U	S'   OU R                  XX5      U	S'   U R                  U/ SQ5      nUb0  U(       a  U R	                  X-5      U	S'   OU R                  X5      U	S'   U R                  U/ SQ5      nSnU(       aC  U R                  US5      nUc  SU	S'   U R                  U R                  X5      5      I Sh  vN nO[US   (       a)  U R                  U R                  X5      5      I Sh  vN nO(U R                  U R                  X5      5      I Sh  vN nU R                  US0 5      nU R                  UU5      $  GN) N NW N07f)a  
edit a trade order

https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#amend-order-by-orderid

:param str id: cancel order id
:param str symbol: unified symbol of the market to create an order in
:param str type: 'market' or 'limit'
:param str side: 'buy' or 'sell'
:param float amount: how much of currency you want to trade in units of base currency
:param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.posSide]: either 'Merged' or 'Long' or 'Short'
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
Nr  r4   r  r|  r  r  r  r  r  r}  r~  	baseQtyEVr  )r   r  r  r  r  r  r  rC   r  )rj  r  r  r  r  r  r  amount_to_precisionr  r  privatePutGOrdersReplacer%  privatePutOrdersReplaceprivatePutSpotOrdersr  r  )r  r4   r  r  r]  r  r   r'  r  rp  r  rq  finalQtyr   rD  r  r  s                    r  
edit_orderphemex.edit_order
  sJ      !!!V$fTl
 **6?IN6OY#?@!(+v5V6(;Kv;U$!.I!#I%)%<%<VH=Mu%U	"%)ZZ%>	"##FK86K=1#+K (,(@(@AQSY(Z%'+zz&'A$))&2YZ#&*&=&=f&S
#&*jj&F
#6#JK&&vy9G%-	"!::4;;w;WXXHF^!99$++g:VWWH!66t{{77STTH~~h3f--[ 	"N YWTsF   IH?F"I9I:2I,I-(II*IIIIc                   #    Uc  [        U R                  S-   5      eU R                  5       I Sh  vN   U R                  U5      nSUS   0nU R	                  USS5      nU R                  USS/5      nUb  XeS'   OXS'   SnUS   S	:X  d	  US   S
:X  aC  U R                  US5      nUc  SUS'   U R                  U R                  XS5      5      I Sh  vN nO[US   (       a)  U R                  U R                  XS5      5      I Sh  vN nO(U R                  U R                  XS5      5      I Sh  vN nU R                  US0 5      n	U R                  X5      $  GN& N NV N/7f)a  
cancels an open order

https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#cancel-single-order-by-orderid

:param str id: order id
:param str symbol: unified symbol of the market the order was made in
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.posSide]: either 'Merged' or 'Long' or 'Short'
:returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
Nz) cancelOrder() requires a symbol argumentr  r4   r  r|  r  r  r  r  r  r  rC   r  )r#   r4   rj  r  r  r  r  privateDeleteGOrdersCancelr%  privateDeleteOrdersCancelprivateDeleteSpotOrdersr  r  )
r  r4   r  r'  r  rp  r  rD  r  r  s
             r  cancel_orderphemex.cancel_order>  s`     >#DGG.Y$YZZ!!!V$fTl
 **6?IN6OY#?@$!.I!#I(v%)9V)C&&vy9G%-	"!<<T[[=YZZHF^!;;DKK<XYYH!99$++g:VWWH~~h3--- 	"  [YWsF   /E EB E E2E E(E .E/)E E E E c                 n  #    Uc  [        U R                  S-   5      eU R                  5       I Sh  vN   U R                  U5      nU R	                  USSS5      nU R                  USS/5      nSUS   0nU(       a  XES'   SnUS	   S
:X  d	  US	   S:X  a)  U R                  U R                  XR5      5      I Sh  vN nO[US   (       a)  U R                  U R                  XR5      5      I Sh  vN nO(U R                  U R                  XR5      5      I Sh  vN nU R                  SU05      /$  N Nv NE N7f)ay  
cancel all open orders in a market

https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#cancelall

:param str symbol: unified market symbol of the market to cancel orders in
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
Nz- cancelAllOrders() requires a symbol argumentrk  r   Fr  r4   untriggerredr  r  r  rC   r  )r#   r4   rj  r  rn  r  privateDeleteGOrdersAllr%  privateDeleteOrdersAllprivateDeleteSpotOrdersAllr  )r  r  r'  r  r   rp  rD  s          r  cancel_all_ordersphemex.cancel_all_ordersd  s@     >#DGG.]$]^^!!!V$##FFIuE6FI#67fTl

 &-N#(v%)9V)C!99$++g:VWWH F^!88W9UVVH "<<T[[=YZZH OO 
 	
S 	" X W [sF   /D5D-BD58D/92D5+D1,(D5D3D5/D51D53D5c                   #    Uc  [        U R                  S-   5      eU R                  5       I Sh  vN   U R                  U5      nSUS   0nU R	                  USS5      nU R                  USS/5      nUb  XeS'   OXS'   SnUS   S	:X  d	  US   S
:X  a)  U R                  U R                  XS5      5      I Sh  vN nO[US   (       a)  U R                  U R                  XS5      5      I Sh  vN nO(U R                  U R                  XS5      5      I Sh  vN nU R                  US0 5      nUn	[        U[        5      (       ap  [        U5      n
U
S:  aK  Ub$  [        U R                  S-   U-   S-   U-   S-   5      e[        U R                  S-   U-   S-   U-   S-   5      eU R                  US0 5      n	O0US   (       a&  U R!                  US/ 5      nU R                  US0 5      n	U R#                  X5      $  GN GN? GN N7f)ah  

https://phemex-docs.github.io/#query-orders-by-ids

fetches information on an order made by the user
:param str id: the order id
:param str symbol: unified symbol of the market the order was made in
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
Nz( fetchOrder() requires a symbol argumentr  r4   r  r|  r  r  r  r  rA   r  r   z fetchOrder() z order with clientOrderId z
 not foundz order with id r   r  )r#   r4   rj  r  r  r  (privateGetApiDataGFuturesOrdersByOrderIdr%  %privateGetApiDataSpotsOrdersByOrderIdprivateGetExchangeOrderr  r  r  r$  r(   r  r   r  )r  r4   r  r'  r  rp  r  rD  r  r  	numOrdersr  s               r  fetch_orderphemex.fetch_order  s     >#DGG.X$XYY!!!V$fTl
 **6?IN6OY#?@$!.I!#I(v%)9V)C!JJ4;;W^KghhHF^!GGT[HdeeH!99$++g:VWWHx4dD!!D	I1} ,'2B(BV(KNj(jmz(z  ~J  )J  K  K'2B(BV(KN_(_bd(dgs(sttNN4B/EF^>>$3DNN4B/E..? 	" ieWsG   /G?G4BG?8G792G?+G:,(G?G=C G?7G?:G?=G?c                 ~  #    Uc  [        U R                  S-   5      eU R                  5       I Sh  vN   U R                  U5      nSUS   0nUb  X&S'   Ub  X6S'   SnUS   S:X  d	  US   S	:X  a1  US   US
'   U R	                  U R                  Xd5      5      I Sh  vN nO[US   (       a)  U R                  U R                  Xd5      5      I Sh  vN nO(U R                  U R                  Xd5      5      I Sh  vN nU R                  US0 5      nU R                  USU5      n	U R                  XX#5      $  GN N Nj NC7f)a  
fetches information on multiple orders made by the user

https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#queryorder

:param str symbol: unified market symbol of the market orders were made in
:param int [since]: the earliest time in ms to fetch orders for
:param int [limit]: the maximum number of order structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
Nz) fetchOrders() requires a symbol argumentr  r4   startr   r  r  r  r  rC   r  r  )r#   r4   rj  r  "privateGetExchangeOrderV2OrderListr%  privateGetExchangeOrderListprivateGetApiDataSpotsOrdersr  r   parse_orders
r  r  r  r   r'  r  rp  rD  r  r  s
             r  fetch_ordersphemex.fetch_orders  s@     >#DGG.Y$YZZ!!!V$fTl
 $G$G(v%)9V)C"("2GJ!DDT[[QXEabbHF^!==dkk'>Z[[H!>>t{{7?[\\Hx4~~dFD1  u<<' 	" c[\sF   /D=D4A)D=D72D=D9(D=7D;8=D=7D=9D=;D=c                 :  #    U R                  5       I Sh  vN   Uc  [        U R                  S-   5      eU R                  5       I Sh  vN   U R                  U5      nSUS   0nSn US   S:X  d	  US   S:X  a)  U R	                  U R                  Xd5      5      I Sh  vN nO\US   (       a)  U R                  U R                  Xd5      5      I Sh  vN nO)U R                  U R                  Xd5      5      I Sh  vN n U R                  US	0 5      n	[        U	[        5      (       a  U R                  XX#5      $ U R                  U	S
/ 5      n
U R                  XX#5      $  GNI GN N N Nn! [         a#  n[        U[        5      (       a  / s SnA$ UeSnAff = f7f)a  
fetch all unfilled currently open orders

https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#queryopenorder
https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md
https://github.com/phemex/phemex-api-docs/blob/master/Public-Spot-API-en.md#spotListAllOpenOrder

:param str symbol: unified market symbol
:param int [since]: the earliest time in ms to fetch open orders for
:param int [limit]: the maximum number of open order structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
Nz- fetchOpenOrders() requires a symbol argumentr  r4   r  r  r  rC   r  r  )rj  r#   r4   r  privateGetGOrdersActiveListr%  privateGetOrdersActiveListprivateGetSpotOrders	Exceptionr  r(   r  r  r  r   )r  r  r  r   r'  r  rp  rD  er  r  s              r  fetch_open_ordersphemex.fetch_open_orders  sx     !!!>#DGG.]$]^^!!!V$fTl
 
	h6)VH-=-G!%!A!A$++gB^!__!%!@!@WA]!^^!%!:!:4;;w;W!XX
 x4dD!!$$T5@@>>$3D$$T5@@3 	" 	" `^X 	!]++	G	s   FE2F	E"
F)5E+ E%E+ #F$-E+ E'E+ F#E+ :E);E+ ?A!F"F%E+ 'E+ )E+ +
F5FFFFFFc                   #    U R                  5       I Sh  vN   SnUb  U R                  U5      n0 nUb  US   US'   Ub  X&S'   Ub  X6S'   SnUb  U R                  US5      S:X  a?  U R                  USS5      US'   U R                  U R	                  Xd5      5      I Sh  vN nO[US	   (       a)  U R                  U R	                  Xd5      5      I Sh  vN nO(U R                  U R	                  Xd5      5      I Sh  vN nU R                  US
0 5      n[        U[        5      (       a  U R                  XX#5      $ U R                  US/ 5      n	U R                  XX#5      $  GNJ N N Nj7f)a  
fetches information on multiple closed orders made by the user

https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#queryorder
https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md#queryorder
https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedgedd-Perpetual-API.md#query-closed-orders-by-symbol
https://github.com/phemex/phemex-api-docs/blob/master/Public-Spot-API-en.md#spotDataOrdersByIds

:param str symbol: unified market symbol of the market orders were made in
:param int [since]: the earliest time in ms to fetch orders for
:param int [limit]: the maximum number of order structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.settle]: the settlement currency to fetch orders for
:returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
Nr4   r  r  r   r  r  r  rC   r  r  )rj  r  r  r  r%  r  privateGetExchangeSpotOrderr  r  r  r  r   r	  s
             r  fetch_closed_ordersphemex.fetch_closed_orders  sh      !!![[(F
 &tGH$G$GN 0 0 Bf L"&"2"268V"LGJ!DDT[[QXEabbHF^!==dkk'>Z[[H!==dkk'>Z[[HJ x4dD!!$$T5@@>>$3D$$T5@@{ 	" c[[sG   E)E B	E) E#!2E)E%(E)<E'=A$E)#E)%E)'E)c                 D  #    U R                  5       I Sh  vN   SnUb  U R                  U5      nSnU R                  SXT5      u  pd0 nUb  [        SU5      nX7S'   US:g  =(       a     USL =(       d    U R	                  US5      S:H  nU(       a  SUS'   S	US
'   Uc  SUS'   OUb  US   US'   Ub  X'S'   Sn	U(       a)  U R                  U R                  Xt5      5      I Sh  vN n	O\US:X  a.  SUS'   U R                  U R                  Xt5      5      I Sh  vN n	O(U R                  U R                  Xt5      5      I Sh  vN n	Sn
U(       a  U R                  U	S/ 5      n
O&U R                  U	S0 5      n
U R                  U
S/ 5      n
U R                  XX#5      $  GN N N N`7f)a  
fetch all trades made by the user

https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md#query-user-trade
https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#query-user-trade
https://github.com/phemex/phemex-api-docs/blob/master/Public-Spot-API-en.md#spotDataTradesHist

:param str symbol: unified market symbol
:param int [since]: the earliest time in ms to fetch trades for
:param int [limit]: the maximum number of trades structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
Nrm   r   r   rA   r  r  r  r   offsetr4   r  r  rC   r   	tradeTyper  r  )rj  r  r  r  r  $privateGetExchangeOrderV2TradingListr%  privateGetExchangeOrderTrade!privateGetExchangeSpotOrderTradesr  r  )r  r  r  r   r'  r  r  rp  isUSDTSettledrD  r  s              r  fetch_my_tradesphemex.fetch_my_tradesh  s     !!![[(F99/6ZUOE$Gqv~.p4CSCSTZ\dCeioCo"(GJ !GH}#&  &tGH$G!FFt{{SZGcddHV^#*GK !>>t{{7?[\\H!CCDKKPWD`aaHR ??8VR8D??8VR8D??44D  u<<U 	", e ]asG   F FC	F  F!3F F(F =F>AF F F F r=  c                   #    U R                  5       I Sh  vN   U R                  U5      nSUS   0nU R                  U R                  S5      nU R	                  XQ5      nU R                  U R                  S0 5      nU R                  USSU5      nU R                  XxU5      nUc  [        U R                  S-   5      eXS'   U R                  US5      nU R                  U R                  XB5      5      I Sh  vN n	U R                  U	S	0 5      n
U R                  U
S
5      nU R                  U
S5      nU R                  U5        U	USUUS.$  GN6 NW7f)ax  
fetch the deposit address for a currency associated with self account
:param str code: unified currency code
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.network]: the chain name to fetch the deposit address e.g. ETH, TRX, EOS, SOL, etc.
:returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
Nr  r4   r  r  network	chainNamez3 fetchDepositAddress() requires a network parameterr  addresstag)r  r  r"  r$  r%  )rj  r  r  r  safe_string_uppersafe_string_upper_2r  r#   r4   r  )privateGetExchangeWalletsV2DepositAddressr%  r  check_address)r  r=  r'  r  rp  r  defaultNetworkr  r"  rD  r  r$  r%  s                r  fetch_deposit_addressphemex.fetch_deposit_address  sV     !!!==&
 ..7HI//F>>$,,
B?**69k>Z""8g>?#DGG.c$cdd#*K YYvy1FGGT[Hdee  x4""43tU+7#
 	
G 	" fs#   EEC E7E8AEEc                    #    U R                  5       I Sh  vN   SnUb  U R                  U5      nU R                  U5      I Sh  vN nU R                  US/ 5      nU R	                  XuX#5      $  NX N+7f)a  
fetch all deposits made to an account
:param str code: unified currency code
:param int [since]: the earliest time in ms to fetch deposits for
:param int [limit]: the maximum number of deposits structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
Nr  )rj  r  $privateGetExchangeWalletsDepositListr   parse_transactionsr  r=  r  r   r'  r  rD  r  s           r  fetch_depositsphemex.fetch_deposits5  sw      !!!}}T*HBB6JJ* ~~h3&&tuDD5 	" K!   A3A/.A3A1*A31A3c                    #    U R                  5       I Sh  vN   SnUb  U R                  U5      nU R                  U5      I Sh  vN nU R                  US/ 5      nU R	                  XuX#5      $  NX N+7f)a  
fetch all withdrawals made from an account
:param str code: unified currency code
:param int [since]: the earliest time in ms to fetch withdrawals for
:param int [limit]: the maximum number of withdrawals structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
Nr  )rj  r  %privateGetExchangeWalletsWithdrawListr   r/  r0  s           r  fetch_withdrawalsphemex.fetch_withdrawalsZ  sw      !!!}}T*HCCFKK* ~~h3&&tuDD5 	" Lr3  c                 J    SSSSSSSSSSSSSSSS.nU R                  X!U5      $ )Nokfailedpendingr^  )SuccessSucceedrX  zSecurity check failedSecurityCheckFailedExpiredzAddress RiskzSecurity CheckingSecurityCheckingzPending ReviewzPending TransferAmlCsApporverZ  	Confirmed	Cancelledre  rf  s      r  parse_transaction_statusphemex.parse_transaction_status  sK     %-#+$!* )' )%"#
" &99r  transactionr  c                 b   U R                  US5      nU R                  US5      nS nU R                  US5      nU R                  US5      nU R                  Xr5      nUS   nU R                  US5      n	U R                  U/ SQ5      n
U R                  US5      nU R	                  U R                  U R                  US	5      US
   5      5      nUc  U R                  US5      nS nUb  SnUUS.nU R                  U R                  US5      5      nU R	                  U R                  U R                  US5      US
   5      5      nUc  U R                  US5      n0 SU_SU_SU_SU
_SU R                  U
5      _SU R                  U	5      _SU_SU_SS _SU_SU_SS _SU_SU_SU_SU_SS _S S US.E$ )Nr4   r$  txHashr  r=  r#  )r  
submitedAtsubmittedAtr  feeEvr  feeRv
withdrawalr  r  amountEvamountRvr  txidrT  rU  r"  	addressToaddressFromr%  tagTotagFromr  updated)commentinternalr?  )
r  safe_currencysafe_integer_nr
  r  r  r  rD  rW  network_id_to_code)r  rF  r  r4   r$  r%  rP  r.  r=  	networkIdrT  r  r  r?  r  r  s                   r  parse_transactionphemex.parse_transaction  sa   H k40"";	:X6%%k:>
%%j;$$[+>	''5_`	%%k6:##DLL1A1A+w1WYabnYo$pq?&&{G<GD C ..t/?/?X/VW""4<<0@0@j0Y[cdp[q#rs>%%k:>F
K
"
 D
 	

 Y/
 t..y9
 w
 
 4
 3
 S
 t
 D
 f
 
  f!
" t#
$ )
 	
r  c                 6  #    U R                  5       I Sh  vN   U R                  U5      nSnU R                  USSS5      nU R                  USS/5      nSnSnU R	                  US5      nUb  U R                  U5      nUS   nUS   nOU R                  USSU5      u  pRU R                  SXb5      u  p2US:H  nU(       a  SnOUS:X  a  SnOUc
  US	:X  a  S
OSnU R                  U5      n	SU	S   0n
SnU(       ap  SnU R                  USSS5      u  pUS:X  a)  U R                  U R                  X5      5      I Sh  vN nOQU R                  U R                  X5      5      I Sh  vN nO(U R                  U R                  X5      5      I Sh  vN nU R                  US0 5      nU R                  US/ 5      n/ n[        S[        U5      5       H(  nUU   nUR!                  U R#                  U5      5        M*     U R%                  USUS5      $  GN N N N7f)aI  
fetch all open positions

https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md#query-trading-account-and-positions
https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#query-account-positions
https://phemex-docs.github.io/#query-account-positions-with-unrealized-pnl

:param str[] [symbols]: list of unified market symbols
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.code]: the currency code to fetch positions for, USD, BTC or USDT, USDT is the default
:param str [params.method]: *USDT contracts only* 'privateGetGAccountsAccountPositions' or 'privateGetGAccountsAccountPositions' default is 'privateGetGAccountsAccountPositions'
:returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
Nr  r=  r  r   r  rt   BTCr   r  r4   methodrL  r  	positionsr  F)rj  market_symbolsr  r  r  r  rK  r  r  rL  r%  privateGetGAccountsPositionsrM  r  r#  r$  r&  parse_positionfilter_by_array_positions)r  r  r'  r  r=  r  r  firstSymbolr  r  rp  rD  r`  r  ra  r2  r3  positions                     r  fetch_positionsphemex.fetch_positions  s8     !!!%%g.!!&*ffE6J#78&&w2"[[-FH%F(#D!::6CSU]_cdNF99:JF[&(Du_D\$05uD==&
 F!::6CSU]  `E  FNF>>!%!I!I$++V]Jf!gg!%!B!B4;;wC_!``!DDT[[QXEabbHZ x4OOD+r:	q#i.)A |HMM$--h78 * --fhOOm 	"> h`bsG   HHD%H<H=(H%H&(HHBHHHHrg  c                    U R                  US5      nU R                  X25      nUS   nU R                  USS5      nU R                  USS5      nU R                  USS5      n[        R                  " Xg5      nU R                  USS	5      n	[        R
                  " X5      n
U R                  US
S5      nU R                  USS5      nU R                  USS5      nU R                  US5      nU R                  U5      nU R                  [        R                  " U R                  USS5      5      5      nU R                  USS5      nU R                  US5      nS nUb
  US:X  a  SOSnS nUS   (       a6  US:X  a  [        R                  " UU5      nO[        R                  " UU5      nOUS:X  aB  [        R                  " [        R
                  " SU5      [        R
                  " SU5      5      nOA[        R                  " [        R
                  " SU5      [        R
                  " SU5      5      n[        R                  " [        R                  " UU5      U5      nU R                  USU5      n[        R
                  " X5      nU R                  US5      nU R                  0 SU_SU R                  US5      _SU_S U R                  U5      _SU_S!U R                  US"5      _S#U R                  U5      _SU_S
U_S$U R                  U5      _S%U R                  U5      _SU R                  U5      _S&S _S'U R                  U5      _S(S _S)U R                  US*S+5      _S,U R                  U	5      _U R                  U
5      U R                  U5      U R                  U5      U R                  U5      S U(       a  S-OS.UU R                  US/5      S0:H  S S S S1.E5      $ )2Nr  positionMarginpositionMarginRvr  valueRvmaintMarginReqmaintMarginReqRrassignedPosBalanceassignedPosBalanceRvliquidationPriceliquidationPriceRp	markPricemarkPriceRpsizesizeRqr  r   
leverageRravgEntryPriceavgEntryPriceRpr]  Buylongshortr   r  unRealisedPnlRvcrossMarginr  r4   execSeq	contractsrealizedPnlcurTermRealisedPnlRvunrealizedPnl
collateralnotional	lastPrice
entryPricerT  lastUpdateTimestampr   rf  initialMargincrossisolatedposModeHedged)initialMarginPercentagemaintenanceMarginmaintenanceMarginPercentagemarginRatiorU  r   r]  r   r   r   r   )r  r  r  r.   rB  
string_divr  r  rv  r  
string_abs
string_subsafe_positionr  ro  )r  rg  r  r  r  r  notionalString!maintenanceMarginPercentageStringmaintenanceMarginStringinitialMarginStringinitialMarginPercentageStringrr  markPriceStringr  r  r  r   entryPriceStringrawSider]  	priceDiffr  apiUnrealizedPnlr  isCrosss                            r  rd  phemex.parse_position  sT   P ##Hh7!!(3!''2BDVW
++HgyI,0,>,>xIY[m,n)")"4"4^"g"00;OQgh(/(:(:;N(_%--h8JL`a,,X{MR&&xB	v~>!22<@$$W%7%79K9KHV`bn9o%qr--hIZ[""8V4%.6WD
 	(v~#..@PQ	#../?Q	 v~#..w/A/A#GW/XZaZlZlmp  sB  [C  D	#..w/A/A#/WY`YkYklo  rB  ZC  D	**7+=+=i+SUgh++H6GW(()@M//(M:!! #
H#
$""8Y7#
 f#
 **95	#

 L#
 4++H6LM#
 T../?@#
 #
  0#
 $++J7#
 )).9#
 **?;#
 #
 $++,<=#
 #
  "4#<#<XGWYa#b!#
" T../BC##
$ (,'8'89V'W!%!2!23J!K+/+<+<=^+_,,[9%,'*&&x;xG!#9#
  	r  c                   #    Uc  [        U R                  S-   5      eU R                  5       I Sh  vN   U R                  U5      nSUS   0nUb"  US:  a  [	        U R                  S-   5      eX6S'   SnUS   S	:H  =(       d    US   S
:H  nU(       a)  U R                  U R                  Xd5      5      I Sh  vN nO(U R                  U R                  Xd5      5      I Sh  vN nU R                  US0 5      n	U R                  U	S/ 5      n
/ n[        S[        U
5      5       H  nX   nU R                  US5      nU R                  USS5      nU R                  U R                  US5      5      nUR                  UU R                  US5      UUU R!                  U5      SU R#                  XU5      S.5        M     U$  GN GN	 N7f)a/  
fetch the history of funding payments paid and received on self account

https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#futureDataFundingFeesHist

:param str symbol: unified market symbol
:param int [since]: the earliest time in ms to fetch funding history for
:param int [limit]: the maximum number of funding history structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `funding history structure <https://docs.ccxt.com/#/?id=funding-history-structure>`
Nz1 fetchFundingHistory() requires a symbol argumentr  r4   r   z7 fetchFundingHistory() limit argument cannot exceed 200r   r  r  r  r  r  r   
createTimer  r  r  )r  r  r=  rT  rU  r4   r  )r#   r4   rj  r  r$   $privateGetApiDataGFuturesFundingFeesr%  #privateGetApiDataFuturesFundingFeesr  r#  r$  r  r  r  r  r&  rW  parse_funding_fee_to_precision)r  r  r  r   r'  r  rp  rD  rq  r  r  r2  r3  entryrT  execFeecurrencyCodes                    r  fetch_funding_historyphemex.fetch_funding_history  s     >#DGG.a$abb!!!V$fTl

 s{ +d!dee$G *f4Rx8HF8R!FFt{{SZGcddH!EEdkkRYFbccH. x4tVR0q#d)$AGE))%>I(([IG2243C3CE:3VWLMM**5(;$& LL3==g|\  % q 	" ecs5   /GF<BG6F?7(GG CG?GGr  c                     Ub  Uc  U$ US   S:H  =(       d    US   S:H  nU(       dM  U R                  U5      nU R                  US   S5      nU R                  U5      n[        R                  " X5      nU$ )Nr  r  r  r  r  )rX  r  rA  r.   rB  )r  r  r  r  rq  r  r|  tickPrecisions           r  r  %phemex.parse_funding_fee_to_precisiond  s~    =L0L *f4Rx8HF8R)),7H$$Xf%5|DE 007M&&u<Er  c                   #    U R                  5       I Sh  vN   U R                  U5      nUS   (       d  [        U R                  S-   5      eSUS   0n0 nUS   (       d)  U R	                  U R                  XB5      5      I Sh  vN nO(U R                  U R                  XB5      5      I Sh  vN nU R                  US0 5      nU R                  Xc5      $  N NS N,7f)z
fetch the current funding rate
:param str symbol: unified market symbol
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
NrC   z0 fetchFundingRate() supports swap contracts onlyr  r4   r   r2  )	rj  r  r%   r4   r  r%  r  r  parse_funding_rater  s          r  fetch_funding_ratephemex.fetch_funding_ratep  s      !!!V$f~DGG&XXYYfTl
 h!33DKK4PQQH!55dkk'6RSSH0 8R8&&v66I 	" RSs4   CCA-CC(C-C.)CCCc                    U R                  US5      nU R                  X25      nU R                  USS5      nU R                  U R                  US5      U5      nU R                  U R                  US5      U5      nU R	                  U R                  US5      U5      nU R	                  U R                  US5      U5      n	0 SU_SU_S	U R                  US
U5      _SU R                  USU5      _SS _SS _SU_SU R                  U5      _SU R                  USU5      _SS _SS _SU R                  USU	5      _SS _SS _SS _SS _SS _SS 0E$ )Nr  rT  rf  markEpindexEpfundingRateErpredFundingRateErr  rt  ru  
indexPriceindexPriceRpinterestRateestimatedSettlePricerU  fundingRatefundingRateRrfundingTimestampfundingDatetimenextFundingRatepredFundingRateRrnextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeinterval)r  r  ro  rM  r  r  rW  )
r  r  r  r  r  rT  r  r  r  nextFundingRateErs
             r  r  phemex.parse_funding_rate  s   L ##Hh7!!(3--hXN	d..xBFK,,t//)DfMT%5%5h%PRXY LL)9)9(DW)XZ`a
H
f
 ))(M6J
 $**8^WM	

 D
 #D
 
 Y/
 4++Ho}U
 
 t
 t//:MO`a
 #D
 "4
 "4
  '!
" &t#
$ %
 	
r  c                 (  #    U R                  5       I Sh  vN   U R                  U5      nUS   U R                  X$5      S.nU R                  U R	                  XS5      5      I Sh  vN nU R	                  U R                  Xd5      SU05      $  Nw N)7f)a  
Either adds or reduces margin in an isolated position in order to set the margin to a specific value

https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md#assign-position-balance-in-isolated-marign-mode

:param str symbol: unified market symbol of the market to set margin in
:param float amount: the amount to set the margin to
:param dict [params]: parameters specific to the exchange API endpoint
:returns dict: A `margin structure <https://docs.ccxt.com/#/?id=add-margin-structure>`
Nr4   )r  posBalanceEvr  )rj  r  r  privatePostPositionsAssignr%  parse_margin_modification)r  r  r  r'  r  rp  rD  s          r  
set_marginphemex.set_margin  s      !!!V$Tl JJv6
 88W9UVV {{499(KfN
  	 	" Ws"   BBAB&B'(BBc                 .    SS0nU R                  X!U5      $ )N0r9  re  rf  s      r  parse_margin_statusphemex.parse_margin_status  s#    
 &99r  r  c                     U R                  S U5      nU R                  US5      nU(       a  SOSnUU R                  S U5      SSS S X$   U R                  U R	                  US5      5      S S S.
$ )Nr   r  r  setr  r=  )
r  r  r  r   r  r8  r=  r  rT  rU  )r  r  r  r  r  )r  r  r  r   codeCurrencys        r  r   phemex.parse_margin_modification  s     !!$///&)4!(vg&&tV4$(..t/?/?f/MN
 	
r  r   c                   #    Uc  [        U R                  S-   5      eU R                  5       I Sh  vN   U R                  U5      nUS   (       d  [	        U R                  S-   5      eUR                  5       nUS:w  a  US:w  a  [        U R                  S-   5      eSUS	   0nUS:H  nU R                  US
   SS/5      (       a  U R                  US5      nUc  [        U R                  S-   5      eU(       a*  [        R                  " [        R                  " U5      5      O[        R                  " U5      US'   U R                  U R                  XS5      5      I Sh  vN $ U R                  US5      nUS:X  a  SnUc  [        U R                  S-   5      eXS'   U R                  U R                  XS5      5      I Sh  vN $  GN Nh N	7f)a%  
set margin mode to 'cross' or 'isolated'

https://phemex-docs.github.io/#set-leverage

:param str marginMode: 'cross' or 'isolated'
:param str symbol: unified market symbol
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: response from the exchange
Nz+ setMarginMode() requires a symbol argumentrC   z- setMarginMode() supports swap contracts onlyr  r  z@ setMarginMode() marginMode argument should be isolated or crossr  r4   r  r  r  r   zA setMarginMode() requires a "leverage" parameter for USDT marketsrx  r   z. setMarginMode() requires a leverage parameter)r#   r4   rj  r  r%   lowerr$   in_arrayr  r.   
string_negr  privatePutGPositionsLeverager%  r  privatePutPositionsLeverage)	r  r   r  r'  r  rp  r  currentLeverager   s	            r  set_margin_modephemex.set_margin_mode  s     >#DGG.[$[\\!!!V$f~DGG&UUVV%%'
#
g(=TWW'iijjfTl
 '==)FF+;<<"..vzBO&'2u(uvv_fG$6$6w7I7I/7Z$[lsl~l~  @O  mPGL!::4;;w;WXXX$$VZ8 H#DGG.^$^__&
55dkk'6RSSS/ 	"  Y Ts5   /GGD-GG A G G
GG
Gr   c                 N  #    U R                  SUS5        U R                  5       I Sh  vN   U R                  U5      nUS   S:w  a  [        U R                  S-   5      eSUS   0nU(       a  SUS	'   OS
US	'   U R                  U R                  XS5      5      I Sh  vN $  Nw N7f)a  
set hedged to True or False for a market

https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#switch-position-mode-synchronously

:param bool hedged: set to True to use dualSidePosition
:param str symbol: not used by binance setPositionMode()
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: response from the exchange
r   r  Nr  r  z5 setPositionMode() supports USDT settled markets onlyr4   r  targetPosModeOneWay)check_required_argumentrj  r  r%   r4   %privatePutGPositionsSwitchPosModeSyncr%  )r  r   r  r'  r  rp  s         r  set_position_modephemex.set_position_mode@  s      	$$%6I!!!V$(v%DGG&]]^^fTl
 '/GO$'/GO$??G@\]]] 	" ^s"   'B%B!A2B%B#B%#B%c                 p  #    U R                  5       I Sh  vN   UbD  U R                  US5      nU R                  U5      nUS   S:w  a  [        U R                  S-   5      eU R                  U5      I Sh  vN nU R                  US0 5      nU R                  US5      nU R                  XqS5      $  N N=7f)	a|  
retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes
:param str[]|None symbols: list of unified market symbols
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a dictionary of `leverage tiers structures <https://docs.ccxt.com/#/?id=leverage-tiers-structure>`, indexed by market symbols
Nr   r  r  z7 fetchLeverageTiers() supports USD settled markets onlyr  r  r  )rj  r  r  r%   r4   publicGetCfgV2Productsr   parse_leverage_tiers)r  r  r'  r  r  rD  r  r  s           r  fetch_leverage_tiersphemex.fetch_leverage_tiersY  s      !!!OOGQ/E[['Fh5(*c cdd44V<<^ x4^^D,7
((hGGo 	" =s"   B6B2AB66B47<B64B6c                 d   U R                  US5      nU R                  X25      nUS   S   n/ nSn[        S[        U5      5       Hg  nXG   nU R	                  US5      n	UR                  U R                  US5      U R                  X25      US   UU	U R                  US5      S	US
.5        U	nMi     U$ )zY
:param dict info: Exchange market response for 1 market
:param dict market: CCXT market
r  r  r  r   r   r   r  r  N)tierr  r  minNotionalmaxNotionalmaintenanceMarginRater  r  )r  r  r#  r$  r  r&  r  r  )
r  r  r  r  r  tiersr  r3  r  r  s
             r  parse_market_leverage_tiers"phemex.parse_market_leverage_tiers  s      ##D(3!!(3Vn\2
q#j/*A=D++D':KLLA**8<"8,**)-)9)9$@S)T#	 	 &K + r  r   GETc                    U R                  X@R                  U5      5      nSU R                  X5      -   nUn	Sn
US:X  d  US:X  d  US:X  d  U	S:X  a   U(       a  U R                  U5      n
U	SU
-   -  n	US:X  GaH  U R	                  5         U R                  5       nU R                  U R                  S	S
5      nU R                  X5      n[        U5      nU R                  US.nSnUS:X  a  US:H  =(       d    US:H  =(       d    US:H  nU(       aF  U R                  US5      c3  U R                  U R                  SS5      nUU R                  5       -   US'   U R                  U5      nUnSUS'   X-   U-   U-   nU R                  U R                  U5      U R                  U R                   5      ["        R$                  5      US'   U R'                  U R(                  S   U   5      U	-   n	XXeS.$ )Nr  r  r  DELETEPUTz/positions/assign?r   r  r  )zx-phemex-access-tokenr  POSTr   r   r   r|  r  r  zapplication/jsonzContent-Typezx-phemex-request-signaturer   )r   r`  bodyheaders)r  extract_paramsimplode_paramsurlencode_with_array_repeatcheck_required_credentialsr  r  r  r  ry  r   r  r  jsonhmacencoder   hashlibsha256implode_hostnamer   )r  pathr   r`  r'  r  r  r  requestPathr   queryStringrT  xPhemexRequestExpiryr  expiryStringpayloadisOrderPlacementr4   auths                      r  signphemex.sign  s   		&"5"5d";<D//==eO8!35cUhNh">>uEs[(()++-I#'#4#4T\\C\^`#a XXi>Fv;L)-+7G G$(J$6#hDM<Q#hW[_gWg #''	:B!--dllJU,.,>y)))F+*<',|;gED48IIdkk$>OQUQ\Q\]a]h]hQikrkyky4zG01##DIIe$4S$9:S@dOOr  r   c                   #    Uc  [        U R                  S-   5      eUS:  d  US:  a  [        U R                  S-   5      eU R                  5       I Sh  vN   U R	                  USS5      nU R                  US5      nU R                  US	5      nU R                  U5      nS
US   0nSn	US   S:X  d	  US   S:X  aR  U(       d  Uc  Uc  XS'   OUb  UOUn
Ub  UOUnXS'   XS	'   U R                  U R                  X5      5      I Sh  vN n	U	$ XS'   U R                  U R                  X5      5      I Sh  vN n	U	$  N N6 N
7f)a  
set the level of leverage for a market

https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#set-leverage

:param float leverage: the rate of leverage, 100 > leverage > -100 excluding numbers between -1 to 1
:param str symbol: unified market symbol
:param dict [params]: extra parameters specific to the exchange API endpoint
:param bool [params.hedged]: set to True if hedged position mode is enabled(by default long and short leverage are set to the same value)
:param float [params.longLeverageRr]: *hedged mode only* set the leverage for long positions
:param float [params.shortLeverageRr]: *hedged mode only* set the leverage for short positions
:returns dict: response from the exchange
Nz) setLeverage() requires a symbol argumentir  z6 setLeverage() leverage should be between -100 and 100r   FlongLeverageRrshortLeverageRrr  r4   r  r  r  rx  r   )
r#   r4   r$   rj  r  r  r  r  r%  r  )r  r   r  r'  isHedgedr  r  r  rp  rD  longVarshortVars               r  set_leveragephemex.set_leverage   sj      >#DGG.Y$YZZtOCTWW'__``!!!>>&(E:**63CD++F4EFV$fTl
 (v%)9V)C 6?;R(0%-;-G.h/>/J?QY,3()-5)*!>>t{{7?[\\H  #+J!==dkk'>Z[[H+ 	"" ] \s7   AED=B2ED?	-E6E7E?EEfromAccount	toAccountc           	      n  #    U R                  5       I Sh  vN   U R                  U5      nU R                  U R                  S0 5      nU R	                  XsU5      nU R	                  XtU5      n	U R                  X&5      n
SnSnUS:X  a	  U	S:X  a  SnOUS:X  a  U	S:X  a  SnUbV  US   UU
S.nU R                  U R                  X5      5      I Sh  vN nU R                  US	0 5      nU R                  X5      nOUUU	U
US   U R	                  US
S5      S.nU R                  U R                  X5      5      I Sh  vN nU R                  U5      nU R                  U R                  S0 5      nU R                  USS5      nU(       a(  US   c  X<S'   US   c  XLS'   US   c  X,S'   US   c  XS'   U$  GN N N{7f)a  
transfer currency internally between wallets on the same account

https://phemex-docs.github.io/#transfer-between-spot-and-futures
https://phemex-docs.github.io/#universal-transfer-main-account-only-transfer-between-sub-to-main-main-to-sub-or-sub-to-sub

:param str code: unified currency code
:param float amount: amount to transfer
:param str fromAccount: account to transfer from
:param str toAccount: account to transfer to
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.bizType]: for transferring between main and sub-acounts either 'SPOT' or 'PERPETUAL' default is 'SPOT'
:returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
Nr  rA   rD   r   r   r4   )r  moveOprN  r  bizTypeSPOT)
fromUserIdtoUserIdrN  r  r  r   r  Tr  r  r  r  )rj  r  r  r  r  r  privatePostAssetsTransferr%  parse_transfer"privatePostAssetsUniversalTransferr  )r  r=  r  r  r  r'  r  r  fromIdtoIdscaledAmmount	directionr   rp  rD  r  transferOptionsr  s                     r  r   phemex.transfer+  s     !!!==&7GL!!.{K9E

64	V 0IxDFNI $TN#)G
 ";;DKK<XYYH ??8VR8D**4:H % )$TN++FIvFG "DDT[[QXEabbH **84H//$,,
BG"&..B[]a"b"&.*5'$,(1%!)%+"
#+'+$ 	"$ Z2 cs6   F5F.B7F5F1A(F57F38A7F51F53F5c                   #    U R                  5       I Sh  vN   Uc  [        U R                  S-   5      eU R                  U5      nSUS   0nUb  X&S'   Ub  X6S'   U R	                  U R                  Xd5      5      I Sh  vN nU R                  US0 5      nU R                  US/ 5      n	U R                  XX#5      $  N N>7f)	a  
fetch a history of internal transfers made on an account

https://phemex-docs.github.io/#query-transfer-history

:param str code: unified currency code of the currency transferred
:param int [since]: the earliest time in ms to fetch transfers for
:param int [limit]: the maximum number of  transfers structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `transfer structures <https://docs.ccxt.com/#/?id=transfer-structure>`
Nz* fetchTransfers() requires a code argumentr  r4   r  r   r  r  )	rj  r#   r4   r  privateGetAssetsTransferr%  r  r   parse_transfers)
r  r=  r  r   r'  r  rp  rD  r  	transferss
             r  fetch_transfersphemex.fetch_transfers{  s      !!!<#DGG.Z$Z[[==&
 $G$G66t{{77STT* x4NN44	##IFFE 	" Us"   C B<A(C ?B> =C >C r   c                    U R                  US5      nU R                  US5      nU R                  US5      nU R                  U5      nU R                  US5      nU R                  Xr5      nU R                  US5      n	S n
S nU	S:X  a  Sn
SnO
U	S	:X  a  Sn
SnU R                  US
5      nUUUU R	                  U5      UUU
UU R                  U5      S.	$ )NlinkKeyr  rN  r  r]  r   rC   rA   r   r  )	r  r4   rT  rU  r  r  r  r  r  )r  rL  r  r  rW  parse_transfer_status)r  r   r  r4   r  rN  amountTransferedr.  r=  r]  r%  r&  rT  s                r  r#  phemex.parse_transfer  s    4 h	2!!(H5##Hj9<<1%%h
;
&&z<  6219FDQYFD%%h=	"Y/&!008

 
	
r  c                 4    SSSSS.nU R                  X!U5      $ )NrY  r^  r9  r:  )r`  rc  rn  11re  rf  s      r  r3  phemex.parse_transfer_status  s*    	
 &99r  c           
      8  #    Uc  [        U R                  S-   5      eU R                  5       I Sh  vN   U R                  U5      nUS   S:H  =(       d    US   S:H  nUS   (       d  [	        U R                  S-   5      eSnU R                  US	S
5      u  ptU(       a  U R                  S	XUSUS5      I Sh  vN $ SnU(       a  SUS   -   S-   nOSUS   -   S-   nSU0n	Ub  X)S'   Ub  X9S'   U R                  SX5      u  pSn
U(       a)  U R                  U R                  X5      5      I Sh  vN n
O(U R                  U R                  X5      5      I Sh  vN n
U R                  U
S0 5      nU R                  US5      n/ n[        S[        U5      5       HO  nX   nU R                  US5      nUR                  UUU R!                  US5      UU R#                  U5      S.5        MQ     U R%                  US5      nU R'                  UXU5      $  GN GN\ N N7f)a  
fetches historical funding rate prices

https://phemex-docs.github.io/#query-funding-rate-history-2

:param str symbol: unified symbol of the market to fetch the funding rate history for
:param int [since]: timestamp in ms of the earliest funding rate to fetch
:param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>` to fetch
:param dict [params]: extra parameters specific to the exchange API endpoint
:param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
:param int [params.until]: timestamp in ms of the latest funding rate
:returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
Nz5 fetchFundingRateHistory() requires a symbol argumentr  r  r  rC   z7 fetchFundingRateHistory() supports swap contracts onlyFrb   paginate8hr  .r4   FR8Hr  r  r  r   endr  r  r   fundingTimer  )r  r  r  rT  rU  rT  )r#   r4   rj  r  r$   rK  "fetch_paginated_call_deterministichandle_until_option(v2GetApiDataPublicDataFundingRateHistoryr%  (v1GetApiDataPublicDataFundingRateHistoryr  r#  r$  r  r&  r  rW  rX  filter_by_symbol_since_limit)r  r  r  r   r'  r  isUsdtSettledr:  customSymbolrp  rD  r  ratesr2  r3  itemrT  sorteds                     r  fetch_funding_rate_history!phemex.fetch_funding_rate_history  sE     >#DGG.e$eff!!!V$x(F2PfX6F&6Pf~TWW'``aa88AZ\fg@@AZ\bkprvx~  AD  E  E  E-6L!11F:Ll
 $G$G225'J!JJ4;;W^KghhH!JJ4;;W^KghhH" x4f-q#e*%A8D))$>IMM #//mD& LL3  & fk200NNs 	" E  ihsH   /HHBH7H8A6H.H/(HHB9HHHHr$  r%  c                   #    U R                  XE5      u  pEU R                  5       I Sh  vN   U R                  U5        U R                  U5      nSnU R	                  U5      u  puSnUb  U R                  U5      nU R                  U R                  S5      n	Uc4  U R                  X5      (       d  US   nO[        U R                  S-   5      eUS   UUUR                  5       S.n
Ub  XJS'   U R                  U R                  X5      5      I Sh  vN nU R                  US0 5      nU R                  X5      $  GN N+7f)a  
make a withdrawal

https://phemex-docs.github.io/#create-withdraw-request

:param str code: unified currency code
:param float amount: the amount to withdraw
:param str address: the address to withdraw to
:param str tag:
:param dict [params]: extra parameters specific to the phemex api endpoint
:param str [params.network]: unified network code
:returns dict: a `transaction structure <https://github.com/ccxt/ccxt/wiki/Manual#transaction-structure>`
Nr  r4   z8 withdraw() requires an extra argument params["network"])r  r$  r  r#  
addressTagr  )handle_withdraw_tag_and_paramsrj  r)  r  handle_network_code_and_paramsnetwork_code_to_idr  r  r  r#   r4   upper1privatePostPhemexWithdrawWalletsApiCreateWithdrawr%  r  r\  )r  r=  r  r$  r%  r'  r  networkCoder[  r  rp  rD  r  s                r  r   phemex.withdraw5  s?     99#F!!!7#==&"AA&I	"//<IoodllMBMM$44$TN	'2l(lmm "*	
 ?$'L!OOPTP[P[\cPlmm8 ~~h3%%d55g 	", ns"   'D>D9C&D>D<)D><D>c                 L  #    U R                  5       I Sh  vN   U R                  U5      nUS   (       d  [        U R                  S-   5      eSUS   0nU R	                  U R                  XB5      5      I Sh  vN nU R                  US5      nU R                  Xc5      $  N N)7f)a,  
retrieves the open interest of a trading pair

https://phemex-docs.github.io/#query-24-hours-ticker

:param str symbol: unified CCXT market symbol
:param dict [params]: exchange specific parameters
:returns dict} an open interest structure{@link https://docs.ccxt.com/#/?id=open-interest-structure:
Nr  z: fetchOpenInterest is only supported for contract markets.r  r4   r2  )rj  r  r$   r4   r  r%  r  parse_open_interestr  s          r  fetch_open_interestphemex.fetch_open_interesty  s      !!!V$j!TWW'ccddfTl
 11$++g2NOO, (3''77= 	" Ps"   B$B A!B$8B"9(B$"B$c                    U R                  US5      S-  nU R                  US5      nU R                  UU R                  XB5      U R                  US5      S U R                  US5      S UU R	                  U5      S.U5      $ )NrT  i@B r  r  openInterestRv)r  r  r  r  openInterestAmountopenInterestValuerT  rU  )r  r  safe_open_interestr  rW  )r  interestr  rT  r4   s        r  rV  phemex.parse_open_interest  s    $ %%h<wF	h1&&&&r2**8Z@"&"2"28=M"N!%"Y/	(
 	 		r  fromCodetoCodec                 n  #    U R                  5       I Sh  vN   U R                  U5      nU R                  U5      nU R                  US5      nUUU R                  X75      S.nU R	                  U R                  X5      5      I Sh  vN n	U R                  U	S0 5      n
U R                  XU5      $  N N+7f)a  
fetch a quote for converting from one currency to another

https://phemex-docs.github.io/#rfq-quote

:param str fromCode: the currency that you want to sell and convert from
:param str toCode: the currency that you want to buy and convert into
:param float amount: how much you want to trade in units of the from currency
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
Nr  )fromCurrency
toCurrencyfromAmountEvr  )rj  r  r  r  privateGetAssetsQuoter%  r  parse_conversion)r  r`  ra  r  r'  rc  rd  r  rp  rD  r  s              r  fetch_convert_quotephemex.fetch_convert_quote  s      !!!}}X.]]6*
&&|\B
$  JJv:

 33DKK4PQQ& ~~h3$$TDD; 	" Rs"   B5B1A0B5B3*B53B5c                 
  #    U R                  5       I Sh  vN   U R                  U5      nU R                  U5      nU R                  US5      nUUUS.n	Ub  U R                  XH5      U	S'   U R	                  U R                  X5      5      I Sh  vN n
U R                  U
S0 5      nU R                  US5      nU R                  X5      nU R                  US5      nU R                  X5      nU R                  XU5      $  N Nq7f)a  
convert from one currency to another

https://phemex-docs.github.io/#convert

:param str id: the id of the trade that you want to make
:param str fromCode: the currency that you want to sell and convert from
:param str toCode: the currency that you want to buy and convert into
:param float [amount]: how much you want to trade in units of the from currency
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
Nr  )r=  rc  rd  re  r  rc  rd  )
rj  r  r  r  privatePostAssetsConvertr%  r  r  rX  rg  )r  r4   r`  ra  r  r'  rc  rd  r  rp  rD  r  fromCurrencyId
fromResulttoCurrencyIdr  s                   r  create_convert_tradephemex.create_convert_trade  s     !!!}}X.]]6*
&&|\B
$ 

 &*jj&DGN#66t{{77STT  ~~h3))$?''E
''l;9$$Tr::A 	" Us#   DC?A8DDA0DDc                 \  #    U R                  5       I Sh  vN   0 nUb  XS'   Ub  X%S'   Ub  X5S'   U R                  SXT5      u  pTU R                  U R                  XT5      5      I Sh  vN nU R	                  US0 5      nU R                  US/ 5      nU R                  XSSX#5      $  N N@7f)	a  
fetch the users history of conversion trades

https://phemex-docs.github.io/#query-convert-history

:param str [code]: the unified currency code
:param int [since]: the earliest time in ms to fetch conversions for
:param int [limit]: the maximum number of conversion structures to retrieve, default 20, max 200
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.until]: the end time in ms
:param str [params.fromCurrency]: the currency that you sold and converted from
:param str [params.toCurrency]: the currency that you bought and converted into
:returns dict[]: a list of `conversion structures <https://docs.ccxt.com/#/?id=conversion-structure>`
Nrc  	startTimer   endTimer  r  rd  )rj  rA  privateGetAssetsConvertr%  r  r   parse_conversions)	r  r=  r  r   r'  rp  rD  r  r  s	            r  fetch_convert_trade_history"phemex.fetch_convert_trade_history  s      !!!&*N##(K $G229gN55dkk'6RSS. ~~h3~~dFB/%%d.,PU]]E 	" Ts"   B,B(AB,)B**?B,*B,
conversionrc  rd  c                 f   U R                  US0 5      nU R                  US5      nU R                  USU5      nU R                  USU R                  US5      5      nU R                  Xr5      nU R                  USU R                  US5      5      n	U R                  X5      n
U R                  US5      nU R                  US5      nU R	                  U R                  US5      U5      nUc%  Ub"  U R	                  U R                  US	5      U5      nU R	                  U R                  US
5      U5      nUc%  Ub"  U R	                  U R                  US5      U5      nUUU R                  U5      U R                  US5      UU R                  U5      U
U R                  U5      U R                  US5      S S.
$ )N	quoteArgs	requestAtr  rc  r=  rd  r  re  origin
toAmountEvproceedsr   )
r  rT  rU  r4   rc  
fromAmountrd  toAmountr   r?  )r  r  r  r  r  rW  r  r  )r  rx  rc  rd  rz  requestTimerT  fromCoinr`  toCoinra  fromValueScaletoValueScaler  r  s                  r  rg  phemex.parse_conversionO  s   V NN:{B?	''	;?%%j,L	##J@P@PQ]_e@fg**8B!!*lD<L<LZY_<`a((<**<F((\B\\$"2"2:~"NP^_
)"7d&6&6y(&K^\J<< 0 0\ JLY	 5||D$4$4Y
$K\ZH"Y/"":v6$++J7 ))(3%%i9
 	
r  httpCodereasonr   r`  r  r  c
                 B   Uc  g U R                  USU5      n
U R                  U
S5      nU R                  U
S5      nUba  US:w  a[  U R                  S-   U-   nU R                  U R                  S   X5        U R                  U R                  S   X5        [        U5      eg )Nerrorr=  msgr  r  r  r  )r  r  r4   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   )r  r  r  r   r`  r  r  rD  requestHeadersrequestBodyr  	errorCodemessagefeedbacks                 r  handle_errorsphemex.handle_errors  s     '8<$$UF3	""5%0!	S(8ww}t+H001I9_001I7]))r   ru  )r   r   N)Nrg  rh  r   r   N)NN)q__name__
__module____qualname____firstlineno__r   r  r  dictr  r  r   r   r7  r   rI  rQ  r`  ry  r   r   rr  r  r  r  r  rM  rL  r  r  r  r  r   r  r  r   r   r  r   r  r0  r@  rH  r   rP  r   rh  r#  ry  r  r  r  r   r  r   r   floatr   r  r  r  r  r  r
  r  r  r  r
   r+  r   r1  r6  rD  r	   r\  r   rh  rd  r  r  r   r  r  r   r  r  r  r  boolr  r   r  r   r  r  r@  r  r   r   r/  r#  r3  rJ  r   rW  rV  r   rh  ro  rv  rg  r  __static_attributes____classcell__)r  s   @r  r0   r0      s   V	# V	p*J JXc cJ *, bV bH -/ @: @D	
F 	
  KQ & @DB 8S 8 8S\ 8t48D 8
76 7
I& I
I& I
I& I

 
4 
8 ?CQUdhqs NL NL NL3 NL^a NLx|  ~B  yC NL`U4 U U6 Un 68 E1 E1F E1N 6:" 37 3 3@ <@d[] *? *?S *? *?bfglbm *?XZ Zv Z Zx1)f-)^ *, c1 c1J: :.3S 3"Hs Hjd jF jX3lf l\4 4v 4 4 mqy{ R. R.I R.Y R.X] R.fi R.h fjx|  FH =.3 =. =.9 =.I =._b =.ru =.~ 9=R $.S $.# $.L 59 9
c 9
v 8<B ,/C ,/ ,/\ 04$UYbd != !=C !=s !=imnsit !=F 59tZ^gi 'Ac 'A 'ATW 'Anrsxny 'AR 7;\`ik MA MA3 MAVY MAptuzp{ MA^ 37TX\eg X=C X=s X=RU X=t =? 1
 1
> 1
f 04$UYbd #E #EC #Es #Eimnyiz #EJ 37TX\eg #EC #Es #ERU #Elpq|l} #EJ:s :(q
T q
X q
Q\ q
f 8<B DPW DP4PX> DPLNt NV N` 9=4^bkm F# FS FX[ FP
F 
Y\ 
 <> +7s +7+ +7Z@
6 @
[ @
D CE s E I[ ::
d 
F 
N` 
0 DHPR $T $TS $TL CGr ^d ^C ^2 =A ^H' ^HP] ^H@# #$|J\ #J &eBSW  PD ?C2 )3 ) )V ac N3 N NC NTW Ngt N` 154VZce .G# .GS .GPS .Gjno|j} .G`4
t 4
x 4
= 4
l:C :C : >BPTcgpr IOs IO# IO]` IOV QU]_ B63 B6 B6 B6# B6do B6H =? (8 (8TF > SW_a )E# )Es )EC )Efp )EV ]aik -;S -;C -; -;VY -;pz -;^ =Atbfoq 1^c 1^ 1^\_ 1^vz  |F  wG 1^fE
4 E
x E
\d E
pz E
Nc 3 S # X\ dg  r  r0   )7 ccxt.async_support.base.exchanger   ccxt.abstract.phemexr   r  r  r   ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   ccxt.base.decimal_to_precisionr-   ccxt.base.preciser.   r0   r  r  r  <module>r     s    6 ,    `  `  `  `  `  `  `  * 0 - - . ' & . ) * - + . * 4 %HNX{ HNr  