
    !:h                        d dl mZ d dlmZ d dlZd dlZd dlmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ 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,y)    )Exchange)ImplicitAPIN)AccountAnyBalances
CurrenciesCurrencyDepositAddressIntLedgerEntryMarketNumOrder	OrderBook	OrderSide	OrderTypeStrStringsTickerTickersTradeTradingFeeInterfaceTradingFeesTransactionTransferEntry)List)ExchangeError)AuthenticationError)PermissionDenied)ArgumentsRequired)
BadRequest)InsufficientFunds)NullResponse)	TICK_SIZE)Precisec                       e Zd Zdef fdZi fdefdZdedefdZ	i fde
e   fdZdedefdZi fdefd	Zi fd
edefdZdi fdedefdZdPdededefdZddi fd
ededede
e   fdZdPdededefdZdi fd
ededefdZdddi fd
ededede
e   fdZdPdedefdZi fdefdZ dQdefdZ!dPdedede"fdZ#i fde
e$   fdZ%dede$fd Z&i fde'fd!Z(de'fd"Z)dddi fd#ed
e*dedede
e+   f
d$Z,dddi fd
e*dedefd%Z-dddi fd
e*dedefd&Z.di fd'ed
e*fd(Z/di fd'ed
e*fd)Z0d#e*fd*Z1dPd+edede+fd,Z2di fd
ed-e3d.e4d/e5d0e6f
d1Z7di fd'ed
e*fd2Z8di fd
e*fd3Z9dddi fd4e*dedede
e:   fd5Z;dPd6ed7ede:fd8Z<d9 Z=dddi fd4e*dedede
e>   fd:Z?dPd;ed7ede>fd<Z@d#e*fd=ZAi fd4ed/e5d>ed?edeBf
d@ZCi fd4ed/e5d>ed?edeBf
dAZDi fd4ed/e5d>ed?edeBf
dBZEdPdCed7edeBfdDZFi fd4edeGfdEZHdPd7edeGfdFZIdGdHi ddfdIZJd4eKdJedKedLedMedNefdOZL xZMS )Rcexreturnc                    | j                  t        t        |          ddg 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d%dd&dd'dd(dd)did*d+d,d-d.d/d0d1gd2d3i d4d4d4d5d4d4d4d4d6d7i i d8d9d:d4d;d9d<d4d=d9d>d9d?d9d@d4dAd4dBd9dCd4dDd4dEd4dFd4dGd9dHd4dId5d9d4d4dJd7d-d	d	dd d	d	d	d ddd	ddKd	d	d	dd	d	d	dLd d d d	dMd	d	d	dNd d	dMdOd4dOd	d	d	dPdQdMidR	d d dSd d dSdTt        i t
        t        t        t        t
        t        t        t        dUdVdWdXdYdZd[d\d]d^d_d`i dadbdcdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dddi dddddddddddddddddddddddddddddddddddddddddid      S )Nr'   zCEX.IO)GBEUCYRUi,  TCORSspotmarginFswapfutureoptioncancelAllOrderscancelOrdercreateOrdercreateReduceOnlyOrdercreateStopOrdercreateTriggerOrderfetchAccountsfetchBalancefetchClosedOrderfetchClosedOrdersfetchCurrenciesfetchDepositAddressfetchDepositsWithdrawalsfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchLedgerfetchMarkets
fetchOHLCVfetchOpenOrderfetchOpenOrdersfetchOrderBookfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeestransferzchttps://user-images.githubusercontent.com/1294454/27766442-8ddc33b0-5ed8-11e7-8b98-f786aef0f3c9.jpgz)https://trade.cex.io/api/spot/rest-publicz"https://trade.cex.io/api/spot/rest)publicprivatezhttps://cex.iozhttps://trade.cex.io/docs/zhttps://cex.io/fee-schedulez!https://cex.io/limits-commissionsz!https://cex.io/r/0/up105393824/0/)logoapiwwwdocfeesreferral   
   )get_server_timeget_pairs_infoget_currencies_infoget_processing_info
get_tickerget_trade_historyget_order_bookget_candles)getpostget_my_current_fee   get_fee_strategyget_my_volumedo_create_accountget_my_account_status_v3get_my_wallet_balanceget_my_ordersdo_my_new_orderdo_cancel_my_orderdo_cancel_all_ordersra   rb   r`   get_my_transaction_historyget_my_funding_historydo_my_internal_transferr^   )get_deposit_addressdo_deposit_funds_from_walletdo_withdrawal_funds_to_wallet)IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedleveragemarketBuyRequiresPricemarketBuyByCostselfTradePreventiontrailingicebergi  )rz   limittriggerr   symbolRequiredi )rz   r   daysBackdaysBackCanceled	untilDaysr   r   r   r   )	sandboxr6   createOrdersfetchMyTrades
fetchOrderrI   fetchOrdersr=   rG   )linearinverse)r/   r1   r2   )z/You have negative balance on following accountsz2Mandatory parameter side should be one of BUY,SELLz,API orders from Main account are not allowedzcheck failedzInsufficient fundsz3Get deposit address for main account is not allowedz%Market Trigger orders are not allowedzkey not passed or incorrect)exactbroad1m5m15m30m1h2h4h1d)r   r   r   r   r   r   r   r   networksBTCbitcoinERC20BSC20binancesmartchainDOGEdogecoinALGOalgorandXLMstellarATOMcosmosLTClitecoinXRPrippleFTMfantomMINAminaTHETAthetaXTZtezosTIAcelestiaCRONOScronosMATICpolygonTONtonTRC20tronSOLANAsolanaSGBsongbirdDYDXdydxDASHdashZILzilliqaEOSeos
AVALANCHEC	avalancheETHPOWethereumpowNEARnearARBarbitrumDOTpolkadotOPToptimismINJ	injectiveADAcardanoONTontologyICPicpkavakusamaseineoneo3xdc)KAVAKSMSEINEONEO3XDC)idname	countries	rateLimitprohasurlsrT   featuresprecisionMode
exceptions
timeframesoptions)	deep_extendsuperr'   describer$   r"   r!   r   r   )self	__class__s    P/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/async_support/cex.pyr   zcex.describe   s   c4 9 ;1$$$ %$ 	$
 %$ %$ "4$ t$ t$ ($ "4$ %d$  $ $ #D$  $T!$" "4#$$ &t%$& +D'$( &u)$* #E+$, *5-$. $U/$0 t1$2 3$4 d5$6 !$7$8 "49$: !$;$< t=$> ?$@ TA$B tC$D #DE$F DG$L ~IC (317 @  +,*+/0/1&'-.*+'(	 ,a*A ( ,Q	
 3A 0 ( *1 -a / )! &q ,Q 5a 1!  21!" .r#$ 01899:)'T  %&+(,,0,1).+06:#'#'"'#'	( #($)27+//4$)#()$, %)%)"&&+!%#($)*/( $(&+!%$*,-%+#($)*/	*  #[0d ##
 ##m:v 'GXJTDN$.*;K[=G3F	 	  -9-W- 0- J	-
 J- 9- H- :- 8- 8- F- W- 7- :- h-  Y!-" 5#-$ V%-& h'-( :)-* F+-, F--. 9/-0 51-2 !+3-4 m5-6 F7-8 :9-: :;-< :=-> ;?-@ 9A-B :C-D 5E-F ##  " !Y-/id>
 d d	    c                   K   g }|j                  | j                  |             |j                  | j                  |             t        j                  |  d{   }| j                  |d   dg       }| j                  |d   di       }| j                  |d      }| j                  ||      }| j                  | j                  |            S 7 tw)a   
        fetches all available currencies on an exchange

        https://trade.cex.io/docs/#rest-public-api-calls-currencies-info

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        Nr   datarY   currency)appendpublicPostGetCurrenciesInfopublicPostGetProcessingInfoasynciogather	safe_list	safe_dictindex_byr   parse_currenciesto_array)r   paramspromises	responsesdataCurrenciesdataNetworkscurrenciesIndexedr  s           r  fetch_currencieszcex.fetch_currencies   s      88@A 	88@A, "..(33		!fbA~~ilFB? MM.*E 1<@$$T]]4%899 4s   ACCA5CrawCurrencyc                    | j                  |d      }| j                  |      }| j                  |d      rdnd}| j                  | j	                  | j                  |d                  }i }| j                  |di       }t        |j                               }t        dt        |            D ]  }	||	   }
||
   }| j                  |
      }| j                  |d      dk(  }| j                  |d	      dk(  }|
|d ||d | j                  |d
      || j                  |d      d d| j                  |d      d dd|d
||<    | j                  ||d |d | j                  |d      | j                  |d      d |d d dd d dd||d      S )Nr  fiatcrypto	precisionblockchainsr   depositenabled
withdrawalwithdrawalFee
minDepositminmaxminWithdrawal)r  withdraw)
r   networkr0   r  r&  activefeer  limitsinfowalletDepositwalletWithdrawal)amountr&  )r   coder   typer(  r  r&  r)  r  r*  r   r+  )safe_stringsafe_currency_code	safe_boolparse_numberparse_precisionr  listkeysrangelennetwork_id_to_codesafe_numbersafe_currency_structure)r   r  r   r/  r0  currencyPrecisionr   rawNetworksr7  j	networkId
rawNetworknetworkCoder  r&  s                  r  parse_currencyzcex.parse_currency6  s   k:6&&r*V<v( --d.B.B4CSCST_alCm.nonn[-DK$$&'q#d)$ 	AQI$Y/J11)<K&&z9=JG''
LAYNH&"$''
OD.  $//
LI# 
  $//
OL#!	 #'%H[!	6 ++~~k?C{4FG*  
  	 !+-
  	r  c                    K   | j                  |       d{   }| j                  |dg       }| j                  |      S 7 (w)a  
        retrieves data on all markets for ace

        https://trade.cex.io/docs/#rest-public-api-calls-pairs-info

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        Nr  )publicPostGetPairsInfor  parse_markets)r   r  responser  s       r  fetch_marketszcex.fetch_marketsq  sE      44V<<, ~~h3!!$''/ =s   AA )Amarketc                 p   | j                  |d      }| j                  |      }| j                  |d      }| j                  |      }|dz   |z   }|dz   |z   }| j                  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 | j                  |d      | j                  |d      d| j                  |d      | j                  |d      d| j                  |d      | j                  |d      dd d dd| j                  |d      | j	                  | j                  | j                  |d                  | j	                  | j                  | j                  |d                   | j	                  | j                  | j                  |d!                  d"d d |d#
      S )$Nbasequote-/r   symbolbaseIdquoteIdsettlesettleIdr0  r/   Tr0   Fr1   r2   r3   contractr   r   baseMinbaseMaxr"  minPricemaxPricequoteMinquoteMax)r.  pricecostr   baseLotSizepricePrecisionbasePrecisionquotePrecision)r.  r[  rK  rL  )
contractSizeexpiryexpiryDatetimestrike
optionTyper*  r  r(  createdr+  )r1  r2  safe_market_structurer;  r4  r5  )r   rI  rP  rK  rQ  rL  r   rO  s           r  parse_marketzcex.parse_market  sz   !!&&1&&v.""673''0CZ%e#)) 3+
"3+
f3+
 D3+
 f	3+

 U3+
 w3+
 d3+
 3+
 F3+
 D3+
 e3+
 E3+
 e3+
 e3+
 3+
  d!3+
" t#3+
$ !"  ++FI>++FI>
  ++FJ?++FJ?
  ++FJ?++FJ?
  & **6=A**4+?+?@P@PQWYi@j+kl))$*>*>t?O?OPVXg?h*ij**4+?+?@P@PQWYi@j+kl e3+
 3 3	r  c                    K   | j                  |       d{   }| j                  |d      }| j                  |d      }|S 7 *w)a  
        fetches the current integer timestamp in milliseconds from the exchange server
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        Nr  	timestamp)publicPostGetServerTimer  safe_integer)r   r  rG  r  rj  s        r  
fetch_timezcex.fetch_time  sJ      55f== ~~h/%%dK8	 >s   AA+ArO  c                    K   | j                          d{    | j                  |g|       d{   }| j                  ||i       S 7 27 w)a  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://trade.cex.io/docs/#rest-public-api-calls-ticker

        :param str symbol:
        :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>`
        N)load_marketsfetch_tickersr  )r   rO  r  rG  s       r  fetch_tickerzcex.fetch_ticker  sM      !!!++VHf==~~h33 	"=s   AA	AAAANsymbolsc                   K   | j                          d{    i }|| j                  |      |d<   | j                  | j                  ||             d{   }| j	                  |di       }| j                  ||      S 7 j7 +w)a  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://trade.cex.io/docs/#rest-public-api-calls-ticker

        :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>`
        Npairsr  )ro  
market_idspublicPostGetTickerextendr  parse_tickers)r   rr  r  requestrG  r  s         r  rp  zcex.fetch_tickers  s      !!!#w7GG11$++gv2NOO6 ~~h3!!$00A 	" Ps"   BBA BB*BBtickerc                    | j                  |d      }| j                  ||      }| j                  i d|dd dd d| j                  |d      d| j                  |d      d| j                  |d      d	d d
| j                  |d      dd dd dd d| j                  |d      dd d| j                  |d      d| j                  |d      dd d| j                  |d      | j                  |d      |d|      S )Nr   rO  rj  datetimehighlowbidbestBid	bidVolumeaskbestAsk	askVolumevwapopencloselastpreviousClosechangepriceChange
percentagepriceChangePercentageaverage
baseVolumevolumequoteVolume)r  r+  )r1  safe_symbolsafe_tickerr;  )r   rz  rI  marketIdrO  s        r  parse_tickerzcex.parse_ticker  s   ##FD1!!(F3 !
f!
!
 !
 D$$VV4	!

 4##FE2!
 4##FI6!
 !
 4##FI6!
 !
 D!
 D!
 T%%ff5!
 T!
 d&&v}=!
 $**63JK!
  t!!
" $**68<#!
$  ++FMB'!
( ) 	r  sincer   c                   K   | j                          d{    | j                  |      }d|d   i}|| j                  |      |d<   d}| j                  |dd      \  }}|| j                  |      |d<   |t	        |d      |d	<   | j                  | j                  ||             d{   }| j                  |d
i       }	| j                  |	dg       }
| j                  |
|||      S 7 7 @w)am  
        get the list of most recent trades for a particular symbol

        https://trade.cex.io/docs/#rest-public-api-calls-trade-history

        :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
        :param int [params.until]: timestamp in ms of the latest entry
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Npairr   fromDateISOuntiltill	toDateISOi'  pageSizer  trades)
ro  rI  iso8601handle_param_integer_2r#  publicPostGetTradeHistoryrw  r  r  parse_trades)r   rO  r  r   r  rI  ry  r  rG  r  r  s              r  fetch_tradeszcex.fetch_trades6  s     !!!V$F4L
 %)\\%%8GM"33FGVLv#'<<#6GK "%eU"3GJ77GV8TUU  ~~h3h3  >>? 	" Vs"   C/C+BC/,C--?C/-C/tradec                 P   | j                  |d      }| j                  |      }| j                  d |      }| j                  ||| j	                  |      |d   | j                  |d      d d d | j                  |d      | j                  |d      | j                  |d      d d d|      S )NdateISOrO  tradeIdsider[  r.  )r+  rj  r|  rO  r   orderr0  takerOrMakerr  r[  r.  r\  r)  )r1  	parse8601safe_market
safe_trader  safe_string_lower)r   r  rI  dateStrrj  s        r  parse_tradezcex.parse_traded  s     ""5)4NN7+	!!$/"Y/X&""5)4 **5&9%%eW5&&uh7 
  	r  c                 :  K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  |di       }| j                  |d      }| j                  ||d   |      S 7 7 Aw)a9  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://trade.cex.io/docs/#rest-public-api-calls-order-book

        :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  rj  rO  )ro  rI  publicPostGetOrderBookrw  r  rl  parse_order_book)	r   rO  r   r  rI  ry  rG  	orderBookrj  s	            r  fetch_order_bookzcex.fetch_order_book  s      !!!V$F4L
 44T[[&5QRR& NN8VR8	%%i=	$$Yx0@)LL5 	"
 Ss#   BBA BBA BBr   c                   K   d}| j                  |dd      \  }}|t        | j                  dz         | j                          d{    | j	                  |      }|d   | j
                  |   |d}|| j                  |      |d<   d}	| j                  |dd	      \  }	}|	| j                  |	      |d
<   n$|"| j                  | j                               |d
<   ||	|t        | j                  dz         ||	|t        | j                  dz         |||d<   | j                  | j                  ||             d{   }
| j                  |
dg       }| j                  |||||      S 7 )7 /w)a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://trade.cex.io/docs/#rest-public-api-calls-candles

        :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]: 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]: timestamp in ms of the latest entry
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        NrG   dataTypezO fetchOHLCV requires a parameter "dataType" to be either "bestBid" or "bestAsk"r   )r  
resolutionr  fromISOr  r  toISOzO fetchOHLCV does not support fetching candles with both a limit and since/untilzP fetchOHLCV requires a limit parameter when fetching candles with since or untilr   r  )handle_option_and_paramsr    r   ro  rI  r   r  r  millisecondspublicPostGetCandlesrw  r  parse_ohlcvs)r   rO  	timeframer  r   r  r  rI  ry  r  rG  r  s               r  fetch_ohlcvzcex.fetch_ohlcv  s     88zZ&#DGG.$  A  A!!!V$4L//)4 

 !%e!4GI33FGVLv#||E2GG]#||D,=,=,?@GG!2u7H#DGG.$  A  A5#4%-#DGG  /A  %A  B  B$GG224;;w3OPP$ ~~h3  vy%GGS 	", Qs%   AE6E1	C;E6E4-E64E6c           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )Nrj  r  r}  r~  r  r  )rl  r;  )r   ohlcvrI  s      r  parse_ohlcvzcex.parse_ohlcv  sl    e[1UF+UF+UE*UG,UH-
 	
r  c                    K   | j                          d{    | j                  |       d{   }| j                  |di       }| j                  |di       }| j                  |d      S 7 U7 >w)aS  
        fetch the trading fees for multiple markets

        https://trade.cex.io/docs/#rest-public-api-calls-candles

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>` indexed by market symbols
        Nr  
tradingFeeT)ro  privatePostGetMyCurrentFeer  parse_trading_fees)r   r  rG  r  rW   s        r  fetch_trading_feeszcex.fetch_trading_fees  so      !!!88@@ ~~h3~~dL"5&&tT22 	"@s   A0A,A0A.=A0.A0c                    i }t        |j                               }t        dt        |            D ]9  }||   }d }|r| j	                  |      }| j                  ||   |      }|||d   <   ; t        dt        | j                              D ]<  }| j                  |   }	|	|vs| j                  |	      }| j                  ||      ||	<   > |S )Nr   rO  )r6  r7  r8  r9  r  parse_trading_feerr  rI  )
r   rG  
useKeyAsIdresultr7  ikeyrI  parsedrO  s
             r  r  zcex.parse_trading_fees
  s    HMMO$q#d)$ 	.Aq'CF))#.++HSM6BF'-F6(#$	. q#dll+, 	JA\\!_Ff$V,!%!7!7&!Iv		J
 r  r)  c                 t    || j                  |d      | j                  |d      | j                  |d      d d dS )NrO  percent)r+  rO  makertakerr  	tierBased)r1  r;  )r   r)  rI  s      r  r  zcex.parse_trading_fee  sE    &&vx8%%c95%%c95
 	
r  c                   K   | j                          d {    | j                  |       d {   }| j                  |di       }| j                  |di       }| j                  |      }| j	                  ||      S 7 f7 Ow)Nr  balancesPerAccounts)ro  privatePostGetMyAccountStatusV3r  r  parse_accounts)r   r  rG  r  balancesarrayss         r  fetch_accountszcex.fetch_accounts%  s|     !!!==fEE* ~~h3>>$(=rBx(""66223 	"Es    BA=BA?AB?Baccountc                     d d d |dS )N)r   r0  r/  r+   )r   r  s     r  parse_accountzcex.parse_accountA  s    	
 	
r  c                   K   d}| j                  |dd      \  }}d}| j                  |dd      \  }}d}|dk(  rS| j                  |       d{   }| j                  |di       }| j                  |di       }| j                  ||i       }n,| j                  |       d{   }| j                  |di       }| j	                  |      S 7 {7 *w)	ap  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://trade.cex.io/docs/#rest-private-api-calls-account-status-v3

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.method]: 'privatePostGetMyWalletBalance' or 'privatePostGetMyAccountStatusV3'
        :param dict [params.account]:  in case 'privatePostGetMyAccountStatusV3' is chosen, self can specify the account name(default is empty string)
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        Nr   methodprivatePostGetMyWalletBalancer  r  r  )handle_param_stringr  r  r  parse_balance)r   r  accountNamer  accountBalancerG  r  r  s           r  fetch_balancezcex.fetch_balanceI  s      "66vy"MV11&(Dcd66!AA&IIH >>(FB7D~~d,A2FH!^^Hk2FN!??GGH "^^HfbAN!!.11A J$ Hs%   ACC
AC!C")CCc                 8   d|i}t        |j                               }t        dt        |            D ]U  }||   }| j	                  ||i       }| j                  |      }| j                  |d      | j                  |d      d}|||<   W | j                  |      S )Nr+  r   balanceOnHoldbalance)usedtotal)r6  r7  r8  r9  r  r2  r1  safe_balance)	r   rG  r  r7  r  r  r  r/  r  s	            r  r  zcex.parse_balance|  s    H
 HMMO$q#d)$ 	#Aq'CnnXsB7G**3/D((/B))'9=G #F4L	#   ((r  statusc                   K   | j                          d{    i }|dk(  }|rd|d<   d}|| j                  |      }|d   |d<   |||d<   |||d<   n|r| j                         d	z
  |d<   d}	| j                  |d
d      \  }	}|	|	|d<   | j	                  | j                  ||             d{   }
| j                  |
dg       }| j                  ||||      S 7 7 -w)a  
        fetches information on multiple orders made by the user

        https://trade.cex.io/docs/#rest-private-api-calls-orders

        :param str status: order status to fetch for
        :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 int [params.until]: timestamp in ms of the latest entry
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        NclosedTarchivedr   r  r  serverCreateTimestampFroml    P% r  r  serverCreateTimestampTor  )ro  rI  r  r  privatePostGetMyOrdersrw  r  parse_orders)r   r  rO  r  r   r  ry  isClosedOrdersrI  r  rG  r  s               r  fetch_orders_by_statuszcex.fetch_orders_by_status  s     !!! H,"&GJ[[(F$TlGFO"'GJ38G/0373D3D3FIb3bG/033FGVLv16G-.44T[[&5QRRR ~~h3  vue<<} 	"( Ss"   C CBC 0C1,C C c                 H   K   | j                  d||||       d{   S 7 w)>  

        https://trade.cex.io/docs/#rest-private-api-calls-orders

        fetches information on multiple canceled orders made by the user
        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: timestamp in ms of the earliest order, default is None
        :param int [limit]: max number of orders to return, default is None
        :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>`
        r  Nr  r   rO  r  r   r  s        r  fetch_closed_orderszcex.fetch_closed_orders  s(      0065%QWXXXX   " "c                 H   K   | j                  d||||       d{   S 7 w)r  r  Nr  r  s        r  fetch_open_orderszcex.fetch_open_orders  s'      00vVVVVr  r   c           	         K   | j                          d{    dt        |      i}| j                  |dd| j                  ||             d{   }|d   S 7 B7 w)a  
        fetches information on an open order made by the user

        https://trade.cex.io/docs/#rest-private-api-calls-orders

        :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
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NorderIdr   )ro  intr   rw  r   r   rO  r  ry  r  s         r  fetch_open_orderzcex.fetch_open_order  sg      !!!s2w
 --fdD$++gW]B^__ay 	" `!   AA8AA
AAc           	         K   | j                          d{    dt        |      i}| j                  |dd| j                  ||             d{   }|d   S 7 B7 w)a  
        fetches information on an closed order made by the user

        https://trade.cex.io/docs/#rest-private-api-calls-orders

        :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
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r   )ro  r  r  rw  r  s         r  fetch_closed_orderzcex.fetch_closed_order  sh      !!!s2w
 //dDKKPWY_D`aaay 	" br  c           	      >    ddddddddd}| j                  |||      S )Nr  r  expiredrejected	cancelingcanceled)PENDING_NEWNEWPARTIALLY_FILLEDFILLEDEXPIREDREJECTEDPENDING_CANCEL	CANCELLEDr1  r   r  statusess      r  parse_order_statuszcex.parse_order_status  s8    ! & ")#	
 &&99r  r  c           	         | j                  |d      }| j                  |d      }d }|
||dz   |z   }| j                  ||      }|d   }| j                  | j                  |d            }i }| j                  |d      }	|	-| j                  |d      }
| j	                  |
      }||d<   |	|d	<   | j                  |d
      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  i d| j                  |d      d| j                  |d      d|d| j                  |      d| j                  |d      dd d|d| j                  |d      d| j                  |d      dd d| j                  |d      d| j                  |d      d| j                  |d      d|d	|d| j                  |d      d |d ||d |d!|      S )"N	currency1	currency2rM  rO  r  	feeAmountfeeCurrencyr  r\  serverCreateTimestamprequestedAmountCcy1executedAmountCcy1executedAmountCcy2r   r  clientOrderIdrj  r|  lastUpdateTimestamplastTradeTimestampr0  	orderTyper   postOnlyr  r[  r{   	stopPricer.  r  averagePricefilled)	remainingr  r)  r  r+  )	r1  r  r  r;  r2  rl  
safe_orderr  r  )r   r  rI  r  r  r  rO  r  r)  r  
currencyIdfeeCoderj  requestedBaseexecutedBaseexecutedQuotes                   r  parse_orderzcex.parse_order'  s   B $$UK8	$$UK8	 Y%: 32H!!(F3!(()9)9%)JK$$UK8	 ))%?J--j9G%C
O#CK%%e-DE	((0EF''/CD((0DE  
$""5)4 
T--e_E 
  
 Y/	 

 "4#4#4U<Q#R 
 !$ 
 f 
 D**5+> 
 4++E=A 
  
 D**5&9 
 T%%eW5 
 D,,UK@ 
 m 
 M 
  t''~>! 
" l# 
$ - 
. / 	r  r0  r  r.  r[  c                   K   d}| j                  |dd      \  }}|t        | j                  dz         | j                          d{    | j	                  |      }| j                         |d   |d   || j                  |j                               |j                         | j                         | j                  ||      d}	d}
| j                  |ddd	      \  }
}|d
k(  r| j                  ||      |	d<   |
|	d<   d}| j                  |d      \  }}|
d|	d<   ||	d<   | j                  | j                  |	|             d{   }| j                  |d      }| j!                  ||      S 7 &7 +w)aV  
        create a trade order

        https://trade.cex.io/docs/#rest-private-api-calls-new-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 fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.accountId]: account-id to use(default is empty string)
        :param float [params.triggerPrice]: the price at which a trigger order is triggered at
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr6   	accountIdz createOrder() : API trading is now allowed from main account, set params["accountId"] or .options["createOrder"]["accountId"] to the name of your sub-accountrP  rQ  )r#  r  r  r4  r&  r  rj  
amountCcy1r   GTCr   r[  r{   z
Stop Limitr0  r(  r  )r  r    r   ro  rI  uuid
capitalizelowerupperr  amount_to_precisionprice_to_precisionr  privatePostDoMyNewOrderrw  r  r2  )r   rO  r0  r  r.  r[  r  r4  rI  ry  r   r{   rG  r  s                 r  create_orderzcex.create_orderu  s      	 99&-Q\]	6#DGG  /O  %O  P  P!!!V$!YY[)	*"6JJL**,2266B	
 ";;FMS`bghV7?#66vuEGG%0GM"#77Of#*GFO#/GK 55dkk'66RSSb ~~h/f--Q 	", Ts%   AE3E.	C<E3E1)E31E3c                 J  K   | j                          d{    t        |      dt        | j                               z   | j                         d}| j	                  | j                  ||             d{   }| j                  |di       }| j                  |      S 7 7 *w)a  
        cancels an open order

        https://trade.cex.io/docs/#rest-private-api-calls-cancel-order

        :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
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nc_)r  cancelRequestIdrj  r  )ro  r  strr  privatePostDoCancelMyOrderrw  r  r2  )r   r   rO  r  ry  rG  r  s          r  cancel_orderzcex.cancel_order  s      !!!2w#c4+<+<+>&@@**,

 88Wf9UVV ~~h3%% 	" Ws"   B#BAB#6B!7)B#!B#c                 J  K   | j                          d{    | j                  |       d{   }| j                  |di       }| j                  |dg       }g }t	        dt        |            D ]  }||   }|j                  d|i        | j                  |      S 7 7 qw)a  
        cancel all open orders in a market

        https://trade.cex.io/docs/#rest-private-api-calls-cancel-all-orders

        :param str symbol: alpaca cancelAllOrders cannot setting symbol, it will cancel all open orders
        :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>`
        Nr  clientOrderIdsr   r#  )ro  privatePostDoCancelAllOrdersr  r  r8  r9  r  r  )	r   rO  r  rG  r  idsordersr  r   s	            r  cancel_all_orderszcex.cancel_all_orders  s      !!!::6BB ~~h3nnT#3R8q#c(# 	1AQBMM?B/0	1   ((% 	"Bs    B#BB#B!A0B#!B#r/  c                 z  K   | j                          d{    d}i }|| j                  |      }|d   |d<   |||d<   |||d<   d}| j                  |dd      \  }}|||d<   | j                  | j	                  ||             d{   }| j                  |d	g       }	| j                  |	|||      S 7 7 -w)
a|  
        fetch the history of changes, actions done by the user or operations that altered the balance of the user

        https://trade.cex.io/docs/#rest-private-api-calls-transaction-history

        :param str [code]: unified currency code
        :param int [since]: timestamp in ms of the earliest ledger entry
        :param int [limit]: max number of ledger entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest ledger entry
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
        Nr   r  dateFromr  r  r  dateTor  )ro  r  r  "privatePostGetMyTransactionHistoryrw  r  parse_ledger)
r   r/  r  r   r  r  ry  r  rG  r  s
             r  fetch_ledgerzcex.fetch_ledger	  s      !!!}}T*H"*4.GJ"'GJ"'GJ33FGVLv %GH@@WV\A]^^  ~~h3  x>>? 	" _s"   B;B7A4B;B9,B;9B;itemr  c                 B   | j                  |d      }d }t        j                  |d      rd}t        j                  d|      }nd}| j                  |d      }| j	                  ||      }| j                  ||      }| j                  |d      }| j                  |      }| j                  |d      }	| j                  || j                  |d	      || j                  |d
d      d d | j                  |	      || j                  |      || j                  |      d d d d d|      S )Nr.  0outz-1inr  rj  r0  transactionIdr4  r  )r+  r   	directionr  referenceAccountreferenceIdr0  r  r.  rj  r|  beforeafterr  r)  )r1  r%   	string_le
string_mulsafe_currencyr2  r  safe_ledger_entryparse_ledger_entry_typer4  r  )
r   rQ  r  r.  rW  r-  r/  timestampStringrj  r0  s
             r  parse_ledger_entryzcex.parse_ledger_entry7  s2   !!$1	VS)I''f5FI%%dJ7
%%j(;&&z8<**4=NN?3	f-%%""49"''k2> $006''/"Y/'
  ! 	r  c                 4    dddd}| j                  |||      S )Nr  r  r)  )r  r&  
commissionr  )r   r0  
ledgerTypes      r  r`  zcex.parse_ledger_entry_typeW  s)     $


 
D$77r  c                 j  K   | j                          d{    i }d}|| j                  |      }|||d<   |||d<   d}| j                  |dd      \  }}|||d<   | j                  | j	                  ||             d{   }| j                  |dg       }	| j                  |	|||      S 7 7 -w)ap  
        fetch history of deposits and withdrawals

        https://trade.cex.io/docs/#rest-private-api-calls-funding-history

        :param str [code]: unified currency code for the currency of the deposit/withdrawals, default is None
        :param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None
        :param int [limit]: max number of deposit/withdrawals to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        NrL  r  r  r  rM  r  )ro  r  r  privatePostGetMyFundingHistoryrw  r  parse_transactions)
r   r/  r  r   r  ry  r  r  rG  r  s
             r  fetch_deposits_withdrawalszcex.fetch_deposits_withdrawals_  s      !!!}}T*H"'GJ"'GJ33FGVLv %GH<<T[[RX=YZZ& ~~h3&&tXueDDC 	" [s"   B3B/A,B3B1,B31B3transactionc                    | j                  |d      }| j                  |d      }|dk(  rdnd}| j                  ||      }| j                  |d      }| j                  |      }i d|d| j                  |d	      d
d d|d|dd d| j                  |d      d| j	                  | j                  |d            d|d| j                  |      dd dd dd dd dd dd dd d || j                  |d      dd dS )Nr  rW  r&  r  r  	updatedAtr+  r   txIdtxidr0  r'  r.  r  rj  r|  addressaddressFrom	addressTotagtagFromtagToupdatedcommissionAmount)r  r\  )commentr)  internal)r1  r2  r  r;  parse_transaction_statusr  )	r   rj  r  r-  rW  r0  r/  rl  rj  s	            r  parse_transactionzcex.parse_transaction  s   %%k:>
$$[+>	 )Z 7|i&&z8<$$[+>	NN9-	
K
$"";7
 D
 D	

 
 t
 d&&{H=
 d33D4D4D[RZ4[\
 
 Y/
 t
 4
 
 4
 t
  T!
" t#
$  ((6HI /
 	
r  c                 4    dddd}| j                  |||      S )Nr  pendingok)r  r|  approvedr  r  s      r  ry  zcex.parse_transaction_status  s)    " 

 &&99r  fromAccount	toAccountc                    K   d}|dk7  r#|dk7  r| j                  |||||       d{   }n| j                  |||||       d{   }| j                  ddd      }|r
||d<   ||d<   |S 7 C7 'w)a-  
        transfer currency internally between wallets on the same account

        https://trade.cex.io/docs/#rest-private-api-calls-internal-transfer

        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: 'SPOT', 'FUND', or 'CONTRACT'
        :param str toAccount: 'SPOT', 'FUND', or 'CONTRACT'
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        Nr  rP   fillResponseFromRequestTr  r  )transfer_between_sub_accounts%transfer_between_main_and_sub_accounthandle_option)r   r/  r.  r  r  r  rP   r  s           r  rP   zcex.transfer  s      ?{b0!??fk[dflmmH!GGfVaclntuuH"&"4"4ZAZ\`"a"&1H]#$-H[! nus!   %A/A+A/A-&A/-A/c                   K   | j                          d {    | j                  |      }|dk(  }|r|n|}| j                  |d| j                               }	|d   | j	                  ||      ||	d}
d }|r*| j                  | j                  |
|             d {   }n)| j                  | j                  |
|             d {   }| j                  |di       }| j                  ||      S 7 7 U7 -w)Nr  guidr   )r  r.  r4  
clientTxIdr  )
ro  r  r1  r7  currency_to_precision#privatePostDoDepositFundsFromWalletrw  $privatePostDoWithdrawalFundsToWalletr  parse_transfer)r   r/  r.  r  r  r  r  fromMaintargetAccountr  ry  rG  r  s                r  r  z)cex.transfer_between_main_and_sub_account  s     !!!==&2%%-	;		< 00v>&	
 !EEdkkRY[aFbccH!FFt{{SZ\bGcddH ~~h3""422= 	" dds4   C4C.BC4C0)C4C2*C40C42C4c                 4  K   | j                          d {    | j                  |      }|d   | j                  ||      ||d}| j                  | j	                  ||             d {   }| j                  |di       }	| j                  |	|      S 7 }7 +w)Nr   )r  r.  fromAccountIdtoAccountIdr  )ro  r  r  privatePostDoMyInternalTransferrw  r  r  )
r   r/  r.  r  r  r  r  ry  rG  r  s
             r  r  z!cex.transfer_between_sub_accounts  s     !!!==& 00v>($	
 ==dkk'SY>Z[[ ~~h3""422% 	" \s"   BBAB*B+*BBrP   c                     | j                  |d      }| j                  ||      }|| j                  |dd      d d |d d d | j                  | j                  |d            d	S )Nr  rV  r  r  )	r+  r   rj  r|  r  r.  r  r  r  )r1  r2  safe_string_2ry  )r   rP   r  r-  currencyCodes        r  r  zcex.parse_transfer  st    . %%h
;
..z8D$$XM$33D4D4DXx4XY

 
	
r  c                   K   d}| j                  |dd      \  }}|t        | j                  dz         | j                          d{    d}| j	                  |      \  }}| j                  |      }||d   | j                  |      d}| j                  | j                  ||             d{   }| j                  |di       }| j                  ||      S 7 7 +w)a  
        fetch the deposit address for a currency associated with self account

        https://trade.cex.io/docs/#rest-private-api-calls-deposit-address

        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.accountId]: account-id(default to empty string) to refer to(at self moment, only sub-accounts allowed by exchange)
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        Nr6   r4  z fetchDepositAddress() : main account is not allowed to fetch deposit address from api, set params["accountId"] or .options["createOrder"]["accountId"] to the name of your sub-accountr   )r4  r  
blockchainr  )r  r    r   ro  handle_network_code_and_paramsr  network_code_to_idprivatePostGetDepositAddressrw  r  parse_deposit_address)	r   r/  r  r4  rB  r  ry  rG  r  s	            r  fetch_deposit_addresszcex.fetch_deposit_address*  s      	 99&-Q\]	6#DGG  /h  %h  i  i!!!"AA&IV==&" 11+>

 ::4;;wPV;WXX ~~h3))$99- 	" Ys%   ACC	A'C0C1*CCc                     | j                  |d      }| j                  |d      }| j                  ||      }| j                  |       ||d   | j                  | j                  |d            |d dS )Nro  r  r/  r  )r+  r  r'  ro  rr  )r1  r^  check_addressr:  )r   depositAddressr  ro  r-  s        r  r  zcex.parse_deposit_addressQ  s}    "">9=%%njA
%%j(;7#" (..t/?/?P\/]^
 	
r  rQ   GETc                 P   | j                   d   |   dz   | j                  ||      z   }| j                  || j                  |            }|dk(  r5|dk(  r|r|d| j	                  |      z   z  }n| j                  |      }ddi}n| j                          t        | j                               }	| j                  |      }||	z   |z   }
| j                  | j                  |
      | j                  | j                        t        j                  d      }d| j                  |	|d	}||||d
S )NrT   rN  rQ   r  ?Content-Typezapplication/jsonbase64)r  z
X-AGGR-KEYzX-AGGR-TIMESTAMPzX-AGGR-SIGNATURE)urlr  bodyheaders)r   implode_paramsomitextract_params	urlencodejsoncheck_required_credentialsrB  secondshmacencodesecrethashlibsha256apiKey)r   pathrT   r  r  r  r  r  queryr  auth	signatures               r  signzcex.sign^  s   iis#c)D,?,?f,MM		&$"5"5d";<(?3!666Cyy'"$6 ++-$,,.)G99U#D'>D(D		$++d"3T[[5Mw~~_ghI 2"kk$+$-	G fdwOOr  reasonr  r  r  r  c
                    |`|t        | j                  dz         |d   dk(  r#| j                  |      }
| j                  |
      }nt        | j                  dz   |z         | j	                  |d      }|]| j                  dz   |z   }| j                  | j                  d   ||       | j                  | j                  d   ||       t        |      |j                  d	      dk\  rb| j                  |d
i       }| j	                  |d      }|;| j                  | j                  d   ||       t        | j                  dz   |z         y )Nz returned empty responser   {z returned unparsed response: error r   r   rm   r  rejectReasonz createOrder() )r#   r   fix_stringified_json_members
parse_jsonr1  throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   findr  )r   r/  r  r  r  r  r  rG  requestHeadersrequestBodyfixedr  feedbackr  r  s                  r  handle_errorszcex.handle_errorsx  sI    |"477-G#GHHaC99$???51"477-L#Lt#STT  73ww}t+H001I5RZ[001I5RZ[))88%&!+>>(FB7D++D.AL'44T__W5M|]ij#DGG.?$?,$NOOr  )N)F)N__name__
__module____qualname__r   r   r   r  dictr	   rC  r   r   rH  rh  r   rm  rB  r   rq  r   r   rp  r  r   r  r  r   r  r6  r  r  r   r  r  r   r  r   r  r  r   r  r  r   r   r  r  r   r  r  r  r2  r   r   floatr   r>  rD  rJ  r   rP  rb  r`  r   ri  rz  ry  r   rP   r  r  r  r
   r  r  r  r  r  __classcell__)r   s   @r  r'   r'      sg   e# eN -/ 4:: 4:l9$ 98 9v *,  (V  (D:4 :F :x ') S ( 68 4 4F 4 6:" *17 *1 *1X4  6 2 <@d[] ,? ,?S ,? ,?bfglbm ,?\ v  > @DB %MS %M %MS\ %MN 8<$]ajl ;H ;HC ;HWZ ;Hquvzq{ ;Hz
 
4 
 /1 3[ 32 "
T 
6 
EX 
 +- 3g 38
T 
g 
 *, 12 12f) )  GKY]lpy{ L=3 L= L=SV L=fi L=  AE  FK  AL L=\ 7;\`ik Y Y3 YVY Y 59tZ^gi Wc W WTW W =A  c $ ?C2 3  $: :L Lv L L\ mqy{ \. \.I \.Y \.X] \.fi \.| 9=R &S &# &0 59 )c )< .2SW`b ,?s ,?# ,?S ,?gklwgx ,?\t x ; @8 <@daenp -ES -E -E[^ -Euy  {F  vG -E^
T 
X 
Q\ 
B:s : ac 3  C TW gt 0 ~@ 3 3U 3ad 3qt 3  ER 3B vx 3 3U 3Y\ 3il 3  }J 3*#
t #
x #
= #
J =? %: %:> %:N
h 
R` 
 &eBSW P4# s  c TX `c r  r'   )- ccxt.async_support.base.exchanger   ccxt.abstract.cexr   r	  r  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   r   r    r!   r"   r#   ccxt.base.decimal_to_precisionr$   ccxt.base.preciser%   r'   r  r  r  <module>r     sk    6 )   D  D  D  D  D  D  D  * 0 - . ' . ) 4 %z(K zr  