
    E#i6                    |   S SK Jr  S SKJ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"J/r/  S SK"J0r0  S SK1J2r2  S SK3J4r4   " S S\\5      r5g)    )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    E/home/james-whalen/.local/lib/python3.13/site-packages/ccxt/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_numberx  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                 X   U R                  U5      nU R                  U5      nX#/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$ )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
datar   perpProductsV2
riskLimitsriskLimitsV2
currenciesr  currencyr   r  	perpetualperpetualv2perpetualpilotr  r  8)v2GetPublicProductsv1GetExchangePublicProducts
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_marketsq  s.    !44V<l !<<VD"3!G
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&!! )" r  c                    U R                  U5      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$ )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
r  r  r   r  r  
minValueEv
maxValueEvNr5   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  r0  r1  r  r4   r;  valueScaleStringr  r8  r9  	minAmount	maxAmountr  precisionStrings                     r  fetch_currenciesphemex.fetch_currenciesU  s    ++F3 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 r  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$  rO  sort_by)r  	orderbookr  rR  bidsKeyasksKeyrM  rN  r  r0  sidesr1  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           
      L   U R                  5         U R                  U5      nSUS   0nSnUS   S:H  =(       d    US   S:H  nUS   (       a(  U(       a!  U R                  U R                  XS5      5      nOJUb'  US::  a!  U R	                  U R                  XS5      5      nO U R                  U R                  XS5      5      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$ )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
r  r4   Nr  r  r  r   r1   r0  bookorderbook_prR  ư>bidsasksr   r   sequencerT  )load_marketsr  v2GetMdV2Orderbookr#  v1GetMdOrderbookv1GetMdFullbookr  safe_value_2safe_integer_productr^  r  )r  r  r   r%  r  requestrB  isStableSettledr0  ra  rR  rW  s               r  fetch_order_bookphemex.fetch_order_book  s/    	V$fTl
 !(+v5V6(;Kv;U(..t{{7/KLH!00W1MN//G0LM4 8R8  C--fk8L	00y&RXZ[]^`fg	!..vzB	'r  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      $ rr  )r.   sumrt  ru  rv  )r  enry  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  rK  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  rJ  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  rJ  r  r  safe_timestamprK  )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                 d   U R                  5         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      nOU R                  U R                  X5      5      nO^Ub;  U R                  U5      S
-  nU R                  5       U-
  nU R                  UU-  5      nU R!                  U R                  X5      5      nU R#                  US0 5      nU R%                  US/ 5      nU R'                  UXbX75      $ )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
r4   )r  
resolutionuntiltor  r  r  r   Nr   r   r   fromd   r  rows)rg  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  	userLimitrm  r  rn  usesSpecialFromToEndpointmaxLimitrB  candleDurationr  nowduration	timeDeltar  r  s                        r  fetch_ohlcvphemex.fetch_ohlcv4  sK    	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66t{{77ST66t{{77ST   //	:TA --/%7	)))h*>?..t{{7/KLH x4~~dFB/  v%KKr  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  rR  rc  lastEpcloseRp
turnoverEv
turnoverRvvolumevolumeEvvolumeRqopenEprS  highhighEphighRplowlowEplowRpr  bidEp	bidVolumer  askEp	askVolumevwapopencloser   previousClosechanger   average)r  quoteVolumer  )	r  safe_marketrl  rK  safe_string_2r  rJ  safe_tickerrU  )
r  r  r  marketIdr  rR  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         U R                  U5      nSUS   0nSnUS   (       aU  US   (       d	  US   S:X  a!  U R                  U R                  XB5      5      nOAU R	                  U R                  XB5      5      nO U R                  U R                  XB5      5      nU R                  US0 5      nU R                  Xc5      $ )	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>`
r  r4   NrC   r   r  r  r0  )rg  r  v1GetMdTicker24hrr#  v2GetMdV2Ticker24hrv1GetMdSpotTicker24hrr  r  r  r  r%  r  rm  rB  r0  s          r  fetch_tickerphemex.fetch_ticker  s     	V$fTl
 &>i F8$4$=11$++g2NO33DKK4PQ11$++g2NOHZ (B7  00r  symbolsc                    U R                  5         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      nO?US:X  d  U R                  US5      S:X  a  U R                  U5      nOU R                  U5      nU R                  US	/ 5      n	U R                  X5      $ )
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  r0  )rg  r  r  handle_market_type_and_paramshandle_sub_type_and_paramsr  v1GetMdSpotTicker24hrAllr  v1GetMdTicker24hrAllv2GetMdV2Ticker24hrAllr  parse_tickers)
r  r  r%  r  firstr  subTypequeryrB  r0  s
             r  fetch_tickersphemex.fetch_tickers"  s     	OOGQ/E[['F99.&Y99.&Y		&&)6>44U;H	!T%5%5fh%G5%P007H2259H(B7!!&22r  c                    U R                  5         U R                  U5      nSUS   0nSnUS   S:H  =(       d    US   S:H  nUS   (       a(  U(       a!  U R                  U R                  Xd5      5      nO U R	                  U R                  Xd5      5      nU R                  US0 5      n	U R                  U	S	S
/ 5      n
U R                  XX#5      $ )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>`
r  r4   Nr  r  r  r   r0  tradestrades_p)rg  r  v2GetMdV2Trader#  v1GetMdTrader  rk  parse_trades)r  r  r  r   r%  r  rm  rB  rn  r0  r  s              r  fetch_tradesphemex.fetch_tradesB  s     	V$fTl
 !(+v5V6(;Kv;U(**4;;w+GHH((W)EFH" 8R8""68ZD  >>r  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   rc  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  rR  rS  orderr  r[  takerOrMakerr   r  r  r=  )r  r  
isinstancelistr"  rl  r
  numbersRealrK  rJ  r  r  	omit_zeror  parse_order_typer  r  
safe_traderU  )r  r  r  r4   r[  
costStringr  r=  feeCostStringfeeRateStringfeeCurrencyCoder  r  orderIdr  tradeLengthrR  priceStringamountStringsideIdr  
currencyIdr  r  r  settlementCurrencyIds                             r  parse_tradephemex.parse_traden  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lastUpdateTimeNsrc  totalusedrR  rS  )r  r!  r"  r  r  r  r  accountr  r.   
string_addrl  r  rU  safe_balance)r  rB  rR  r0  r  r1  balancer+  r;  r  ry  r7  r1  r2  r3  r5  lockedTradingBalancelockedWithdrawr6  r4  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  r7  r  r  r0  accountBalanceEvaccountBalanceRvtotalUsedBalanceEvtotalUsedBalanceRvr  r5  r6  )	r  r  r  r  r  r7  r  r  r9  )r  rB  r0  r  r:  r+  r;  r  r  r7  r@  rB  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                 R   U R                  5         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bn  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      nOU R                  U R                  XQ5      5      nOtU R                  US5      nUc  [        U R
                  S-   U-   S-   5      eU R                  U R                  XQ5      5      nO U R                  U R                  XQ5      5      nUS:X  a  U R                  U5      $ U R                  U5      $ )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)rg  r  r  r  r$   r4   handle_option_and_paramsr  #privateGetGAccountsAccountPositionsr#  "privateGetAccountsAccountPositionsr#   privateGetSpotWalletsrE  r=  )	r  r%  r  r;  rB  rm  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+#GGT[HdeH#FFt{{SZGcdH++FJ?#+DGG  7I  -I  LP  -P  SZ  -Z  [  [55dkk'6RS11$++g2NOHl 6>**844&&x00r  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]  r^  r_  r`  ra  r  910Limitr   rb  )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
FillOrKillrb  )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createTimeNsrc  cumFeeEvr  r  r  r   stopPxEpr   r  r4   clientOrderIdrR  rS  lastTradeTimestampr  postOnlyr   r   r  r  r  filled)	remainingr  r=  r  )r  r"  r  rK  rJ  r  r  r  re  r
  r   safe_integer_product_2r  rv  r  
safe_orderrU  )r  r  r  r4   r  r  r  r   r  r  r  r  r  r  r[  r  rR  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  rb  )r  r[  rZ  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&  ry  clOrdIdr   r  r  r[  	orderTypepriceRprz  orderQty
orderQtyRqcumQtycumQtyRq	leavesQtyleavesQtyRqr  rc  r  cumValue
cumValueRvr  r   r   stopPxstopPxRpr   
reduceOnlyexecInst
ReduceOnlyTtakeProfitRp
stopLossRpr	  r  r  r  r  r  r4   r  rS  rR  r  r  r  r   r   r   r   r  )r  r  r  r  r  r=  r  )r  r"  r  safe_symbolr  re  r  r
  r   rK  r  rl  r  rv  r  r  r  rU  )r  r  r  r4   r  r  r  r  r[  r  r   r  r  r  rR  r  r  r   r   r  r  r  
takeProfitstopLossfeeValuer  r=  s                              r  parse_swap_orderphemex.parse_swap_order5	  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         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      n%OKUSK   (       a!  U R9                  U R7                  X5      5      n%O U R;                  U R7                  X5      5      n%U R=                  U%SL0 5      n&U R?                  U&U5      $ )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>`
r4   )r  r[  r  ry  r  r  Nr  r  r  r  r  r  )r  	stopPricer   r  r  )r  r  r  r  r   rA   qtyTypeByBaser   StopMarketIfTouchedByQuoterl  	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  rz  r   r   r  r  ) rg  r  
capitalizer  r  r  r  uuid16r  safe_string_nprice_to_precisionr  r  rs  r.   r@  r  r#   r4   r  r  r
  r  handle_param_stringrk  r'   privatePostGOrdersr#  privatePostOrdersprivatePostSpotOrdersr  r  )'r  r  r  r[  r  r   r%  r  requestSiderm  r  r  stopLossDefinedr  takeProfitDefinedrn  r  r   r  r  r)  r(  quoteAmountr"  r   r  r  r  r   stopLossTriggerPricestopLossTriggerPriceTypeslLimitPricetakeProfitTriggerPricetakeProfitTriggerPriceTypetpLimitPricer   r   rB  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..t{{7/KLHJ--dkk'.JKH11$++g2NOHZ ~~h3f--r  r4   c                 :   U R                  5         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(       a;  U R                  US5      nUc  SU	S'   U R                  U R                  X5      5      nOKUS   (       a!  U R                  U R                  X5      5      nO U R                  U R                  X5      5      nU R                  US0 5      nU R                  UU5      $ )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>`
r  r4   r  ry  r  r  r  Nr  r  rz  r{  	baseQtyEVr  )r   r  r  r  r  r  r  rC   r  )rg  r  r  r  r  r  r  amount_to_precisionr  r  privatePutGOrdersReplacer#  privatePutOrdersReplaceprivatePutSpotOrdersr  r  )r  r4   r  r  r[  r  r   r%  r  rm  r  rn  finalQtyr   rB  r  r  s                    r  
edit_orderphemex.edit_order
  s%     	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4T[[5QRHF^33DKK4PQH00W1MNH~~h3f--r  c                 j   Uc  [        U R                  S-   5      eU R                  5         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S5      nUc  SUS'   U R                  U R                  XS5      5      nOKUS   (       a!  U R                  U R                  XS5      5      nO U R                  U R                  XS5      5      nU R                  US0 5      n	U R                  X5      $ )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  ry  r  r  r  r  r  r  rC   r  )r#   r4   rg  r  r  r  r  privateDeleteGOrdersCancelr#  privateDeleteOrdersCancelprivateDeleteSpotOrdersr  r  )
r  r4   r  r%  r  rm  r  rB  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%-	"66t{{77STHF^55dkk'6RSH33DKK4PQH~~h3--r  c                    Uc  [        U R                  S-   5      eU R                  5         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      nOKUS   (       a!  U R                  U R                  XR5      5      nO U R                  U R                  XR5      5      nU R                  SU05      /$ )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 argumentrh  r   Fr  r4   untriggerredr  r  r  rC   r  )r#   r4   rg  r  rk  r  privateDeleteGOrdersAllr#  privateDeleteOrdersAllprivateDeleteSpotOrdersAllr  )r  r  r%  r  r   rm  rB  s          r  cancel_all_ordersphemex.cancel_all_ordersc  s    >#DGG.]$]^^V$##FFIuE6FI#67fTl

 &-N#(v%)9V)C33DKK4PQH F^224;;w3OPH 66t{{77STH OO 
 	
r  c                    Uc  [        U R                  S-   5      eU R                  5         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      nOKUS   (       a!  U R                  U R                  XS5      5      nO U R                  U R                  XS5      5      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      $ )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  ry  r  r  r  r  rA   r  r   z fetchOrder() z order with clientOrderId z
 not foundz order with id r   r  )r#   r4   rg  r  r  r  (privateGetApiDataGFuturesOrdersByOrderIdr#  %privateGetApiDataSpotsOrdersByOrderIdprivateGetExchangeOrderr  r  r  r"  r(   r  r  r  )r  r4   r  r%  r  rm  r  rB  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DDT[[QXEabHF^AA$++gB^_H33DKK4PQH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..r  c                 $   Uc  [        U R                  S-   5      eU R                  5         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  a)  US   US
'   U R	                  U R                  Xd5      5      nOKUS   (       a!  U R                  U R                  Xd5      5      nO U R                  U R                  Xd5      5      nU R                  US0 5      nU R                  USU5      n	U R                  XX#5      $ )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   rg  r  "privateGetExchangeOrderV2OrderListr#  privateGetExchangeOrderListprivateGetApiDataSpotsOrdersr  r  parse_orders
r  r  r  r   r%  r  rm  rB  r  r  s
             r  fetch_ordersphemex.fetch_orders  s    >#DGG.Y$YZZV$fTl
 $G$G(v%)9V)C"("2GJ>>t{{7?[\HF^77G8TUH88W9UVHx4~~dFD1  u<<r  c                    U R                  5         Uc  [        U R                  S-   5      eU R                  5         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      nOLUS   (       a!  U R                  U R                  Xd5      5      nO!U R                  U R                  Xd5      5      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      $ ! [         a#  n[        U[        5      (       a  / s SnA$ UeSnAff = 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  )rg  r#   r4   r  privateGetGOrdersActiveListr#  privateGetOrdersActiveListprivateGetSpotOrders	Exceptionr  r(   r  r  r  r  )r  r  r  r   r%  r  rm  rB  er  r  s              r  fetch_open_ordersphemex.fetch_open_orders  sM    	>#DGG.]$]^^V$fTl
 
	h6)VH-=-G;;DKK<XY::4;;w;WX44T[[5QR
 x4dD!!$$T5@@>>$3D$$T5@@  	!]++	G	s0   2D5 
*D5 5 D5 5
E"?EE"EE"c                 |   U R                  5         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  a7  U R                  USS5      US'   U R                  U R	                  Xd5      5      nOKUS	   (       a!  U R                  U R	                  Xd5      5      nO U R                  U R	                  Xd5      5      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      $ )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  )rg  r  r  r  r#  r  privateGetExchangeSpotOrderr  r  r  r  r  r  s
             r  fetch_closed_ordersphemex.fetch_closed_orders  sC     	[[(F
 &tGH$G$GN 0 0 Bf L"&"2"268V"LGJ>>t{{7?[\HF^77G8TUH77G8TUHJ x4dD!!$$T5@@>>$3D$$T5@@r  c                    U R                  5         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      n	OLUS:X  a&  SUS'   U R                  U R                  Xt5      5      n	O U R                  U R                  Xt5      5      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      $ )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  )rg  r  r  r  r  $privateGetExchangeOrderV2TradingListr#  privateGetExchangeOrderTrade!privateGetExchangeSpotOrderTradesr  r  )r  r  r  r   r%  r  r  rm  isUSDTSettledrB  r  s              r  fetch_my_tradesphemex.fetch_my_tradesg  s    	[[(F99/6ZUOE$Gqv~.p4CSCSTZ\dCeioCo"(GJ !GH}#&  &tGH$G@@WA]^HV^#*GK 88W9UVH==dkk'>Z[HR ??8VR8D??8VR8D??44D  u<<r  r;  c                 t   U R                  5         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      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.$ )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>`
r  r4   r  r  network	chainNameNz3 fetchDepositAddress() requires a network parameterr  addresstag)r  r  r  r!  r"  )rg  r  r  r  safe_string_uppersafe_string_upper_2r  r#   r4   r  )privateGetExchangeWalletsV2DepositAddressr#  r  check_address)r  r;  r%  r  rm  r  defaultNetworkr  r  rB  r  r!  r"  s                r  fetch_deposit_addressphemex.fetch_deposit_address  s=    	==&
 ..7HI//F>>$,,
B?**69k>Z""8g>?#DGG.c$cdd#*K YYvy1FAA$++gB^_  x4""43tU+7#
 	
r  c                     U R                  5         SnUb  U R                  U5      nU R                  U5      nU R                  US/ 5      nU R	                  XuX#5      $ )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  )rg  r  $privateGetExchangeWalletsDepositListr  parse_transactionsr  r;  r  r   r%  r  rB  r  s           r  fetch_depositsphemex.fetch_deposits4  s`     	}}T*H<<VD* ~~h3&&tuDDr  c                     U R                  5         SnUb  U R                  U5      nU R                  U5      nU R                  US/ 5      nU R	                  XuX#5      $ )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  )rg  r  %privateGetExchangeWalletsWithdrawListr  r,  r-  s           r  fetch_withdrawalsphemex.fetch_withdrawalsY  s`     	}}T*H==fE* ~~h3&&tuDDr  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SucceedrU  zSecurity check failedSecurityCheckFailedExpiredzAddress RiskzSecurity CheckingSecurityCheckingzPending ReviewzPending TransferAmlCsApporverW  	Confirmed	Cancelledrb  rc  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  txidrR  rS  r  	addressToaddressFromr"  tagTotagFromr  updated)commentinternalr=  )
r  safe_currencysafe_integer_nr
  r  r  r  r@  rU  network_id_to_code)r  rB  r  r4   r!  r"  rL  r+  r;  	networkIdrR  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                    U R                  5         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(       a`  SnU R                  USSS5      u  pUS:X  a!  U R                  U R                  X5      5      nOAU R                  U R                  X5      5      nO U R                  U R                  X5      5      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      $ )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   methodrI  r  	positionsr  F)rg  market_symbolsr  r  r  r  rH  r  r  rI  r#  privateGetGAccountsPositionsrJ  r  r!  r"  r$  parse_positionfilter_by_array_positions)r  r  r%  r  r;  r  r  firstSymbolr  r  rm  rB  r\  r  r]  r0  r1  positions                     r  fetch_positionsphemex.fetch_positions  s    	%%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>>CCDKKPWD`a<<T[[=YZ>>t{{7?[\HZ x4OOD+r:	q#i.)A |HMM$--h78 * --fhOOr  rc  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
entryPricerR  lastUpdateTimestampr  rc  initialMargincrossisolatedposModeHedged)initialMarginPercentagemaintenanceMarginmaintenanceMarginPercentagemarginRatiorS  r   r[  r   r   r   r   )r  r  r  r.   r@  
string_divr  r  rs  r  
string_abs
string_subsafe_positionr  rl  )r  rc  r  r  r  r  notionalString!maintenanceMarginPercentageStringmaintenanceMarginStringinitialMarginStringinitialMarginPercentageStringrn  markPriceStringr}  r  r  r   entryPriceStringrawSider[  	priceDiffr  apiUnrealizedPnlr  isCrosss                            r  r`  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                 D   Uc  [        U R                  S-   5      eU R                  5         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      nO U R                  U R                  Xd5      5      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$ )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;  rR  rS  r4   r  )r#   r4   rg  r  r$   $privateGetApiDataGFuturesFundingFeesr#  #privateGetApiDataFuturesFundingFeesr  r!  r"  r  r  r  r  r$  rU  parse_funding_fee_to_precision)r  r  r  r   r%  r  rm  rB  rn  r  r  r0  r1  entryrR  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@@WA]^H??G@\]H. x4tVR0q#d)$AGE))%>I(([IG2243C3CE:3VWLMM**5(;$& LL3==g|\  % r  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  )rT  r  r?  r.   r@  )r  r  r  r  rn  r  ry  tickPrecisions           r  r  %phemex.parse_funding_fee_to_precisionc  s~    =L0L *f4Rx8HF8R)),7H$$Xf%5|DE 007M&&u<Er  c                 x   U R                  5         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      nO U R                  U R                  XB5      5      nU R                  US0 5      nU R                  Xc5      $ )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>`
rC   z0 fetchFundingRate() supports swap contracts onlyr  r4   r   r0  )	rg  r  r%   r4   r  r#  r  r  parse_funding_rater  s          r  fetch_funding_ratephemex.fetch_funding_rateo  s     	V$f~DGG&XXYYfTl
 h--dkk'.JKH//G0LMH0 8R8&&v66r  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  rR  rc  markEpindexEpfundingRateErpredFundingRateErr  rp  rq  
indexPriceindexPriceRpinterestRateestimatedSettlePricerS  fundingRatefundingRateRrfundingTimestampfundingDatetimenextFundingRatepredFundingRateRrnextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeinterval)r  r  rl  rK  r  r  rU  )
r  r  r  r  r  rR  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         U R                  U5      nUS   U R                  X$5      S.nU R                  U R	                  XS5      5      nU R	                  U R                  Xd5      SU05      $ )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>`
r4   )r  posBalanceEvr  )rg  r  r  privatePostPositionsAssignr#  parse_margin_modification)r  r  r  r%  r  rm  rB  s          r  
set_marginphemex.set_margin  s~     	V$Tl JJv6
 224;;w3OP {{499(KfN
  	r  c                 .    SS0nU R                  X!U5      $ )N0r5  rb  rc  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  r5  r;  r  rR  rS  )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                 V   Uc  [        U R                  S-   5      eU R                  5         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      $ 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      $ )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
z+ 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 marketsrt  r   z. setMarginMode() requires a leverage parameter)r#   r4   rg  r  r%   lowerr$   in_arrayr  r.   
string_negr  privatePutGPositionsLeverager#  r  privatePutPositionsLeverage)	r  r   r  r%  r  rm  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4T[[5QRR$$VZ8 H#DGG.^$^__&
//G0LMMr  r   c                    U R                  SUS5        U R                  5         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      $ )
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  r  r  z5 setPositionMode() supports USDT settled markets onlyr4   r  targetPosModeOneWay)check_required_argumentrg  r  r%   r4   %privatePutGPositionsSwitchPosModeSyncr#  )r  r   r  r%  r  rm  s         r  set_position_modephemex.set_position_mode?  s     	$$%6IV$(v%DGG&]]^^fTl
 '/GO$'/GO$99$++g:VWWr  c                 @   U R                  5         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      nU R                  US0 5      nU R                  US5      nU R                  XqS5      $ )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
r   r  r  z7 fetchLeverageTiers() supports USD settled markets onlyr  r  r  )rg  r  r  r%   r4   publicGetCfgV2Productsr  parse_leverage_tiers)r  r  r%  r  r  rB  r  r  s           r  fetch_leverage_tiersphemex.fetch_leverage_tiersX  s     	OOGQ/E[['Fh5(*c cdd..v6^ x4^^D,7
((hGGr  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  r1  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   ry  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  rv  r   r  r  jsonhmacencoder   hashlibsha256implode_hostnamer   )r  pathr   r\  r%  r  r  r  requestPathr   queryStringrR  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                 F   Uc  [        U R                  S-   5      eUS:  d  US:  a  [        U R                  S-   5      eU R                  5         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  aJ  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      n	U	$ XS'   U R                  U R                  X5      5      n	U	$ )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  rt  r   )
r#   r4   r$   rg  r  r  r  r  r#  r  )r  r   r  r%  isHedgedr  r  r  rm  rB  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)*88W9UVH  #+J77G8TUHr  fromAccount	toAccountc           	      (   U R                  5         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bN  US   UU
S.nU R                  U R                  X5      5      nU R                  US	0 5      nU R                  X5      nOMUU	U
US   U R	                  US
S5      S.nU R                  U R                  X5      5      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$ )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>`
r  NrA   rD   r   r   r4   )r  moveOprJ  r  bizTypeSPOT)
fromUserIdtoUserIdrJ  r  r  r   r  Tr  r  r  r  )rg  r  r  r  r  r  privatePostAssetsTransferr#  parse_transfer"privatePostAssetsUniversalTransferr  )r  r;  r  r  r  r%  r  r  fromIdtoIdscaledAmmount	directionr   rm  rB  r  transferOptionsr  s                     r  r   phemex.transfer*  s    	==&7GL!!.{K9E

64	V 0IxDFNI $TN#)G
 55dkk'6RSH ??8VR8D**4:H % )$TN++FIvFG >>t{{7?[\H **84H//$,,
BG"&..B[]a"b"&.*5'$,(1%!)%+"
#+'+$r  c                 T   U R                  5         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      nU R                  US0 5      nU R                  US/ 5      n	U R                  XX#5      $ )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>`
z* fetchTransfers() requires a code argumentr  r4   r  r   r  r  )	rg  r#   r4   r  privateGetAssetsTransferr#  r  r  parse_transfers)
r  r;  r  r   r%  r  rm  rB  r  	transferss
             r  fetch_transfersphemex.fetch_transfersz  s     	<#DGG.Z$Z[[==&
 $G$G00W1MN* x4NN44	##IFFr  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  rJ  r  r[  r   rC   rA   r   r  )	r  r4   rR  rS  r  r  r  r  r  )r  rJ  r  r  rU  parse_transfer_status)r  r   r  r4   r  rJ  amountTransferedr+  r;  r[  r!  r"  rR  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      $ )NrV  r[  r5  r6  )r]  r`  rk  11rb  rc  s      r  r/  phemex.parse_transfer_status  s*    	
 &99r  c           
         Uc  [        U R                  S-   5      eU R                  5         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      $ 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      n
O U R                  U R                  X5      5      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      $ )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  rR  rS  rR  )r#   r4   rg  r  r$   rH  "fetch_paginated_call_deterministichandle_until_option(v2GetApiDataPublicDataFundingRateHistoryr#  (v1GetApiDataPublicDataFundingRateHistoryr  r!  r"  r  r$  r  rU  rV  filter_by_symbol_since_limit)r  r  r  r   r%  r  isUsdtSettledr6  customSymbolrm  rB  r  ratesr0  r1  itemrR  sorteds                     r  fetch_funding_rate_history!phemex.fetch_funding_rate_history  s    >#DGG.e$effV$x(F2PfX6F&6Pf~TWW'``aa88AZ\fg::;TV\ejlprxz}~~-6L!11F:Ll
 $G$G225'JDDT[[QXEabHDDT[[QXEabH" x4f-q#e*%A8D))$>IMM #//mD& LL3  & fk200NNr  r!  r"  c                 N   U R                  XE5      u  pEU R                  5         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      nU R                  US0 5      nU R                  X5      $ )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_paramsrg  r&  r  handle_network_code_and_paramsnetwork_code_to_idr  r  r  r#   r4   upper1privatePostPhemexWithdrawWalletsApiCreateWithdrawr#  r  rX  )r  r;  r  r!  r"  r%  r  networkCoderW  r  rm  rB  r  s                r  r   phemex.withdraw4  s$    99#F7#==&"AA&I	"//<IoodllMBMM$44$TN	'2l(lmm "*	
 ?$'L!II$++V]Jfg8 ~~h3%%d55r  c                    U R                  5         U R                  U5      nUS   (       d  [        U R                  S-   5      eSUS   0nU R	                  U R                  XB5      5      nU R                  US5      nU R                  Xc5      $ )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:
r  z: fetchOpenInterest is only supported for contract markets.r  r4   r0  )rg  r  r$   r4   r  r#  r  parse_open_interestr  s          r  fetch_open_interestphemex.fetch_open_interestx  s     	V$j!TWW'ccddfTl
 ++DKK,HI, (3''77r  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      $ )NrR  i@B r  r  openInterestRv)r  r  r  r  openInterestAmountopenInterestValuerR  rS  )r  r  safe_open_interestr  rU  )r  interestr  rR  r4   s        r  rR  phemex.parse_open_interest  s    $ %%h<wF	h1&&&&r2**8Z@"&"2"28=M"N!%"Y/	(
 	 		r  fromCodetoCodec                 >   U R                  5         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      n	U R                  U	S0 5      n
U R                  XU5      $ )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>`
r  )fromCurrency
toCurrencyfromAmountEvr  )rg  r  r  r}  privateGetAssetsQuoter#  r  parse_conversion)r  r\  r]  r  r%  r_  r`  r  rm  rB  r  s              r  fetch_convert_quotephemex.fetch_convert_quote  s     	}}X.]]6*
&&|\B
$  JJv:

 --dkk'.JK& ~~h3$$TDDr  c                    U R                  5         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      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      $ )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>`
r  )r;  r_  r`  ra  r  r_  r`  )
rg  r  r  r}  privatePostAssetsConvertr#  r  r  rT  rc  )r  r4   r\  r]  r  r%  r_  r`  r  rm  rB  r  fromCurrencyId
fromResulttoCurrencyIdr  s                   r  create_convert_tradephemex.create_convert_trade  s     	}}X.]]6*
&&|\B
$ 

 &*jj&DGN#00W1MN  ~~h3))$?''E
''l;9$$Tr::r  c                 ,   U R                  5         0 nUb  XS'   Ub  X%S'   Ub  X5S'   U R                  SXT5      u  pTU R                  U R                  XT5      5      nU R	                  US0 5      nU R                  US/ 5      nU R                  XSSX#5      $ )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>`
r_  	startTimer   endTimer  r  r`  )rg  r=  privateGetAssetsConvertr#  r  r  parse_conversions)	r  r;  r  r   r%  rm  rB  r  r  s	            r  fetch_convert_trade_history"phemex.fetch_convert_trade_history  s     	&*N##(K $G229gN//G0LM. ~~h3~~dFB/%%d.,PU]]r  
conversionr_  r`  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  r_  r;  r`  r  ra  origin
toAmountEvproceedsr   )
r  rR  rS  r4   r_  
fromAmountr`  toAmountr   r=  )r  r  r  r  r  rU  r  r  )r  rt  r_  r`  rv  requestTimerR  fromCoinr\  toCoinr]  fromValueScaletoValueScaler{  r|  s                  r  rc  phemex.parse_conversionN  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  rB  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   rr  )r   r   N)Nrd  re  r   r   N)NN)q__name__
__module____qualname____firstlineno__r   r  r  dictr  r  r   r   r5  r   rG  rO  r^  rv  r   r   ro  r}  r  r  r  rK  rJ  r  r  r  r  r   r  r  r   r   r  r   r  r-  r=  rE  r   rM  r   re  r   rv  r  r  r  r   r  r   r   floatr   r  r  r  r  r  r  r  r  r  r
   r(  r   r.  r2  r@  r	   rX  r   rd  r`  r  r  r   r  r  r   r  r  r  r  boolr  r   r  r   r  r  r>  r  r   r   r+  r  r/  rF  r   rS  rR  r   rd  rk  rr  rc  r  __static_attributes____classcell__)r  s   @r  r0   r0      s   V	# V	p*J JXc cJ $& b$v, bH ') @Z @D	
F 	
  KQ & :>b 8s 83 8Y 8t48D 8
76 7
I& I
I& I
I& I

 
4 
8 9=4^bkm NL# NL# NLS NLX[ NLrvw{r| NL`U4 U U6 Un 02 E13 E1f E1N 04B 3W 37 3@ 6:UW *?3 *?s *?# *?\`af\g *?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 gksu R.3 R.i R.y R.RW R.`c R.h `drv  @B =.S =.# =.Y =.i =.Y\ =.lo =.~ 37r $.s $.C $.L /32 9
 9
v 26b ,/c ,/3 ,/\ *.Dt\^ !=3 !=c != !=cghmcn !=F /3TXac 'A 'A3 'Ac 'Ahlmrhs 'AR 154VZce MA# MAS MAPS MAjnotju MA^ -1tRV_a X=c X= X=C X=t 79 1
# 1
^ 1
f *.Dt\^ #E3 #Ec #E #Ecghsct #EJ -1tRV_a #Ec #E #EC #Efjkvfw #EJ:s :(q
T q
X q
Q\ q
f 26b DPw DPT(^ DPLNt NV N` 37TX\eg FC Fs FRU FP
F 
Y\ 
 68 +7 +7K +7Z@
6 @
[ @
D =?  e CU ::
d 
F 
N` 
0 >B" $N# $Ns $NL =A X Xc X2 7;2 ^HG ^H- ^H@# #$|J\ #J &eBSW  PD 9=R )S )# )V [] NS N% Nc Nc Nan N` +/TPT]_ .GC .Gs .G# .Gdhivdw .G`4
t 4
x 4
= 4
l:C :C : 8<$]ajl IO IOC IOWZ IOV KOWY B6S B6% B6# B6C B6^i B6H 79 (8# (8TF > MQY[ )EC )E )Ec )E`j )EV W[ce -;s -;c -;3 -;PS -;jt -;^ 7;\`ik 1^ 1^3 1^VY 1^ptu  qA 1^fE
4 E
x E
\d E
pz E
Nc 3 S # X\ dg  r  r0   )6ccxt.base.exchanger   ccxt.abstract.phemexr   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    ( ,   `  `  `  `  `  `  `  * 0 - - . ' & . ) * - + . * 4 %HNX{ HNr  