
    !:ho                    |   d dl mZ d dlm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"m/Z/ d dl"m0Z0 d dl1m2Z2 d dl3m4Z4  G d dee      Z5y)    )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    E/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/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_numberu  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                 V   | j                  |      }| j                  |      }||g\  }}| 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 )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
        datar   perpProductsV2
riskLimitsriskLimitsV2
currenciesr  currencyr   r  	perpetualperpetualv2perpetualpilotr  r  8)v2GetPublicProductsv1GetExchangePublicProducts
safe_value	safe_dict	safe_listarray_concatindex_byrangelenr  r  extendr  r  append)r  paramsv2ProductsPromisev1ProductsPromise
v2Products
v1Productsv1ProductsDatav2ProductsDatar   perpetualProductsV2r  r  r  riskLimitsByIdv1ProductsByIdcurrenciesByCoderesultir  r  r3   riskLimitValuesv1ProductsValuesr  currencyValuesr  s                             r  fetch_marketszphemex.fetch_marketsn  s=    !44V<l !<<VD"35F!G
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&!!	"" r  c                    | j                  |      }| 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 )z
        fetches all available currencies on an exchange
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        r
  r  r   r  r4   r  r  
minValueEv
maxValueEvNr  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   r4  r  valueScaleStringr  r1  r2  	minAmount	maxAmountr  precisionStrings                       r  fetch_currencieszphemex.fetch_currenciesR  s    ++F3 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 r  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  rF  sort_by)r  	orderbookr  rH  bidsKeyasksKeyrD  rE  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           
         | j                          | j                  |      }d|d   i}d}|d   r*|d   dk(  r"| j                  | j                  ||            }nJ|'|dk  r"| j	                  | j                  ||            }n!| j                  | j                  ||            }| j                  |di       }| j                  |d	d
i       }| j                  |dd      }	| j                  |||	dddd|      }
| j                  |d      |
d<   |
S )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
        r  r3   Nr   r  r     r*  bookorderbook_prH  ư>bidsasksr   r   sequencerJ  )load_marketsr  v2GetMdV2Orderbookr  v1GetMdOrderbookv1GetMdFullbookr  safe_value_2safe_integer_productrT  r  )r  r  r   r  r  requestr:  r*  rW  rH  rM  s              r  fetch_order_bookzphemex.fetch_order_book  s#    	V$fTl
 (x 0F :..t{{7F/KLH!00Wf1MN//GV0LM4 8R8  C--fk8L	00vy&RXZ[]^`fg	!..vzB	'r  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  rq  )r  r  r  s      r  to_evzphemex.to_ev  s&    NMzz&&"677r  c                 8    |||S | j                  ||d         S Nr  rt  )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 rf  )r.   sumrh  ri  rj  )r  enrm  ro  s       r  r  zphemex.from_en  sD    :"+88G$4$4e<7|r  c                 R    |||S | j                  || j                  |d            S rw  r  r  )r  epr  s      r  rB  zphemex.from_ep  .    JFNI||B 1 1&, GHHr  c                 R    |||S | j                  || j                  |d            S rs  r}  )r  evr  s      r  rA  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  rA  r  r  safe_timestamprB  )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                    | j                          | 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                  ||            }n| j                  | j                  ||            }n^|;| j                  |      d	z  }| j                         |z
  }| j                  ||z        }| j!                  | j                  ||            }| j#                  |di       }| j%                  |dg       }| j'                  |||||      S )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
        r3   )r  
resolutionuntiltor   r  r  Nr   r   r   fromd   r
  rows)r]  r  r  r   safe_integer_2omitr  parse_timeframer7  roundsecondspublicGetMdV2KlineListr  publicGetMdV2KlineLastmillisecondsparse_to_intpublicGetMdV2Kliner  r  parse_ohlcvs)r  r  	timeframer  r   r  r  	userLimitrc  r  usesSpecialFromToEndpointmaxLimitr:  candleDurationr  nowduration	timeDeltar
  r  s                       r  fetch_ohlcvzphemex.fetch_ohlcv2  sf    	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66t{{7F7ST66t{{7F7ST   //	:TA --/%7	)))h*>?..t{{7F/KLH x4~~dFB/  vy%KKr  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  rH  rY  lastEpcloseRp
turnoverEv
turnoverRvvolumevolumeEvvolumeRqopenEprI  highhighEphighRplowlowEplowRpr  bidEp	bidVolumer  askEp	askVolumevwapopencloser   previousClosechanger   average)r  quoteVolumer  )	r  safe_marketrb  rB  safe_string_2r  rA  safe_tickerrK  )
r  r  r  marketIdr  rH  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                    | j                          | j                  |      }d|d   i}d}|d   rQ|d   s|d   dk(  r"| j                  | j                  ||            }nC| j	                  | j                  ||            }n!| j                  | j                  ||            }| j                  |di       }| j                  ||      S )	a   
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

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

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        r  r3   NrB   r   r  r  r*  )r]  r  v1GetMdTicker24hrr  v2GetMdV2Ticker24hrv1GetMdSpotTicker24hrr  r  r  r  r  r  rc  r:  r*  s          r  fetch_tickerzphemex.fetch_ticker  s     	V$fTl
 &>i F8$4$=11$++gv2NO33DKK4PQ11$++gv2NOHZ (B7  00r  symbolsc                    | j                          d}|#| j                  |d      }| j                  |      }d}| j                  d||      \  }}d}| j	                  d||      \  }}| j                  |d      }d}|dk(  r| j                  |      }n=|dk(  s| j                  |d      dk(  r| j                  |      }n| j                  |      }| j                  |d	g       }	| j                  |	|      S )
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>44U;H	!T%5%5fh%G5%P007H2259H(B7!!&'22r  c                 l   | j                          | j                  |      }d|d   i}d}|d   r*|d   dk(  r"| j                  | j                  ||            }n!| j	                  | j                  ||            }| j                  |di       }| j                  |dd	g       }	| j                  |	|||      S )
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>`
        r  r3   Nr   r  r  r*  tradestrades_p)r]  r  v2GetMdV2Trader  v1GetMdTrader  ra  parse_trades)
r  r  r  r   r  r  rc  r:  r*  r  s
             r  fetch_tradeszphemex.fetch_trades?  s     	V$fTl
 (x 0F :**4;;w+GHH((Wf)EFH" 8R8""68ZD  >>r  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   rY  r  r   r   r   transactTimeNs	createdAtexecIdexecIDorderIDr  r  rQ  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  rH  rI  orderr  rQ  takerOrMakerr   r  r  r6  )r  r  
isinstancelistr  rb  r  numbersRealrB  rA  r  r  	omit_zeror  parse_order_typer  r  
safe_traderK  )r  r  r  r3   rQ  
costStringr  r6  feeCostStringfeeRateStringfeeCurrencyCoder  r  orderIdr  tradeLengthrH  priceStringamountStringsideIdr  
currencyIdr  r  r  settlementCurrencyIds                             r  parse_tradezphemex.parse_tradej  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lastUpdateTimeNsrY  totalusedrH  rI  )r  r  r  r  r  r  r  accountr  r.   
string_addrb  r  rK  safe_balance)r  r:  rH  r*  r
  r+  balancer  r4  r  rm  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  r4  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                 L   | j                          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	      \  }}||nd}||}n|}| j                  |      }|d
   |d<   |d
   d	k(  r"| j                  | j                  ||            }n| j                  | j                  ||            }nu| j                  |d      }|t        | j
                  dz   |z   dz         | j                  | j                  ||            }n!| j                  | j                  ||            }|dk(  r| j                  |      S | j                  |      S )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   r4  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  r4  r:  rc  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+#GGT[]cHdeH#FFt{{SZ\bGcdH++FJ?#+DGG  7I  -I  LP  -P  SZ  -Z  [  [55dkk'66RS11$++gv2NOHl 6>**844&&x00r  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  r@  rA  rB  rC  rD  r  910Limitr   rE  )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
FillOrKillrE  )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	ordStatusrQ  r  actionTimeNscreateTimeNsrY  cumFeeEvr  r  r  r   stopPxEpr   r  r3   clientOrderIdrH  rI  lastTradeTimestampr  postOnlyr   r   r  r  r  filled)	remainingr  r6  r  )r  r  r  rB  rA  r  r  r  rH  r  r  safe_integer_product_2r  rW  r  
safe_orderrK  )r  r   r  r3   rh  r  r  r   r  rl  rk  r  r  r  rQ  r  rH  r6  feeCostr   r   rj  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  rE  )r  rQ  rP  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  rY  clOrdIdr   r  rb  rQ  	orderTypepriceRprZ  orderQty
orderQtyRqcumQtycumQtyRq	leavesQtyleavesQtyRqrc  rY  r  cumValue
cumValueRvr  r   r   stopPxstopPxRpr   
reduceOnlyexecInst
ReduceOnlyTtakeProfitRp
stopLossRpr  r  r  rf  r  r  r3   rh  rI  rH  ri  r  rj  r   r   r   r   r  )rk  rl  r  r  r  r6  r  )r  r  r  safe_symbolr  rH  rr  r  r  rB  r  rb  r  rW  r  r  rn  rK  )r  r   r  r3   rh  r  r  r  rQ  r  r   r  rk  rl  rH  r  ri  r   r   rj  r  r  
takeProfitstopLossfeeValuer  r6  s                              r  parse_swap_orderzphemex.parse_swap_order1	  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  rp  )r  r   r  isSwaphasPnls        r  parse_orderzphemex.parse_order	  s^    6&^MU,B^X]H]V((77$$UF33r  rQ  r  r   c                    | j                          | 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                  |	|            }$nH|dH   r"| j9                  | j7                  |	|            }$n!| j;                  | j7                  |	|            }$| j=                  |$dIi       }%| j?                  |%|      S )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>`
        r3   )r  rQ  r  rY  rh  r  Nr  r  r  )r  	stopPricer   r  r  r  rg  )r  r  r  r  r   r@   qtyTypeByBaser   StopMarketIfTouchedByQuoterN  	StopLimitr  r  r   r  r  z createOrder() z. requires a price argument or a cost parameterr`  r[  rB   r   FposSider  r  r  LongShortMergedrx  rw  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tpPxRprv  rZ  r   r   r  r
  ) r]  r  
capitalizer  r  r  r  uuid16r  safe_string_nprice_to_precisionrx  r  rg  r.   r9  r  r#   r3   ru  r  r  r  handle_param_stringra  r'   privatePostGOrdersr  privatePostOrdersprivatePostSpotOrdersr  r  )&r  r  r  rQ  r  r   r  r  requestSiderc  rh  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	  s*   , 	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%..t{{7F/KLHJ--dkk'6.JKH11$++gv2NOHZ ~~h3f--r  r3   c                    | j                          | 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}|r;| j                  |d      }|d|	d<   | j                  | j                  |	|            }nH|d   r"| j                  | j                  |	|            }n!| j                  | j                  |	|            }| j                  |di       }| j                  ||      S )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>`
        r  r3   rh  rY  r  r  Nr  rv  rZ  r[  	baseQtyEVrx  )r   r  r  r  rg  r  r  rB   r
  )r]  r  r  r  r  rx  r  amount_to_precisionru  r  privatePutGOrdersReplacer  privatePutOrdersReplaceprivatePutSpotOrdersr  r  )r  r3   r  r  rQ  r  r   r  r  rc  rh  isUSDTSettledfinalQtyr   r:  r  r
  s                    r  
edit_orderzphemex.edit_order
  s*     	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4T[[&5QRHF^33DKK4PQH00Wf1MNH~~h3f--r  c                 R   |t        | j                  dz         | j                          | j                  |      }d|d   i}| j	                  |dd      }| j                  |ddg      }|||d<   n||d<   d}|d   d	k(  r;| j                  |d
      }|d|d
<   | j                  | j                  ||            }nH|d   r"| j                  | j                  ||            }n!| j                  | j                  ||            }| j                  |di       }	| j                  |	|      S )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   rh  rY  r  r  r  r  r  rB   r
  )r#   r3   r]  r  r  r  r  privateDeleteGOrdersCancelr  privateDeleteOrdersCancelprivateDeleteSpotOrdersr  r  )
r  r3   r  r  r  rc  rh  r:  r  r
  s
             r  cancel_orderzphemex.cancel_order8  s=    >#DGG.Y$YZZV$fTl
 **6?IN6OY#?@$!.GI!#GI(v%&&vy9G%-	"66t{{7F7STHF^55dkk'66RSH33DKK4PQH~~h3f--r  c                    |t        | j                  dz         | j                          | j                  |      }| j	                  |ddd      }| j                  |ddg      }d|d   i}|r||d<   d}|d	   d
k(  r"| j                  | j                  ||            }nH|d   r"| j                  | j                  ||            }n!| j                  | j                  ||            }| j                  d|i      gS )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 argumentrJ  r   Fr  r3   untriggerredr  r  rB   r  )r#   r3   r]  r  ra  r  privateDeleteGOrdersAllr  privateDeleteOrdersAllprivateDeleteSpotOrdersAllrn  )r  r  r  r  r   rc  r:  s          r  cancel_all_orderszphemex.cancel_all_orders^  s    >#DGG.]$]^^V$##FFIuE6FI#67fTl

 &-GN#(v%33DKK4PQH F^224;;w3OPH 66t{{7F7STH OO 
 	
r  c                 v   |t        | j                  dz         | j                          | j                  |      }d|d   i}| j	                  |dd      }| j                  |ddg      }|||d<   n||d<   d}|d   d	k(  r"| j                  | j                  ||            }nH|d
   r"| j                  | j                  ||            }n!| j                  | j                  ||            }| 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 )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   rh  rY  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  rc  rh  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%DDT[[QXZ`EabHF^AA$++gW]B^_H33DKK4PQHx4dD!D	I1} ,'2B(BV(KNj(jmz(z  ~J  )J  K  K'2B(BV(KN_(_bd(dgs(sttNN4B/EF^>>$3DNN4B/Ev..r  c                    |t        | j                  dz         | j                          | j                  |      }d|d   i}|||d<   |||d<   d}|d   dk(  r*|d   |d	<   | j	                  | j                  ||            }nH|d
   r"| j                  | j                  ||            }n!| j                  | j                  ||            }| j                  |di       }| j                  |d|      }	| j                  |	|||      S )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  rc  r:  r
  r  s
             r  fetch_orderszphemex.fetch_orders  s    >#DGG.Y$YZZV$fTl
 $GG$GG(v%"("2GJ>>t{{7TZ?[\HF^77GV8TUH88Wf9UVHx4~~dFD1  vue<<r  c                    | j                          |t        | j                  dz         | j                          | j                  |      }d|d   i}d}	 |d   dk(  r"| j	                  | j                  ||            }nH|d   r"| j                  | j                  ||            }n!| j                  | j                  ||            }| j                  |di       }	t        |	t              r| j                  |	|||      S | j                  |	d	g       }
| j                  |
|||      S # t        $ r}t        |t              rg cY d}~S |d}~ww xY 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  rc  r:  er
  r  s              r  fetch_open_orderszphemex.fetch_open_orders  sK    	>#DGG.]$]^^V$fTl
 
	h6);;DKKQW<XY::4;;wPV;WX44T[[&5QR
 x4dD!$$T65%@@>>$3D$$T65%@@  	!]+	G	s%   A2D& &	E/E EEEc                 n   | j                          d}|| j                  |      }i }||d   |d<   |||d<   |||d<   d}|| j                  |d      dk(  r8| j                  |dd      |d<   | j                  | j	                  ||            }nH|d	   r"| j                  | j	                  ||            }n!| j                  | j	                  ||            }| j                  |d
i       }t        |t              r| j                  ||||      S | j                  |dg       }	| j                  |	|||      S )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  sS     	[[(F
 &tGH$GG$GGN 0 0 Bf L"&"2"268V"LGJ>>t{{7TZ?[\HF^77GV8TUH77GV8TUHJ x4dD!$$T65%@@>>$3D$$T65%@@r  c                 r   | j                          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                  ||            }nH|d   r"| j                  | j                  ||            }n!| j                  | j                  ||            }d}	|r| j                  |dg       }	n&| j                  |di       }	| j                  |	dg       }	| j                  |	|||      S )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  rc  r  r:  r
  s
             r  fetch_my_tradeszphemex.fetch_my_tradesb  sh    	[[(FUOE$GG4ZT-=-=fh-OSY-Y"(GJ !GH}#&  &tGH$GG@@WV\A]^HF^88Wf9UVH==dkk'SY>Z[HR ??8VR8D??8VR8D??44D  vue<<r  r4  c                 Z   | j                          | j                  |      }d|d   i}| j                  | j                  d      }| j	                  ||      }| j                  | j                  di       }| j	                  |d|      }| j                  |||      }|	|d   |d<   n||d<   | j                  |d      }| j                  | j                  ||            }	| j                  |	di       }
| j                  |
d	      }| j                  |
d
      }| j                  |       |	|d||dS )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>`
        r  r3   r  r  networkN	chainNamer
  addresstag)r  r  r  r  r  )r]  r  r  r  safe_string_upperr  r  +privateGetPhemexUserWalletsV2DepositAddressr  r  check_address)r  r4  r  r  rc  r  defaultNetworkr  r  r:  r
  r  r  s                r  fetch_deposit_addresszphemex.fetch_deposit_address  s>    	==&
 ..7HI//F>>$,,
B?((NK""8Wg>?#+D>GK #*GK YYvy1FCCDKKPWY_D`a x4""43tU+7#
 	
r  c                     | j                          d}|| j                  |      }| j                  |      }| j                  |dg       }| j	                  ||||      S )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  r4  r  r   r  r  r:  r
  s           r  fetch_depositszphemex.fetch_deposits%  sd     	}}T*H<<VD* ~~h3&&tXueDDr  c                     | j                          d}|| j                  |      }| j                  |      }| j                  |dg       }| j	                  ||||      S )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_withdrawalsJ  sd     	}}T*H==fE* ~~h3&&tXueDDr  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Succeedr8  zSecurity check failedSecurityCheckFailedExpiredzAddress RiskzSecurity CheckingSecurityCheckingzPending ReviewzPending TransferAmlCsApporver:  	Confirmed	CancelledrE  rF  s      r  parse_transaction_statuszphemex.parse_transaction_statuso  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  r4  r  )r  
submitedAtsubmittedAtr  feeEvr  feeRv
withdrawalrf  r  amountEvamountRvr  txidrH  rI  r  	addressToaddressFromr  tagTotagFromr  updated)commentinternalr6  )
r  safe_currencysafe_integer_nr  r  r  r  r  rK  network_id_to_code)r  r  r  r3   r  r  r  r  r4  	networkIdrH  r  ro  r6  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                    | j                          | 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}|rbd}| j                  |ddd      \  }}|dk(  r"| j                  | j                  |
|            }nC| j                  | j                  |
|            }n!| j                  | j                  |
|            }| j                  |di       }| j                  |dg       }g }t        dt        |            D ]'  }||   }|j!                  | j#                  |             ) | j%                  |d|d      S )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  r4  r  r   r  rs   BTCr   r  r3   methodr-  r
  	positionsr  F)r]  market_symbolsr  r  r  r  r,  r  r  r-  r  privateGetAccountsPositionsr.  r  r  r  r  parse_positionfilter_by_array_positions)r  r  r  r  r4  r  r  firstSymbolr  r  rc  r:  r&  r
  r'  r*  r+  positions                     r  fetch_positionszphemex.fetch_positions  s*    	%%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>>CCDKKPWY_D`a;;DKKQW<XY>>t{{7TZ?[\HZ x4OOD+r:	q#i.) 	9A |HMM$--h78	9 --fhOOr  r-  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avgEntryPriceRprQ  Buylongshortr  r  r  crossMarginr  r3   	contractsunrealizedPnl
collateralnotional	lastPrice
entryPricerH  lastUpdateTimestampinitialMargininitialMarginPercentagecrossisolatedF)
maintenanceMarginmaintenanceMarginPercentagemarginRatiorI  r   rQ  r   r   r   r   )r  r  r  r.   r9  
string_divr  r  rg  r  
string_abs
string_subsafe_position)r  r-  r  r  r  rE  notionalString!maintenanceMarginPercentageStringmaintenanceMarginStringinitialMarginStringinitialMarginPercentageStringr7  markPriceStringrC  r  r  r   entryPriceStringrawSiderQ  	priceDiffr  rD  rP  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                    |t        | j                  dz         | j                          | j                  |      }d|d   i}|"|dkD  rt	        | j                  dz         ||d<   d}|d   d	k(  }|r"| j                  | j                  ||            }n!| j                  | j                  ||            }| 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 )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  r4  rH  rI  r3   r  )r#   r3   r]  r  r$   $privateGetApiDataGFuturesFundingFeesr  #privateGetApiDataFuturesFundingFeesr  r  r  r  r  r  r  r  rK  parse_funding_fee_to_precision)r  r  r  r   r  r  rc  r:  isUsdtr
  r  r*  r+  entryrH  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+@@WV\A]^H??GU[@\]H. x4tVR0q#d)$ 	AGE))%>I(([IG2243C3CE:3VWLMM**5(;$& LL3==gv|\ 	 r  rg  c                     |||S |d   dk(  }|sM| j                  |      }| j                  |d   d      }| j                  |      }t        j                  ||      }|S )Nr  r  r  r  )r  r  r8  r.   r9  )r  r  r  rg  rd  r  rm  tickPrecisions           r  rc  z%phemex.parse_funding_fee_to_precisionN  sq    =L0L!V+)),7H$$Xf%5|DE 007M&&um<Er  c                 j   | j                          | j                  |      }|d   st        | j                  dz         d|d   i}i }|d   s"| j	                  | j                  ||            }n!| j                  | j                  ||            }| j                  |di       }| j                  ||      S )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>`
        rB   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_rateZ  s     	V$f~DGG&XXYYfTl
 h--dkk'6.JKH//GV0LMH0 8R8&&vv66r  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  rH  rY  markEpindexEpfundingRateErpredFundingRateErr  r9  r:  
indexPriceindexPriceRpinterestRateestimatedSettlePricerI  fundingRatefundingRateRrfundingTimestampfundingDatetimenextFundingRatepredFundingRateRrnextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeinterval)r  r  rb  rB  r  r  rK  )
r  r  r  r  r  rH  ro  rp  rq  nextFundingRateErs
             r  rl  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                     | j                          | j                  |      }|d   | j                  ||      d}| j                  | j	                  ||            }| j	                  | j                  ||      d|i      S )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>`
        r3   )r  posBalanceEvr  )r]  r  ru  privatePostPositionsAssignr  parse_margin_modification)r  r  r  r  r  rc  r:  s          r  
set_marginzphemex.set_margin  s     	V$Tl JJvv6
 224;;w3OP {{499(FKfN
  	r  c                 0    ddi}| j                  |||      S )N0r  rE  rF  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  setrM  r4  )
r  r  r  r   r  r  r4  r  rH  rI  )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                    |t        | j                  dz         | j                          | 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                  ||            S )a]  
        set margin mode to 'cross' or 'isolated'

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

        :param str marginMode: 'cross' or 'isolated'
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        z+ setMarginMode() requires a symbol argumentrB   r  r  z= setMarginMode() supports swap(non USDT based) contracts onlyrM  rL  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   rc  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 
 //GV0LMMr  r   c                    | j                  d|d       | j                          | j                  |      }|d   dk7  rt        | j                  dz         d|d   i}|rd|d<   nd	|d<   | j                  | j                  ||            S )
a  
        set hedged to True or False for a market

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

        :param bool hedged: set to True to use dualSidePosition
        :param str symbol: not used by binance setPositionMode()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        r   r  r  r  z5 setPositionMode() supports USDT settled markets onlyr3   HedgedtargetPosModeOneWay)check_required_argumentr]  r  r%   r3   %privatePutGPositionsSwitchPosModeSyncr  )r  r   r  r  r  rc  s         r  set_position_modezphemex.set_position_mode#  s     	$$%6IV$(v%DGG&]]^^fTl
 '/GO$'/GO$99$++gv:VWWr  c                 >   | j                          |C| j                  |d      }| j                  |      }|d   dk7  rt        | j                  dz         | j                  |      }| j                  |di       }| j                  |d      }| j                  ||d      S )a  
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes
        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `leverage tiers structures <https://docs.ccxt.com/#/?id=leverage-tiers-structure>`, indexed by market symbols
        r   r  r  z7 fetchLeverageTiers() supports USD settled markets onlyr
  r  r  )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..v6^ x4^^D,7
((WhGGr  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  rN  N)tierr  r  minNotionalmaxNotionalmaintenanceMarginRater  r  )r  r  r  r  r  r  rz  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   rY  r  r  zapplication/jsonzContent-Typezx-phemex-request-signaturer   )r   r&  bodyheaders)r  extract_paramsimplode_paramsurlencode_with_array_repeatcheck_required_credentialsr  r  r  rz  rj  r   r  r  jsonhmacencoder   hashlibsha256implode_hostnamer   )r  pathr   r&  r  r  r  r  requestPathr   queryStringrH  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                 &   |t        | j                  dz         |dk  s|dkD  rt        | j                  dz         | j                          | j	                  |dd      }| j                  |d      }| j                  |d	      }| j                  |      }d
|d   i}d}	|d   dk(  rE|s
||||d<   n||n|}
||n|}|
|d<   ||d	<   | j                  | j                  ||            }	|	S ||d<   | j                  | j                  ||            }	|	S )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  rc  r:  longVarshortVars               r  set_leveragezphemex.set_leverage  sJ     >#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)*88Wf9UVH  #+GJ77GV8TUHr  fromAccount	toAccountc           	          | j                          | 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}|P|d   ||
d}| j                  | j                  ||            }| j                  |d	i       }| j                  ||      }nN||	|
|d   | j	                  |d
d      d}| j                  | j                  ||            }| j                  |      }| j                  | j                  di       }| j                  |dd      }|r(|d   ||d<   |d   ||d<   |d   ||d<   |d   ||d<   |S )a#  
        transfer currency internally between wallets on the same account

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

        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from
        :param str toAccount: account to transfer to
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.bizType]: for transferring between main and sub-acounts either 'SPOT' or 'PERPETUAL' default is 'SPOT'
        :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        r  Nr@   rC   r   r   r3   )r  moveOpr  r
  bizTypeSPOT)
fromUserIdtoUserIdr  r  r  r   r  Tr  r  r  r  )r]  r  r  r  r  ru  privatePostAssetsTransferr  parse_transfer"privatePostAssetsUniversalTransferr  )r  r4  r  r  r  r  r  r  fromIdtoIdscaledAmmount	directionr   rc  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
 55dkk'66RSH ??8VR8D**4:H % )$TN++FIvFG >>t{{7TZ?[\H **84H//$,,
BG"&..B[]a"b"&.*5'$,(1%!)%+"
#+'+$r  c                 X   | j                          |t        | j                  dz         | j                  |      }d|d   i}|||d<   |||d<   | j	                  | j                  ||            }| j                  |di       }| j                  |dg       }	| j                  |	|||      S )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>`
        z* fetchTransfers() requires a code argumentr  r3   r  r   r
  r  )	r]  r#   r3   r  privateGetAssetsTransferr  r  r  parse_transfers)
r  r4  r  r   r  r  rc  r:  r
  	transferss
             r  fetch_transferszphemex.fetch_transfers^  s     	<#DGG.Z$Z[[==&
 $GG$GG00Wf1MN* x4NN44	##IxFFr  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  rQ  r   rB   r@   r   r`  )	r  r3   rH  rI  r  r  r  r  r  )r  rA  r  r  rK  parse_transfer_status)r  r   r  r3   r  r  amountTransferedr  r4  rQ  r  r  rH  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 )Nr9  r>  r  r  )r@  rC  rM  11rE  rF  s      r  r  zphemex.parse_transfer_status  s,    	
 &&99r  c           
         |t        | j                  dz         | j                          | j                  |      }|d   dk(  }|d   st	        | j                  dz         d}| j                  |dd	      \  }}|r| j                  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                  |	|            }
n!| j                  | j                  |	|            }
| j                  |
di       }| j                  |d      }g }t        dt        |            D ]O  }||   }| j                  |d      }|j                  ||| j!                  |d      || j#                  |      d       Q | j%                  |d      }| j'                  ||||      S )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   fundingTimerw  )r  r  rw  rH  rI  rH  )r#   r3   r]  r  r$   r,  "fetch_paginated_call_deterministichandle_until_option(v2GetApiDataPublicDataFundingRateHistoryr  (v1GetApiDataPublicDataFundingRateHistoryr  r  r  r  r  r  rK  rL  filter_by_symbol_since_limit)r  r  r  r   r  r  isUsdtSettledr  customSymbolrc  r:  r
  ratesr*  r+  itemrH  sorteds                     r  fetch_funding_rate_historyz!phemex.fetch_funding_rate_history  s    >#DGG.e$effV$x(F2f~TWW'``aa88AZ\fg&::;TV\^cejlprxz}~~-6L!11F:Ll
 $GG$GG225'6JDDT[[QXZ`EabHDDT[[QXZ`EabH" x4f-q#e*% 		A8D))$>IMM #//mD& LL3 		 fk200NNr  r  c                 L   | j                  ||      \  }}| j                          | j                  |       | j                  |      }d}| j	                  |      \  }}d}|| j                  |      }| j                  | j                  d      }	|0| j                  ||	      s|d   }nt        | j                  dz         |d   |||j                         d}
|||
d<   | j                  | j                  |
|            }| j                  |di       }| j                  ||      S )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  r4  r  r  r  r  r  networkCoder"  r  rc  r:  r
  s                r  r   zphemex.withdraw  s0    99#vFV7#==&"AA&IV	"//<IoodllMBMM$4$TN	'2l(lmm "*	
 ?$'GL!II$++V]_eJfg8 ~~h3%%dH55r  c                    | j                          | j                  |      }|d   st        | j                  dz         d|d   i}| j	                  | j                  ||            }| j                  |d      }| j                  ||      S )a\  
        retrieves the open interest of a trading pair

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

        :param str symbol: unified CCXT market symbol
        :param dict [params]: exchange specific parameters
        :returns dict} an open interest structure{@link https://docs.ccxt.com/#/?id=open-interest-structure:
        r  z: fetchOpenInterest is only supported for contract markets.r  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
 ++DKK,HI, (3''77r  c                    | j                  |d      dz  }| j                  |d      }| j                  || j                  ||      | j                  |d      d | j                  |d      d || j	                  |      d|      S )NrH  i@B r  r  openInterestRv)r  r  r  r  openInterestAmountopenInterestValuerH  rI  )r  r  safe_open_interestr  rK  )r  interestr  rH  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                 D   | j                          | j                  |      }| j                  |      }| j                  |d      }||| j                  ||      d}| j	                  | j                  ||            }	| j                  |	di       }
| j                  |
||      S )a+  
        fetch a quote for converting from one currency to another

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

        :param str fromCode: the currency that you want to sell and convert from
        :param str toCode: the currency that you want to buy and convert into
        :param float amount: how much you want to trade in units of the from currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
        r  )fromCurrency
toCurrencyfromAmountEvr
  )r]  r  r  rq  privateGetAssetsQuoter  r  parse_conversion)r  r  r  r  r  r
  r  r  rc  r:  r
  s              r  fetch_convert_quotezphemex.fetch_convert_quote  s     	}}X.]]6*
&&|\B
$  JJvz:

 --dkk'6.JK& ~~h3$$T<DDr  c                    | j                          | j                  |      }| j                  |      }| j                  |d      }|||d}	|| j                  ||      |	d<   | j	                  | j                  |	|            }
| j                  |
di       }| j                  |d      }| j                  ||      }| j                  |d      }| j                  ||      }| j                  |||      S )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>`
        r  )r4  r
  r  r  r
  r
  r  )
r]  r  r  rq  privatePostAssetsConvertr  r  r  r  r  )r  r3   r  r  r  r  r
  r  r  rc  r:  r
  fromCurrencyId
fromResulttoCurrencyIdr  s                   r  create_convert_tradezphemex.create_convert_trade  s     	}}X.]]6*
&&|\B
$ 

 &*jj&DGN#00Wf1MN  ~~h3))$?''E
''l;j9$$T:r::r  c                 6   | j                          i }|||d<   |||d<   |||d<   | j                  d||      \  }}| j                  | j                  ||            }| j	                  |di       }| j                  |dg       }| j                  ||dd||      S )a  
        fetch the users history of conversion trades

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

        :param str [code]: the unified currency code
        :param int [since]: the earliest time in ms to fetch conversions for
        :param int [limit]: the maximum number of conversion structures to retrieve, default 20, max 200
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.until]: the end time in ms
        :param str [params.fromCurrency]: the currency that you sold and converted from
        :param str [params.toCurrency]: the currency that you bought and converted into
        :returns dict[]: a list of `conversion structures <https://docs.ccxt.com/#/?id=conversion-structure>`
        r
  	startTimer   endTimer
  r  r  )r]  r  privateGetAssetsConvertr  r  r  parse_conversions)	r  r4  r  r   r  rc  r:  r
  r  s	            r  fetch_convert_trade_historyz"phemex.fetch_convert_trade_history  s     	&*GN##(GK $GG229gvN//GV0LM. ~~h3~~dFB/%%dD.,PUW\]]r  
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	requestAtr`  r
  r4  r  r  r  origin
toAmountEvproceedsr   )
r  rH  rI  r3   r
  
fromAmountr  toAmountr   r6  )r  r  r  r  r  rK  r  r  )r  r  r
  r  r  requestTimerH  fromCoinr  toCoinr  fromValueScaletoValueScaler#  r$  s                  r  r  zphemex.parse_conversion2  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errorr4  msgr  r  r  r  )r  r  r3   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   )r  r*  r+  r   r&  r  r  r:  requestHeadersrequestBodyr-  	errorCodemessagefeedbacks                 r  handle_errorszphemex.handle_errorsy  s     '8<$$UF3	""5%0!	S(8ww}t+H001I9V^_001I7T\]))r  rf  )r   r   N)NrZ  r[  r   r   N)NN)o__name__
__module____qualname__r   r  r  dictr  r  r   r   r/  r   r?  rF  rT  rj  r   r   rd  rq  ru  rx  r  rB  rA  r  r  r  r  r   r  r  r   r   r  r   r  r  r#  r*  r   r1  r   rH  r  rW  rp  rr  r  r   r  r   r   floatr   r  r  r  r  r  r  r  r  r  r
   r  r   r  r  r  r	   r#  r   r.  r*  rh  rc  r   rm  rl  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  r7  r6  __classcell__)r  s   @r  r0   r0      s   S	# S	j*J JXc cJ $& b$v, bH ') BZ BH	
F 	
  KQ & :>b 7s 73 7Y 7r48F 8
76 7
I& I
I& I
I& I

 
4 
8 26DW[df ML# MLc MLQT MLkoptku ML^U4 U U6 Un 02 E13 E1f E1N 04B 3W 37 3@ 6:UW )?3 )?s )?# )?\`af\g )?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 gksu Q.3 Q.i Q.y Q.RW Q.`c Q.f `drv  @B =.S =.# =.Y =.i =.Y\ =.lo =.~ 37r $.s $.C $.L /32 9
 9
v 26b ,/c ,/3 ,/\ *.Dt\^ !=3 !=c != !=cghmcn !=F /3TXac 'A 'A3 'Ac 'Ahlmrhs 'AR 154VZce MA# MAS MAPS MAjnotju MA^ -1tRV_a U=c U= U=C U=n 79 *
# *
^ *
X *.Dt\^ #E3 #Ec #E #Ecghsct #EJ -1tRV_a #Ec #E #EC #Efjkvfw #EJ:s :(q
T q
X q
Q\ q
f 26b DPw DPT(^ DPLHt HV HT 37TX\eg FC Fs FRU FP
F 
Y\ 
 68 +7 +7K +7Z@
6 @
[ @
D =?  e CU ::
d 
F 
N` 
0 >B" N# Ns N> =A X Xc X2 7;2 ^HG ^H- ^H@# #$|J\ #J &eBSW  PD 9=R )S )# )V [] NS N% Nc Nc Nan N` +/TPT]_ .GC .Gs .G# .Gdhivdw .G`4
t 4
x 4
= 4
l:C :C : 8<$]ajl IO IOC IOWZ IOV DHPR B6S B6% B6# B6Wb B6H 79 (8# (8TF > MQY[ )EC )E )Ec )E`j )EV W[ce -;s -;c -;3 -;PS -;jt -;^ 7;\`ik 1^ 1^3 1^VY 1^ptu  qA 1^fE
4 E
x E
\d E
pz E
Nc 3 S # X\ dg r  r0   )6ccxt.base.exchanger   ccxt.abstract.phemexr   r  r  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   ccxt.base.decimal_to_precisionr-   ccxt.base.preciser.   r0    r  r  <module>rF     s    ( ,   `  `  `  `  `  `  `  * 0 - - . ' & . ) * - + . * 4 %lMX{ lMr  