
    i-Y                    t   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 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m)Z) d dlm*Z* d dl+m,Z, d dl-m.Z.  G d dee          Z/dS )    )Exchange)ImplicitAPIN)Balances
CurrenciesCurrencyIntMarginModificationMarketNumOrder	OrderBook	OrderSide	OrderTypeStrStringsTickerTickersTradeTransactionTransferEntry)List)ExchangeError)AuthenticationError)PermissionDenied)AccountSuspended)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidOrder)OrderNotFound)CancelPending)DuplicateOrderId)NotSupported)DDoSProtection)RateLimitExceeded)	TICK_SIZE)Precisec                   F    e Zd Z fdZd_dZd Zd Zi fdee         fdZ	i fde
fdZd`defdZdadefdZdi fdededefdZd Zd_defdZd_defdZd Zd_defdZd_defdZd_defdZd_dedefdZdddi fdedededee         fdZd_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#d_dede"fd#Z$d$ Z%d% Z&i fde'fd&Z(d' Z)d( Z*d) Z+d_defd*Z,d+ Z-d_defd,Z.d_dede/fd-Z0di fded.e1d/e2d0e3d1e4f
d2Z5ddddi fd3eded.e1d/e2d0e4d1e4fd4Z6di fd3ede7fd5Z8di fde7fd6Z9di fd3ede7fd7Z:dddi fde7dededee/         fd8Z;dddi fde7dededee/         fd9Z<dddi fde7dededee/         fd:Z=dddi fde7dedefd;Z>i fd<efd=Z?dddi fd<e7dededee@         fd>ZAdddi fd<e7dededee@         fd?ZBd@ ZCd_dAeDde@fdBZEdi fd efdCZFd_defdDZGdddi fde7dedefdEZHi fdefdFZId_defdGZJi fded0e3deKfdHZLdI ZMd_dedeKfdJZNdi fdKede7fdLZOdi fdMePde7fdNZQdi fd efdOZRd_defdPZSdQdRi ddfdSZTdi fdTede7fdUZUi fd<ed0e3dVedWedeVf
dXZWdddi fd<e7dedefdYZXd_dAeDfdZZYd[ ZZdddi fde7dedefd\Z[di fd<ed0e3fd]Z\d^ Z] xZ^S )bphemexc                    |                      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d5d6d7dd8dd9dd:dd;dd<dd=dd>dd?dd@ddAddBddCddDddEddddddddddddF
dGdHdIdJdKdJdLdMdNdOdNdLdPdQdRdSdTdUdVdWi dXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzdzdzdzdzdzdzdzdzdzdzdzd{idydzdzdzdzdzdzdzdzdzd|	idydzdzdzdzdzdzd}ii d~dddddzddzddzddzddzddddddddzddzddzddzddzddzddzi ddzddzddzddzddddddzddzddzddzddzddzddzddzddzddzddzi ddzddzddzddzddzddzddzddzddzddzddzddzddzddzddzddzddzi ddddddddzddzddzddzddzddzddzddzddzddzddzddzddzddzdddddzdzdzdzdddddddddddÜdĜdt          dddd|                     dȦ          |                     dȦ          dɜidddd˜di dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          i dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          i dt          dt          dt          dt          dt          dt           dt           dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          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          d*t          d+t          d,t          d-t          d.t          d/t          d0t          d1t          d2t          i d3t          d4t          d5t          d6t          d7t          d8t          d9t          d:t          d;t          d<t          d=t          d>t          d?t          d@t          dAt          dBt          dCt          i dDt          dEt          dFt          dGt          dHt          dIt          dJt          dKt          dLt          dMt          dNt          dOt          dPt          dQt          dRt          dSt          dTt          t          t          t          t          t          t          t          t          t"          t          t$          t"          t          dUt"          t"          t          t          t          t          dVdWdXdYdZdd[d\d]d^d_d\id`dddag dbdcdidd	          S (e  Nidr*   namePhemex	countriesCN	rateLimitg      ^@versionv1	certifiedFproThostnamezapi.phemex.comhasCORSspotmarginswapfutureoption	addMargincancelAllOrderscancelOrderclosePositioncreateOrdercreateReduceOnlyOrdercreateStopLimitOrdercreateStopMarketOrdercreateStopOrder	editOrderfetchBalancefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositsfetchFundingHistoryfetchFundingRatefetchFundingRateHistoriesfetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLeveragefetchLeverageTiersfetchMarketLeverageTiersemulatedfetchMarketsfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchPositionsfetchPositionsRiskfetchPremiumIndexOHLCVfetchTickerfetchTickersfetchTradesfetchTradingFee)
fetchTradingFeesfetchTransfersfetchWithdrawalsreduceMargin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)r3   v2publicprivatezhttps://{hostname}/v1zhttps://{hostname}z"https://{hostname}/exchange/publiczhttps://phemex.comz)https://github.com/phemex/phemex-api-docsz"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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)rx   r3   rw   ry   precisionModer   tradingz0.001)	tierBased
percentagetakermakerrequiredCredentials)apiKeysecret
exceptions401412600119999100011000210003100041000511001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611128)11129111301113111132111331113430000300183400335104399953999639997)z401 Insufficient privilegez401 Request IP mismatchzFailed to find api-keyzMissing required parameterz!API Signature verification failedzApi key not found)exactbroadoptions
CCXT123456<   TRXETHBNB)TRC20ERC20BEP20USDTlinear)r9   r;   )BUSDFEITUSDUSDUSDCUSDDUSDPr_  fillResponseFromRequest)	brokerIdx-phemex-request-expirycreateOrderByQuoteRequiresPricenetworksdefaultNetworksdefaultSubTypeaccountsByTypestableCoinsrt   )deep_extendsuperr*   describer'   parse_numberr   r   r#   r!   r"   r   r    r   r   r   r%   r   r&   )self	__class__s    _/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/async_support/phemex.pyrs  zphemex.describe!   s   fd 3 3 < < > > VA
(VA
HVA
 $VA
 	VA

 tVA
 VA
 4VA
 (VA
  >>> %> 	>
 %> %> U> "4> t>  > t> (> '> (> "4>  T!>" #> >$ +E%>& )%'>( $T)>* '+>, (->. "4/>0 &t1>2  3>4 &t5>6 #D7>8 ,U9>: *4;>< $U=>> "5?>@ *5A>B +EC>D  E> > >F %dG>H +JI>J K>L !%M>N  O>P dQ>R "4S>T dU>V !$W>X tY>Z !$[>\ %e]>^ )%_>` ta>b c>d te>f "5g> >h %*"&$( %#!!%#'  {> > >VA
P }=:N?	  2.B3	  ,B<K # # QVA
|  de e u	
 v f f g g g w g h i i  j!}VA
` +,,-$%)*$%,-'(,-()$%/0>? " '(()$%*+.//03445EF
 
 +,+,'(-.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 lQU UaVA
L YMVA
N !&"&!..w77!..w77	 OVA
^ "$ $_VA
f Y.Y :Y J	Y ZY -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 Y 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 Y 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 Y 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 Y 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 Y 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 Y 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 YV *)))))''-..-&qY Y Yv 3C/?.A2<9L)< wc cgVA
n (+-37"""  E$ #+"$# #	  	  	  .t7 oVA
 V V V	    Nc                     ||S |                     d          }d                    |          }|                     d          }|                     |d          S )N,  r   )splitjoinsafe_number)ru  valuepartss      rw  parse_safe_numberzphemex.parse_safe_number  sS    =LC  C  q)))rx  c                    |                      |d          }|                     |dd          }|                      |d          }|                      |d          }|                     |          }|                     |          }|                     |          }d}	||k    rd}	|                     |d          }
|                     |d	          }|                     |d
          }|                      |d          }|                      |d          }|                      |d          }|                      |d          }|                      |d          }|                      |dd          }d }|dk    r|                     d          }n[|                    d          r1|                    d          }|                     |d                   }n|                     |          }|                     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'|	 |	|                     |                     ||                    |                     |                     ||                    |d d d d |
||| 	                    |d(d)          | 
                    |d*          d+|                     d          | 
                    |d,          d-d d d-|                     |                     ||
                    |                     |                     ||
                    d-d |                     |                      |d.                    d-d/d |d0          S )1NsymbolbaseCurrencycontractUnderlyingAssetsquoteCurrencysettleCurrencyFT
priceScale
ratioScale
valueScale
minPriceEp
maxPriceEpmakerFeeRateErtakerFeeRateErstatuscontractSizer|  r_  1r   r,   /:basequotesettlebaseIdquoteIdsettleIdtyper;   r9   r:   r<   r=   activeListedcontractr`  lotSizeqtyStepSizetickSizeamountpricemaxLeverageminmaxmaxOrderQtyleverager  r  costinverser   r   r  expiryexpiryDatetimestrike
optionTyper  r  r  	precisionlimitscreatedinfo)safe_stringsafe_string_2safe_currency_codesafe_integerrt  findr}  safe_market_structurefrom_ensafe_number_2r  )ru  marketr,   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  contractSizeStringr  r  s                        rw  parse_swap_marketzphemex.parse_swap_market  sW   d fh//##FN<VWW""6?;;##F,<==&&v..''00((22wG&&v|<<
&&v|<<
&&v|<<
%%fl;;
%%fl;;
))&2BCC))&2BCC!!&(33!--fncJJ V,,S11LL$$S)) 	A ',,S11E,,U1X66LL  ,,-?@@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'OPP&&t||NJ'O'OPP("$$$,,VYNN))&*==   ,,S11++FMBB 
   
  ,,T\\*j-Q-QRR,,T\\*j-Q-QRR 
  ,,T-=-=fm-T-TUU  $ i5+
 5+
 5+
 5 5 5	rx  c                 x   |                      |d          }|                     |d          }|                     |d          }|                     |d          }|                     |          }|                     |          }|                     |d          }|                     |                     |d                    }	|                     |                     |d                    }
|                     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 |                     |d          |                     |d          d d d d d |                     |d          |                     |d          |                     |d          |	|
d d d d!|	|                     |                     |d"                    d!|
d d!|                     |                     |d#                    |                     |                     |d$                    d!d%d |d&          S )'Nr  r  r  r  r  baseTickSizequoteTickSizer,   r  r  r  r  r  r  r  r9   Tr:   Fr;   r<   r=   r  r  r  r`  defaultTakerFeedefaultMakerFeer  r  r  r  r  maxBaseOrderSizeminOrderValuemaxOrderValuer  r  )safe_string_lowerr  r  r  r  r  r  )ru  r  r  r,   r  r  r  r  r  precisionAmountprecisionPrices              rw  parse_spot_marketzphemex.parse_spot_market  s   J %%ff55fh//""6?;;!!&.99&&v..''00!!&(33001A1A&.1Y1YZZ//0@0@0Y0YZ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A++FLAA++FLAA)'    
 +11$2B2B6K]2^2^__ 
 * 
  11$2B2B6?2[2[\\11$2B2B6?2[2[\\  $ i5+
 5+
 5+
 5 5 5	rx  returnc                 H  K   |                      |           d{V }|                     |           d{V }|                     |dg           }|                     |di           }|                     |dg           }|                     |dg           }|                     ||          }|                     |dg           }|                     |dg           }	|                     ||	          }|                     |dg           }
|                     |d          }|                     |d          }|                     |
d	          }g }t          d
t          |                    D ]9}||         }|                     |d          }|dk    s|dk    r|                     |d          }|                     ||i           }| 	                    ||          }|                     ||i           }| 	                    ||          }| 
                    |          }nq|                     |d          }|                     ||i           }|                     |dd          }| 	                    |d|i          }|                     |          }|                    |           ;|S )z
        retrieves data on all markets for phemex
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        Ndatar   perpProductsV2
riskLimitsriskLimitsV2
currenciesr  currencyr   r  	perpetualperpetualv2r  r  8)v2GetPublicProductsv1GetExchangePublicProducts
safe_valuearray_concatindex_byrangelenr  r  extendr  r  append)ru  params
v2Products
v1Productsv1ProductsDatav2ProductsDatar   perpetualProductsV2r  r  r  riskLimitsByIdv1ProductsByIdcurrenciesByCoderesultir  r  r,   riskLimitValuesv1ProductsValuesr  currencyValuesr  s                           rw  fetch_marketszphemex.fetch_markets  s       33F;;;;;;;;
l  ;;FCCCCCCCC
VR@@H VR@@??>:rBB"oon>NPRSS$$X/BCC__^\2FF
~~rJJ&&z<@@
__^\2FF
z8<<~x@@==Z@@q#h--(( 	" 	"Aa[F))&&99D##)>)>%%fh77"&//."b"I"IV_==#'??>2r#J#J V-=>>//77#//GG!%1A<QS!T!T!--nlCPP
VlJ-GHH//77MM&!!!!rx  c                   K   |                      |           d{V }|                     |di           }|                     |dg           }i }t          dt          |                    D ]T}||         }|                     |d          }|                     |d          }	|                     |          }
|                     |d          }|                     |d          }t          |          }|                     |d	          }|                     |d
          }d}d}d}|z|                     |          }|                     |          }|                     t          j
        ||                    }|                     t          j
        ||                    }|||
|	|dk    ddd|||ddddd|i d||
<   V|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
        Nr  r  r   r  r-   r  r  
minValueEv
maxValueEvr  r  )r  ru   )r,   r  coder-   r  depositru   feer  r  r  rl  )r  r  r  r  r  r  intparse_precisionrt  r(   
string_mul)ru  r  responser  r  r  r  r  r,   r-   r  r  valueScaleStringr  r  r  	minAmount	maxAmountr  precisionStrings                       rw  fetch_currencieszphemex.fetch_currencies  s      11&99999999 x44__T<<<
q#j//** (	 (	A!!}H!!(J77B##Hf55D**2..D%%h99F#//,GG-..J))(LAAJ))(LAAJ!I!I!I%"&"6"67G"H"H --o>>	 --g.@_.].]^^	 --g.@_.].]^^	  H, &  )( 
  $#! !	 	 )+ F4LL. rx  r   r   r  c                 @   |t          | j        dz             |                     ||          }|d         r|                     ||          }|                     |                     |                     ||          |                    |                     |          gS )Nz/ customParseBidAsk() requires a market argumentr9   )r   r,   r  from_evrt  from_ep)ru  bidaskpriceKey	amountKeyr  r  s         rw  custom_parse_bid_askzphemex.custom_parse_bid_ask  s    >#DG._$_```!!&)44&> 	2\\&&11Fdll4+;+;FH+M+MvVVWWf%%
 	
rx  bidsasksc	           
         |||                      |          d d}	||g}
t          dt          |
                    D ]x}|
|         }g }|                     ||          }t          dt          |                    D ]3}|                    |                     ||         |||                     4||	|<   y|                     |	|         dd          |	|<   |                     |	|         d          |	|<   |	S )N)r  	timestampdatetimenoncer   T)iso8601r  r  r  r  r  sort_by)ru  	orderbookr  r
  bidsKeyasksKeyr  r  r  r  sidesr  sider   bidasksks                   rw  custom_parse_order_bookzphemex.custom_parse_order_book  s	   "Y//	
 
 '"q#e**%% 	" 	"A8DFooi66G1c'll++ b bd77
HiY_``aaaa!F4LL,,vg4@@w,,vg::wrx  r  limitc           
        K   |                                   d{V  |                     |          }d|d         i}d}|d         r<|d         dk    r0|                     |                     ||                     d{V }ng|6|dk    r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |di           }|                     |d	d
i           }|                     |dd          }	| 	                    |||	dddd|          }
| 
                    |d          |
d<   |
S )ae  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#queryorderbook
        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        Nr  r,   r`  r  r_     r  bookorderbook_pr
  ư>r  r  r   r   sequencer  )load_marketsr  v2GetMdV2Orderbookr  v1GetMdOrderbookv1GetMdFullbookr  safe_value_2safe_integer_productr  r  )ru  r  r  r  r  requestr  r  r  r
  r  s              rw  fetch_order_bookzphemex.fetch_order_book/  s      !!!!!!!!!V$$fTl
 ( 	Tx 0F : :!44T[[&5Q5QRRRRRRRRHH!!%!6!6t{{7F7S7S!T!TTTTTTT!%!5!5dkk'66R6R!S!SSSSSSS4 8R88  CC--fk8LL	00vy&RXZ[]^`fgg	!..vzBB	'rx  c                     |                      |          }t          |          }|j        |z
  |_        |                                 t	          |          }|                     |          S N)number_to_stringr(   decimalsreducestrparse_to_int)ru  nscalestringNprecisepreciseStrings         rw  to_enzphemex.to_enf  sa    ''**'"""+e3G  ///rx  c                 F    |||S |                      ||d                   S Nr  r2  )ru  r  r  s      rw  to_evzphemex.to_evn  s)    NMzz&&"6777rx  c                 F    |||S |                      ||d                   S Nr  r5  )ru  r  r  s      rw  to_epzphemex.to_eps  s)    Mv~Lzz%!5666rx  c                     |d S t          |          }|                     |j        |          |_        |                                 t	          |          S r'  )r(   sumr)  r*  r+  )ru  enr.  r0  s       rw  r  zphemex.from_enx  sL    :4"++88G$4e<<7||rx  c                 b    |||S |                      ||                     |d                    S r8  r  r  )ru  epr  s      rw  r  zphemex.from_ep  4    JFNI||B 1 1&, G GHHHrx  c                 b    |||S |                      ||                     |d                    S r4  r>  )ru  evr  s      rw  r  zphemex.from_ev  r@  rx  c                 b    |||S |                      ||                     |d                    S )Nr  r>  )ru  err  s      rw  from_erzphemex.from_er  r@  rx  c                    |F|d         r>|                      |                     |                     |d          |                    }n|                     |d          }|                     |d          |                      |                     |                     |d          |                    |                      |                     |                     |d          |                    |                      |                     |                     |d          |                    |                      |                     |                     |d          |                    |gS )Nr9      r   r      r      )rt  r  r  r  safe_timestampr  )ru  ohlcvr  
baseVolumes       rw  parse_ohlcvzphemex.parse_ohlcv  s9    F6N**4<<8H8HPQ8R8RTZ+[+[\\JJ))%33Jq))dll4+;+;E1+E+EvNNOOdll4+;+;E1+E+EvNNOOdll4+;+;E1+E+EvNNOOdll4+;+;E1+E+EvNNOO
 	
rx  r   sincec                   K   |                                   d{V  |                     |          }|}|d         |                     | j        ||          d}|                     |dd          }	|                     |dg          }|d         s|d         dk    o|dup|	du}
d	}|
rd
}||}t          ||          |d<   d}|d         s|d         dk    r|	||                     |          }|%t          t          |d	z                      }||d<   n|	dz  ||z  z
  }|	#t          t          |	d	z                      |d<   n)|||z  z   }| 
                                }||k    r|}||d<   |                     |                     ||                     d{V }n|                     |                     ||                     d{V }nx|G|                     |          d	z  }|                                 |z
  }|                     ||z            }|                     |                     ||                     d{V }|                     |di           }|                     |dg           }|                     |||||          S )a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#querykline
        :see: 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
        Nr,   )r  
resolutionuntiltor`  r  r_  i  i  r  fromd   r  rows)r  r  r  r   safe_integer_2omitr  parse_timeframer  roundsecondspublicGetMdV2KlineListr  publicGetMdV2KlineLastmillisecondsr,  publicGetMdV2Kliner  	safe_listparse_ohlcvs)ru  r  	timeframerN  r  r  r  	userLimitr$  rQ  usesSpecialFromToEndpointmaxLimitr  candleDurationrR  nowduration	timeDeltar  rU  s                       rw  fetch_ohlcvzphemex.fetch_ohlcv  s      !!!!!!!!!V$$	Tl**4?IyQQ
 
 ##FGT::6G9--&,X&6&T&:Jf:T  %H]bjn]n  ]Gty  BF  uF!$ 	H=Euh//( 	Svh/699!u'8!%!5!5i!@!@$edl 3 344E&+GFOO #S[X-FGE$$'edl(;(;$<$<GDMM (^";<B,,..CCxx $&GDM!%!<!<T[[RX=Y=Y!Z!ZZZZZZZ!%!<!<T[[RX=Y=Y!Z!ZZZZZZZ   //	::TA --//%7	)))h*>??!44T[[&5Q5QRRRRRRRRH x44~~dFB//  vy%KKKrx  c                 &   |                      |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 dd d d |||d!|          S )"Nr  r
  r  lastEpcloseRp
turnoverEv
turnoverRvvolumevolumeEvvolumeRqopenEpr  highhighEphighRplowlowEplowRpbidbidEp	bidVolumeaskaskEp	askVolumevwapopencloselastpreviousClosechanger   average)rL  quoteVolumer  )	r  safe_marketr#  r  r  rE  r  safe_tickerr  )
ru  tickerr  marketIdr  r
  r  r  rL  r  s
             rw  parse_tickerzphemex.parse_ticker  s   l ##FH55!!(F33!--fk8LL	||D..vxKKVTTll4#5#5flL#Y#Y[abb%%fh77
d&8&8Z&X&XZ`aaJ||D,,VX>>GG !
f!
!
 Y//!
 DLL!3!3FHh!O!OQWXX	!

 4<< 2 267G L LfUU!
 4<< 0 0 A A6JJ!
 !
 4<< 0 0 A A6JJ!
 !
 D!
 D!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ %&)!
 !
 !
* +  	rx  c                 ,  K   |                                   d{V  |                     |          }d|d         i}d}|d         rt|d         s|d         dk    r0|                     |                     ||                     d{V }n_|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |di           }|                     ||          S )	a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#query24hrsticker
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nr  r,   r;   r  r  rd  r  )r  r  v1GetMdTicker24hrr  v2GetMdV2Ticker24hrv1GetMdSpotTicker24hr	safe_dictr  ru  r  r  r  r$  r  r  s          rw  fetch_tickerzphemex.fetch_tickerO  sI      !!!!!!!!!V$$fTl
 &> 	Vi  XF8$4$=$=!%!7!7GV8T8T!U!UUUUUUU!%!9!9$++gv:V:V!W!WWWWWWW!77GV8T8TUUUUUUUUHZ (B77  000rx  symbolsc                   K   |                                   d{V  d}|+|                     |d          }|                     |          }d}|                     d||          \  }}d}|                     d||          \  }}|                     |d          }d}|dk    r|                     |           d{V }nW|dk    s|                     |d          dk    r|                     |           d{V }n| 	                    |           d{V }| 
                    |d	g           }	|                     |	|          S )
a  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        :see: https://phemex-docs.github.io/#query-24-hours-ticker-for-all-symbols-2     # spot
        :see: https://phemex-docs.github.io/#query-24-ticker-for-all-symbols             # linear
        :see: 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   ri   r  r9   r  r  rd  r  )r  r  r  handle_market_type_and_paramshandle_sub_type_and_paramsrW  v1GetMdSpotTicker24hrAllr  v1GetMdTicker24hrAllv2GetMdV2Ticker24hrAllr_  parse_tickers)
ru  r  r  r  firstr  subTypequeryr  r  s
             rw  fetch_tickerszphemex.fetch_tickers  s      !!!!!!!!!OOGQ//E[[''F99.&RXYYf99.&RXYY		&&))6>>!::5AAAAAAAAHH	!!T%5%5fh%G%G5%P%P!66u========HH!88????????H(B77!!&'222rx  c                   K   |                                   d{V  |                     |          }d|d         i}d}|d         r<|d         dk    r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |di           }|                     |dd	g           }	|                     |	|||          S )
aL  
        get the list of most recent trades for a particular symbol
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#querytrades
        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Nr  r,   r`  r  r_  r  tradestrades_p)r  r  v2GetMdV2Trader  v1GetMdTrader  r"  parse_trades)
ru  r  rN  r  r  r  r$  r  r  r  s
             rw  fetch_tradeszphemex.fetch_trades  s#      !!!!!!!!!V$$fTl
 ( 	Mx 0F : :!00Wf1M1MNNNNNNNNHH!..t{{7F/K/KLLLLLLLLH" 8R88""68ZDD  >>>rx  c                 *	   d }d }d }d }d }d }d }	d }
|                      |d          }|                     ||          }|d         }d }d }t          |t                    rt	          |          }|                     |dd          }|dk    r|                      ||dz
            }|                     ||dz
            }|                      ||dz
            }|                      ||dz
            }t          ||dz
           t          j                  r,| 	                    ||          }| 
                    ||          }n|                     |dd          }||                     |d	          }|                     |d
d          }|                      |d          }|d         dk    r|                     |d          }|dk    s|dk    r|}n|
|dk    rdnd}|                      |d          }|dk    rd}n|dk    rd}|                      |d          }|                      |d          }|                      |d          }|                      |d          }|                      |d          }	|                      |d          }|                     |          }
n|                     |d          }|                     |                      |d                    }|                      |d          }|dk    rd}| 	                    |                      |d           |          }| 
                    |                      |d!          |          }|                      |d"|          }|                     |                     |d#d$          |          }|                     |                      |d%          |          }||                     |                      |d&          |          }	|d'         r*|                     |                      |d(                    }
nC|                     |d)          }|+|                      |d*          }|                     |          }
||	|
d+}|                     |||||                     |          ||||||||d,|          S )-Nr  r   r  rH  r   r   r   transactTimeNs	createdAtexecIdexecIDorderIDr  r_  r  buysellr  ordTyper  2r  execPriceRp	execQtyRqexecValueRv	execFeeRv	feeRateRrr  
execStatus	MakerFillr   execPriceEpexecBaseQtyEvexecQtyexecQuoteQtyEvexecValueEv	execFeeEv	feeRateErr9   feeCurrencyr  settlementCurrency)r  rater  )r  r,   r  r
  r  orderr  r  takerOrMakerr  r  r  r  )r  r  
isinstancelistr  r#  r  numbersRealr  r  r  r  r  parse_order_typerE  r  
safe_trader  )ru  trader  r,   r  
costStringr  r  feeCostStringfeeRateStringfeeCurrencyCoder  r  orderIdr  tradeLengthr
  priceStringamountStringsideIdr  
currencyIdr  r  settlementCurrencyIds                            rw  parse_tradezphemex.parse_trade  s   J 
!!###E844!!(F33! eT"" ;	e**K11%HEEIQ%%e[1_==))%qAAD**5+/BBK++E;?CCL%a0',?? B"ll;??#||L&AA11%9I8TTI  --e[AA	##E8X>>B&&ui88Gh6))//v>>eOO6)9)9!DD'%+s]]55D**5)<<c>>#DD^^"D"..umDD#//{CC!--e]CC
 $ 0 0 D D $ 0 0 D D!--eZ@@
"&"9"9*"E"E--eV<<,,T-=-=eY-O-OPP!--e\BB
,,#*L"ll4+;+;E=+Q+QSYZZ#||D,<,<UO,T,TV\]]#//y,OO!\\$*<*<UDTVc*d*dflmm
 $T-=-=e[-Q-QSY Z Z ,$(LL1A1A%1U1UW]$^$^Mf~ \*.*A*A$BRBRSXZgBhBh*i*i#vv>>+373C3CDJ^3_3_0.2.E.EFZ.[.[O%%+ C
 "Y//( " 
  
   	rx  c                 ~   d }d|i}|                      |dg           }t          dt          |                    D ]P}||         }|                     |d          }|                     |          }|                      | j        |i           }	|                     |	dd          }
|                                 }|                     |d          }|                     |d          }|                     |d	          }|                     ||
          }|                     ||
          }|                     ||
          }t          j
        ||          }|                     |d
d          }||nt          ||          }||d<   ||d<   |||<   R||d<   |                     |          |d<   |                     |          S )Nr  r  r   r  r     	balanceEvlockedTradingBalanceEvlockedWithdrawEvlastUpdateTimeNsr  totalusedr
  r  )r  r  r  r  r  r  r  accountr  r(   
string_addr#  r  r  safe_balance)ru  r  r
  r  r  r  balancer  r  r  r.  r  r  r  r  r  lockedTradingBalancelockedWithdrawr  r  s                       rw  parse_spot_balancezphemex.parse_spot_balance  s   2 	(#x44q#d))$$ 	# 	#A1gG))':>>J**:66DtbAAH%%ha@@EllnnG((+>>I%)%5%5g?W%X%X"#//9KLLLLE22E#'<<0F#N#N !\\*:EBBN%&:NKKD#88BTV^__-6->((STdEeEeI$GG"GFO"F4LL'{!\\)44z  (((rx  c                 L   d|i}|                      |di           }|                      |di           }|                     |d          }|                     |          }|                     |          }|                     |dd          }|                                 }	|                     |dd          }
|                     |d	d
          }|dk    }|r|                     |
|          n|
|	d<   |r|                     ||          n||	d<   |	||<   |                     |          S )Nr  r  r  r  r  r  accountBalanceEvaccountBalanceRvtotalUsedBalanceEvtotalUsedBalanceRvr_  r  r  )	r  r  r  r  r  r  r  r  r  )ru  r  r  r  r  r  r  r  r  r  r  r  needsConversions                rw  parse_swap_balancezphemex.parse_swap_balance  s6   > (#x44//$	266%%gz::
&&z22==&&&&xqAA
,,..--g7IK]^^!//9MOcdd6>IXn4<<(8*EEE^nJYq$,,'9:FFF_qt  (((rx  c                 ,  K   |                                   d{V  d}|                     dd|          \  }}|                     |d          }|                     |dg          }d}i }|dk    r#|dk    rt	          | j        dz   |z   dz             |dk    rd}|                     |ddd	          \  }}||d}||}n|}|                     |          }|d
         |d<   |d
         d	k    r0|                     | 	                    ||                     d{V }n| 
                    | 	                    ||                     d{V }n|                     |d          }|t          | j        dz   |z   dz             |                     | 	                    ||                     d{V }n/|                     | 	                    ||                     d{V }|dk    r|                     |          n|                     |          }	|	S )a  
        query for balance and get the amount of funds available for trading or funds locked in orders
        :see: https://phemex-docs.github.io/#query-wallets
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#query-account-positions
        :see: 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>`
        NrH   r  r9   r;   z does not support z markets, only spot and swapr  r_  r,   r  zP fetchBalance() requires a code parameter or a currency or settle parameter for z type)r  r  r  rW  r   r,   handle_option_and_paramsr  #privateGetGAccountsAccountPositionsr  "privateGetAccountsAccountPositionsr   privateGetSpotWalletsr  r  )
ru  r  r  r  r  r$  r  coinr  r  s
             rw  fetch_balancezphemex.fetch_balance;  s      !!!!!!!!!99.$PVWWf//6F8,,FNNTW';;dBEccddd6>>F!::6>S[]cddNFF6#5#DD!D==..&.tn
#D>V++%)%M%MdkkZaciNjNj%k%kkkkkkkHH%)%L%LT[[Y`bhMiMi%j%jjjjjjjHH++FJ??#+DG  7I  -I  LP  -P  SZ  -Z  [  [  [!%!;!;DKKQW<X<X!Y!YYYYYYY!77GV8T8TUUUUUUUUHl 8<v~~((222DLcLcdlLmLmrx  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}|                      |||          S )NCreatedr  UntriggeredDeactivatedclosed	TriggeredRejectedrejectedNewPartiallyFilledFilledCanceledcanceledr  r  34567r  r  ru  r  statusess      rw  parse_order_statuszphemex.parse_order_status  s    
v
6
 8
 	

 

 6
 v
 h
 

 
 
 
 
 
 
  !
" #
& &&999rx  c                 N    ddddddddddddd}|                      |||          S )Nr  r  stop	stopLimit)r  r  r   r  r  r  r  r  910Limitr
   r  )ru  r  typess      rw  r  zphemex.parse_order_type  sL    
 
 tT222rx  c                 >    ddddd}|                      |||          S )NGTCPOIOCFOK)GoodTillCancelPostOnlyImmediateOrCancel
FillOrKillr  )ru  timeInForcetimeInForcess      rw  parse_time_in_forcezphemex.parse_time_in_force  s4    #!&	
 
 k;GGGrx  c           
      <   |                      |d          }|                      |d          }|t          |          dk     rd }|                      |d          }|                     ||          }|d         }|                     |                      |d          |          }|                     |                      |d          |          }|                     |                     |                      |d          |                    }	|                     |                     |dd	          |          }
|                     |                     |d
d          |          }|                     |                      |d          |          }|                     |                      |d                    }| 	                    |d          }| 
                    |                      |d                    }|                     |ddd          }d }|                     |                      |d          |          }||d d}|                     |                      |d                    }|                     |                     |                     |                      |d                                        }|dk    }|                     i d|d|d|d|d|                     |          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	ordStatusr  r  actionTimeNscreateTimeNsr  cumFeeEvr  r  r  stopPxEpr  r  r,   clientOrderIdr
  r  lastTradeTimestampr  postOnlyr  	stopPricetriggerPricer  r  r  )filled	remainingr  r  r  )r  r  r  r  r  	omit_zeror  rE  r  r  r  safe_integer_product_2r  rt  
safe_orderr  )ru  r  r  r,   r,  r  r  r  r  r2  r1  r  r  r  r  r  r
  r  feeCostr  r/  r.  s                         rw  parse_spot_orderzphemex.parse_spot_order  s   r eY//((	::%C,>,>,B,B M##E844!!(F33!T--eY??HHd..ukBBFKKNN4<<0@0@HY0Z0Z\b#c#cdd	d00HXYY[abb||D..u6GVVX^__,,t//|DDfMM(()9)9%)M)MNN%%eV44$$T%5%5eY%G%GHH//~~W_``	,,t//zBBFKK  C ..t/?/?}/U/UVV%%dnnT\\$BRBRSXZdBeBe5f5f&g&ghh	4'  
E 
" 
 ] 
 	 

 Y// 
 !$ 
 f 
 D 
 ; 
  
 D 
 U 
  
 I 
 f 
  D! 
" w# 
$ "- 
  
  
. /  	rx  c                 :    ddd}|                      |||          S )Nr  r  )r  r  r  )ru  r  r  s      rw  parse_order_sidezphemex.parse_order_sidez  s.    
 
 tT222rx  c                    |                      |dd          }|                      |dd          }|t          |          dk     rd }|                     |d          }|                     ||          }|                     |                     |d                    }|                     |                     |d                    }|                     |                     |d	                    }	|                     |d
          }
|
*|                     |                     |d          |          }
| 	                    |dd          }| 	                    |dd          }| 	                    |dd          }| 
                    |dd          }||                     |d          }| 	                    |dd          }| 
                    |dd          }|dk    rd }|                     |                     |d                    }|                     | 	                    |dd                    }|dk    }|                     |d          }|                     |d          }|dk    rd }|                     |d!          }|                     |d"          }|                     i d#|d$|d%|d&|                     |          d'|d(|d|d)|	d|d*|d|d|d+|
d,|d-|d.|d/|||||d |d d d0          S )1Nr  r  r  clOrdIdr   r  r&  r  	orderTypepriceRpr  orderQty
orderQtyRqcumQtycumQtyRq	leavesQtyleavesQtyRqr'  r  r  cumValue
cumValueRvr  r   r  stopPxstopPxRpr  
reduceOnlyexecInst
ReduceOnlyTtakeProfitRp
stopLossRpr  r,   r,  r  r
  r-  r  r.  r  r/  r0  takeProfitPricestopLossPrice)r  r1  r2  r  r  r  r  r  )r  r  r  safe_symbolr  r9  r  r  r  r  r#  r  r  r3  r  r5  r  )ru  r  r  r,   r,  r  r  r  r  r  r  r  r1  r2  r
  r  r-  r  r/  r.  rH  rI  
takeProfitstopLosss                           rw  parse_swap_orderzphemex.parse_swap_order  s   L y)<<**5)YGG%C,>,>,B,B M##E844!!(F33(()9)9%)M)MNN$$T%;%;E6%J%JKK$$T%5%5e[%I%IJJ  	22=LL!1!1%!C!CVLLE##E:|DD##E8Z@@&&uk=II	--e^XNN	))%==I!!%\BB!66u>NPXYY""!%..t/?/?}/U/UVVNN4#5#5eXz#R#RSS	4'__UL99
##E:66|##J%%e^<<
##E<88  
E 
" 
 ] 
 Y//	 

  
 !"4 
 f 
 D 
 ; 
  
 * 
 D 
 U 
  
 I 
  z! 
" X# 
$ "3 
  
  
   	rx  c                     |                      |dd          }d|v pd|v pd|v }|s|r|                     ||          S |                     ||          S )Nr;   F	closedPnlclosedPnlRv
totalPnlRv)	safe_boolrR  r7  )ru  r  r  isSwaphasPnls        rw  parse_orderzphemex.parse_order"	  sq    66&^MU,B^X]H] 	8V 	8((777$$UF333rx  r  r  r  r  c                 B  K   |                                   d{V  |                     |          }|                     |          }|                     |          }|                     |d          }	|d         ||d}
|                     |dd          }|                     |d          }|du}|                     |d          }|du}|9|                     | j        d	d
          }|||                                 z   |
d<   n||
d<   |                     |ddg          }| 	                    |g d          }|?|d         dk    r| 
                    ||          |
d<   n|                     ||          |
d<   |                     |g d          }|d         rM|                     |dd          }|dk    s|dk    s|dk    r|d}||
d<   |dk    r|                     |d          }|                     |d          }| j        d         rv|U|                     |          }|                     |          }t          j        ||          }|                     |          }n|t#          | j        dz   |z   dz             ||n|}|                     |          }|                     ||          |
d<   n|                     |          }|                     ||          |
d<   n|d         r|                     |d          }|d }|                     |          }||
d<   |	|	|
d<   |d         dk    r||
d!<   n|                     |          |
d"<   ||                     |d#d$          }||
d#<   |s|r |r|                     |d%d&          }|t/          | j        d'z             |d         dk    r| 
                    ||          |
d(<   n|                     ||          |
d)<   |                     |d*d+          }|v|d         dk    rB|d$k    r;|d,k    r5|d-k    r/|d.k    r)|d/k    r#|d0k    r|d1k    rt/          | j        d2z             n#|d$k    r|d,k    rt/          | j        d3z             ||
d+<   |r|                     |d%d&          }|t/          | j        d4z             |d         dk    r| 
                    ||          |
d5<   n|                     ||          |
d6<   |                     |d*d7          }|v|d         dk    rB|d$k    r;|d,k    r5|d-k    r/|d.k    r)|d/k    r#|d0k    r|d1k    rt/          | j        d2z             n#|d$k    r|d,k    rt/          | j        d3z             ||
d7<   |d8k    s|d9k    s|d:k    rT|d         dk    r| 
                    ||          |
d;<   n.|                     |          }|                     ||          |
d<<   |                     |d=          }|U|d         dk    r| 
                    ||          |
d5<   n|                     ||          |
d6<   |                     |d=          }|                     |d>          }|U|d         dk    r| 
                    ||          |
d(<   n|                     ||          |
d)<   |                     |d>          }|                     |d          }d} |d         dk    r0|                     |                     |
|                     d{V } ng|d?         r0|                     |                     |
|                     d{V } n/|                     |                     |
|                     d{V } |                     | d@i           }!|                     |!|          S )Aa  
        create a trade order
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#place-order
        :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 fullfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :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
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NrH  r,   )r  r  r  r  r,  rQ  rP  ri  rW  )rF  r/  r0  r  r_  rG  r+  )rF  r/  rQ  rP  r0  r9   qtyTypeByBaser
   StopMarketIfTouchedByQuoter  rk  z createOrder() z. requires a price argument or a cost parameterr$  r  r;   posSideMergedr?  r>  triggerTypeByMarkPricer0  r/  z createOrder() requires a trigger price in params["stopLoss"]["triggerPrice"], or params["stopLoss"]["stopPrice"] for a stop loss orderrL  
stopLossEptriggerPriceType	slTriggerByLastPriceByIndexPrice
ByAskPrice
ByBidPriceByMarkPriceLimitByLastPriceLimitz createOrder() take profit trigger price type must be one of "ByMarkPrice", "ByIndexPrice", "ByAskPrice", "ByBidPrice", "ByMarkPriceLimit", "ByLastPriceLimit" or "ByLastPrice"z\ createOrder() take profit trigger price type must be one of "ByMarkPrice", or "ByLastPrice"z createOrder() requires a trigger price in params["takeProfit"]["triggerPrice"], or params["takeProfit"]["stopPrice"] for a take profit orderrK  takeProfitEp	tpTriggerr  	StopLimitLimitIfTouchedr=  r  rM  rN  r  r  )r  r  
capitalizer  r  r  rV  uuid16rW  safe_string_nprice_to_precisionr9  r  r(  r(   r  rt  r   r,   r6  r  r,  r"  r    privatePostGOrdersr  privatePostOrdersprivatePostSpotOrdersr  rZ  )"ru  r  r  r  r  r  r  r  requestSiderH  r$  r,  rQ  stopLossDefinedrP  takeProfitDefinedri  r/  r\  r  r  r  quoteAmountr  ra  rc  stopLossTriggerPricestopLossTriggerPriceTypetakeProfitTriggerPricetakeProfitTriggerPriceTyperM  rN  r  r  s"                                     rw  create_orderzphemex.create_order)	  s
       !!!!!!!!!V$$ood++t$$__V\::
 Tl	
 
8 **69oNN??6:66#4/__V\::
't3 ''j,OOH#%-%=	"!.GIYYv	?'CDDF&&v/V/V/VWW	 h6))&*&=&=fi&P&P
##&*jjF&C&C
#6#d#d#dee&> H	JoofiBBG  dfnn$BS:S:S$'G!(GI)##''776622< AB J('+'<'<V'D'D&*&;&;E&B&B&-&8{&S&S#00==/:K0Kg0U  YI  1I  J  J  J"&,vvT!22488
(,

:v(F(F%%#44V<<'+zz,'G'G$$F^ 1	J,,VY??G"oog..G!(GI%(2%h6))(.%%&*&7&7&?&?
#$"..v}mTT)4& "J"3 "J" H+/+<+<X~Wb+c+c(+3*47  6  ,  @  @  @h'611040G0GPd0e0e--04

;OQW0X0X-/3/A/A(L^`k/l/l,/;!(+v55 8M I IPhlyPyPy  AY  ]k  Ak  Ak  rJ  NZ  rZ  rZ  ay  }I  aI  aI  Ph  l~  P~  P~  E]  as  Es  Es&247  >o  4o  'p  'p  !p 8M I IPhlyPyPy&247  >\  4\  ']  ']  !]/G,$ J-1->->z>[f-g-g*-5*47  6E  ,E  F  F  Fh'611262I2I&Rh2i2i//26**=SU[2\2\/151C1CHN`bm1n1n.1=!(+v55 :m K KRlp}R}R}  E_  cq  Eq  Eq  xR  Vb  xb  xb  iC  GS  iS  iS  Zt  xJ  ZJ  ZJ  Qk  oA  QA  QA&247  >o  4o  'p  'p  !p :m K KRlp}R}R}&247  >\  4\  ']  ']  !]/I,GOO!4!4$BR:R:Rh6))%)%<%<VU%K%K	"""33E::%)ZZV%D%D	"**63DEE&h6))*.*A*A&/*Z*Z''*.**_f*M*M'YYv'899F((AA$h6))(,(?(?(V(V%%(,

=&(I(I%YYv77F6<00(v%%!44T[[&5Q5QRRRRRRRRHHJ 	V!33DKK4P4PQQQQQQQQHH!77GV8T8TUUUUUUUUHZ ~~h33f---rx  r,   c                   K   |                                   d{V  |                     |          }d|d         i}	|                     |dd          }
|                     |ddg          }|d         dk    }|
|
|	d<   n||	d<   |;|r |                     |d         |          |	d	<   n|                     ||          |	d
<   |                     |d          }|                     |dg          }|||	d<   n=|;|r |                     |d         |          |	d<   n|                     ||          |	d<   |                     |dd          }|5|r|                     ||          |	d<   n|                     ||          |	d<   |                     |ddg          }d}|rM|                     |d          }|d|	d<   | 	                    | 
                    |	|                     d{V }ng|d         r0|                     | 
                    |	|                     d{V }n/|                     | 
                    |	|                     d{V }|                     |di           }|                     ||          S )aH  
        edit a trade order
        :see: 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 fullfilled, in units of the base currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.posSide]: either 'Merged' or 'Long' or 'Short'
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r,   r,  r  r  r_  r  r=  r  r  	baseQtyEVr?  rF  r/  rG  r+  ra  rb  r;   r  )r  r  r  rW  ru  r9  r  amount_to_precisionr6  privatePutGOrdersReplacer  privatePutOrdersReplaceprivatePutSpotOrdersr  rZ  )ru  r,   r  r  r  r  r  r  r  r$  r,  isUSDTSettledfinalQtyr/  r  ra  r  s                    rw  
edit_orderzphemex.edit_order!
  s      !!!!!!!!!V$$fTl
 **6?INN6OY#?@@)V3$!.GI!#GI ?%)%<%<VH=Mu%U%U	""%)ZZv%>%>	"##FK886K=11#+GK   B(,(@(@AQSY(Z(Z%%'+zz&&'A'A$&&vxEE	  D&*&=&=fi&P&P
##&*jjF&C&C
#6Hk#:;; 	U&&vy99G%-	"!::4;;wPV;W;WXXXXXXXXHHF^ 	U!99$++gv:V:VWWWWWWWWHH!66t{{7F7S7STTTTTTTTH~~h33f---rx  c                    K   |t          | j        dz             |                                  d{V  |                     |          }d|d         i}|                     |dd          }|                     |ddg          }|||d<   n||d<   d}|d         d	k    rM|                     |d
          }|d|d
<   |                     |                     ||                     d{V }ng|d         r0| 	                    |                     ||                     d{V }n/| 
                    |                     ||                     d{V }|                     |di           }	|                     |	|          S )a  
        cancels an open order
        :see: 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  r,   r,  r  r  r  r_  ra  rb  r;   r  )r   r,   r  r  r  rW  r  privateDeleteGOrdersCancelr  privateDeleteOrdersCancelprivateDeleteSpotOrdersr  rZ  )
ru  r,   r  r  r  r$  r,  r  ra  r  s
             rw  cancel_orderzphemex.cancel_order^
  s      >#DG.Y$YZZZ!!!!!!!!!V$$fTl
 **6?INN6OY#?@@$!.GI!#GI(v%%&&vy99G%-	"!<<T[[RX=Y=YZZZZZZZZHHF^ 	X!;;DKKQW<X<XYYYYYYYYHH!99$++gv:V:VWWWWWWWWH~~h33f---rx  c                   K   |t          | j        dz             |                                  d{V  |                     |          }d|d         i}d}|d         dk    r0|                     |                     ||                     d{V }ng|d         r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|S )a  
        cancel all open orders in a market
        :see: 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 argumentr  r,   r  r_  r;   )r   r,   r  r  privateDeleteGOrdersAllr  privateDeleteOrdersAllprivateDeleteSpotOrdersAll)ru  r  r  r  r$  r  s         rw  cancel_all_orderszphemex.cancel_all_orders
  s/      >#DG.]$]^^^!!!!!!!!!V$$fTl

 (v%%!99$++gv:V:VWWWWWWWWHHF^ 	[!88Wf9U9UVVVVVVVVHH!<<T[[RX=Y=YZZZZZZZZHrx  c                   K   |t          | j        dz             |                                  d{V  |                     |          }|d         dk    rt	          | j        dz             d|d         i}|                     |dd	          }|                     |dd	g          }|||d	<   n||d
<   d}|d         r0|                     |                     ||                     d{V }n/| 	                    |                     ||                     d{V }| 
                    |di           }|}	t          |t                    rtt          |          }
|
dk     rH|#t          | j        dz   |z   dz   |z   dz             t          | j        dz   |z   dz   |z   dz             | 
                    |di           }	|                     |	|          S )a?  
        fetches information on an order made by the user
        :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  r_  z?fetchOrder() is not supported yet for USDT settled swap marketsr  r,   r,  r  r  r9   r  r   z fetchOrder() z order with clientOrderId z
 not foundz order with id r   )r   r,   r  r  r$   r  rW  privateGetSpotOrdersActiver  privateGetExchangeOrderr  r  r  r  r!   rZ  )ru  r,   r  r  r  r$  r,  r  r  r  	numOrderss              rw  fetch_orderzphemex.fetch_order
  s2      >#DG.X$XYYY!!!!!!!!!V$$(v%%tw)jjkkkfTl
 **6?INN6OY#?@@$!.GI!#GI&> 	X!<<T[[RX=Y=YZZZZZZZZHH!99$++gv:V:VWWWWWWWWHx44dD!! 	1D		I1}} ,'2B(BV(KNj(jmz(z  ~J  )J  K  K  K'2B(BV(KN_(_bd(dgs(stttOOD!R00Ev...rx  c                   K   |t          | j        dz             |                                  d{V  |                     |          }d|d         i}|||d<   |||d<   d}|d         dk    r;|d         |d	<   |                     |                     ||                     d{V }ng|d
         r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |di           }| 	                    |d|          }	| 
                    |	|||          S )a[  
        fetches information on multiple orders made by the user
        :see: 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  r,   startr  r  r_  r  r;   r  rU  )r   r,   r  r  "privateGetExchangeOrderV2OrderListr  privateGetExchangeOrderListprivateGetSpotOrdersr  r_  parse_orders
ru  r  rN  r  r  r  r$  r  r  rU  s
             rw  fetch_orderszphemex.fetch_orders
  s      >#DG.Y$YZZZ!!!!!!!!!V$$fTl
 $GG$GG(v%%"("2GJ!DDT[[QXZ`EaEabbbbbbbbHHF^ 	U!==dkk'SY>Z>Z[[[[[[[[HH!66t{{7F7S7STTTTTTTTHx44~~dFD11  vue<<<rx  c                 r  K   |                                   d{V  |t          | j        dz             |                                   d{V  |                     |          }d|d         i}d}	 |d         dk    r0|                     |                     ||                     d{V }ng|d         r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }n0# t          $ r#}t          |t                    rg cY d}~S |d}~ww xY w|                     |di           }	t          |	t                    r|                     |	|||          S |                     |	d	g           }
|                     |
|||          S )
a  
        fetch all unfilled currently open orders
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#queryopenorder
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md
        :see: 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  r,   r  r_  r;   r  rU  )r  r   r,   r  privateGetGOrdersActiveListr  privateGetOrdersActiveListr  	Exceptionr  r!   r  r  r  r_  )ru  r  rN  r  r  r  r$  r  er  rU  s              rw  fetch_open_orderszphemex.fetch_open_orders
  s      !!!!!!!!!>#DG.]$]^^^!!!!!!!!!V$$fTl
 
	h6))!%!A!A$++gW]B^B^!_!_______ Y!%!@!@WV\A]A]!^!^^^^^^^!%!:!:4;;wPV;W;W!X!XXXXXXX 	 	 	!]++ 						G	 x44dD!! 	A$$T65%@@@>>$33D$$T65%@@@s%   2B#D 
E D>6E<D>>Ec                 *  K   |                                   d{V  d}||                     |          }i }||d         |d<   |||d<   |||d<   d}||                     |d          dk    rJ|                     |dd          |d<   |                     |                     ||                     d{V }ng|d	         r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |d
i           }t          |t                    r| 
                    ||||          S |                     |dg           }	| 
                    |	|||          S )a  
        fetches information on multiple closed orders made by the user
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#queryorder
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md#queryorder
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedgedd-Perpetual-API.md#query-closed-orders-by-symbol
        :see: 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>`
        Nr,   r  r  r  r  r_  r  r;   r  rU  )r  r  r  r  r  r  privateGetExchangeSpotOrderr  r  r  r  r_  r  s
             rw  fetch_closed_orderszphemex.fetch_closed_orders  s      !!!!!!!!![[((F
 &tGH$GG$GGN 0 0 B Bf L L"&"2"268V"L"LGJ!DDT[[QXZ`EaEabbbbbbbbHHF^ 	\!==dkk'SY>Z>Z[[[[[[[[HH!==dkk'SY>Z>Z[[[[[[[[HJ x44dD!! 	A$$T65%@@@>>$33D$$T65%@@@rx  c                    K   |                                   d{V  d}||                     |          }i }|t          d|          }||d<   |du p|                     |d          dk    }|rd|d<   d|d<   |d|d<   n|d	         |d
<   |||d<   d}|r0|                     |                     ||                     d{V }ng|d         r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }d}	|r|                     |dg           }	n.|                     |di           }	|                     |	dg           }	| 	                    |	|||          S )a  
        fetch all trades made by the user
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md#query-user-trade
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#query-user-trade
        :see: 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>`
        N   r  r  r_  r  r   offsetr,   r  r  r;   r  rU  )
r  r  r  r  $privateGetExchangeOrderV2TradingListr  privateGetExchangeOrderTrade!privateGetExchangeSpotOrderTradesr  r  )
ru  r  rN  r  r  r  r$  r  r  r  s
             rw  fetch_my_tradeszphemex.fetch_my_tradesX  s       !!!!!!!!![[((FUOOE$GG4ZT-=-=fh-O-OSY-Y 	-"(GJ !GH}#&  &tGH$GG 	b!FFt{{SZ\bGcGcddddddddHHF^ 	b!>>t{{7TZ?[?[\\\\\\\\HH!CCDKKPWY_D`D`aaaaaaaaHR  	5??8VR88DD??8VR88D??444D  vue<<<rx  r  c                   K   |                                   d{V  |                     |          }d|d         i}|                     | j        d          }|                     ||          }|                     | j        di           }|                     |d|          }|                     |||          }||d         |d<   n||d<   |                     |d          }|                     |                     ||                     d{V }	|                     |	di           }
|                     |
d	          }|                     |
d
          }| 	                    |           |||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>`
        Nr  r,   rm  rl  network	chainNamer  addresstag)r  r  r  r  r  )
r  r  r  rV  safe_string_upperr  rW  +privateGetPhemexUserWalletsV2DepositAddressr  check_address)ru  r  r  r  r$  rm  defaultNetworkrl  r  r  r  r  r  s                rw  fetch_deposit_addresszphemex.fetch_deposit_address  s      !!!!!!!!!==&&
 //$,8IJJ//FF??4<R@@((NKK""8Wg>>?#+D>GK  #*GK YYvy11FII$++V]_eJfJfgggggggg x44""433tU++7###
 
 	
rx  c                    K   |                                   d{V  d}||                     |          }|                     |           d{V }|                     |dg           }|                     ||||          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ru  r  rN  r  r  r  r  r  s           rw  fetch_depositszphemex.fetch_deposits  s       !!!!!!!!!}}T**HBB6JJJJJJJJ* ~~h33&&tXueDDDrx  c                    K   |                                   d{V  d}||                     |          }|                     |           d{V }|                     |dg           }|                     ||||          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           rw  fetch_withdrawalszphemex.fetch_withdrawals>  s       !!!!!!!!!}}T**HCCFKKKKKKKK* ~~h33&&tXueDDDrx  c                 T    dddddddddddddddd}|                      |||          S )Nokfailedpendingr  )SuccessSucceedr  zSecurity check failedSecurityCheckFailedExpiredzAddress RiskzSecurity CheckingSecurityCheckingzPending ReviewzPending TransferAmlCsApporver  	Confirmed	Cancelledr  r  s      rw  parse_transaction_statuszphemex.parse_transaction_statusc  sU     %-#+$!* )' )%"#
 
" &&999rx  r  c                    |                      |d          }|                      |d          }d }|                      |d          }|                      |d          }|                     ||          }|d         }|                      |d          }	|                     |g 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S )Nr,   r  txHashr  r  r  )r  
submitedAtsubmittedAtr  feeEvr  feeRv
withdrawalr*  r  amountEvamountRvr  txidr
  r  r  	addressToaddressFromr  tagTotagFromr  updated)commentinternalr  )
r  safe_currencysafe_integer_nr  rt  r  r  r  r  network_id_to_code)ru  transactionr  r,   r  r  r  r  r  	networkIdr
  r  r6  r  r  r  s                   rw  parse_transactionzphemex.parse_transactionw  s   H k400"";	::X66%%k:>>
%%j(;;$$[+>>	''5_5_5_``	%%k6::##DLL1A1A+w1W1WYabnYo$p$pqq?&&{G<<GD  C ..t/?/?X/V/VWW""4<<0@0@j0Y0Y[cdp[q#r#rss>%%k:>>F
K
"
 D
 	

 Y//
 t..y99
 w
 
 4
 3
 S
 t
 D
 f
 
  f!
" t#
$ )
 
 
 	
rx  c                   K   |                                   d{V  |                     |          }d}|                     |d          }d}d}|                     |d          }|&|                     |          }|d         }|d         }n|                     |ddd          \  }}|                     d||          \  }}|dk    }|rd}n#||dk    rdnd	}n|                     |d
          }|                     |          }	d|	d         i}
d}|rd}|                     |ddd          \  }}|dk    r0|                     | 	                    |
|                     d{V }n_| 
                    | 	                    |
|                     d{V }n/|                     | 	                    |
|                     d{V }|                     |di           }|                     |dg           }g }t          dt          |                    D ]2}||         }|                    |                     |                     3|                     |d|d          S )a.  
        fetch all open positions
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md#query-trading-account-and-positions
        :see: https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#query-account-positions
        :see: 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 [param.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  r   r  re   rd  r_  r`  BTCr  r,   methodr  r  	positionsr  F)r  market_symbolsr  r  r  r  rW  r  r  r  privateGetAccountsPositionsr  r  r  r  r  parse_positionfilter_by_array_positions)ru  r  r  r  r  r  r  firstSymbolr  r  r$  r  r  r  r  r  r  positions                     rw  fetch_positionszphemex.fetch_positions  s      !!!!!!!!!%%g..
33&&w22"[[--FH%F(#DD!::6CSU]_deeNFF99:JFTZ[[&( 	/DD\$0055uDDYYvv..F==&&
  	cF!::6CSU]  `E  F  FNFF>>>!%!I!I$++V]_eJfJf!g!ggggggg!%!A!A$++gW]B^B^!_!_______!DDT[[QXZ`EaEabbbbbbbbHZ x44OOD+r::	q#i..)) 	9 	9A |HMM$--h778888--fhOOOrx  c                    |                      |d          }|                     ||          }|d         }|                     |dd          }|                     |dd          }|                     |dd          }t          j        ||          }|                     |dd	          }	t          j        |	|          }
|                     |d
d          }|                     |dd          }|                      |d          }|                     |d          }|                     |          }| 	                    t          j
        |                     |dd                              }|                     |dd          }|                      |d          }d }|
|dk    rdnd}d }|                      |d          }|dk    r2|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        ||          }|                     |d          }|                     i d|dd d|d| 	                    |          d|d| 	                    |          d|d
|d | 	                    |          d!| 	                    |          d| 	                    |          d"d d#| 	                    |          d$d d%d d&| 	                    |	          d'| 	                    |
          | 	                    |          | 	                    |          | 	                    |          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avgEntryPriceRpr  Buylongshortr  rd  r  crossMarginr  r,   	contractsunrealizedPnl
collateralnotional	lastPrice
entryPricer
  lastUpdateTimestampinitialMargininitialMarginPercentagecrossisolatedF)
maintenanceMarginmaintenanceMarginPercentagemarginRatior  
marginModer  hedgedr   rN  rM  )r  r  r  r(   r  
string_divr  r  r(  rt  
string_abs
string_subsafe_position)ru  r  r  r  r  r	  notionalString!maintenanceMarginPercentageStringmaintenanceMarginStringinitialMarginStringinitialMarginPercentageStringr  markPriceStringr  r  r  r  entryPriceStringrawSider  	priceDiffr  r  r  isCrosss                            rw  r  zphemex.parse_positionl  s   P ##Hh77!!(F33!''2BDVWW
++HgyII,0,>,>xIY[m,n,n)")"4^Ef"g"g"00;OQghh(/(:;NP^(_(_%--h8JL`aa,,X{MRR$$Xv66	v~>>!22<@@$$W%79K9KHV`bn9o9o%q%qrr--hIZ[[""8V44%..66WD	##Hj99uv~~#.@PQQ		#./?QQ		 v~~#.w/A#GW/X/XZaZlmp  sB  [C  [C  D  D		#.w/A#/W/WY`Yklo  rB  ZC  ZC  D  D	*7+=i+S+SUghh()@*MM//(M::!! #
H#
$#
 f#
 **955	#

 L#
 T..}==#
 #
  0#
 $++J77#
 )).99#
 **?;;#
 #
 $++,<==#
 #
 "4#
  T../BCC!#
" &t'8'89V'W'W##
$ "&!2!23J!K!K+/+<+<=^+_+_,,[99%,<''*!#7#
 #
 #
   	rx  c                   K   |t          | j        dz             |                                  d{V  |                     |          }d|d         i}|"|dk    rt	          | j        dz             ||d<   d}|d         d	k    r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |d
i           }|                     |dg           }	g }
t          dt          |	                    D ]}|	|         }|                     |d          }|
                    ||                     |d          |                     |                     |d                    ||                     |          d|                     |                     |d          |          d           |
S )as  
        fetch the history of funding payments paid and received on self account
        :see: 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  r,   r  z7 fetchFundingHistory() limit argument cannot exceed 200r  r  r_  r  rU  r   
createTimer  r  )r  r  r  r
  r  r,   r  )r   r,   r  r  r   $privateGetApiDataGFuturesFundingFeesr  #privateGetApiDataFuturesFundingFeesr  r  r  r  r  r  r  r  r  )ru  r  rN  r  r  r  r$  r  r  rU  r  r  entryr
  s                 rw  fetch_funding_historyzphemex.fetch_funding_history  s!      >#DG.a$abbb!!!!!!!!!V$$fTl

 s{{ +d!deee$GG(v%%!FFt{{SZ\bGcGcddddddddHH!EEdkkRY[aFbFbccccccccH. x44tVR00q#d))$$ 	 	AGE))%>>IMM**5(;;//0@0@
0S0STT& LL33,,t'7'7{'K'KVTT      rx  c                   K   |                                   d{V  |                     |          }|d         st          | j        dz             d|d         i}i }|d         s0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |di           }|                     ||          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>`
        Nr;   z0 fetchFundingRate() supports swap contracts onlyr  r,   r`  r  )	r  r  r   r,   r  r  r  r  parse_funding_rater  s          rw  fetch_funding_ratezphemex.fetch_funding_rate9  s      !!!!!!!!!V$$f~ 	ZDG&XXYYYfTl
 h 	T!33DKK4P4PQQQQQQQQHH!55dkk'66R6RSSSSSSSSH0 8R88&&vv666rx  c           	      ^   |                      |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 S )Nr  r
  r  r  r  markEpr  
indexPriceindexEpindexPriceRpinterestRateestimatedSettlePricer  fundingRatefundingRateErfundingTimestampfundingDatetimenextFundingRatepredFundingRateErpredFundingRateRrnextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetime)r  rO  r#  r  r  r  rE  )ru  r  r  r  r  r
  s         rw  r,  zphemex.parse_funding_ratef  s   L ##Hh77!!(F33--hXNN	
H
f
 d&8&88]&[&[]cdd
 $,,t'9'9(I~'^'^`fgg	

 D
 #D
 
 Y//
 4<<(8(8?(S(SU[\\
 
 t
 t||D,>,>xI\^q,r,rtz{{
 #D
 "4
 "4
  '!
" &t#
 	
rx  c                 X  K   |                                   d{V  |                     |          }|d         |                     ||          d}|                     |                     ||                     d{V }|                     |                     ||          d|i          S )a?  
        Either adds or reduces margin in an isolated position in order to set the margin to a specific value
        :see: 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>`
        Nr,   )r  posBalanceEvr  )r  r  r6  privatePostPositionsAssignr  parse_margin_modification)ru  r  r  r  r  r$  r  s          rw  
set_marginzphemex.set_margin  s       !!!!!!!!!V$$Tl JJvv66
 
 88Wf9U9UVVVVVVVV {{499(FKKfN
   	rx  c                 8    ddi}|                      |||          S )N0r  r  r  s      rw  parse_margin_statuszphemex.parse_margin_status  s(    
 &&999rx  c                    |                      d |          }|                     |d          }|rdnd}||                     d |          ddd d ||         |                     |                     |d                    d d d
S )Nr  r  r  setr  r  )
r  r  r  r  r  r  r  r  r
  r  )r  r  rO  rH  r  )ru  r  r  r  codeCurrencys        rw  rD  z phemex.parse_margin_modification  s     !!$////&)44!(5vvg&&tV44$<(..t/?/?f/M/MNN
 
 	
rx  r  c                 <  K   |t          | j        dz             |                                  d{V  |                     |          }|d         r|d         dk    rt	          | j        dz             |                                }|dk    r|dk    rt          | j        d	z             |                     |d
          }|dk    rd}|t          | j        dz             |d         |d}|                     | 	                    ||                     d{V S )a'  
        set margin mode to 'cross' or 'isolated'
        :param str marginMode: 'cross' or 'isolated'
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        Nz+ setMarginMode() requires a symbol argumentr;   r  r_  z= setMarginMode() supports swap(non USDT based) contracts onlyr  r  z@ setMarginMode() marginMode argument should be isolated or crossr  r   z. setMarginMode() requires a leverage parameterr,   )r  r  )
r   r,   r  r  r   lowerr   r  privatePutPositionsLeverager  )ru  r  r  r  r  r  r$  s          rw  set_margin_modezphemex.set_margin_mode  sS      >#DG.[$[\\\!!!!!!!!!V$$f~ 	g!1V!;!;DG&eefff%%''
##
g(=(=TW'iijjj$$VZ88  H#DG.^$^___Tl 
 
 55dkk'66R6RSSSSSSSSSrx  r  c                 d  K   |                      d|d           |                                  d{V  |                     |          }|d         dk    rt          | j        dz             d|d         i}|rd|d	<   nd
|d	<   |                     |                     ||                     d{V S )a  
        set hedged to True or False for a market
        :see: 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
        rs   r  Nr  r_  z5 setPositionMode() supports USDT settled markets onlyr,   HedgedtargetPosModeOneWay)check_required_argumentr  r  r   r,   %privatePutGPositionsSwitchPosModeSyncr  )ru  r  r  r  r  r$  s         rw  set_position_modezphemex.set_position_mode  s       	$$%6III!!!!!!!!!V$$(v%%DG&]]^^^fTl
  	0'/GO$$'/GO$??GU[@\@\]]]]]]]]]rx  c                   K   |                                   d{V  |N|                     |d          }|                     |          }|d         dk    rt          | j        dz             |                     |           d{V }|                     |di           }|                     |d          }|                     ||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
        Nr   r  rd  z7 fetchLeverageTiers() supports USD settled markets onlyr  r  r  )r  r  r  r   r,   publicGetCfgV2Productsr_  parse_leverage_tiers)ru  r  r  r  r  r  r  r  s           rw  fetch_leverage_tierszphemex.fetch_leverage_tiers  s       !!!!!!!!!OOGQ//E[[''Fh5((*c cddd44V<<<<<<<<^ x44^^D,77
((WhGGGrx  c                 l   |                      d|          }|d         d         }g }d}t          dt          |                    D ]m}||         }|                     |d          }|                    |                     |d          |d         |||                     |d          d|d	           |}n|S )
zq
        :param dict info: Exchange market response for 1 market
        :param dict market: CCXT market
        Nr  r  r   r  r   r  r  )tierr  minNotionalmaxNotionalmaintenanceMarginRater  r  )r  r  r  r  r  r;  r  )	ru  r  r  r  tiersr]  r  r\  r^  s	            rw  parse_market_leverage_tiersz"phemex.parse_market_leverage_tierso  s      !!$//Vn\2
q#j//** 	& 	&Aa=D++D'::KLLA"8,**)-)9)9$@S)T)T#     &KKrx  rx   GETc                    |                      ||                     |                    }d|                     ||          z   }|}	d}
|dk    s|dk    s|dk    s|	dk    r|r|                     |          }
|	d|
z   z  }	|dk    rQ|                                  |                                 }|                     | j        d	d
          }|                     ||          }t          |          }| j
        |d}d}|dk    r||dk    p|dk    p|dk    }|rL|                     |d          6|                     | j        dd          }||                                 z   |d<   |                     |          }|}d|d<   ||
z   |z   |z   }|                     |                     |          |                     | j                  t"          j                  |d<   |                     | j        d         |                   |	z   }	|	|||dS )Nr  r{  rb  DELETEPUTz/positions/assign?ry   rj  rX  )zx-phemex-access-tokenrj  POSTr   r   r   r  ri  rW  zapplication/jsonzContent-Typezx-phemex-request-signaturer~   )rz   r  bodyheaders)rW  extract_paramsimplode_paramsurlencode_with_array_repeatcheck_required_credentialsrZ  r  rV  r;  r+  r   r  rs  jsonhmacencoder   hashlibsha256implode_hostnamerv   )ru  pathr~   r  r  ri  rh  r  requestPathrz   queryStringr
  xPhemexRequestExpiryr  expiryStringpayloadisOrderPlacementr,   auths                      rw  signzphemex.sign  s9   		&$"5"5d";";<<D//f===eOO8!3!35cUhNhNh )">>uEEs[(()++---I#'#4#4T\C\^`#a#a XXi)=>>Fv;;L)-+7 G G$(J$6#hDM<Q#hW[_gWg # ?''	::B!--dlJUU,.,>y)))F++*<',|;gED48IIdkk$>O>OQUQ\Q\]a]hQiQikrky4z4zG01##DIe$4S$9::S@fdwOOOrx  r  c                   K   |t          | j        dz             |dk     s|dk    rt          | j        dz             |                                  d{V  |                     |dd          }|                     |d          }|                     |d	          }|                     |          }d
|d         i}d}	|d         dk    rR|s
||||d<   n||n|}
||n|}|
|d<   ||d	<   |                     |                     ||                     d{V }	n4||d<   | 	                    |                     ||                     d{V }	|	S )a+  
        set the level of leverage for a market
        :see: 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 argumentirT  z6 setLeverage() leverage should be between -100 and 100r  FlongLeverageRrshortLeverageRrr  r,   r  r_  r   r  )
r   r,   r   r  rW  r  r  privatePutGPositionsLeverager  rN  )ru  r  r  r  isHedgedr~  r  r  r$  r  longVarshortVars               rw  set_leveragezphemex.set_leverage  s      >#DG.Y$YZZZtOOCTW'__```!!!!!!!!!>>&(E::**63CDD++F4EFFV$$fTl
 (v%% 6 6?;R(0%%-;-G..h/>/J??QY,3()-5)*!>>t{{7TZ?[?[\\\\\\\\HH"*GJ!==dkk'SY>Z>Z[[[[[[[[Hrx  fromAccount	toAccountc           	        K   |                                   d{V  |                     |          }|                     | j        di           }|                     |||          }|                     |||          }	|                     ||          }
d}d}|dk    r	|	dk    rd}n|dk    r|	dk    rd}|i|d         ||
d}|                     |                     ||                     d{V }|                     |d	i           }|                     ||          }ng||	|
|d         |                     |d
d          d}| 	                    |                     ||                     d{V }|                     |          }|                     | j        di           }| 
                    |dd          }|r4|d         ||d<   |d         ||d<   |d         ||d<   |d         ||d<   |S )aU  
        transfer currency internally between wallets on the same account
        :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>`
        Nro  r9   r<   r   r   r,   )r  moveOpr  r  bizTypeSPOT)
fromUserIdtoUserIdr  r  r  rt   rh  Tr  r  r  r  )r  r  r  rV  r  r6  privatePostAssetsTransferr  parse_transfer"privatePostAssetsUniversalTransferrW  )ru  r  r  r  r  r  r  ro  fromIdtoIdscaledAmmount	directionrt   r$  r  r  transferOptionsrh  s                     rw  rt   zphemex.transfer  sf      !!!!!!!!!==&&7GLL!!.+{KK	9EE

6844	V 0 0IIxDFNNI $TN#) G
 ";;DKKQW<X<XYYYYYYYYH ??8VR88D**4::HH % )$TN++FIvFF G "DDT[[QXZ`EaEabbbbbbbbH **844H//$,
BGG"&..B[]a"b"b" 	,&.*5'$,(1%!)%+"
#+'+$rx  c                   K   |                                   d{V  |t          | j        dz             |                     |          }d|d         i}|||d<   |||d<   |                     |                     ||                     d{V }|                     |di           }|                     |dg           }	|                     |	|||          S )	a  
        fetch a history of internal transfers made on an account
        :param str code: unified currency code of the currency transferred
        :param int [since]: the earliest time in ms to fetch transfers for
        :param int [limit]: the maximum number of  transfers structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transfer structures <https://docs.ccxt.com/#/?id=transfer-structure>`
        Nz* fetchTransfers() requires a code argumentr  r,   r  r  r  rU  )	r  r   r,   r  privateGetAssetsTransferr  r  r_  parse_transfers)
ru  r  rN  r  r  r  r$  r  r  	transferss
             rw  fetch_transferszphemex.fetch_transfers)  s      !!!!!!!!!<#DG.Z$Z[[[==&&
 $GG$GG66t{{7F7S7STTTTTTTT* x44NN444	##IxFFFrx  c                    |                      |d          }|                      |d          }|                      |d          }|                     |          }|                      |d          }|                     ||          }|                     |d          }	d }
d }|	dk    rd}
d}n
|	d	k    rd}
d}|                     |d
          }||||                     |          |||
||                     |          d	S )NlinkKeyr  r  r  r  r   r;   r9   r   r&  )	r  r,   r
  r  r  r  r  r  r  )r  r  r  r  r  parse_transfer_status)ru  rt   r  r,   r  r  amountTransferedr  r  r  r  r  r
  s                rw  r  zphemex.parse_transferV  s   4 h	22!!(H55##Hj99<<11%%h
;;
&&z8<<  622199FDDQYYFD%%h==	"Y//&!0088

 

 
	
rx  c                 >    ddddd}|                      |||          S )Nr  r  r  r  )r   r  r  11r  r  s      rw  r  zphemex.parse_transfer_status  s4    	
 
 &&999rx  c           
        K   |t          | j        dz             |                                  d{V  |                     |          }|d         dk    }|d         st	          | j        dz             d}|                     |dd	          \  }}|r!|                     d|||d
|d           d{V S d}|rd|d         z   dz   }nd|d         z   dz   }d|i}	|||	d<   |||	d<   |                     d|	|          \  }	}d}
|r0|                     | 	                    |	|                     d{V }
n/| 
                    | 	                    |	|                     d{V }
|                     |
di           }|                     |d          }g }t          dt          |                    D ]b}||         }|                     |d          }|                    |||                     |d          ||                     |          d           c|                     |d          }|                     ||||          S )a  
        fetches historical funding rate prices
        :see: https://phemex-docs.github.io/#query-funding-rate-history-2
        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: timestamp in ms of the earliest funding rate to fetch
        :param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>` to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :param int [params.until]: timestamp in ms of the latest funding rate
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
        Nz5 fetchFundingRateHistory() requires a symbol argumentr  r_  r;   z7 fetchFundingRateHistory() supports swap contracts onlyFrT   paginate8hrT  .r,   FR8Hr  r  r  r  endr  rU  r   fundingTimer5  )r  r  r5  r
  r  r
  )r   r,   r  r  r   r  "fetch_paginated_call_deterministichandle_until_option(v2GetApiDataPublicDataFundingRateHistoryr  (v1GetApiDataPublicDataFundingRateHistoryr  r  r  r  r  r  r  r  filter_by_symbol_since_limit)ru  r  rN  r  r  r  isUsdtSettledr  customSymbolr$  r  r  ratesr  r  itemr
  sorteds                     rw  fetch_funding_rate_historyz!phemex.fetch_funding_rate_history  s      >#DG.e$efff!!!!!!!!!V$$x(F2f~ 	bTW'``aaa88AZ\fgg& 	E@@AZ\bdikprvx~  AD  E  E  E  E  E  E  E  E  E 	;-6LL!11F:Ll
 $GG$GG225'6JJ 	i!JJ4;;W^`fKgKghhhhhhhhHH!JJ4;;W^`fKgKghhhhhhhhH" x44f--q#e**%% 		 		A8D))$>>IMM #//mDD& LL33      fk2200NNNrx  c                   K   |                      ||          \  }}|                                  d{V  |                     |           |                     |          }d}|                     |          \  }}d}||                     |          }|                     | j        d          }	|6|                     ||	          s	|d         }nt          | j
        dz             |d         |||                                d}
|||
d<   |                     |                     |
|                     d{V }|                     |di           }|                     ||          S )a  
        make a withdrawal
        :see: 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>`
        Nrp  r,   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  rV  in_arrayr   r,   upper1privatePostPhemexWithdrawWalletsApiCreateWithdrawr  r  r  )ru  r  r  r  r  r  r  networkCoder  rp  r$  r  r  s                rw  ru   zphemex.withdraw  s      99#vFFV!!!!!!!!!7###==&&"AA&IIV	"//<<IoodlMBBMM$44 n$TN		'2l(lmmm "**	
 
 ?$'GL!OOPTP[P[\cekPlPlmmmmmmmm8 ~~h33%%dH555rx  c
                 d   |d S |                      |d|          }
|                     |
d          }|                     |
d          }|f|dk    r`| j        dz   |z   }|                     | j        d         ||           |                     | j        d         ||           t          |          d S )Nerrorr  msgrG  r|  rT  rU  )r  r  r,   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   )ru  httpCodereasonrz   r  ri  rh  r  requestHeadersrequestBodyr  	errorCodemessagefeedbacks                 rw  handle_errorszphemex.handle_errors   s    4 '8<<$$UF33	""5%00!	S(8(8w}t+H001I9V^___001I7T\]]])))trx  r'  )r   r   N)Nr  r  r   r   N)___name__
__module____qualname__rs  r  r  r  r   r
   r  r   r  r  r  r+  r   r   r%  r2  r6  r9  r  r  r  rE  r  rM  ri  r   r  r  r   r   r  r   r  r  r  r  r   r  r  r  r  r7  r9  rR  r   rZ  r   r   floatr   r  r  r   r  r  r  r  r  r  r  r  r   r  r  r  r   r  r  r  r*  r-  r,  r	   rE  rH  rD  rO  boolrV  rZ  ra  r|  r  r   rt   r  r  r  r  ru   r  __classcell__)rv  s   @rw  r*   r*      s       W W W W Wr* * * *E E ENc c cJ *, ^ ^V ^ ^ ^ ^@ -/ A A: A A A AF	
 	
F 	
 	
 	
 	
   KQ    & @DB 5 5S 5 5S\ 5 5 5 5n0 0 08 8F 8 8 8 8
7 76 7 7 7 7
  I I& I I I I
I I& I I I I
I I& I I I I

 
 
4 
 
 
 
8 8<$]ajl KL KL KLC KLWZ KLquvzq{ KL KL KL KLZU U6 UV U U U Un 68 C1 C1 C1F C1 C1 C1 C1J 6:" 3 37 3 3 3 3 3< <@d[] '? '? '?S '? '?bfglbm '? '? '? '?R| | |5 | | | ||1) 1) 1)f-) -) -)^ *, ` ` ` ` ` `D: : :,3 3 3"H H Hk kf k k k kZ3 3 3_ _f _ _ _ _B4 4 45 4 4 4 4 mqy{ v. v. v.I v.Y v.X] v.fi v. v. v. v.p HL_csw  GK  TV ;. ;.3 ;. ;.9 ;.S\ ;.mp ;.  AD ;. ;. ;. ;.z 9=R ". ".S ".# ". ". ". ".H 59  c    4 8<B %/ %/C %/ %/ %/ %/ %/N 04$UYbd = = =C =s =imnsit = = = =B 59tZ^gi %A %Ac %A %ATW %Anrsxny %A %A %A %AN 7;\`ik KA KA KA3 KAVY KAptuzp{ KA KA KA KAZ 37TX\eg S= S=C S=s S=RU S= S= S= S=j =? *
 *
 *
 *
 *
 *
X 04$UYbd #E #E #EC #Es #Eimnyiz #E #E #E #EJ 37TX\eg #E #EC #Es #ERU #Elpq|l} #E #E #E #EJ: : :(q
 q
x q
; q
 q
 q
 q
f 8<B @P @PW @P @P @P @PDH Hv H H H HT 9=4^bkm A A# AS AX[ A A A AF <> +7 +7s +7 +7 +7 +7Z;
 ;
6 ;
 ;
 ;
 ;
z CE  s E I[    6: : :
 
f 
HZ 
 
 
 
0 DHPR T T TS T T T T8 CGr ^ ^d ^C ^ ^ ^ ^. =A ^H ^H' ^H ^H ^H ^H@! ! ! ! ! !F &eBSW  P  P  P  PD ?C2 ' '3 ' ' ' ' 'R ac J J3 J JC JTW Jgt J J J JX 154VZce +G +G# +GS +GPS +G +G +G +GZ4
 4
 4
 4
 4
 4
l: : : >BPTcgpr GO GOs GO# GO]` GO GO GO GOR EIQS @6 @63 @6 @6 @6 @6 @6D      rx  r*   )0 ccxt.async_support.base.exchanger   ccxt.abstract.phemexr   rq  r  ccxt.base.typesr   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%   r&   ccxt.base.decimal_to_precisionr'   ccxt.base.preciser(   r*    rx  rw  <module>r     s   6 5 5 5 5 5 , , , , , ,   K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K       * * * * * * 0 0 0 0 0 0 - - - - - - - - - - - - . . . . . . ' ' ' ' ' ' & & & & & & . . . . . . ) ) ) ) ) ) * * * * * * * * * * * * - - - - - - ) ) ) ) ) ) + + + + + + . . . . . . 4 4 4 4 4 4 % % % % % %RD RD RD RD RDX{ RD RD RD RD RDrx  