
    im                         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 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Transaction)List)ExchangeError)
BadRequest)	TICK_SIZE)Precisec                       e Zd Z fdZi fdee         fdZdefdZdefdZ	i f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i fdeded	ede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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i fdedef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 )%zaifc                    |                      t          t          |                                           dddg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idg ddd d!d|                     d"          |                     d#          d$id%d&d&d&d&d&d&d&d&d'id(d)d)d)d)d*d)d)d)d+d)d)d,id(d&d&d&d&d-id(d.d.d)d/d/d/d0id%d&d&d&d&d&d1id2i t
          d3t          ii d4d5          S )6Nr   ZaifJPd   1CORSspotTmarginswapFfutureoptioncancelOrdercreateMarketOrdercreateOrderfetchBalancefetchClosedOrdersfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchMarkets)
fetchMarkOHLCVfetchOpenInterestHistoryfetchOpenOrdersfetchOrderBookfetchPremiumIndexOHLCVfetchTickerfetchTradesfetchTradingFeefetchTradingFeeswithdrawzchttps://user-images.githubusercontent.com/1294454/27766927-39ca2ada-5eeb-11e7-972f-1b4199518ca6.jpgrestzhttps://api.zaif.jpzhttps://zaif.jp)zChttps://techbureau-api-document.readthedocs.io/ja/latest/index.htmlzhttps://corp.zaif.jp/api-docsz'https://corp.zaif.jp/api-docs/api_linksz%https://www.npmjs.com/package/zaif.jpz%https://github.com/you21979/node-zaifzhttps://zaif.jp/fee?lang=en)logoapiwwwdocfeestradingz0.0010)
percentagetakermakerget   )zdepth/{pair}zcurrencies/{pair}zcurrencies/allzcurrency_pairs/{pair}zcurrency_pairs/allzlast_price/{pair}zticker/{pair}ztrades/{pair}post   
   2   )active_orderscancel_orderdeposit_historyget_id_infoget_info	get_info2get_personal_infotradetrade_historyr8   withdraw_history)createInvoice
getInvoicegetInvoiceIdsByOrderNumbercancelInvoiceB   !   )get_positionsposition_historyactive_positionscreate_positionchange_positioncancel_position)zgroups/{group_id}zlast_price/{group_id}/{pair}zticker/{group_id}/{pair}ztrades/{group_id}/{pair}zdepth/{group_id}/{pair})publicprivateecapitlapifapizunsupported currency_pair)exactbroad)idname	countries	rateLimitversionhasurlsr>   r;   optionsprecisionMode
exceptions)deep_extendsuperr   describeparse_numberr   r   )self	__class__s    ]/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/async_support/zaif.pyrs   zzaif.describe   s   dD 1 1 : : < < $ 	
 % % t $U t  $T &u #E *5 $U  "5!" #$ #(,1#'"&*/###($) 7  < ~1 )   6   "&!..w77!..s33  ()-.*+12./-.)*)*	 	 )*()+,'($&%&-.!")+$%,-   )*&'67)*	  )+,.,-+-+-+- 	 -.89454534 ]7 7p& 0	 k|?
 |?
 | | |	    returnc                 f   K   |                      |           d{V }|                     |          S )a(  
        :see: https://zaif-api-document.readthedocs.io/ja/latest/PublicAPI.html#id12
        retrieves data on all markets for zaif
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        N)publicGetCurrencyPairsAllparse_markets)ru   paramsmarketss      rw   fetch_marketszzaif.fetch_markets   sC       66v>>>>>>>>, !!'***rx   c                    |                      |d          }|                      |d          }|                    d          \  }}|                     |          }|                     |          }|dz   |z   }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 |d
S )Ncurrency_pairrh   /rg   symbolbasequotesettlebaseIdquoteIdsettleIdtyper   Tr    r!   Fr"   r#   activecontractlinearitem_unit_stepaux_unit_point)amountprice)minmaxitem_unit_minaux_unit_min)leverager   r   cost)
inversecontractSizeexpiryexpiryDatetimestrike
optionType	precisionlimitscreatedinfo)safe_stringsplitsafe_currency_codesafe_numberrt   parse_precision)	ru   marketrg   rh   r   r   r   r   r   s	            rw   parse_marketzzaif.parse_market   s2   fo66//**S//&&v..''00e#0
"0
f0
 D0
 U	0

 d0
 f0
 w0
 0
 F0
 D0
 d0
 E0
 e0
 e0
 d0
  !0
" d#0
$  "**63CDD**4+?+?@P@PQWYi@j@j+k+kll    
  ++FODD 
  ++FNCC 
    $ _0
 0
 0
 0	
rx   c                 ,   |                      |di           }|                      |d          }|d d d}|                      |di           }t          |                                          }t          dt	          |                    D ]w}||         }|                     |          }	|                     ||          }
|                                 }|
|d<   |
|d<   |||v r|                     ||          |d<   |||	<   x|                     |          S )Nry   deposit)r   	timestampdatetimefundsr   freetotal)	
safe_valuelistkeysrangelenr   r   accountsafe_balance)ru   responsebalancesr   resultr   currencyIdsi
currencyIdcodebalancer   s               rw   parse_balancezzaif.parse_balance   s'   ??8Xr:://(I66
 

 '2665::<<((q#k**++ 
	# 
	#A$QJ**:66D&&uj99GllnnG%GFO&GG"(('+'7'7'L'LGG$"F4LL  (((rx   c                    K   |                                   d{V  |                     |           d{V }|                     |          S )aw  
        :see: https://zaif-api-document.readthedocs.io/ja/latest/TradingAPI.html#id10
        query for balance and get the amount of funds available for trading or funds locked in orders
        :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privatePostGetInfor   )ru   r}   r   s      rw   fetch_balancezzaif.fetch_balance  se       !!!!!!!!!0088888888!!(+++rx   Nr   limitc                   K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     ||d                   S )aH  
        :see: https://zaif-api-document.readthedocs.io/ja/latest/PublicAPI.html#id34
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :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
        Npairrg   r   )r   r   publicGetDepthPairextendparse_order_book)ru   r   r   r}   r   requestr   s          rw   fetch_order_bookzzaif.fetch_order_book  s       !!!!!!!!!V$$F4L
 00Wf1M1MNNNNNNNN$$Xvh/?@@@rx   r   c                    |                      d |          }|                     |d          }|                     |d          }t          j        ||          }|                     |d          }|                     i d|dd dd d|                     |d          d|                     |d          d	|                     |d	          d
d d|                     |d          dd d|dd d|d|dd dd dd dd |||d|          S )Nvwapvolumelastr   r   r   highlowbid	bidVolumeask	askVolumeopenclosepreviousClosechangerA   average)
baseVolumequoteVolumer   )safe_symbolr   r   
string_mulsafe_ticker)ru   tickerr   r   r   r   r   r   s           rw   parse_tickerzzaif.parse_ticker  s    !!$////%%fh77
(T::// !
f!
!
 !
 D$$VV44	!

 4##FE22!
 4##FE22!
 !
 4##FE22!
 !
 D!
 D!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ %&)!
 !
 !
* +  	rx   c                   K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     ||          S )a  
        :see: https://zaif-api-document.readthedocs.io/ja/latest/PublicAPI.html#id22
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nr   rg   )r   r   publicGetTickerPairr   r   )ru   r   r}   r   r   r   s         rw   fetch_tickerzzaif.fetch_tickerE  s       !!!!!!!!!V$$F4L
 //GV0L0LMMMMMMMM   000rx   c                    |                      |d          }|dk    rdnd}|                     |d          }|                     |dd          }|                      |d          }|                      |d	          }|                      |d
          }|                     ||d          }	|                     ||||                     |          |	d |d d ||d d d|          S )N
trade_typer   buyselldaterg   tidr   r   r   _)rg   r   r   r   r   r   sideordertakerOrMakerr   r   r   fee)r   safe_timestampsafe_string_2r   
safe_tradeiso8601)
ru   rQ   r   r   r   rg   priceStringamountStringmarketIdr   s
             rw   parse_tradezzaif.parse_trade`  s    |44uuV''v66	tU33&&ug66''x88##E?;;!!(FC88"Y//  " 
  
   	rx   sincec                 H  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }t	          |          }|dk    r|d         }	|	sg }|                     ||||          S )a2  
        :see: https://zaif-api-document.readthedocs.io/ja/latest/PublicAPI.html#id28
        get the list of most recent trades for a particular symbol
        :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   rg   rE   r   )r   r   publicGetTradesPairr   r   parse_trades)
ru   r   r   r   r}   r   r   r   	numTrades
firstTrades
             rw   fetch_tradeszzaif.fetch_trades  s       !!!!!!!!!V$$F4L
 11$++gv2N2NOOOOOOOO MM	>>!!J   65%@@@rx   r   r   r   r   c                   K   |                                   d{V  |dk    rt          | j        dz             |                     |          }|d         |dk    rdnd||d}|                     |                     ||                     d{V }	|                     |	t          |	d	         d
                   d|          S )a  
        :see: https://zaif-api-document.readthedocs.io/ja/latest/MarginTradingAPI.html#id23
        create a trade order
        :param str symbol: unified symbol of the market to create an order in
        :param str type: must be '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   z' createOrder() allows limit orders onlyrg   r   r   r   )r   actionr   r   ry   order_id)r   rg   )r   r   rg   r   privatePostTrader   
safe_orderstr)
ru   r   r   r   r   r   r}   r   r   r   s
             rw   create_orderzzaif.create_order  s       !!!!!!!!!7??*S STTTV$$#D\ $eeE	
 
 ..t{{7F/K/KLLLLLLLLhx(455 
  
   	rx   rg   c                 l   K   d|i}|                      |                     ||                     d{V S )a  
        :see: https://zaif-api-document.readthedocs.io/ja/latest/TradingAPI.html#id37
        cancels an open order
        :param str id: order id
        :param str symbol: not used by zaif cancelOrder()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  N)privatePostCancelOrderr   )ru   rg   r   r}   r   s        rw   rK   zzaif.cancel_order  sJ       
 00Wf1M1MNNNNNNNNNrx   c           	         |                      |d          }|dk    rdn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|          S )Nr   r   r   r   r   r   r   r   r   rg   clientOrderIdr   lastTradeTimestampstatusr   r   r   r   timeInForcepostOnlyr   	stopPricetriggerPricer   filled)	remainingtradesr   r   r   )r   r   r   r  r   )
ru   r   r   r   r   r   r   r   r   rg   s
             rw   parse_orderzzaif.parse_order  s    x00uuV''{;;	##E?;;!!(FC88  00!!%22eT**  
" 
T 
  
 Y//	 

 !$ 
 f 
 f 
 G 
 4 
  
 D 
 U 
  
 D 
 D 
  f! 
" d# 
$ - 
  
  
. /  	rx   c                    K   |                                   d{V  d}i }| |                     |          }|d         |d<   |                     |                     ||                     d{V }|                     |d         |||          S )a$  
        :see: https://zaif-api-document.readthedocs.io/ja/latest/MarginTradingAPI.html#id28
        fetch all unfilled currently open orders
        :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>`
        Nrg   r   ry   )r   r   privatePostActiveOrdersr   parse_ordersru   r   r   r   r}   r   r   r   s           rw   fetch_open_orderszzaif.fetch_open_orders  s       !!!!!!!!!
 [[((F'-d|GO$55dkk'66R6RSSSSSSSS  (!3VUEJJJrx   c                    K   |                                   d{V  d}i }| |                     |          }|d         |d<   |                     |                     ||                     d{V }|                     |d         |||          S )aJ  
        :see: https://zaif-api-document.readthedocs.io/ja/latest/TradingAPI.html#id24
        fetches information on multiple closed orders made by the user
        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nrg   r   ry   )r   r   privatePostTradeHistoryr   r  r  s           rw   fetch_closed_orderszzaif.fetch_closed_orders  s       !!!!!!!!!	
 [[((F'-d|GO$55dkk'66R6RSSSSSSSS  (!3VUEJJJrx   r   c                   K   |                      ||          \  }}|                     |           |                                  d{V  |                     |          }|dk    rt	          | j        dz   |z   dz             |d         ||d}|||d<   |                     |                     ||                     d{V }|                     |d          }	| 	                    |	|          S )	a  
        :see: https://zaif-api-document.readthedocs.io/ja/latest/TradingAPI.html#id41
        make a withdrawal
        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        NJPYz withdraw() does not allow z withdrawalsrg   )currencyr   addressmessagery   )
handle_withdraw_tag_and_paramscheck_addressr   r  r   rg   privatePostWithdrawr   	safe_dictparse_transaction)
ru   r   r   r  tagr}   r  r   r   
returnDatas
             rw   r8   zzaif.withdraw0  s      99#vFFV7###!!!!!!!!!==&&5==*G G$ NQ_ _``` 
 
 ?!$GI//GV0L0LMMMMMMMM" ^^FH55
%%j(;;;rx   r  c                 J   |                      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S )Nr   r   )r   r  rg   txidr   r   networkaddressFromr  	addressTor   r   r  r  updatedtagFromr&  tagTocomment)internalr   r   )safe_currencyr   r   )ru   transactionr  r   feeCosts        rw   r%  zzaif.parse_transaction^  s_    %%dH55//+u55$V, C
$"";55
D$$[&99
 
 	

 t
 4
 t
 
 d
 D
 (
 d
 t
 t
 4
  T!
" t#
$ )
 
 
 	
rx   c                     |                                  t          d          z  }t          |          }t          |d          S )Ni  z.8f)millisecondsr  floatformat)ru   numnonces      rw   custom_noncezzaif.custom_nonce  s9      ""SYY.c

eU###rx   r`   GETc                    | j         d         d         dz   }|dk    r(|d| j        z   dz   |                     ||          z   z  }n|dk    r(|d| j        z   dz   |                     ||          z   z  }n|                                  |dk    r|dz  }n|d	k    r|d	z  }n|d
z  }|                                 }|                     |                     ||d|                    }d| j        |                     | 	                    |          | 	                    | j
                  t          j                  d}||||dS )Nr;   r9   r   r`   zapi/rd   zfapi/rb   rc   tapi)methodr:  z!application/x-www-form-urlencoded)zContent-TypeKeySign)urlr?  bodyheaders)rm   rk   implode_paramscheck_required_credentialsr;  	urlencoder   apiKeyhmacencodesecrethashlibsha512)	ru   pathr;   r?  r}   rD  rC  rB  r:  s	            rw   signz	zaif.sign  sj   iv&,(??6DL(3.1D1DT61R1RRRCCF]]7T\)C/$2E2EdF2S2SSSCC++---g~~wwv%%''E>>$++/ / # #  D
 !D{		$++d"3"3T[[5M5Mw~^^ G
 fdwOOOrx   c
                 N   |d S | j         dz   |z   }
|                     |d          }|S|                     | j        d         ||
           |                     | j        d         ||
           t          |
          |                     |dd          }|st          |
          d S )N errorre   rf   successT)rg   r   throw_exactly_matched_exceptionrp   throw_broadly_matched_exceptionr   	safe_bool)ru   httpCodereasonrB  r?  rD  rC  r   requestHeadersrequestBodyfeedbackrR  rS  s                rw   handle_errorszzaif.handle_errors  s    4 7S=4'  733001I5RZ[[[001I5RZ[[[)))..9d;; 	*)))trx   )N)(__name__
__module____qualname__rs   r   r   r   r   r   r   r   r  r   r   r   r   r   r   r   r   r   r   r   r7  r	   r  r   rK   r
   r  r  r  r8   r   r   r%  r;  rO  r\  __classcell__)rv   s   @rw   r   r      s       } } } } }~ *, + +V + + + +>7
f 7
 7
 7
 7
r) ) ) ) ). *, 	, 	, 	, 	, 	, 	, @DB A AS A AS\ A A A A"& &6 &V & & & &P 68 1 1 1F 1 1 1 16# # #5 # # # #J <@d[] !A !A !AS !A !Abfglbm !A !A !A !AF mqy{   I Y X] fi    8 9=R O OS O# O O O O* * *5 * * * *X 59tZ^gi K Kc K KTW Knrsxny K K K K, 7;\`ik K K K3 KVY Kptuzp{ K K K K8 EIQS ,< ,<3 ,< ,< ,< ,< ,<\+
 +
x +
; +
 +
 +
 +
Z$ $ $
 &eBSW P P P P4      rx   r   ) ccxt.async_support.base.exchanger   ccxt.abstract.zaifr   rL  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   ccxt.base.decimal_to_precisionr   ccxt.base.preciser   r    rx   rw   <module>ri     s   6 5 5 5 5 5 * * * * * *  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J  J       * * * * * * ' ' ' ' ' ' 4 4 4 4 4 4 % % % % % %h
 h
 h
 h
 h
8[ h
 h
 h
 h
 h
rx   