
    !:h                       d dl mZ d dlm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    B/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/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                 j   g }|j                  | j                  |             |j                  | j                  |             |}| j                  |d   dg       }| j	                  |d   di       }| j                  |d      }| j                  ||      }| j                  | j                  |            S )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
        r   datarY   currency)	appendpublicPostGetCurrenciesInfopublicPostGetProcessingInfo	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, 		!fbA~~ilFB? MM.*E 1<@$$T]]4%899r  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-  r.  currencyPrecisionr   rawNetworksr5  j	networkId
rawNetworknetworkCoder  r$  s                  r  parse_currencyzcex.parse_currency5  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                 l    | j                  |      }| j                  |dg       }| j                  |      S )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
        r  )publicPostGetPairsInfor	  parse_markets)r   r  responser  s       r  fetch_marketszcex.fetch_marketsp  s9     ..v6, ~~h3!!$''r  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settleIdr.  r/   Tr0   Fr1   r2   r3   contractr   r   baseMinbaseMaxr   minPricemaxPricequoteMinquoteMax)r,  pricecostr   baseLotSizepricePrecisionbasePrecisionquotePrecision)r,  rY  rI  rJ  )
contractSizeexpiryexpiryDatetimestrike
optionTyper(  r  r&  createdr)  )r/  r0  safe_market_structurer9  r2  r3  )r   rG  rN  rI  rO  rJ  r   rM  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                 p    | j                  |      }| j                  |d      }| j                  |d      }|S )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
        r  	timestamp)publicPostGetServerTimer
  safe_integer)r   r  rE  r  rh  s        r  
fetch_timezcex.fetch_time  s>     //7 ~~h/%%dK8	r  rM  c                 n    | j                          | j                  |g|      }| j                  ||i       S )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>`
        )load_marketsfetch_tickersr
  )r   rM  r  rE  s       r  fetch_tickerzcex.fetch_ticker  s7     	%%vh7~~h33r  Nsymbolsc                     | j                          i }|| j                  |      |d<   | j                  | j                  ||            }| j	                  |di       }| j                  ||      S )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>`
        pairsr  )rm  
market_idspublicPostGetTickerextendr
  parse_tickers)r   rp  r  requestrE  r  s         r  rn  zcex.fetch_tickers  sp     	#w7GG++DKK,HI6 ~~h3!!$00r  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   rM  rh  datetimehighlowbidbestBid	bidVolumeaskbestAsk	askVolumevwapopencloselastpreviousClosechangepriceChange
percentagepriceChangePercentageaverage
baseVolumevolumequoteVolume)r  r)  )r/  safe_symbolsafe_tickerr9  )r   rx  rG  marketIdrM  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                    | j                          | j                  |      }d|d   i}|| j                  |      |d<   d}| j                  |dd      \  }}|| j                  |      |d<   |t	        |d      |d	<   | j                  | j                  ||            }| j                  |d
i       }	| j                  |	dg       }
| j                  |
|||      S )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>`
        pairr   NfromDateISOuntiltill	toDateISOi'  pageSizer  trades)
rm  rG  iso8601handle_param_integer_2r!  publicPostGetTradeHistoryru  r
  r	  parse_trades)r   rM  r  r   r  rG  rw  r  rE  r  r  s              r  fetch_tradeszcex.fetch_trades5  s     	V$F4L
 %)\\%%8GM"33FGVLv#'<<#6GK "%eU"3GJ11$++gv2NO  ~~h3h3  >>r  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dateISOrM  tradeIdsiderY  r,  )r)  rh  rz  rM  r   orderr.  takerOrMakerr  rY  r,  rZ  r'  )r/  	parse8601safe_market
safe_trader  safe_string_lower)r   r  rG  dateStrrh  s        r  parse_tradezcex.parse_tradec  s     ""5)4NN7+	!!$/"Y/X&""5)4 **5&9%%eW5&&uh7 
  	r  c                 
   | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |di       }| j                  |d      }| j                  ||d   |      S )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
        r  r   r  rh  rM  )rm  rG  publicPostGetOrderBookru  r
  rj  parse_order_book)	r   rM  r   r  rG  rw  rE  	orderBookrh  s	            r  fetch_order_bookzcex.fetch_order_book  s     	V$F4L
 ..t{{7F/KL& NN8VR8	%%i=	$$Yx0@)LLr  r   c                    d}| j                  |dd      \  }}|t        | j                  dz         | j                          | 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                  ||            }
| j                  |
dg       }| j                  |||||      S )a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://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   rm  rG  r   r  r  millisecondspublicPostGetCandlesru  r	  parse_ohlcvs)r   rM  	timeframer  r   r  r  rG  rw  r  rE  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,,T[[&-IJ$ ~~h3  vy%GGr  c           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )Nrh  r  r{  r|  r  r  )rj  r9  )r   ohlcvrG  s      r  parse_ohlcvzcex.parse_ohlcv  sl    e[1UF+UF+UE*UG,UH-
 	
r  c                     | j                          | j                  |      }| j                  |di       }| j                  |di       }| j                  |d      S )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
        r  
tradingFeeT)rm  privatePostGetMyCurrentFeer
  parse_trading_fees)r   r  rE  r  rW   s        r  fetch_trading_feeszcex.fetch_trading_fees  sY     	226: ~~h3~~dL"5&&tT22r  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   rM  )r4  r5  r6  r7  r  parse_trading_feerp  rG  )
r   rE  
useKeyAsIdresultr5  ikeyrG  parsedrM  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 )NrM  percent)r)  rM  makertakerr  	tierBased)r/  r9  )r   r'  rG  s      r  r  zcex.parse_trading_fee  sE    &&vx8%%c95%%c95
 	
r  c                     | j                          | j                  |      }| j                  |di       }| j                  |di       }| j                  |      }| j	                  ||      S )Nr  balancesPerAccounts)rm  privatePostGetMyAccountStatusV3r
  r  parse_accounts)r   r  rE  r  balancesarrayss         r  fetch_accountszcex.fetch_accounts$  sf    77?* ~~h3>>$(=rBx(""6622r  accountc                     d d d |dS )N)r   r.  r-  r)   )r   r  s     r  parse_accountzcex.parse_account@  s    	
 	
r  c                 p   d}| j                  |dd      \  }}d}| j                  |dd      \  }}d}|dk(  rK| j                  |      }| j                  |di       }| j                  |di       }| j                  ||i       }n$| j                  |      }| j                  |di       }| j	                  |      S )	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  accountBalancerE  r  r  s           r  fetch_balancezcex.fetch_balanceH  s     "66vy"MV11&(Dcd66;;FCH >>(FB7D~~d,A2FH!^^Hk2FN99&AH "^^HfbAN!!.11r  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)r4  r5  r6  r7  r
  r0  r/  safe_balance)	r   rE  r  r5  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                    | j                          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                  ||            }
| j                  |
dg       }| j                  ||||      S )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>`
        closedTarchivedNr   r  r  serverCreateTimestampFroml    P% r  r  serverCreateTimestampTor  )rm  rG  r  r  privatePostGetMyOrdersru  r	  parse_orders)r   r  rM  r  r   r  rw  isClosedOrdersrG  r  rE  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-...t{{7F/KLR ~~h3  vue<<r  c                 ,    | j                  d||||      S )>  

        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  r  r   rM  r  r   r  s        r  fetch_closed_orderszcex.fetch_closed_orders  s     **8VUE6RRr  c                 ,    | j                  d||||      S )r  r  r  r  s        r  fetch_open_orderszcex.fetch_open_orders  s     **665%PPr  r   c           	          | j                          dt        |      i}| j                  |dd| j                  ||            }|d   S )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>`
        orderIdNr   )rm  intr  ru  r   r   rM  r  rw  r  s         r  fetch_open_orderzcex.fetch_open_order  sN     	s2w
 ''dDKKQW<XYayr  c           	          | j                          dt        |      i}| j                  |dd| j                  ||            }|d   S )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>`
        r  Nr   )rm  r   r  ru  r  s         r  fetch_closed_orderzcex.fetch_closed_order  sN     	s2w
 ))&$dkk'SY>Z[ay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r/  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	currency2rK  rM  r  	feeAmountfeeCurrencyr  rZ  serverCreateTimestamprequestedAmountCcy1executedAmountCcy1executedAmountCcy2r   r  clientOrderIdrh  rz  lastUpdateTimestamplastTradeTimestampr.  	orderTyper   postOnlyr  rY  r{   	stopPricer,  r  averagePricefilled)	remainingr  r'  r  r)  )	r/  r  r  r9  r0  rj  
safe_orderr  r  )r   r  rG  r  r  r  rM  r  r'  r  
currencyIdfeeCoderh  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  r.  r  r,  rY  c                    d}| j                  |dd      \  }}|t        | j                  dz         | j                          | 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                  |	|            }| j                  |d      }| j!                  ||      S )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-accountrN  rO  )r  r  r  r0  r"  r  rh  
amountCcy1r   GTCr   rY  r{   z
Stop Limitr.  r$  r  )r  r    r   rm  rG  uuid
capitalizelowerupperr  amount_to_precisionprice_to_precisionr  privatePostDoMyNewOrderru  r
  r.  )r   rM  r.  r  r,  rY  r  r0  rG  rw  r   r{   rE  r  s                 r  create_orderzcex.create_ordert  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 //GV0LMb ~~h/f--r  c                    | j                          t        |      dt        | j                               z   | j                         d}| j	                  | j                  ||            }| j                  |di       }| j                  |      S )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>`
        c_)r  cancelRequestIdrh  r  )rm  r   strr  privatePostDoCancelMyOrderru  r
  r.  )r   r   rM  r  rw  rE  r  s          r  cancel_orderzcex.cancel_order  s     	2w#c4+<+<+>&@@**,

 224;;w3OP ~~h3%%r  c                    | j                          | j                  |      }| j                  |di       }| j                  |dg       }g }t	        dt        |            D ]  }||   }|j                  d|i        | j                  |      S )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>`
        r  clientOrderIdsr   r  )rm  privatePostDoCancelAllOrdersr
  r	  r6  r7  r  r  )	r   rM  r  rE  r  idsordersr  r   s	            r  cancel_all_orderszcex.cancel_all_orders  s     	44V< ~~h3nnT#3R8q#c(# 	1AQBMM?B/0	1   ((r  r-  c                 J   | j                          d}i }|| j                  |      }|d   |d<   |||d<   |||d<   d}| j                  |dd      \  }}|||d<   | j                  | j	                  ||            }| j                  |d	g       }	| j                  |	|||      S )
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  )rm  r  r  "privatePostGetMyTransactionHistoryru  r	  parse_ledger)
r   r-  r  r   r  r  rw  r  rE  r  s
             r  fetch_ledgerzcex.fetch_ledger  s     	}}T*H"*4.GJ"'GJ"'GJ33FGVLv %GH::4;;wPV;WX  ~~h3  x>>r  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  rh  r.  transactionIdr0  r  )r)  r   	directionr  referenceAccountreferenceIdr.  r  r,  rh  rz  beforeafterr  r'  )r/  r%   	string_le
string_mulsafe_currencyr0  r  safe_ledger_entryparse_ledger_entry_typer2  r  )
r   rM  r  r,  rS  r)  r-  timestampStringrh  r.  s
             r  parse_ledger_entryzcex.parse_ledger_entry6  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   r.  
ledgerTypes      r  r\  zcex.parse_ledger_entry_typeV  s)     $


 
D$77r  c                 :   | j                          i }d}|| j                  |      }|||d<   |||d<   d}| j                  |dd      \  }}|||d<   | j                  | j	                  ||            }| j                  |dg       }	| j                  |	|||      S )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>`
        NrH  r  r  r  rI  r  )rm  r  r  privatePostGetMyFundingHistoryru  r	  parse_transactions)
r   r-  r  r   r  rw  r  r  rE  r  s
             r  fetch_deposits_withdrawalszcex.fetch_deposits_withdrawals^  s     	}}T*H"'GJ"'GJ33FGVLv %GH66t{{7F7ST& ~~h3&&tXueDDr  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  rS  r$  r  r  	updatedAtr)  r   txIdtxidr.  r%  r,  r  rh  rz  addressaddressFrom	addressTotagtagFromtagToupdatedcommissionAmount)r  rZ  )commentr'  internal)r/  r0  r  r9  parse_transaction_statusr  )	r   rf  r  r)  rS  r.  r-  rh  rh  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  rx  approvedr  r  s      r  ru  zcex.parse_transaction_status  s)    " 

 &&99r  fromAccount	toAccountc                     d}|dk7  r|dk7  r| j                  |||||      }n| j                  |||||      }| j                  ddd      }|r
||d<   ||d<   |S )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99$U^`fgHAA$P[]fhnoH"&"4"4ZAZ\`"a"&1H]#$-H[!r  c                    | j                          | j                  |      }|dk(  }|r|n|}| j                  |d| j                               }	|d   | j	                  ||      ||	d}
d }|r"| j                  | j                  |
|            }n!| j                  | j                  |
|            }| j                  |di       }| j                  ||      S )Nr  guidr   )r  r,  r0  
clientTxIdr  )
rm  r  r/  r3  currency_to_precision#privatePostDoDepositFundsFromWalletru  $privatePostDoWithdrawalFundsToWalletr
  parse_transfer)r   r-  r,  r{  r|  r  r  fromMaintargetAccountr  rw  rE  r  s                r  r  z)cex.transfer_between_main_and_sub_account  s    ==&2%%-	;		< 00v>&	
 ??GU[@\]H@@WV\A]^H ~~h3""422r  c                    | j                          | j                  |      }|d   | j                  ||      ||d}| j                  | j	                  ||            }| j                  |di       }	| j                  |	|      S )Nr   )r  r,  fromAccountIdtoAccountIdr  )rm  r  r  privatePostDoMyInternalTransferru  r
  r  )
r   r-  r,  r{  r|  r  r  rw  rE  r  s
             r  r  z!cex.transfer_between_sub_accounts  s    ==& 00v>($	
 77GV8TU ~~h3""422r  rP   c                     | j                  |d      }| j                  ||      }|| j                  |dd      d d |d d d | j                  | j                  |d            d	S )Nr  rR  r  r  )	r)  r   rh  rz  r  r,  r{  r|  r  )r/  r0  safe_string_2ru  )r   rP   r  r)  currencyCodes        r  r  zcex.parse_transfer  st    . %%h
;
..z8D$$XM$33D4D4DXx4XY

 
	
r  c                    d}| j                  |dd      \  }}|t        | j                  dz         | j                          d}| j	                  |      \  }}| j                  |      }||d   | j                  |      d}| j                  | j                  ||            }| j                  |di       }| j                  ||      S )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   r0  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   )r0  r  
blockchainr  )r  r    r   rm  handle_network_code_and_paramsr  network_code_to_idprivatePostGetDepositAddressru  r
  parse_deposit_address)	r   r-  r  r0  r@  r  rw  rE  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4T[[&5QR ~~h3))$99r  c                     | j                  |d      }| j                  |d      }| j                  ||      }| j                  |       ||d   | j                  | j                  |d            |d dS )Nrk  r  r-  r  )r)  r  r%  rk  rn  )r/  rZ  check_addressr8  )r   depositAddressr  rk  r)  s        r  r  zcex.parse_deposit_addressP  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   rL  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_credentialsr>  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_jsonr/  throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   findr
  )r   r-  r  r  r  r  r  rE  requestHeadersrequestBodyfixedr  feedbackr  r  s                  r  handle_errorszcex.handle_errorsw  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	   rA  r   r   rF  rf  r   rk  r>  r   ro  r   r   rn  r  r   r  r  r   r  r4  r  r  r   r  r  r   r  r   r  r  r   r  r  r   r   r  r  r  r  r  r  r.  r   r   floatr   r:  r@  rF  r   rL  r^  r\  r   re  rv  ru  r   rP   r  r  r  r
   r  r  r  r   r  __classcell__)r   s   @r  r'   r'      sT   e# eN ') 4:Z 4:l9$ 98 9v $&  ($v,  (D:4 :F :x !# s ( 02 43 4f 4 04B *1W *17 *1X4  6 2 6:UW ,?3 ,?s ,?# ,?\`af\g ,?\ v  > :>b %Ms %M3 %MY %MN 26DW[df ;H# ;Hc ;HQT ;Hkoptku ;Hz
 
4 
 )+ 3{ 32 "
T 
6 
EX 
 %' 34= 38
T 
g 
 $& 12( 12f) )  AESWfjsu L=S L=# L=S L=`c L=z~  @E  {F L=\ 154VZce S# SS SPS S /3TXac Q Q3 Qc Q 7;2 3  $ 9=R S # $: :L Lv L L\ gksu \.3 \.i \.y \.RW \.`c \.| 37r &s &C &0 /32 ) )< (,$TZ\ ,? ,?C ,?s ,?aefqar ,?\t x ; @8 6:[_hj -Es -E# -EUX -Eost  pA -E^
T 
X 
Q\ 
B:s : [] S % c c an 0 xz 3# 3u 3[^ 3kn 3  L 3B pr 3# 3u 3SV 3cf 3  wD 3*#
t #
x #
= #
J 79 %:# %:^ %:N
h 
R` 
 &eBSW P4# s  c TX `c r  r'   ),ccxt.base.exchanger   ccxt.abstract.cexr   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     sh    ( )  D  D  D  D  D  D  D  * 0 - . ' . ) 4 %z(K zr  