
    i                         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 d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZ  G d
 dee          ZdS )    )Exchange)ImplicitAPIN)BalancesCurrencyIntMarketNumOrder	OrderBook	OrderSide	OrderTypeStrTickerTradeTradingFeesTransaction)List)ExchangeError)AuthenticationError)	BadSymbol)	TICK_SIZEc                       e Zd Z fdZdefdZi fdefdZdddi fdededede	e
         fd	Zd%d
ede
fdZdi fdededefdZd%d
edefdZi fdedefdZd%d
edefdZdddi fdededefdZddi fdededede	e         fdZi fdefdZdi fdededededef
dZdi fdedefdZdddi fdededede	e          fdZ!dddi fdededede	e          fdZ"d Z#d%de$de fdZ%d  Z&d!d"i ddfd#Z'd$ Z( xZ)S )&	coincheckc                 d   |                      t          t          |                                           ddddg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	d	ddd	ddd	d	d	d	dd)d*d+d,id-d.d/d0gd1d2g d3ig d4g d5g d6d7d8|                     d9d:d;d<d=d>ddd?          |                     d@dAdBd<dCd>ddd?          |                     dDdEdFd<dGd>ddd?          |                     dHdIdJd<dKd>ddd?          |                     dLdMdBd;dCd=ddd?          dNdOd	d|                     dP          |                     dP          dQit          t          t          dRi dSdT          S )UNr   JPIDi  CORSspotTmarginFswapfutureoption	addMargincancelOrdercloseAllPositionsclosePositioncreateOrdercreateReduceOnlyOrderfetchBalancefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchCrossBorrowRatefetchCrossBorrowRatesfetchDepositsfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLeveragefetchMarginModefetchMarkOHLCVfetchMyTradesfetchOpenInterestHistoryfetchOpenOrdersfetchOrderBookfetchPositionfetchPositionMode)fetchPositionsfetchPositionsRiskfetchPremiumIndexOHLCVfetchTickerfetchTradesfetchTradingFeefetchTradingFeesfetchWithdrawalsreduceMarginsetLeveragesetMarginModesetPositionModewszdhttps://user-images.githubusercontent.com/51840849/87182088-1d6d6380-c2ec-11ea-9c64-8ab9f9b289f5.jpgrestzhttps://coincheck.com/apizhttps://coincheck.comz,https://coincheck.com/documents/exchange/apiz"https://coincheck.com/exchange/feezhttps://coincheck.com/info/fee)logoapiwwwdocfeesget)zexchange/orders/rateorder_bookszrate/{pair}tickertrades)accountszaccounts/balancezaccounts/leverage_balancebank_accountsdeposit_moneyzexchange/orders/openszexchange/orders/transactionsz'exchange/orders/transactions_paginationzexchange/leverage/positionszlending/borrows/matches
send_money	withdraws)	rW   zdeposit_money/{id}/fastzexchange/orderszexchange/transfers/to_leveragez exchange/transfers/from_leveragezlending/borrowszlending/borrows/{id}/repayrY   rZ   )zbank_accounts/{id}zexchange/orders/{id}zwithdraws/{id})rR   postdelete)publicprivatebtc_jpyBTC/JPYBTCJPYbtcjpy)idsymbolbasequotebaseIdquoteIdtyper   etc_jpyETC/JPYETCetcfct_jpyFCT/JPYFCTfctmona_jpyMONA/JPYMONAmonaetc_btcETC/BTC)r`   rm   rq   ru   ry   trading0)	tierBased
percentagemakertaker)zdisabled API Keyzinvalid authentication)exactbroad)re   name	countries	rateLimithasurlsrN   marketsrQ   precisionMode
exceptions)deep_extendsuperr   describesafe_market_structureparse_numberr   r   )self	__class__s    b/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/async_support/coincheck.pyr   zcoincheck.describe   s   i 6 6 ? ? A A000 %0 	0
 %0 %0 U0 t0 $U0  0 t0 (0 0 +E0 )%0  '!0" (#0 0$  %0& &u'0( #E)0* *5+0, $U-0. "5/00 *5102 +E304  506 "5708 !%90:  ;0< +E=0> "4?0@ !$A0B  C0D $UE0 0F #(&+*/###($($( %$!&#(_0 0 0d 7 /E84       
 
 
  5 * *X  55YR[ejuz  GL  Y^  hn  x|  7}  7}  ~  ~55YR[ejuz  GL  Y^  hn  x|  7}  7}  ~  ~  55YR[ejuz  GL  Y^  hn  x|  7}  7}  ~  ~ 66jT^hny~  KQ  ^c  ms  }A  8B  8B  C  C  55YR[ejuz  GL  Y^  hn  x|  7}  7}  ~  ~! 8 !&"&!..s33!..s33	  ' )<.A   cXD
 XD
 X X X	    returnc                    d|i}t          | j                                                  }t          dt	          |                    D ]{}||         }|                     |          }|d         }||v rP|                                 }|dz   }	|                     ||          |d<   |                     ||	          |d<   |||<   ||                     |          S )Ninfor   re   	_reservedfreeused)	list
currencieskeysrangelencurrencyaccountsafe_stringsafe_balance)
r   responseresultcodesicoder   
currencyIdr   reserveds
             r   parse_balancezcoincheck.parse_balance   s    (#T_))++,,q#e**%% 		' 		'A8D}}T**H!$JX%%,,..%3"&"2"28Z"H"H"&"2"28X"F"F&t  (((r   c                    K   |                                   d{V  |                     |           d{V }|                     |          S )az  
        query for balance and get the amount of funds available for trading or funds locked in orders
        :see: https://coincheck.com/documents/exchange/api#order-transactions-pagination
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        N)load_marketsprivateGetAccountsBalancer   )r   paramsr   s      r   fetch_balancezcoincheck.fetch_balance   se       !!!!!!!!!77????????!!(+++r   Nrf   sincelimitc                   K   |                                   d{V  d}||                     |          }|                     |           d{V }|                     |dg           }|                     ||||          }g }	t          dt          |                    D ]3}
|	                    |                     ||
         ddi                     4|	S )a  
        fetch all unfilled currently open orders
        :see: https://coincheck.com/documents/exchange/api#order-opens
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of  open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nordersr   statusopen)	r   marketprivateGetExchangeOrdersOpens
safe_valueparse_ordersr   r   appendextend)r   rf   r   r   r   r   r   	rawOrdersparsedOrdersr   r   s              r   fetch_open_orderszcoincheck.fetch_open_orders   s       !!!!!!!!![[((F;;FCCCCCCCCOOHh;;	((FE5IIq#l++,, 	L 	LAMM$++l1o&7IJJKKKKr   r   c           	      V   |                      |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|          S )Nre   
order_type
created_atpending_amountratepair_clientOrderId	timestampdatetimelastTradeTimestampamount	remainingfilledsiderk   timeInForcepostOnlyr   rf   price	stopPricetriggerPrice)costfeer   averagerU   )r   	parse8601safe_symbol
safe_orderiso8601)r   orderr   re   r   r   r   r   r   r   marketIdrf   s               r   parse_orderzcoincheck.parse_order   s    eT**|44NN4#3#3E<#H#HII	!!%)9::$$U,<==	  //##E622!!(FC88  
" 
T 
  
 Y//	 

 !$ 
 f 
  
 d 
 D 
 D 
 4 
  
 f 
 f 
 U 
  ! 
" D# 
$ - 
  
  
. /  	r   c                   K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     ||d                   S )a9  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: https://coincheck.com/documents/exchange/api#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   re   rf   )r   r   publicGetOrderBooksr   parse_order_book)r   rf   r   r   r   requestr   s          r   fetch_order_bookzcoincheck.fetch_order_book  s       !!!!!!!!!V$$F4L
 11$++gv2N2NOOOOOOOO$$Xvh/?@@@r   c                    |                      d |          }|                     |d          }|                     |d          }|                     i d|d|d|                     |          d|                     |d          d|                     |d          d|                     |d          dd d	|                     |d	          d
d dd dd d|d|dd dd dd dd |                     |d          d |d|          S )Nr   lastrf   r   highlowbid	bidVolumeask	askVolumevwapr   closepreviousClosechanger}   r   volume)
baseVolumequoteVolumer   )r   safe_timestampr   safe_tickerr   )r   rT   r   rf   r   r   s         r   parse_tickerzcoincheck.parse_ticker!  s    !!$//''<<	// !
f!
!
 Y//!
 D$$VV44	!

 4##FE22!
 4##FE22!
 !
 4##FE22!
 !
 D!
 D!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ **68<<)!
 !
 !
* +  	r   c                 <  K   |dk    rt          | j        dz             |                                  d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     ||          S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :see: https://coincheck.com/documents/exchange/api#ticker
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        r`   z$ fetchTicker() supports BTC/JPY onlyNr   re   )r   re   r   r   publicGetTickerr   r   )r   rf   r   r   r   rT   s         r   fetch_tickerzcoincheck.fetch_tickerG  s       YDG&LLMMM!!!!!!!!!V$$F4L
 ++DKK,H,HIIIIIIII   000r   c                    |                      |                     |d                    }|                     |d          }|                     |d          }|                     |d          }|                     ||d          }|d         }|d         }|d         }	d }
d }d }d }d }d }d	|v r|                     |d	          d
k    rd}
n|                     |d	          dk    rd}
|                     |di           }|                     ||          }|                     ||          }|                     |d          |                     |d          d}|                     |d          }|                     |d          }n,|                     |d          }|                     |d          }|                     |||                     |          ||	d |||
||||d|          S )Nr   re   r   r   r   ri   rj   rf   	liquidityTr   Mr~   fundsfee_currencyr   )r   r   r   order_idr   r   )re   r   r   r   rf   rk   r   r   takerOrMakerr   r   r   r   )r   r   safe_marketr   
safe_trader   )r   trader   r   re   priceStringr   ri   rj   rf   r   amountString
costStringr   r   orderIdr   s                    r   parse_tradezcoincheck.parse_traded  s%   > NN4#3#3E<#H#HII	eT**&&uf55##E622!!(FC88!#!
%{33s::&!!%55<<&OOE7B77E++E6::L))%99J ,,UNCC((66 C ##E622D&&uj99GG++E8<<L##E<88DY//"( " 
  
   	r   c                 2  K   |                                   d{V  |                     |          }i }|||d<   |                     |                     ||                     d{V }|                     |dg           }|                     ||||          S )a  
        fetch all trades made by the user
        :see: https://coincheck.com/documents/exchange/api#order-transactions-pagination
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nr   data)r   r   .privateGetExchangeOrdersTransactionsPaginationr   	safe_listparse_trades)	r   rf   r   r   r   r   r   r   transactionss	            r   fetch_my_tradeszcoincheck.fetch_my_trades  s       !!!!!!!!!V$$$GGLLT[[Y`bhMiMijjjjjjjj. ~~h;;  vueDDDr   c                 B  K   |                                   d{V  |                     |          }d|d         i}|||d<   |                     |                     ||                     d{V }|                     |dg           }|                     ||||          S )a&  
        get the list of most recent trades for a particular symbol
        :see: https://coincheck.com/documents/exchange/api#public-trades
        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Nr   re   r   r  )r   r   publicGetTradesr   r	  r
  )	r   rf   r   r   r   r   r   r   r  s	            r   fetch_tradeszcoincheck.fetch_trades  s       !!!!!!!!!V$$F4L
 $GG--dkk'6.J.JKKKKKKKK ~~h33  vue<<<r   c                   K   |                                   d{V  |                     |           d{V }|                     |di           }i }t          dt	          | j                            D ]u}| j        |         }|                     |          }|                     ||d         i           }|||                     |d          |                     |d          ddd	||<   v|S )
aX  
        fetch the trading fees for multiple markets
        :see: https://coincheck.com/documents/exchange/api#account-info
        :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
        Nexchange_feesr   re   	maker_fee	taker_feeTF)r   rf   r~   r   r}   r|   )r   privateGetAccountsr   r   r   symbolsr   safe_number)	r   r   r   rQ   r   r   rf   r   r   s	            r   fetch_trading_feeszcoincheck.fetch_trading_fees  s      !!!!!!!!!0088888888( x"==q#dl++,, 	 	A\!_F[[((F//$tb99C ))#{;;))#{;;"" F6NN r   rk   r   r   r   c                   K   |                                   d{V  |                     |          }d|d         i}|dk    r#|dz   |z   }	|	|d<   |dk    r|	dz   nd}
|||
d	z   <   n||d<   ||d
<   ||d	<   |                     |                     ||                     d{V }|                     |d          }|                     ||d|          S )a  
        create a trade order
        :see: https://coincheck.com/documents/exchange/api#order-new
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float [price]: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   re   r   r   r   buy r   r   )re   r   )r   r   privatePostExchangeOrdersr   r   r   )r   rf   rk   r   r   r   r   r   r   r   prefixr   re   s                r   create_orderzcoincheck.create_order&  s+      !!!!!!!!!V$$F4L
 8d*J$.GL!,0EMMj3&&F)/GFX%&&$(GL!#GFO &GH77GV8T8TUUUUUUUUh-- 
  
   	r   re   c                 l   K   d|i}|                      |                     ||                     d{V S )a}  
        cancels an open order
        :see: https://coincheck.com/documents/exchange/api#order-cancel
        :param str id: order id
        :param str symbol: not used by coincheck cancelOrder()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        re   N)privateDeleteExchangeOrdersIdr   )r   re   rf   r   r   s        r   cancel_orderzcoincheck.cancel_orderG  sJ       "
 77GV8T8TUUUUUUUUUr   r   c                 V  K   |                                   d{V  d}i }| |                     |          }|d         |d<   |||d<   |                     |                     ||                     d{V }|                     |dg           }|                     ||||ddi          S )a  
        fetch all deposits made to an account
        :see: https://coincheck.com/documents/exchange/api#account-deposits
        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nre   r   r   depositsrk   deposit)r   r   privateGetDepositMoneyr   r	  parse_transactions	r   r   r   r   r   r   r   r   r  s	            r   fetch_depositszcoincheck.fetch_depositsU  s       !!!!!!!!!}}T**H"*4.GJ$GG44T[[&5Q5QRRRRRRRR0 ~~h
B77&&tXuefiEXYYYr   c                 @  K   |                                   d{V  d}||                     |          }i }|||d<   |                     |                     ||                     d{V }|                     |dg           }|                     ||||ddi          S )a  
        fetch all withdrawals made from an account
        :see: https://coincheck.com/documents/exchange/api#withdraws
        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr   r  rk   
withdrawal)r   r   privateGetWithdrawsr   r	  r%  r&  s	            r   fetch_withdrawalszcoincheck.fetch_withdrawals  s       !!!!!!!!!}}T**H$GG11$++gv2N2NOOOOOOOO, ~~h33&&tXueflE[\\\r   c                 B    ddddddd}|                      |||          S )Npendingokcanceled)r-  
processingfinishedr/  	confirmedreceived)r   )r   r   statusess      r   parse_transaction_statusz"coincheck.parse_transaction_status  s<     !#""	
 	
 &&999r   r   c                    |                      |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S )Nre   r   addressr   r   r   confirmed_atr   )r   r   r   txidr   r   network	addressToaddressFromtagtagTotagFromrk   updated)commentinternalr   )r   r   r  safe_currency_coder5  r   )r   transactionr   re   r   r7  r   r   r   r   r@  r   feeCosts                r   parse_transactionzcoincheck.parse_transaction  s   6 k400NN4#3#3K#N#NOO	"";	::!!+x88%%k:>>
&&z8<<..t/?/?X/V/VWW..!1!1+~!N!NOO"";66  C
K
"
 D
 	

 Y//
 t
 w
 
 4
 4
 T
 t
 D
 f
 
  f!
" w#
$ )
 
 
 	
r   c                 *    |                                  S N)milliseconds)r   s    r   noncezcoincheck.nonce  s      """r   r]   GETc           	         | j         d         d         dz   |                     ||          z   }|                     ||                     |                    }|dk    r|r|d|                     |          z   z  }n|                                  t          |                                           }	d}
|dk    r1|r.|d|                     |                     |                    z   z  }n,|r*|                     |                     |                    }|}
|	|z   |
z   }d| j	        |	| 
                    |                     |          |                     | j                  t          j                  d	}||||d
S )NrN   rL   /r]   ?r  rK  z!application/x-www-form-urlencoded)zContent-Typez
ACCESS-KEYzACCESS-NONCEzACCESS-SIGNATURE)urlmethodbodyheaders)r   implode_paramsomitextract_params	urlencodecheck_required_credentialsstrrJ  keysortapiKeyhmacencodesecrethashlibsha256)r   pathrN   rP  r   rR  rQ  rO  queryrJ  queryStringauths               r   signzcoincheck.sign  su   iv&,t/B/B4/P/PP		&$"5"5d";";<<(?? 3sT^^E2222++---

%%EK E3U0C0C!D!DDDC '>>$,,u*=*=>>D"&K3;,D C"k %$(IIdkk$.?.?T[AYAY[b[i$j$j	 G fdwOOOr   c
                    |d S |                      |dd          }
|
s|                     |d          }| j        dz   |                     |          z   }|                     | j        d         ||           |                     | j        d         ||           t          | j        dz   |                     |          z             d S )NsuccessTerror r   r   )	safe_boolr   re   jsonthrow_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   )r   httpCodereasonrO  rP  rR  rQ  r   requestHeadersrequestBodyrf  rg  feedbacks                r   handle_errorszcoincheck.handle_errors  s    4
 ..9d;; 	E$$Xw77Ew}tyy':'::H001I5RZ[[[001I4QYZZZ#		(0C0C CDDDtr   rH  )*__name__
__module____qualname__r   r   r   r   r   r   r   r
   r   r   r   rX  r   r   r   r   r   r   r  r  r  r   r  r   r   floatr	   r  r   r   r'  r+  r5  r   rF  rJ  rd  rr  __classcell__)r   s   @r   r   r      s       Y Y Y Y Yv) ) ) ) ) *, 	, 	, 	, 	, 	, 	, 59tZ^gi  c  TW nrsxny    ./ / /5 / / / /b @DB A AS A AS\ A A A A"$ $6 $V $ $ $ $L 68 1 1 1F 1 1 1 1:L L L5 L L L L\ 37TX\eg 'E 'EC 'Es 'ERU 'E 'E 'E 'ER <@d[] = = =S = =bfglbm = = = => /1 * *[ * * * *X mqy{   I Y X] fi    B 9=R V VS V# V V V V 04$UYbd +Z +Z +ZC +Zs +Zimnyiz +Z +Z +Z +ZZ 37TX\eg (] (]C (]s (]RU (]lpq|l} (] (] (] (]T: : :?
 ?
x ?
; ?
 ?
 ?
 ?
B# # # &eBSW P P P P4      r   r   ) ccxt.async_support.base.exchanger   ccxt.abstract.coincheckr   r^  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   r   ccxt.base.decimal_to_precisionr   r    r   r   <module>r     s   6 5 5 5 5 5 / / / / / /  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W       * * * * * * 0 0 0 0 0 0 & & & & & & 4 4 4 4 4 4T T T T T+ T T T T Tr   