
    !:h                       d dl mZ d dlmZ d dlZd dlZd dlZd dlmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z  d dl!m"Z" d dl#m$Z$ d dl#m%Z% d dl#m&Z& d d	l#m'Z' d d
l#m(Z( d dl#m)Z) d dl#m*Z* d dl#m+Z+ d dl#m,Z, d dl#m-Z- d dl#m.Z. d dl#m/Z/ d dl#m0Z0 d dl#m1Z1 d dl2m3Z3 d dl4m5Z5  G d dee      Z6y)    )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                   l    e Zd Zdef fdZdxdZdefdZdefdZi fde	e
   fdZi fdefd	Zdyde
fd
Zdzde
fdZdi fdededefdZd Zdxde
fdZdxde
fdZd Zdxde
fdZdxde
fdZdxde
fdZdxde
defdZdddi fdededede	e   fdZdxdede
defdZi fdedefdZ di fde!de"fdZ#ddi fdededede	e$   fdZ%dxd ede
de$fd!Z&d" Z'd# Z(i fde)fd$Z*d%e+fd&Z,d'e+fd(Z-d)e+fd*Z.dxd+ede
fd,Z/d- Z0dxde
fd.Z1dxd+ede
de2fd/Z3di fded'e4d0e5d1e6d2e7f
d3Z8ddi fd4eded'e4d0e5d1e7d2e7fd5Z9di fd4ede+fd6Z:di fde+fd7Z;di fd4ede+fd8Z<dddi fde+dedede	e2   fd9Z=dddi fde+dedede	e2   fd:Z>dddi fde+dedede	e2   fd;Z?dddi fde+dedefd<Z@i fd=edeAfd>ZBdddi fd=e+dedede	eC   fd?ZDdddi fd=e+dedede	eC   fd@ZEd%e+fdAZFdxdBedCeGdeCfdDZHdi fde!de	eI   fdEZJdxdFede
fdGZKdddi fde+dedefdHZLd{de
dIe+fdJZMi fdedeNfdKZOdxde
deNfdLZPi fded1e6deQfdMZRdN ZSdxdOede
deQfdPZTdi fdQede+fdRZUdi fdSeVde+fdTZWdi fde!deXfdUZYdxde
de	eZ   fdVZ[dWdXi ddfdYZ\di fdZede+fd[Z]i fd=ed1e6d\ed]ede^f
d^Z_dddi fd=e+dedede	e^   fd_Z`dxd`edCeGde^fdaZad%e+de+fdbZbdddi fde+dedefdcZcdi fd=ed1e6ddedeCfdeZdi fdefdfZedxde
fdgZfdi fdhedied1e7degfdjZhdi fd4edhedied1e7degf
dkZidddi fd=e+dedede	eg   fdlZjd{dmedneGdoeGdegfdpZkdqeldredsedteduedvefdwZm xZnS )|phemexreturnc                    | j                  t        t        |          i ddddddgddd	d
dddddddi dd ddddddddddddddddddddddddddd dd!dd"di d#dd$dd%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dd1dd2dd3di d4dd5dd6dd7dd8dd9dd:dd;d<d=dd>dd?dd@ddAddBddCddDddEdi dFddGddHddIddJddKddLddMddNddOddPddQddRddSddTddUddVddWdidXdYdZd[d\d[d]d^d_d`d_d]dadbdcdddedfdgdhi didjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dddddddddddddddddddddddddiddddddddddd	idddddddddii ddddddddddddddddddddddddddddddddddi ddddddddddddddddddddddddddddddddddi ddddddddddddddddddddddddddddddddddi dddddddddddddddddddddddddddddddddddddddddddМdddddddddӜdԜd՜dt        dddd| j                  d٫      | j                  d٫      dڜiddddddddܜdddd dddddݜddddddddޜd ddddddddddddd dddddd d d dddddddddddddddid	ddiddddddܜddddddidddiddidd d dddddddi dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        d t        dt        dt        dt        dt        dt        i dt        dt        dt        d	t        d
t        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        i dt        dt        dt        dt        dt        dt         dt         dt        dt        d t        d!t        d"t        d#t        d$t        d%t        d&t        d't        i d(t        d)t        d*t        d+t        d,t        d-t        d.t        d/t        d0t        d1t        d2t        d3t        d4t        d5t        d6t        d7t        d8t        i d9t        d:t        d;t        d<t        d=t        d>t        d?t        d@t        dAt        dBt        dCt        dDt        dEt        dFt        dGt        dHt        dIt        i dJt        dKt        dLt        dMt        dNt        dOt        dPt        dQt        dRt        dSt        dTt        dUt        dVt        dWt        dXt        dYt        dZt        i d[t        d\t        d]t        d^t        d_t        d`t        dat        dbt        dct        ddt        det        dft        dgt        dht        dit        djt        dkt        i dlt        dmt        dnt        dot        dpt        dqt        drt        dst        dtt        dut        dvt        dwt        dxt        dyt        dzt        d{t        d|t        t        t        t        t        t        t        t        t        t"        t        t$        t"        t        d}t"        t"        t        t        t        t        d~dddddddddddiddddg dddiddddddd
i      S (  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accounts/positions   z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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~   rJ   createOrdersrl   rp   ro   rr   rS   rm   extendsdefault)r   price)r   r   r     )r   rJ   rm   forDerivatives)linearinverse)r   r@   r   rB   rC   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USDTr   )r@   rB   )BUSDFEITUSDUSDUSDCUSDDUSDPr  fillResponseFromRequestByLastPriceByMarkPriceByIndexPrice
ByAskPrice
ByBidPrice)r   r   r   askbid)
brokerIdx-phemex-request-expirycreateOrderByQuoteRequiresPricenetworksdefaultNetworksdefaultSubTypeaccountsByTypestableCoinsr   triggerPriceTypesMap)deep_extendsuperr0   describer-   parse_numberr    r$   r)   r(   r,   r&   r'   r   r"   r%   r*   r!   r+   )self	__class__s    S/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/async_support/phemex.pyr  zphemex.describe!   sT   fd < > R	A
(R	A
HR	A
 $R	A
 	R	A

 tR	A
 R	A
 4R	A
 (R	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R	A
` }=:N?	 2.B3	 ,@<K ##aR	A
L  de e u	
 v f f g g g w g h i i  j!MR	A
p +,,-$%)*$%,-'(,-()$%/0>?" '(()$%*+.//03445EF
 +,01+,'(-.12EF
:,a: &q	:
 ': .q: 5a: 6q: 8: 4Q: 6q: -b: 8: :1:  21!:" 4Q#:$ >q%:& @':( 21):* 4Q+:, 8-:. :1/:0 A!1:2 .q3:4 ,Q5:6 .q7:8 )!9:< /=:> 5a?:@ @A:B A!C:D DQE:F A!G:H >qI:J CAK:L A!M:N ?O:P 4QQ:R <QS:T 8U:V 7W:X =aY:Z /[:\ 0]:^ <Q_:` .qa:b 0c:d <Qe:f )!g:j *1k:l =am:n ?o:p 'q:v%q !!	
 #A +A 7 6q +A :1 :1 A! *1 =a  ?!" 4Q#$ )!%( Ea)* Ea+2 /0'(*+,-./01<=/0 ()+, *+"#&'+,$%()lSVqR	A
^ Y_R	A
` !&"&!..w7!..w7	aR	A
p #&+(, %)$(%)-
 -2).+06:#'#'"&#(	( #($)+/27/4$)#(3$6 %)&+!$$*%&*/& ',#($)*.	# ',!%#($)*.( ',!%$(%)#($)*.$ ',!$$*,2%&#($)*/	*  #KHT y  ),0 )-(,)-1
 &*7 #'$  ##( "#3 "#3 	 ##OkqR	A
H "$IR	A
P 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QR	A
X (+-37""" E$ #+"$#	  .t *)+'')=%YR	A
 R	 R		    Nc                     ||S |j                  d      }dj                  |      }|j                  d      }| j                  |d      S )N,  r   )splitjoinsafe_number)r  valuepartss      r  parse_safe_numberzphemex.parse_safe_numberv  sH    =LC C q))r  marketc                    | j                  |d      }| j                  |d      }| j                  |d|      }| j                  |d      }| j                  |d      }| j                  |      }|j                  dd      }| j                  |      }| j                  |      }	d}
||k7  rd	}
d|vr||k(  r|	}| j                  |d
      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |dd      }d }|	dk(  r| j	                  d      }nH|j                  d      r&|j                  d      }| j	                  |d         }n| j	                  |      }| j                  i d|d|dz   |z   dz   |	z   d|d|d|	d|d|d|dd d!dd"dd d	d#dd$dd%|d&k(  d'd	d(|
 |
| j	                  | j                  ||            | j	                  | j                  ||            |d d d d |||| j                  |d)d*      | j                  |d+      d,| j	                  d      | j                  |d-      d.d d d.| j	                  | j                  ||            | j	                  | j                  ||            d.d | j	                  | j                  |d/            d.d0d |d1      S )2NsymbolcontractUnderlyingAssetsbaseCurrencyquoteCurrencysettleCurrencyr  r  FT
priceScale
ratioScale
valueScale
minPriceEp
maxPriceEpmakerFeeRateErtakerFeeRateErstatuscontractSizer  1r   r3   /:basequotesettlebaseIdquoteIdsettleIdtyperB   r@   rA   rC   rD   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  r3   r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  contractSizeStringr  r  s                         r  parse_swap_marketzphemex.parse_swap_market~  s   d fh/#'#3#3F<V#W !!&.:RS""6?;##F,<=&&v.||C$''0((2w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\\*j-QR,,T\\*j-QR
  ,,T-=-=fm-TU$ i5+
 5 5	r  c                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |      }| j                  |d      }| j                  | j                  |d            }	| j                  | j                  |d            }
| j	                  i d|d|d	z   |z   d
|d|dd d|d|dd d|ddddddddddd|dk(  dddd d | j                  |d      | j                  |d      d d d d d | j                  |d      | j                  |d      | j                  |d      |	|
d d d d!|	| j                  | j                  |d"            d!|
d d!| j                  | j                  |d#            | j                  | j                  |d$            d!d%| j                  |d&      |d'      S )(Nr  r  r  r  r  baseTickSizequoteTickSizer3   r  r  r  r  r  r  r  r@   TrA   FrB   rC   rD   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  r3   r  r  r  r  r  precisionAmountprecisionPrices              r  parse_spot_marketz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                   K   | j                  |      }| j                  |      }t        j                  ||g  d{   \  }}| j	                  |dg       }| j                  |di       }| j                  |dg       }| j                  |dg       }	| j                  ||	      }| j                  |dg       }
| j                  |dg       }| j                  |
|      }
| j                  |dg       }| j                  |
d      }| j                  |d      }| j                  |d	      }g }t        d
t        |            D ]  }||   }| j                  |d      }|dk(  s
|dk(  s|dk(  rn| j                  |d      }| j                  ||i       }| j                  ||      }| j                  ||i       }| j                  ||      }| j                  |      }n]| j                  |d      }| j                  ||i       }| j                  |dd      }| j                  |d|i      }| j                  |      }|j!                  |        |S 7 	w)a  
        retrieves data on all markets for phemex

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

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        Ndatar   perpProductsV2
riskLimitsriskLimitsV2
currenciesr  currencyr   r  	perpetualperpetualv2perpetualpilotr  r  8)v2GetPublicProductsv1GetExchangePublicProductsasynciogather
safe_value	safe_dict	safe_listarray_concatindex_byrangelenr  r  extendr  r  append)r  paramsv2ProductsPromisev1ProductsPromise
v2Products
v1Productsv1ProductsDatav2ProductsDatar   perpetualProductsV2r  r  r  riskLimitsByIdv1ProductsByIdcurrenciesByCoderesultir  r  r3   riskLimitValuesv1ProductsValuesr  currencyValuesr  s                             r  fetch_marketszphemex.fetch_marketso  sU     !44V<l !<<VD'.~~8IK\7]'^!^
JVR@H 
FB?>>.*bA"nn^=MrR$$X/BC^^NL"E
~~nnbI&&z<@
^^NL"E
z8<~x@==Z@q#h-( 	"Aa[F))&&9D#)>DL\D\%%fh7"&..R"HV_=#'>>."b#I V-=>//7#//G!%0@,PR!S!--nlCP
VlJ-GH//7MM&!!	"" E "_s   :IIH	Ic                   K   | j                  |       d{   }| j                  |di       }| j                  |dg       }i }t        dt        |            D ]#  }||   }| j	                  |d      }| j	                  |d      }	| j                  |      }
| j	                  |d      }| j	                  |d      }t        |      }| j	                  |d	      }| j	                  |d
      }d}d}d}|l| j                  |      }| j                  |      }| j                  t        j                  ||            }| j                  t        j                  ||            }|||
|	|dk(  ddd|||ddddd|ddd||
<   & |S 7 kw)z
        fetches all available currencies on an exchange
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        Nr
  r  r   r  r4   r  r  
minValueEv
maxValueEvr  r  )r  r   crypto)r3   r  coder4   r  depositr   feer  r  r  r  r  )r  r  r  r  r  r  intparse_precisionr  r.   
string_mul)r  r!  responser
  r  r,  r-  r  r3   r4   r6  r  valueScaleStringr  r3  r4  	minAmount	maxAmountr  precisionStrings                       r  fetch_currencieszphemex.fetch_currenciesS  s     11&99 x4__T<<
q#j/* )	A!!}H!!(J7B##Hf5D**2.D%%h9F#//,G-.J))(LAJ))(LAJ!I!I!I%"&"6"67G"H --o>	 --g.@.@_.]^	 --g.@.@_.]^	  H, &  )(
  $#!	 )  -F4L%)	T y :s   FFE+Fc                    |t        | j                  dz         | j                  ||      }|d   r| j                  ||      }| j	                  | j                  | j                  ||      |            | j	                  |      gS )Nz/ customParseBidAsk() requires a market argumentr@   )r#   r3   r  from_evr  from_ep)r  bidaskpriceKey	amountKeyr  r  s         r  custom_parse_bid_askzphemex.custom_parse_bid_ask  s    >#DGG._$_``!!&)4&>\\&&1Fdll4+;+;FH+MvVWf%
 	
r  c	           
         ||| j                  |      d d}	||g}
t        dt        |
            D ]`  }|
|   }g }| j                  ||      }t        dt        |            D ](  }|j	                  | j                  ||   |||             * ||	|<   b | j                  |	|   dd      |	|<   | j                  |	|   d      |	|<   |	S )N)r  	timestampdatetimenoncer   T)iso8601r  r  r  r   rH  sort_by)r  	orderbookr  rJ  bidsKeyasksKeyrF  rG  r  r,  sidesr-  sider   bidasksks                   r  custom_parse_order_bookzphemex.custom_parse_order_book  s    "Y/	
 '"q#e*% 	"A8DFooi6G1c'l+ bd77
HiY_`ab!F4L	" ,,vg4@w,,vg:wr  r  r   c           
      t  K   | j                          d{    | j                  |      }d|d   i}d}|d   r2|d   dk(  r*| j                  | j                  ||             d{   }nZ|/|dk  r*| j	                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |di       }| j                  |d	d
i       }| j                  |dd      }	| j                  |||	dddd|      }
| j                  |d      |
d<   |
S 7 7 7 7 tw)aa  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

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

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        Nr  r3   r   r  r     r,  bookorderbook_prJ  ư>bidsasksr   r   sequencerL  )load_marketsr  v2GetMdV2Orderbookr  v1GetMdOrderbookv1GetMdFullbookr  safe_value_2safe_integer_productrV  r  )r  r  r   r!  r  requestr<  r,  rY  rJ  rO  s              r  fetch_order_bookzphemex.fetch_order_book  sN     !!!V$fTl
 (x 0F :!44T[[&5QRRH!!%!6!6t{{7F7S!TT!%!5!5dkk'66R!SS4 8R8  C--fk8L	00vy&RXZ[]^`fg	!..vzB	'Y 	" S USsG   D8D/AD8&D2'0D8D4)D8D6A.D82D84D86D8c                     | j                  |      }t        |      }|j                  |z
  |_        |j                          t	        |      }| j                  |      S N)number_to_stringr.   decimalsreducestrparse_to_numeric)r  nscalestringNprecisepreciseStrings         r  to_enzphemex.to_en  sS    ''*'""++e3G$$]33r  c                 8    |||S | j                  ||d         S Nr  rs  )r  r  r  s      r  to_evzphemex.to_ev  s&    NMzz&&"677r  c                 8    |||S | j                  ||d         S Nr  rv  )r  r   r  s      r  to_epzphemex.to_ep  s&    Mv~Lzz%!566r  c                     ||y t        |      }| j                  |j                  |      |_        |j                          t	        |      S rh  )r.   sumrj  rk  rl  )r  enro  rq  s       r  r  zphemex.from_en   sD    :"+88G$4$4e<7|r  c                 R    |||S | j                  || j                  |d            S ry  r  r  )r  epr  s      r  rD  zphemex.from_ep  .    JFNI||B 1 1&, GHHr  c                 R    |||S | j                  || j                  |d            S ru  r  )r  evr  s      r  rC  zphemex.from_ev  r  r  c                 R    |||S | j                  || j                  |d            S )Nr  r  )r  err  s      r  from_erzphemex.from_er  r  r  c                 @   |7|d   r2| j                  | j                  | j                  |d      |            }n| j                  |d      }| j	                  |d      | j                  | j                  | j                  |d      |            | j                  | j                  | j                  |d      |            | j                  | j                  | j                  |d      |            | j                  | j                  | j                  |d      |            |gS )Nr@      r   r      r      )r  rC  r  r  safe_timestamprD  )r  ohlcvr  
baseVolumes       r  parse_ohlcvz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   sincec                 t  K   | j                          d{    | j                  |      }|}|d   | j                  | j                  ||      d}| j	                  |dd      }	| j                  |dg      }|d   xs |d   dk(  xr
 |duxs |	du}
d	}|
rd
}||}t        ||      |d<   d}|d   s|d   dk(  r|	|| j                  |      }|t        t        |d	z              }||d<   n|	dz  ||z  z
  }|	t        t        |	d	z              |d<   n$|||z  z   }| j                         }||kD  r|}||d<   | j                  | j                  ||             d{   }n| j                  | j                  ||             d{   }nf|;| j                  |      d	z  }| j                         |z
  }| j                  ||z        }| j!                  | j                  ||             d{   }| j#                  |di       }| j%                  |dg       }| j'                  |||||      S 7 7 7 7 Fw)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
        Nr3   )r  
resolutionuntiltor   r  r  r   r   r   fromd   r
  rows)r_  r  r  r   safe_integer_2omitr  parse_timeframer9  roundsecondspublicGetMdV2KlineListr  publicGetMdV2KlineLastmillisecondsparse_to_intpublicGetMdV2Kliner  r  parse_ohlcvs)r  r  	timeframer  r   r!  r  	userLimitre  r  usesSpecialFromToEndpointmaxLimitr<  candleDurationr  nowduration	timeDeltar
  r  s                       r  fetch_ohlcvzphemex.fetch_ohlcv3  s     !!!V$	Tl**4??IyQ
 ##FGT:6G9-&,X&6&T&:Jf:T  %H]bjn]n  ]Gty  BF  uF!$H=Euh/(vh/69!u'8!%!5!5i!@$edl 34E&+GFO #S[X-FGE$$'edl(;$<GDM (^";<B,,.CCx $&GDM!%!<!<T[[RX=Y!ZZ!%!<!<T[[RX=Y!ZZ   //	:TA --/%7	)))h*>?!44T[[&5QRRH x4~~dFB/  vy%KK} 	"F [Z SsH   H8H/EH8H2)H8H4	A&H8/H60A H82H84H86H8tickerc                 p   | j                  |d      }| j                  ||      }|d   }| j                  |dd      }| j                  | j	                  |dd      |      }| j                  | j	                  |dd      |      }| j                  |d      }|#| j                  | j	                  |d	d
      |      }| j                  | j                  |d      |      }	| j                  i d|d|d| j                  |      d| j                  | j	                  |dd      |      d| j                  | j	                  |dd      |      d| j                  | j                  |d      |      dd d| j                  | j                  |d      |      dd dd d|	d|d|dd dd dd d d |||d!|      S )"Nr  rJ  r[  lastEpcloseRp
turnoverEv
turnoverRvvolumevolumeEvvolumeRqopenEprK  highhighEphighRplowlowEplowRpr  bidEp	bidVolumer  askEp	askVolumevwapopencloser   previousClosechanger   average)r  quoteVolumer  )	r  safe_marketrd  rD  safe_string_2r  rC  safe_tickerrM  )
r  r  r  marketIdr  rJ  r   r  r  r  s
             r  parse_tickerzphemex.parse_ticker  s>   l ##FH5!!(F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                   K   | j                          d{    | j                  |      }d|d   i}d}|d   ra|d   s|d   dk(  r*| j                  | j                  ||             d{   }nS| j	                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |di       }| j                  ||      S 7 7 7 W7 /w)	a   
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

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

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nr  r3   rB   r   r  r  r,  )r_  r  v1GetMdTicker24hrr  v2GetMdV2Ticker24hrv1GetMdSpotTicker24hrr  r  r  r  r!  r  re  r<  r,  s          r  fetch_tickerzphemex.fetch_ticker  s      !!!V$fTl
 &>i F8$4$=!%!7!7GV8T!UU!%!9!9$++gv:V!WW!77GV8TUUHZ (B7  00w 	" VWUsF   C1C)AC1+C+,)C1C-)C1?C/ *C1+C1-C1/C1symbolsc                 D  K   | j                          d{    d}|#| j                  |d      }| j                  |      }d}| j                  d||      \  }}d}| j	                  d||      \  }}| j                  |d      }d}|dk(  r| j                  |       d{   }nM|dk(  s| j                  |d      dk(  r| j                  |       d{   }n| j                  |       d{   }| j                  |d	g       }	| j                  |	|      S 7 7 z7 H7 0w)
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   rw   r  r@   r   r  r  r,  )r_  r  r  handle_market_type_and_paramshandle_sub_type_and_paramsr  v1GetMdSpotTicker24hrAllr  v1GetMdTicker24hrAllv2GetMdV2Ticker24hrAllr  parse_tickers)
r  r  r!  r  firstr  subTypequeryr<  r,  s
             r  fetch_tickerszphemex.fetch_tickers   s)     !!!OOGQ/E[['F99.&RXYf99.&RXY		&&)6>!::5AAH	!T%5%5fh%G5%P!66u==H!88??H(B7!!&'22% 	" B=?sF   D DBD D 3D DD -D.*D D D D c                   K   | j                          d{    | j                  |      }d|d   i}d}|d   r2|d   dk(  r*| j                  | j                  ||             d{   }n)| j	                  | j                  ||             d{   }| j                  |di       }| j                  |dd	g       }	| j                  |	|||      S 7 7 k7 Cw)
aH  
        get the list of most recent trades for a particular symbol

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

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Nr  r3   r   r  r  r,  tradestrades_p)r_  r  v2GetMdV2Trader  v1GetMdTrader  rc  parse_trades)
r  r  r  r   r!  r  re  r<  r,  r  s
             r  fetch_tradeszphemex.fetch_trades@  s      !!!V$fTl
 (x 0F :!00Wf1MNNH!..t{{7F/KLLH" 8R8""68ZD  >>; 	" OLs5   CCAC&C')CCA CCCtradec                 V   d }d }d }d }d }d }d }	d }
| j                  |d      }| j                  ||      }|d   }d }d }t        |t              rt	        |      }| j                  |dd      }|dkD  r| j                  ||dz
        }| j                  ||dz
        }| j                  ||dz
        }| j                  ||dz
        }t        ||dz
     t        j                        r| j                  ||      }| j                  ||      }n| j                  |dd      }|| j                  |d	      }| j                  |d
d      }| j                  |d      }|d   dk(  r| j                  |d      }|dk(  s|dk(  r|}n|	|dk(  rdnd}| j                  |d      }|dk(  rd}n|dk(  rd}| j                  |d      }| j                  |d      }| j                  |d      }| j                  | j                  |d            }| j                  |d      }	|%| j                  |d      }| j                  |      }
n| j                  | j                  |d            }||}d}
n| j                  |d      }| j                  | j                  |d            }| j                  |d      }|d k(  rd!}| j                  | j                  |d"      |      }| j                  | j                  |d#      |      }| j                  |d$|      }| j!                  | j                  |d%d&      |      }| j!                  | j                  | j                  |d'            |      }|| j!                  | j                  |d(      |      }	|d)   r"| j                  | j                  |d*            }
nN| j#                  |d+      }|:| j                  |d,      }| j                  |      }
n| j                  |d      }|d}
||	|
d-}| j%                  ||||| j'                  |      ||||||||d.|      S )/Nr  r   r[  r  r   r   r   transactTimeNs	createdAtexecIdexecIDorderIDr  r  rS  buysellr  ordTyper  2r   execPriceRp	execQtyRqexecValueRv	execFeeRv	feeRateRrr  ptFeeRvPT
execStatus	MakerFillr   execPriceEpexecBaseQtyEvexecQtyexecQuoteQtyEvexecValueEv	execFeeEv	feeRateErr@   feeCurrencyr  settlementCurrency)r  rater  )r  r3   r  rJ  rK  orderr  rS  takerOrMakerr   r  r  r8  )r  r  
isinstancelistr  rd  r  numbersRealrD  rC  r  r  	omit_zeror  parse_order_typer  r  
safe_traderM  )r  r  r  r3   rS  
costStringr  r8  feeCostStringfeeRateStringfeeCurrencyCoder  r  orderIdr  tradeLengthrJ  priceStringamountStringsideIdr  
currencyIdr  r  r  settlementCurrencyIds                             r  parse_tradezphemex.parse_tradek  s   r 
!!###E84!!(F3! eT"e*K11%HEIQ%%e[1_=))%qAD**5+/BK++E;?CL%a0',,?"ll;?#||L&A11%9I8TI  --e[A	##E8X>B&&ui8Gh6)//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                    d }d|i}| j                  |dg       }t        dt        |            D ]  }||   }| j                  |d      }| j	                  |      }| j                  | j
                  |i       }	| j                  |	dd      }
| j                         }| j                  |d      }| j                  |d      }| j                  |d	      }| j                  ||
      }| j                  ||
      }| j                  ||
      }t        j                  ||      }| j                  |d
d      }||nt        ||      }||d<   ||d<   |||<   " ||d<   | j                  |      |d<   | j                  |      S )Nr  r
  r   r  r     	balanceEvlockedTradingBalanceEvlockedWithdrawEvlastUpdateTimeNsr[  totalusedrJ  rK  )r  r  r  r  r  r  r  accountr  r.   
string_addrd  r  rM  safe_balance)r  r<  rJ  r,  r
  r-  balancer  r6  r  ro  r  r  r  r  r  lockedTradingBalancelockedWithdrawr  r  s                       r  parse_spot_balancezphemex.parse_spot_balance  s   2 	)x4q#d)$ 	#A1gG))':>J**:6DtbAH%%ha@EllnG((+>I%)%5%5g?W%X"#//9KLLLE2E#'<<0F#N !\\*:EBN%%&:NKD#88BTV^_-6->(STdEeI$GG"GFO"F4L%	#& ({!\\)4z  ((r  c                    d|i}| j                  |di       }| j                  |di       }| j                  |d      }| j                  |      }| j                  |      }| j	                  |dd      }| j                         }	| j                  |dd      }
| j                  |d	d
      }|dk7  }|r| j                  |
|      n|
|	d<   |r| j                  ||      n||	d<   |	||<   | j                  |      S )Nr  r
  r  r  r  r  accountBalanceEvaccountBalanceRvtotalUsedBalanceEvtotalUsedBalanceRvr  r  r  )	r  r  r  r  r  r  r  r  r!  )r  r<  r,  r
  r"  r  r6  r  r  r  r'  r)  needsConversions                r  parse_swap_balancez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                   K   | j                          d{    d}| j                  dd|      \  }}| j                  |d      }| j                  |dg      }d}i }|dk7  r#|dk7  rt	        | j
                  dz   |z   dz         |dk(  rd}| j                  |ddd	      \  }}||~d}||}n|}| j                  |      }|d
   |d<   |d
   d	k(  r*| j                  | j                  ||             d{   }n| j                  | j                  ||             d{   }n| j                  |d      }|t        | j
                  dz   |z   dz         | j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }|dk(  r| j                  |      S | j                  |      S 7 7 7 7 \7 4w)a  
        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>`
        NrP   r6  r@   rB   z does not support z markets, only spot and swapr  r  r3   r  zP fetchBalance() requires a code parameter or a currency or settle parameter for z type)r_  r  r  r  r$   r3   handle_option_and_paramsr  #privateGetGAccountsAccountPositionsr  "privateGetAccountsAccountPositionsr#   privateGetSpotWalletsr,  r%  )	r  r!  r  r6  r<  re  r  coinr  s	            r  fetch_balancezphemex.fetch_balance  s     !!!99.$PVWf/6F8,FNTWW';;dBEccdd6>F!::6>S[]cdNFF6#5#D!D==.&.tn
#D>V+%)%M%MdkkZaciNj%kkH%)%L%LT[[Y`bhMi%jjH++FJ?#+DGG  7I  -I  LP  -P  SZ  -Z  [  [!%!;!;DKKQW<X!YY!77GV8TUUHl 6>**844&&x00m 	"*  lj
 ZUsY   GGCG4G5)GGAG:G;)G$G%,GGGGGr  c                     i ddddddddddd	dd
dddddddddddddddddddddddi}| j                  |||      S )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_statuszphemex.parse_order_status  s    
v
6
 8
 	

 

 6
 v
 h
 

 
 
 
 
 
 
  !
" #
$ %
( &&99r  r  c                 F    ddddddddddddd}| j                  |||      S )Nr  r   stop	stopLimit)r  r  rB  rC  rD  rE  rF  r  910Limitr   rG  )r  r  typess      r  r	  zphemex.parse_order_type  sD    
 tT22r  r   c                 6    ddddd}| j                  |||      S )NGTCr   r   r   )GoodTillCancelPostOnlyImmediateOrCancel
FillOrKillrG  )r  r   timeInForcess      r  parse_time_in_forcezphemex.parse_time_in_force  s,    #!&	
 k;GGr  r  c           
      ^   | j                  |d      }| j                  |d      }|t        |      dk  rd }| j                  |d      }| j                  ||      }|d   }| j                  | j                  |d      |      }| j	                  | j                  |d      |      }| j                  | j	                  | j                  |d      |            }	| j	                  | j                  |dd	      |      }
| j                  | j                  |d
d      |      }| j                  | j                  |d      |      }| j                  | j                  |d            }| j                  |d      }| j                  | j                  |d            }| j                  |ddd      }d }| j	                  | j                  |d      |      }|$|| j                  | j                  |d            d}| j                  | j                  |d            }| j                  | j                  | j                  | j                  |d                        }|dk(  }| j                  i d|d|d|d|d| j!                  |      dd d|d|d|d |d|d!|d"|d#|d$|d%|d&|
|	||d d'|      S )(Nr  clOrdIDr   r  priceEp	baseQtyEvleavesBaseQtyEvcumBaseQtyEvcumBaseValueEvcumQuoteValueEv
quoteQtyEv
avgPriceEp	ordStatusrS  r  actionTimeNscreateTimeNsr[  cumFeeEvr  r  r  r   stopPxEpr   r  r3   clientOrderIdrJ  rK  lastTradeTimestampr  postOnlyr   r   r  r  r  filled)	remainingr  r8  r  )r  r  r  rD  rC  r  r  r  rJ  r  r	  safe_integer_product_2r  rY  r  
safe_orderrM  )r  r  r  r3   rj  r  r  r   r  rn  rm  r  r  r  rS  r  rJ  r8  feeCostr   r   rl  s                         r  parse_spot_orderzphemex.parse_spot_order  s8   r eY/((	:%C,>,B M##E84!!(F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                 2    ddd}| j                  |||      S )Nr  r  )r  r  rG  )r  rS  rR  s      r  parse_order_sidezphemex.parse_order_side+	  s&    
 tT22r  c                    | j                  |dd      }| j                  |dd      }|t        |      dk  rd }| j                  |d      }| j                  ||      }| j	                  ||      }| j                  | j                  |d            }| j                  | j                  |d            }| j                  | j                  |d	            }	| j                  |d
      }
|
"| j                  | j                  |d      |      }
| j                  |dd      }| j                  |dd      }| j                  |dd      }| j                  |dd      }|| j                  |d      }| j                  |dd      }| j                  |dd      }|dk(  rd }| j                  | j                  |d            }| j                  | j                  |dd            }|dk(  }| j                  |d      }| j                  |d      }|dk(  rd }| j                  |d!      }| j                  |d"      }| j                  | j                  |d#            }| j                  | j                  |d$            }d }|	||d%   d&}n||d'd&}| j!                  i d(|d)|d*|d+| j#                  |      d,|d-|d|d.|	d|d/|d|d|d0|
d1|d2|d3|d4||||d ||d d5      S )6Nr  r  r[  clOrdIdr   r  rd  rS  	orderTypepriceRpr\  orderQty
orderQtyRqcumQtycumQtyRq	leavesQtyleavesQtyRqre  r[  r  cumValue
cumValueRvr  r   r   stopPxstopPxRpr   
reduceOnlyexecInst
ReduceOnlyTtakeProfitRp
stopLossRpr  r  r  rh  r  r  r3   rj  rK  rJ  rk  r  rl  r   r   r   r   r  )rm  rn  r  r  r  r8  r  )r  r  r  safe_symbolr  rJ  rt  r  r	  rD  r  rd  r  rY  r  r  rp  rM  )r  r  r  r3   rj  r  r  r  rS  r  r   r  rm  rn  rJ  r  rk  r   r   rl  r  r  
takeProfitstopLossfeeValuer  r8  s                              r  parse_swap_orderzphemex.parse_swap_order2	  s   L y)<**5)YG%C,>,B M##E84!!(F3!!(F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                     | j                  |dd      }d|v xs
 d|v xs d|v }|s|r| j                  ||      S | j                  ||      S )NrB   F	closedPnlclosedPnlRv
totalPnlRv)	safe_boolr  rr  )r  r  r  isSwaphasPnls        r  parse_orderzphemex.parse_order	  s^    6&^MU,B^X]H]V((77$$UF33r  rS  r  r   c                 N  K   | j                          d{    | j                  |      }| j                  |      }| j                  |      }|d   ||d}	| j                  |dd      }
| j	                  |d      }|du}| j	                  |d      }|du}|
6| j                  | j                  dd	      }|0|| j                         z   |	d<   n|
|	d<   | j                  |ddg      }| j                  |g d
      }|3|d   dk(  r| j                  ||      |	d<   n| j                  ||      |	d<   | j                  |g d      }|d   rA| j	                  |dd      }|dk(  s
|dk(  s|dk(  r|d}||dk(  rd|	d<   n
|dk(  rd|	d<   d|	d<   ||	d<   |dk(  r| j                  |d      }| j                  |d      }| j                  d   rl|J| j                  |      }| j                  |      }t        j                  ||      }| j!                  |      }n |t#        | j$                  dz   |z   dz         ||n|}| j                  |      }| j'                  ||      |	d <   n| j                  |      }| j'                  ||      |	d!<   n|d"   r| j)                  |d#d$      }| j                  |d#      }| j+                  |d%      }|=|r9| j)                  |d&      }|r|d'k(  rd(nd'}| j                  |d&      }|d'k(  rd)nd*}nd+}| j                  |      }||	d%<   |d   dk(  r||	d,<   n| j-                  |      |	d-<   || j                  |d.d/      }||	d.<   d}| j/                  |d0      \  }}|t#        | j$                  d1z         |d2k(  r$|d(k(  r|dk(  rdnd3|	d<   n:|d'k(  r5|dk(  rdnd|	d<   n(|d4k(  r#|d(k(  r|dk(  rdnd|	d<   n|d'k(  r|dk(  rdnd3|	d<   |s|r|r| j1                  |d5d6      }|t3        | j$                  d7z         |d   dk(  r| j                  ||      |	d8<   n| j                  ||      |	d9<   | j                  |d:d;      }|#| j                  | j                  d<   ||      |	d;<   | j                  |d=      }|| j                  ||      |	d><   |r| j1                  |d5d6      }|t3        | j$                  d?z         |d   dk(  r| j                  ||      |	d@<   n| j                  ||      |	dA<   | j                  |d:dB      } | #| j                  | j                  d<   | |       |	dB<   | j                  |d=      }!|!| j                  ||!      |	dC<   |dk(  s
|dk(  s|d3k(  rD|d   dk(  r| j                  ||      |	dD<   n&| j                  |      }| j                  ||      |	dE<   | j                  |dF      }"|"E|d   dk(  r| j                  ||"      |	d@<   n| j                  |"|      |	dA<   | j                  |dF      }| j                  |dG      }#|#E|d   dk(  r| j                  ||#      |	d8<   n| j                  |#|      |	d9<   | j                  |dG      }d}$|d   dk(  r*| j5                  | j7                  |	|             d{   }$nX|dH   r*| j9                  | j7                  |	|             d{   }$n)| j;                  | j7                  |	|             d{   }$| j=                  |$dIi       }%| j?                  |%|      S 7 7 7 X7 0w)Ja  
        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>`
        Nr3   )r  rS  r  r[  rj  r  r  r  r  )r  	stopPricer   r  r  r  ri  )r  r  r  r  r   r@   qtyTypeByBaser   StopMarketIfTouchedByQuoterP  	StopLimitr  r  r   r  r  z createOrder() z. requires a price argument or a cost parameterrb  r]  rB   r   FposSider  r  r  LongShortMergedrz  ry  triggerTyper  r   z\ createOrder() also requires a 'triggerDirection' parameter with either 'up' or 'down' valueupLimitIfTouched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tpPxRprx  r\  r   r   r  r
  ) r_  r  
capitalizer  r  r  r  uuid16r  safe_string_nprice_to_precisionrz  r  ri  r.   r;  r  r#   r3   rw  r  r  r  handle_param_stringrc  r'   privatePostGOrdersr  privatePostOrdersprivatePostSpotOrdersr  r  )&r  r  r  rS  r  r   r!  r  requestSidere  rj  r  stopLossDefinedr  takeProfitDefinedr  r   r  r  r  r  quoteAmountr  r   r  r  r  r   stopLossTriggerPricestopLossTriggerPriceTypeslLimitPricetakeProfitTriggerPricetakeProfitTriggerPriceTypetpLimitPricer   r   r<  r
  s&                                         r  create_orderzphemex.create_order	  sS    , !!!V$ood+t$ Tl	
8 **69oN??6:6#4/__V\:
't3 ''j,OH#%-%=	"!.GIYYv	?'CDF))&2YZ#h6)&*&=&=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h6)(.%&*&7&7&?
#'"..v}mT)4&#' +/+C+CFL^+_( &#++DGG  7U  -U  V  V#t+v~CG8CS->Zj	*8<8HV{	*%/v~8<8HV{	*CG8CS->Zj	*"3"+/+<+<X~Wb+c(+3*477  6[  ,[  \  \h'61040G0G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_  ,_  `  `h'61262I2I&Rh2i/26**=SU[2\/151C1CJPbdo1p.1=/3/?/?Mc@d  gA  C]  0^,#'#3#3J#HL#/,0,C,CFL,Y)GO!4$BR:Rh6)%)%<%<VU%K	""33E:%)ZZV%D	"**63DE&h6)*.*A*A&/*Z'*.**_f*M'YYv'89F((A$h6)(,(?(?(V%(,

=&(I%YYv7F(v%!44T[[&5QRRHJ!33DKK4PQQH!77GV8TUUHZ ~~h3f--w 	"R SQUsF   \%\Z\%\.\%\!	)\%2\#3*\%\%!\%#\%r3   c                 L  K   | j                          d{    | j                  |      }d|d   i}	| j                  |dd      }
| j                  |ddg      }|d   dk(  }|
|
|	d<   n||	d<   |0|r| j	                  |d   |      |	d	<   n| j                  ||      |	d
<   | j                  |d      }| j                  |dg      }|||	d<   n2|0|r| j                  |d   |      |	d<   n| j                  ||      |	d<   | j                  |g d      }|-|r| j	                  ||      |	d<   n| j                  ||      |	d<   | j                  |g d      }d}|rC| j                  |d      }|d|	d<   | j                  | j                  |	|             d{   }nX|d   r*| j                  | j                  |	|             d{   }n)| j                  | j                  |	|             d{   }| j                  |di       }| j                  ||      S 7 7 7 X7 0w)aD  
        edit a trade order

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

        :param str id: cancel order id
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.posSide]: either 'Merged' or 'Long' or 'Short'
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r3   rj  r[  r  r  r  rx  r\  r]  	baseQtyEVrz  )r   r  r  r  ri  r  r  rB   r
  )r_  r  r  r  r  rz  r  amount_to_precisionrw  r  privatePutGOrdersReplacer  privatePutOrdersReplaceprivatePutSpotOrdersr  r  )r  r3   r  r  rS  r  r   r!  r  re  rj  isUSDTSettledfinalQtyr   r<  r  r
  s                    r  
edit_orderzphemex.edit_order
  sT      !!!V$fTl
 **6?IN6OY#?@)V3$!.GI!#GI%)%<%<VH=Mu%U	"%)ZZv%>	"##FK86K=1#+GK (,(@(@AQSY(Z%'+zz&&'A$))&2YZ#&*&=&=fl&S
#&*jjv&F
#6#JK&&vy9G%-	"!::4;;wPV;WXXHF^!99$++gv:VWWH!66t{{7F7STTH~~h3f--[ 	"N YWTsF   H$HFH$H.H$H )H$1H"2*H$H$ H$"H$c                   K   |t        | j                  dz         | j                          d{    | j                  |      }d|d   i}| j	                  |dd      }| j                  |ddg      }|||d<   n||d<   d}|d   d	k(  rC| j                  |d
      }|d|d
<   | j                  | j                  ||             d{   }nX|d   r*| j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |di       }	| j                  |	|      S 7 7 7 X7 0w)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  r3   rj  r[  r  r  r  r  r  rB   r
  )r#   r3   r_  r  r  r  r  privateDeleteGOrdersCancelr  privateDeleteOrdersCancelprivateDeleteSpotOrdersr  r  )
r  r3   r  r!  r  re  rj  r<  r  r
  s
             r  cancel_orderzphemex.cancel_order9  sf     >#DGG.Y$YZZ!!!V$fTl
 **6?IN6OY#?@$!.GI!#GI(v%&&vy9G%-	"!<<T[[RX=YZZHF^!;;DKKQW<XYYH!99$++gv:VWWH~~h3f--- 	"  [YWsF   .EEBEE	.E7E8)E!E"*EEEEc                 L  K   |t        | j                  dz         | j                          d{    | j                  |      }| j	                  |ddd      }| j                  |ddg      }d|d   i}|r||d<   d}|d	   d
k(  r*| j                  | j                  ||             d{   }nX|d   r*| j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  d|i      gS 7 7 s7 F7 w)a  
        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 argumentrL  r   Fr  r3   untriggerredr  r  rB   r  )r#   r3   r_  r  rc  r  privateDeleteGOrdersAllr  privateDeleteOrdersAllprivateDeleteSpotOrdersAllrp  )r  r  r!  r  r   re  r<  s          r  cancel_all_orderszphemex.cancel_all_orders_  sA     >#DGG.]$]^^!!!V$##FFIuE6FI#67fTl

 &-GN#(v%!99$++gv:VWWH F^!88Wf9UVVH "<<T[[RX=YZZH OO 
 	
S 	" X W [sF   .D$DA9D$*D+.D$D )D$D"D$D$ D$"D$c                   K   |t        | j                  dz         | j                          d{    | j                  |      }d|d   i}| j	                  |dd      }| j                  |ddg      }|||d<   n||d<   d}|d   d	k(  r*| j                  | j                  ||             d{   }nX|d
   r*| j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |di       }|}	t        |t              rnt        |      }
|
dk  rJ|$t        | j                  dz   |z   dz   |z   dz         t        | j                  dz   |z   dz   |z   dz         | j                  |di       }	n+|d
   r&| j!                  |dg       }| j                  |di       }	| j#                  |	|      S 7 7 17 7 ݭw)a  

        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  r3   rj  r[  r  r  r  r@   r
  r   z fetchOrder() z order with clientOrderId z
 not foundz order with id r   r  )r#   r3   r_  r  r  r  (privateGetApiDataGFuturesOrdersByOrderIdr  %privateGetApiDataSpotsOrdersByOrderIdprivateGetExchangeOrderr  r  r  r  r(   r  r  r  )r  r3   r  r!  r  re  rj  r<  r
  r  	numOrdersr  s               r  fetch_orderzphemex.fetch_order  s     >#DGG.X$XYY!!!V$fTl
 **6?IN6OY#?@$!.GI!#GI(v%!JJ4;;W^`fKghhHF^!GGT[]cHdeeH!99$++gv:VWWHx4dD!D	I1} ,'2B(BV(KNj(jmz(z  ~J  )J  K  K'2B(BV(KN_(_bd(dgs(sttNN4B/EF^>>$3DNN4B/Ev..? 	" ieWsG   .G(GA>G(/G 0.G(G#)G(G&	CG( G(#G(&G(c                 f  K   |t        | j                  dz         | j                          d{    | j                  |      }d|d   i}|||d<   |||d<   d}|d   dk(  r2|d   |d	<   | j	                  | j                  ||             d{   }nX|d
   r*| j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |di       }| j                  |d|      }	| j                  |	|||      S 7 7 7 l7 Dw)aW  
        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  r3   startr   r  r  r  rB   r
  r  )r#   r3   r_  r  "privateGetExchangeOrderV2OrderListr  privateGetExchangeOrderListprivateGetApiDataSpotsOrdersr  r  parse_orders
r  r  r  r   r!  r  re  r<  r
  r  s
             r  fetch_orderszphemex.fetch_orders  sI     >#DGG.Y$YZZ!!!V$fTl
 $GG$GG(v%"("2GJ!DDT[[QXZ`EabbHF^!==dkk'SY>Z[[H!>>t{{7TZ?[\\Hx4~~dFD1  vue<<' 	" c[\sF   .D1D)A D1D+.D1 D-)D1*D/+?D1+D1-D1/D1c                   K   | j                          d{    |t        | j                  dz         | j                          d{    | j                  |      }d|d   i}d}	 |d   dk(  r*| j	                  | j                  ||             d{   }nX|d   r*| j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |di       }	t        |	t              r| j                  |	|||      S | j                  |	d	g       }
| j                  |
|||      S 7 :7 7 7 7 l# t        $ r}t        |t              rg cY d}~S |d}~ww xY ww)
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  r3   r  r  rB   r
  r  )r_  r#   r3   r  privateGetGOrdersActiveListr  privateGetOrdersActiveListprivateGetSpotOrders	Exceptionr  r(   r  r  r  r  )r  r  r  r   r!  r  re  r<  er
  r  s              r  fetch_open_orderszphemex.fetch_open_orders  s|     !!!>#DGG.]$]^^!!!V$fTl
 
	h6)!%!A!A$++gW]B^!__!%!@!@WV\A]!^^!%!:!:4;;wPV;W!XX
 x4dD!$$T65%@@>>$3D$$T65%@@3 	" 	" `^X 	!]+	G	s   FE1FE	F(,E E.E E)E -E.E 2AFFE E E 	F%E>6F7F<E>>FFc                   K   | j                          d{    d}|| j                  |      }i }||d   |d<   |||d<   |||d<   d}|| j                  |d      dk(  r@| j                  |dd      |d<   | j                  | j	                  ||             d{   }nX|d	   r*| j                  | j	                  ||             d{   }n)| j                  | j	                  ||             d{   }| j                  |d
i       }t        |t              r| j                  ||||      S | j                  |dg       }	| j                  |	|||      S 7 C7 7 7 iw)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>`
        Nr3   r  r  r   r  r  r  rB   r
  r  )r_  r  r  r  r  r  privateGetExchangeSpotOrderr  r  r  r  r  r  s
             r  fetch_closed_orderszphemex.fetch_closed_orders  s~      !!![[(F
 &tGH$GG$GGN 0 0 Bf L"&"2"268V"LGJ!DDT[[QXZ`EabbHF^!==dkk'SY>Z[[H!==dkk'SY>Z[[HJ x4dD!$$T65%@@>>$3D$$T65%@@{ 	" c[[sG   E"EBE"E.E"E)E"6E 7A#E"E"E" E"c                   K   | j                          d{    d}|| j                  |      }i }|t        d|      }||d<   |du xs | j                  |d      dk(  }|rd|d<   d|d<   |d|d<   n|d	   |d
<   |||d<   d}|r*| j	                  | j                  ||             d{   }nX|d   r*| j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }d}	|r| j                  |dg       }	n&| j                  |di       }	| j                  |	dg       }	| j                  |	|||      S 7 E7 7 7 ]w)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>`
        Nr   r   r  r  r  r   offsetr3   r  r  rB   r
  r  )
r_  r  r  r  $privateGetExchangeOrderV2TradingListr  privateGetExchangeOrderTrade!privateGetExchangeSpotOrderTradesr  r  )
r  r  r  r   r!  r  re  r  r<  r
  s
             r  fetch_my_tradeszphemex.fetch_my_tradesc  s     !!![[(FUOE$GG4ZT-=-=fh-OSY-Y"(GJ !GH}#&  &tGH$GG!FFt{{SZ\bGcddHF^!>>t{{7TZ?[\\H!CCDKKPWY_D`aaHR ??8VR8D??8VR8D??44D  vue<<O 	"( e\asG   E$EBE$+E,.E$E )E$E"AE$E$ E$"E$r6  c                   K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  d      }| j	                  ||      }| j                  | j                  di       }| j	                  |d|      }| j                  |||      }|	|d   |d<   n||d<   | j                  |d      }| j                  | j                  ||             d{   }	| j                  |	di       }
| j                  |
d	      }| j                  |
d
      }| j                  |       |	|d||dS 7 )7 Ww)a9  
        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
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        Nr  r3   r  r  network	chainNamer
  addresstag)r  r  r  r  r  )r_  r  r  r  safe_string_upperr  r  +privateGetPhemexUserWalletsV2DepositAddressr  r  check_address)r  r6  r!  r  re  r  defaultNetworkr  r  r<  r
  r  r  s                r  fetch_deposit_addresszphemex.fetch_deposit_address  sW     !!!==&
 ..7HI//F>>$,,
B?((NK""8Wg>?#+D>GK #*GK YYvy1FII$++V]_eJfgg x4""43tU+7#
 	
; 	" hs#   ED?CE*E+AEEc                    K   | j                          d{    d}|| j                  |      }| j                  |       d{   }| j                  |dg       }| j	                  ||||      S 7 Y7 -w)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
  )r_  r  $privateGetExchangeWalletsDepositListr  parse_transactionsr  r6  r  r   r!  r  r<  r
  s           r  fetch_depositszphemex.fetch_deposits&  s}      !!!}}T*HBB6JJ* ~~h3&&tXueDD5 	" K!   A4A0-A4A2,A42A4c                    K   | j                          d{    d}|| j                  |      }| j                  |       d{   }| j                  |dg       }| j	                  ||||      S 7 Y7 -w)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
  )r_  r  %privateGetExchangeWalletsWithdrawListr  r  r  s           r  fetch_withdrawalszphemex.fetch_withdrawalsK  s}      !!!}}T*HCCFKK* ~~h3&&tXueDD5 	" Lr  c                 L    dddddddddddddddd}| j                  |||      S )Nokfailedpendingr@  )SuccessSucceedr:  zSecurity check failedSecurityCheckFailedExpiredzAddress RiskzSecurity CheckingSecurityCheckingzPending ReviewzPending TransferAmlCsApporver<  	Confirmed	CancelledrG  rH  s      r  parse_transaction_statuszphemex.parse_transaction_statusp  sM     %-#+$!* )' )%"#
" &&99r  transactionr  c                 ^   | j                  |d      }| j                  |d      }d }| j                  |d      }| j                  |d      }| j                  ||      }|d   }| j                  |d      }	| j                  |g d      }
| j                  |d      }| j	                  | j                  | j                  |d	      |d
               }|| j                  |d      }d }|d}||d}| j                  | j                  |d            }| j	                  | j                  | j                  |d      |d
               }|| j                  |d      }i d|d|d|d|
d| j                  |
      d| j                  |	      d|d|dd d|d|dd d|d|d|d|dd d d |dS )Nr3   r  txHashr  r6  r  )r  
submitedAtsubmittedAtr  feeEvr  feeRv
withdrawalrh  r  amountEvamountRvr  txidrJ  rK  r  	addressToaddressFromr  tagTotagFromr  updated)commentinternalr8  )
r  safe_currencysafe_integer_nr  r  r  r  r  rM  network_id_to_code)r  r  r  r3   r  r  r  r  r6  	networkIdrJ  r  rq  r8  r  r  s                   r  parse_transactionzphemex.parse_transaction  sc   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                 "  K   | j                          d{    | j                  |      }d}| j                  |ddd      }| j                  |ddg      }d}d}| j	                  |d      }|| j                  |      }|d   }|d   }n| j                  |dd|      \  }}| j                  d||      \  }}|dk(  }|rd}n|dk(  rd}n|	|d	k(  rd
nd}| j                  |      }	d|	d   i}
d}|rrd}| j                  |ddd      \  }}|dk(  r*| j                  | j                  |
|             d{   }nS| j                  | j                  |
|             d{   }n)| j                  | j                  |
|             d{   }| j                  |di       }| j                  |dg       }g }t        dt        |            D ]'  }||   }|j!                  | j#                  |             ) | j%                  |d|d      S 7 7 7 7 w)a  
        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 'privateGetAccountsPositions' default is 'privateGetGAccountsAccountPositions'
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        Nr  r6  r  r   r  rs   BTCr   r  r3   methodr/  r
  	positionsr  F)r_  market_symbolsr  r  r  r  r.  r  r  r/  r  privateGetAccountsPositionsr0  r  r  r  r   parse_positionfilter_by_array_positions)r  r  r!  r  r6  r  r  firstSymbolr  r  re  r<  r)  r
  r*  r,  r-  positions                     r  fetch_positionszphemex.fetch_positions  sS     !!!%%g.!!&*ffE6J#78&&w2"[[-FH%F(#D!::6CSU]_cdNFF99:JFTZ[&(Du_D\$05uD==&
 F!::6CSU]  `E  FNFF>>!%!I!I$++V]_eJf!gg!%!A!A$++gW]B^!__!DDT[[QXZ`EabbHZ x4OOD+r:	q#i.) 	9A |HMM$--h78	9 --fhOOm 	"> h_bsG   HHDH2H	3)HH)HHB H	HHHr0  c                    | j                  |d      }| j                  ||      }|d   }| j                  |dd      }| j                  |dd      }| j                  |dd      }t        j                  ||      }| j                  |dd	      }	t        j
                  |	|      }
| j                  |d
d      }| j                  |dd      }| j                  |d      }| j                  |d      }| j                  |      }| j                  t        j                  | j                  |dd                  }| j                  |dd      }| j                  |d      }d }|	|dk(  rdnd}d }| j                  |d      }|dk(  r3|dk(  rt        j                  ||      }nt        j                  ||      }n|dk(  r?t        j                  t        j
                  d|      t        j
                  d|            }n>t        j                  t        j
                  d|      t        j
                  d|            }t        j                  t        j                  ||      |      }t        j
                  ||      }| j                  |d      }| j                  i d|dd d|d| j                  |      d|d| j                  |      d|d
|d | j                  |      d!| j                  |      d| j                  |      d"d d#| j                  |      d$d d%d d&| j                  |	      d'| j                  |
      | j                  |      | j                  |      | j                  |      d |rd(nd)|d*d d d d+
      S ),Nr  positionMarginpositionMarginRvr  valueRvmaintMarginReqmaintMarginReqRrassignedPosBalanceassignedPosBalanceRvliquidationPriceliquidationPriceRp	markPricemarkPriceRpsizer  r   
leverageRravgEntryPriceavgEntryPriceRprS  Buylongshortr  r  r  crossMarginr  r3   	contractsunrealizedPnl
collateralnotional	lastPrice
entryPricerJ  lastUpdateTimestampinitialMargininitialMarginPercentagecrossisolatedF)
maintenanceMarginmaintenanceMarginPercentagemarginRatiorK  r   rS  r   r   r   r   )r  r  r  r.   r;  
string_divr  r  ri  r  
string_abs
string_subsafe_position)r  r0  r  r  r  rH  notionalString!maintenanceMarginPercentageStringmaintenanceMarginStringinitialMarginStringinitialMarginPercentageStringr:  markPriceStringrF  r  r  r   entryPriceStringrawSiderS  	priceDiffr  rG  rS  isCrosss                            r  r-  zphemex.parse_position}  s   P ##Hh7!!(F3!''2BDVW
++HgyI,0,>,>xIY[m,n)")"4"4^Ef"g"00;OQgh(/(:(:;NP^(_%--h8JL`a,,X{MR$$Xv6	v~>!22<@$$W%7%79K9KHV`bn9o%qr--hIZ[""8V4%.6WD	##Hj9u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(()@*M//(M:!! #
H#
$#
 f#
 **95	#

 L#
 T..}=#
 #
  0#
 $++J7#
 )).9#
 **?;#
 #
 $++,<=#
 #
 "4#
  T../BC!#
" &t'8'89V'W##
$ "&!2!23J!K+/+<+<=^+_,,[9%,'*!#7#
  	r  c                 d  K   |t        | j                  dz         | j                          d{    | j                  |      }d|d   i}|"|dkD  rt	        | j                  dz         ||d<   d}|d   d	k(  }|r*| j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |d
i       }	| j                  |	dg       }
g }t        dt        |
            D ]  }|
|   }| j                  |d      }| j                  |dd      }| j                  | j                  |d            }|j                  || j                  |d      ||| j!                  |      d| j#                  |||      d        |S 7 x7 
7 w)ao  
        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  r3   r   z7 fetchFundingHistory() limit argument cannot exceed 200r   r  r  r
  r  r   
createTimer  r  r  )r  r  r6  rJ  rK  r3   r  )r#   r3   r_  r  r$   $privateGetApiDataGFuturesFundingFeesr  #privateGetApiDataFuturesFundingFeesr  r  r  r  r  r  r  r   rM  parse_funding_fee_to_precision)r  r  r  r   r!  r  re  r<  isUsdtr
  r  r,  r-  entryrJ  execFeecurrencyCodes                    r  fetch_funding_historyzphemex.fetch_funding_history  s     >#DGG.a$abb!!!V$fTl

 s{ +d!dee$GG!V+!FFt{{SZ\bGcddH!EEdkkRY[aFbccH. x4tVR0q#d)$ 	AGE))%>I(([IG2243C3CE:3VWLMM**5(;$& LL3==gv|\ 	 q 	" ecs5   .F0F(A0F0!F+")F0F.CF0+F0.F0rj  c                     |||S |d   dk(  }|sM| j                  |      }| j                  |d   d      }| j                  |      }t        j                  ||      }|S )Nr  r  r  r  )r"  r  r:  r.   r;  )r  r  r  rj  rg  r  ro  tickPrecisions           r  rf  z%phemex.parse_funding_fee_to_precisionO  sq    =L0L!V+)),7H$$Xf%5|DE 007M&&um<Er  c                   K   | j                          d{    | j                  |      }|d   st        | j                  dz         d|d   i}i }|d   s*| j	                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |di       }| j                  ||      S 7 7 U7 -w)a  
        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>`
        NrB   z0 fetchFundingRate() supports swap contracts onlyr  r3   r   r,  )	r_  r  r%   r3   r  r  r  r  parse_funding_rater  s          r  fetch_funding_ratezphemex.fetch_funding_rate[  s      !!!V$f~DGG&XXYYfTl
 h!33DKK4PQQH!55dkk'66RSSH0 8R8&&vv66I 	" RSs4   CCA$C;C<)C%C&*CCCc                    | j                  |d      }| j                  ||      }| j                  |dd      }| j                  | j                  |d      |      }| j                  | j                  |d      |      }| j	                  | j                  |d      |      }| j	                  | j                  |d      |      }	i d|d|d	| j                  |d
|      d| j                  |d|      dd dd d|d| j                  |      d| j                  |d|      dd dd d| j                  |d|	      dd dd dd dd dd dd iS )Nr  rJ  r[  markEpindexEpfundingRateErpredFundingRateErr  r<  r=  
indexPriceindexPriceRpinterestRateestimatedSettlePricerK  fundingRatefundingRateRrfundingTimestampfundingDatetimenextFundingRatepredFundingRateRrnextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeinterval)r  r  rd  rD  r  r  rM  )
r  r  r  r  r  rJ  rr  rs  rt  nextFundingRateErs
             r  ro  zphemex.parse_funding_rate  s   L ##Hh7!!(F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                 .  K   | j                          d{    | j                  |      }|d   | j                  ||      d}| j                  | j	                  ||             d{   }| j	                  | j                  ||      d|i      S 7 z7 *w)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>`
        Nr3   )r  posBalanceEvr  )r_  r  rw  privatePostPositionsAssignr  parse_margin_modification)r  r  r  r!  r  re  r<  s          r  
set_marginzphemex.set_margin  s      !!!V$Tl JJvv6
 88Wf9UVV {{499(FKfN
  	 	" Ws"   BBAB(B))BBc                 0    ddi}| j                  |||      S )N0r  rG  rH  s      r  parse_margin_statuszphemex.parse_margin_status  s%    
 &&99r  r
  c                     | j                  d |      }| j                  |d      }|rdnd}|| j                  d |      ddd d ||   | j                  | j	                  |d            d d d
S )Nr   r  r  setrP  r6  )
r  r  r  r   r  r  r6  r  rJ  rK  )r  r  r  r  r  )r  r
  r  r   codeCurrencys        r  r  z phemex.parse_margin_modification  s     !!$///&)4!(vg&&tV4$<(..t/?/?f/MN
 	
r  r   c                   K   |t        | j                  dz         | j                          d{    | j                  |      }|d   r|d   dk(  rt	        | j                  dz         |j                         }|dk7  r|dk7  rt        | j                  d	z         | j                  |d
      }|dk(  rd}|t        | j                  dz         |d   |d}| j                  | j                  ||             d{   S 7 7 w)a]  
        set margin mode to 'cross' or 'isolated'

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

        :param str marginMode: 'cross' or 'isolated'
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        Nz+ setMarginMode() requires a symbol argumentrB   r  r  z= setMarginMode() supports swap(non USDT based) contracts onlyrP  rO  z@ setMarginMode() marginMode argument should be isolated or crossr   r   z. setMarginMode() requires a leverage parameterr3   )r  r   )
r#   r3   r_  r  r%   lowerr$   r  privatePutPositionsLeverager  )r  r   r  r!  r  r   re  s          r  set_margin_modezphemex.set_margin_mode  s     >#DGG.[$[\\!!!V$f~!1V!;DGG&eeff%%'
#
g(=TWW'iijj$$VZ8 H#DGG.^$^__Tl 
 55dkk'66RSSS! 	"  Ts"   .DDCD<D=DDr   c                 D  K   | j                  d|d       | j                          d{    | j                  |      }|d   dk7  rt        | j                  dz         d|d   i}|rd|d	<   nd
|d	<   | j                  | j                  ||             d{   S 7 r7 w)a  
        set hedged to True or False for a market

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

        :param bool hedged: set to True to use dualSidePosition
        :param str symbol: not used by binance setPositionMode()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        r   r  Nr  r  z5 setPositionMode() supports USDT settled markets onlyr3   HedgedtargetPosModeOneWay)check_required_argumentr_  r  r%   r3   %privatePutGPositionsSwitchPosModeSyncr  )r  r   r  r!  r  re  s         r  set_position_modezphemex.set_position_mode$  s      	$$%6I!!!V$(v%DGG&]]^^fTl
 '/GO$'/GO$??GU[@\]]] 	" ^s"   'B BA-B BB B c                 n  K   | j                          d{    |C| j                  |d      }| j                  |      }|d   dk7  rt        | j                  dz         | j                  |       d{   }| j                  |di       }| j                  |d      }| j                  ||d      S 7 7 >w)	a  
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes
        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `leverage tiers structures <https://docs.ccxt.com/#/?id=leverage-tiers-structure>`, indexed by market symbols
        Nr   r  r  z7 fetchLeverageTiers() supports USD settled markets onlyr
  r  r  )r_  r  r  r%   r3   publicGetCfgV2Productsr  parse_leverage_tiers)r  r  r!  r  r  r<  r
  r  s           r  fetch_leverage_tierszphemex.fetch_leverage_tiers=  s      !!!OOGQ/E[['Fh5(*c cdd44V<<^ x4^^D,7
((WhGGo 	" =s"   B5B1AB54B35=B53B5c                 f   | j                  |d      }| j                  ||      }|d   d   }g }d}t        dt        |            D ]h  }||   }| j	                  |d      }	|j                  | j                  |d      | j                  ||      |d   ||	| j                  |d      d	|d
       |	}j |S )zq
        :param dict info: Exchange market response for 1 market
        :param dict market: CCXT market
        r  r  r  r   r   r   r  rQ  N)tierr  r  minNotionalmaxNotionalmaintenanceMarginRater  r  )r  r  r  r  r  r   r|  r  )
r  r  r  r  r  tiersr  r-  r  r  s
             r  parse_market_leverage_tiersz"phemex.parse_market_leverage_tiers  s      ##D(3!!(F3Vn\2
q#j/* 	&Aa=D++D':KLLA**8V<"8,**)-)9)9$@S)T#	 	 &K	& r  r   GETc                    | j                  || j                  |            }d| j                  ||      z   }|}	d}
|dk(  s|dk(  s
|dk(  s|	dk(  r|r| j                  |      }
|	d|
z   z  }	|dk(  r9| j	                          | j                         }| j                  | j                  d	d
      }| j                  ||      }t        |      }| j                  |d}d}|dk(  rr|dk(  xs |dk(  xs |dk(  }|rE| j                  |d      3| j                  | j                  dd      }|| j                         z   |d<   | j                  |      }|}d|d<   ||
z   |z   |z   }| j                  | j                  |      | j                  | j                         t"        j$                        |d<   | j'                  | j(                  d   |         |	z   }	|	|||dS )Nr  r  r  DELETEPUTz/positions/assign?r   r  r  )zx-phemex-access-tokenr  POSTr   r   r   r[  r  r  zapplication/jsonzContent-Typezx-phemex-request-signaturer   )r   r)  bodyheaders)r  extract_paramsimplode_paramsurlencode_with_array_repeatcheck_required_credentialsr  r  r  r|  rl  r   r  r  jsonhmacencoder   hashlibsha256implode_hostnamer   )r  pathr   r)  r!  r  r  r  requestPathr   queryStringrJ  xPhemexRequestExpiryr  expiryStringpayloadisOrderPlacementr3   auths                      r  signzphemex.sign  s   		&$"5"5d";<D//f==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@fdwOOr  r   c                 j  K   |t        | j                  dz         |dk  s|dkD  rt        | j                  dz         | j                          d{    | j	                  |dd      }| j                  |d      }| j                  |d	      }| j                  |      }d
|d   i}d}	|d   dk(  rM|s
||||d<   n||n|}
||n|}|
|d<   ||d	<   | j                  | j                  ||             d{   }	|	S ||d<   | j                  | j                  ||             d{   }	|	S 7 7 87 
w)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  r3   r  r  r?  r   )
r#   r3   r$   r_  r  r  r  privatePutGPositionsLeverager  r  )r  r   r  r!  isHedgedr  r  r  re  r<  longVarshortVars               r  set_leveragezphemex.set_leverage  so      >#DGG.Y$YZZtOCTWW'__``!!!>>&(E:**63CD++F4EFV$fTl
 (v% 6?;R(0%-;-G.h/>/J?QY,3()-5)*!>>t{{7TZ?[\\H  #+GJ!==dkk'SY>Z[[H+ 	"" ] \s7   AD3D-B#D36D/7/D3&D1'D3/D31D3fromAccount	toAccountc           	      f  K   | j                          d{    | j                  |      }| j                  | j                  di       }| j	                  |||      }| j	                  |||      }	| j                  ||      }
d}d}|dk(  r|	dk(  rd}n|dk(  r|	dk(  rd}|X|d   ||
d}| j                  | j                  ||             d{   }| j                  |d	i       }| j                  ||      }nV||	|
|d   | j	                  |d
d      d}| j                  | j                  ||             d{   }| j                  |      }| j                  | j                  di       }| j                  |dd      }|r(|d   ||d<   |d   ||d<   |d   ||d<   |d   ||d<   |S 7 7 7 vw)a#  
        transfer currency internally between wallets on the same account

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

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

684	V 0IxDFNI $TN#)G
 ";;DKKQW<XYYH ??8VR8D**4:H % )$TN++FIvFG "DDT[[QXZ`EabbH **84H//$,,
BG"&..B[]a"b"&.*5'$,(1%!)%+"
#+'+$ 	"$ Z2 cs6   F1F*B6F1F-A*F18F/9A2F1-F1/F1c                   K   | j                          d{    |t        | j                  dz         | j                  |      }d|d   i}|||d<   |||d<   | j	                  | j                  ||             d{   }| j                  |di       }| j                  |dg       }	| j                  |	|||      S 7 7 @w)	a3  
        fetch a history of internal transfers made on an account

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

        :param str code: unified currency code of the currency transferred
        :param int [since]: the earliest time in ms to fetch transfers for
        :param int [limit]: the maximum number of  transfers structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transfer structures <https://docs.ccxt.com/#/?id=transfer-structure>`
        Nz* fetchTransfers() requires a code argumentr  r3   r  r   r
  r  )	r_  r#   r3   r  privateGetAssetsTransferr  r  r  parse_transfers)
r  r6  r  r   r!  r  re  r<  r
  	transferss
             r  fetch_transferszphemex.fetch_transfers_  s      !!!<#DGG.Z$Z[[==&
 $GG$GG66t{{7F7STT* x4NN44	##IxFFE 	" Us"   CB>A(C?C  ?C Cr   c                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |d      }| j                  ||      }| j                  |d      }	d }
d }|	dk(  rd}
d}n	|	d	k(  rd}
d}| j                  |d
      }|||| j	                  |      |||
|| j                  |      d	S )NlinkKeyr  r  r  rS  r   rB   r@   r   rc  )	r  r3   rJ  rK  r  r  r  r  r  )r  rC  r  r  rM  parse_transfer_status)r  r   r  r3   r  r  amountTransferedr  r6  rS  r  r  rJ  s                r  r  zphemex.parse_transfer  s    4 h	2!!(H5##Hj9<<1%%h
;
&&z8<  6219FDQYFD%%h=	"Y/&!008

 
	
r  c                 6    ddddd}| j                  |||      S )Nr;  r@  r  r  )rB  rE  rO  11rG  rH  s      r  r  zphemex.parse_transfer_status  s,    	
 &&99r  c           
        K   |t        | j                  dz         | j                          d{    | j                  |      }|d   dk(  }|d   st	        | j                  dz         d}| j                  |dd	      \  }}|r| j                  d|||d
|d       d{   S d}|rd|d   z   dz   }nd|d   z   dz   }d|i}	|||	d<   |||	d<   | j                  d|	|      \  }	}d}
|r*| j                  | j                  |	|             d{   }
n)| j                  | j                  |	|             d{   }
| j                  |
di       }| j                  |d      }g }t        dt        |            D ]O  }||   }| j                  |d      }|j                  ||| j!                  |d      || j#                  |      d       Q | j%                  |d      }| j'                  ||||      S 7 7 V7 7 w)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  rB   z7 fetchFundingRateHistory() supports swap contracts onlyFra   paginate8hr  .r3   FR8Hr  r  r  r   endr
  r  r   fundingTimerz  )r  r  rz  rJ  rK  rJ  )r#   r3   r_  r  r$   r.  "fetch_paginated_call_deterministichandle_until_option(v2GetApiDataPublicDataFundingRateHistoryr  (v1GetApiDataPublicDataFundingRateHistoryr  r  r  r  r   r  rM  rN  filter_by_symbol_since_limit)r  r  r  r   r!  r  isUsdtSettledr  customSymbolre  r<  r
  ratesr,  r-  itemrJ  sorteds                     r  fetch_funding_rate_historyz!phemex.fetch_funding_rate_history  sV     >#DGG.e$eff!!!V$x(F2f~TWW'``aa88AZ\fg&@@AZ\bdikprvx~  AD  E  E  E-6L!11F:Ll
 $GG$GG225'6J!JJ4;;W^`fKghhH!JJ4;;W^`fKghhH" x4f-q#e*% 		A8D))$>IMM #//mD& LL3 		 fk200NNs 	" E  ihsH   .G<G2A.G<G5 A/G<G8)G<9G::B9G<5G<8G<:G<r  c                 ~  K   | j                  ||      \  }}| j                          d{    | j                  |       | j                  |      }d}| j	                  |      \  }}d}|| j                  |      }| j                  | j                  d      }	|0| j                  ||	      s|d   }nt        | j                  dz         |d   |||j                         d}
|||
d<   | j                  | j                  |
|             d{   }| j                  |di       }| j                  ||      S 7 7 ,w)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  r3   z8 withdraw() requires an extra argument params["network"])r  r  r  r  
addressTagr
  )handle_withdraw_tag_and_paramsr_  r  r  handle_network_code_and_paramsnetwork_code_to_idr  r  in_arrayr#   r3   upper1privatePostPhemexWithdrawWalletsApiCreateWithdrawr  r  r&  )r  r6  r  r  r  r!  r  networkCoder%  r  re  r<  r
  s                r  r   zphemex.withdraw  sM     99#vFV!!!7#==&"AA&IV	"//<IoodllMBMM$4$TN	'2l(lmm "*	
 ?$'GL!OOPTP[P[\cekPlmm8 ~~h3%%dH55g 	", ns"   )D=D8C"D=D;*D=;D=c                 F  K   | j                          d{    | j                  |      }|d   st        | j                  dz         d|d   i}| j	                  | j                  ||             d{   }| j                  |d      }| j                  ||      S 7 7 *w)a\  
        retrieves the open interest of a trading pair

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

        :param str symbol: unified CCXT market symbol
        :param dict [params]: exchange specific parameters
        :returns dict} an open interest structure{@link https://docs.ccxt.com/#/?id=open-interest-structure:
        Nr  z: fetchOpenInterest is only supported for contract markets.r  r3   r,  )r_  r  r$   r3   r  r  r  parse_open_interestr  s          r  fetch_open_interestzphemex.fetch_open_interest]  s      !!!V$j!TWW'ccddfTl
 11$++gv2NOO, (3''77= 	" Ps"   B!BAB!4B5)B!B!c                    | j                  |d      dz  }| j                  |d      }| j                  || j                  ||      | j                  |d      d | j                  |d      d || j	                  |      d|      S )NrJ  i@B r  r  openInterestRv)r  r  r  r  openInterestAmountopenInterestValuerJ  rK  )r  r  safe_open_interestr  rM  )r  interestr  rJ  r3   s        r  r  zphemex.parse_open_interest  s    $ %%h<wF	h1&&&&r62**8Z@"&"2"28=M"N!%"Y/	(
 	 		r  fromCodetoCodec                 t  K   | j                          d{    | j                  |      }| j                  |      }| j                  |d      }||| j                  ||      d}| j	                  | j                  ||             d{   }	| j                  |	di       }
| j                  |
||      S 7 7 ,w)a+  
        fetch a quote for converting from one currency to another

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

        :param str fromCode: the currency that you want to sell and convert from
        :param str toCode: the currency that you want to buy and convert into
        :param float amount: how much you want to trade in units of the from currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
        Nr  )fromCurrency
toCurrencyfromAmountEvr
  )r_  r  r  rs  privateGetAssetsQuoter  r  parse_conversion)r  r
  r  r  r!  r  r  r  re  r<  r
  s              r  fetch_convert_quotezphemex.fetch_convert_quote  s      !!!}}X.]]6*
&&|\B
$  JJvz:

 33DKK4PQQ& ~~h3$$T<DD; 	" Rs"   B8B4A2B8	B6
+B86B8c                   K   | j                          d{    | j                  |      }| j                  |      }| j                  |d      }|||d}	|| j                  ||      |	d<   | j	                  | j                  |	|             d{   }
| j                  |
di       }| j                  |d      }| j                  ||      }| j                  |d      }| j                  ||      }| j                  |||      S 7 7 tw)aW  
        convert from one currency to another

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

        :param str id: the id of the trade that you want to make
        :param str fromCode: the currency that you want to sell and convert from
        :param str toCode: the currency that you want to buy and convert into
        :param float [amount]: how much you want to trade in units of the from currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
        Nr  )r6  r  r  r  r
  r  r  )
r_  r  r  rs  privatePostAssetsConvertr  r  r  r"  r  )r  r3   r
  r  r  r!  r  r  r  re  r<  r
  fromCurrencyId
fromResulttoCurrencyIdr  s                   r  create_convert_tradezphemex.create_convert_trade  s     !!!}}X.]]6*
&&|\B
$ 

 &*jj&DGN#66t{{7F7STT  ~~h3))$?''E
''l;j9$$T:r::A 	" Us#   DDA9DDA3DDc                 f  K   | j                          d{    i }|||d<   |||d<   |||d<   | j                  d||      \  }}| j                  | j                  ||             d{   }| j	                  |di       }| j                  |dg       }| j                  ||dd||      S 7 7 Bw)	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>`
        Nr  	startTimer   endTimer
  r  r  )r_  r  privateGetAssetsConvertr  r  r  parse_conversions)	r  r6  r  r   r!  re  r<  r
  r  s	            r  fetch_convert_trade_historyz"phemex.fetch_convert_trade_history   s      !!!&*GN##(GK $GG229gvN55dkk'66RSS. ~~h3~~dFB/%%dD.,PUW\]]E 	" Ts#   B1B-AB1,B/-AB1/B1
conversionr  r  c                 b   | j                  |di       }| j                  |d      }| j                  |d|      }| j                  |d| j                  |d            }| j                  ||      }| j                  |d| j                  |d            }	| j                  |	|      }
| j                  |d      }| j                  |d      }| j	                  | j                  |d      |      }|$|"| j	                  | j                  |d	      |      }| j	                  | j                  |d
      |      }|$|"| j	                  | j                  |d      |      }||| j                  |      | j                  |d      || j                  |      |
| j                  |      | j                  |d      d d
S )N	quoteArgs	requestAtrc  r  r6  r  r  r  origin
toAmountEvproceedsr   )
r  rJ  rK  r3   r  
fromAmountr  toAmountr   r8  )r  r  r  r  r  rM  r  r  )r  r  r  r  r!  requestTimerJ  fromCoinr
  toCoinr  fromValueScaletoValueScaler&  r'  s                  r  r  zphemex.parse_conversion3  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
                 @   |y | j                  |d|      }
| j                  |
d      }| j                  |
d      }|b|dk7  r]| j                  dz   |z   }| j                  | j                  d   ||       | j                  | j                  d   ||       t        |      y )Nerrorr6  msgr  r  r  r  )r  r  r3   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   )r  r-  r.  r   r)  r  r  r<  requestHeadersrequestBodyr0  	errorCodemessagefeedbacks                 r  handle_errorszphemex.handle_errorsz  s     '8<$$UF3	""5%0!	S(8ww}t+H001I9V^_001I7T\]))r  rh  )r   r   N)Nr\  r]  r   r   N)NN)o__name__
__module____qualname__r   r  r  dictr  r  r   r   r1  r   rA  rH  rV  rl  r   r   rf  rs  rw  rz  r  rD  rC  r  r  r  r  r   r  r  r   r   r  r   r  r  r%  r,  r   r3  r   rJ  r	  rY  rr  rt  r  r   r  r   r   floatr   r  r  r  r  r  r  r  r  r  r
   r  r   r  r  r  r	   r&  r   r1  r-  rk  rf  r   rp  ro  r   r  r  r  r  boolr  r   r  r   r  r  r  r   r   r  r  r  r  r   r  r  r   r  r  r  r  r9  r9  __classcell__)r  s   @r  r0   r0      s   S	# S	j*J JXc cJ *, bV bH -/ B: BH	
F 	
  KQ & @DB 7S 7 7S\ 7r48F 8
76 7
I& I
I& I
I& I

 
4 
8 8<$]ajl ML MLC MLWZ MLquvzq{ ML^U4 U U6 Un 68 E1 E1F E1N 6:" 37 3 3@ <@d[] )? )?S )? )?bfglbm )?VZ Zv Z Zx1)f-)^ *, c1 c1J: :.3S 3"Hs Hjd jF jX3lf l\4 4v 4 4 mqy{ Q. Q.I Q.Y Q.X] Q.fi Q.f fjx|  FH =.3 =. =.9 =.I =._b =.ru =.~ 9=R $.S $.# $.L 59 9
c 9
v 8<B ,/C ,/ ,/\ 04$UYbd != !=C !=s !=imnsit !=F 59tZ^gi 'Ac 'A 'ATW 'Anrsxny 'AR 7;\`ik MA MA3 MAVY MAptuzp{ MA^ 37TX\eg U=C U=s U=RU U=n =? *
 *
> *
X 04$UYbd #E #EC #Es #Eimnyiz #EJ 37TX\eg #EC #Es #ERU #Elpq|l} #EJ:s :(q
T q
X q
Q\ q
f 8<B DPW DP4PX> DPLHt HV HT 9=4^bkm F# FS FX[ FP
F 
Y\ 
 <> +7s +7+ +7Z@
6 @
[ @
D CE s E I[ ::
d 
F 
N` 
0 DHPR T TS T> CGr ^d ^C ^2 =A ^H' ^HP] ^H@# #$|J\ #J &eBSW  PD ?C2 )3 ) )V ac N3 N NC NTW Ngt N` 154VZce .G# .GS .GPS .Gjno|j} .G`4
t 4
x 4
= 4
l:C :C : >BPTcgpr IOs IO# IO]` IOV JNVX B63 B6 B6 B6]h B6H =? (8 (8TF > SW_a )E# )Es )EC )Efp )EV ]aik -;S -;C -; -;VY -;pz -;^ =Atbfoq 1^c 1^ 1^\_ 1^vz  |F  wG 1^fE
4 E
x E
\d E
pz E
Nc 3 S # X\ dg r  r0   )7 ccxt.async_support.base.exchanger   ccxt.abstract.phemexr   r  r  r  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   ccxt.base.decimal_to_precisionr-   ccxt.base.preciser.   r0    r  r  <module>rI     s    6 ,    `  `  `  `  `  `  `  * 0 - - . ' & . ) * - + . * 4 %lMX{ lMr  