
     fp                         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y)    )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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defdZi fd	edefdZd/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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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defd Z!d/d!ed"e"de#fd#Z$d$ Z%d%d&i ddfd'Z&d(e'd)ed*ed+ed,ed-efd.Z( xZ)S )0zaifc                    | j                  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| j	                  d"      | j	                  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    C/var/www/html/py/new-venv/lib/python3.12/site-packages/ccxt/zaif.pyrs   zzaif.describe   sW   dD : < $ 	
 % % t $U t  $T &u #E *5 $U  "5!" #$ #(,1#'"&*/###($) 7< ~1 ) 6  "&!..w7!..s3 ()-.*+12./-.)*)*	 )*()+,'($&%&-.!")+$%,-  )*&'67)*	 )+,.,-+-+-+-	 -.89454534]7p& 0	k|?
 | |	    returnc                 F    | j                  |      }| j                  |      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
        )publicGetCurrencyPairsAllparse_markets)ru   paramsmarketss      rw   fetch_marketszzaif.fetch_markets   s'     008, !!'**rx   marketc                 .   | j                  |d      }| j                  |d      }|j                  d      \  }}| j                  |      }| j                  |      }|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 | j                  |d      | j	                  | j                  | j                  |d                  dd d d| j                  |d      d d| j                  |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   r   rg   rh   r   r   r   r   r   s	            rw   parse_marketzzaif.parse_market   s   fo6/**S/&&v.''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**4+?+?@P@PQWYi@j+kl  
  ++FOD
  ++FNC
  $ _0
 0	
rx   c                    | j                  |di       }| j                  |d      }|d d d}| j                  |di       }t        |j                               }t        dt	        |            D ]d  }||   }| j                  |      }	| j                  ||      }
| j                         }|
|d<   |
|d<   |||v r| j                  ||      |d<   |||	<   f | j                  |      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

 '265::<(q#k*+ 
	#A$QJ**:6D&&uj9GllnG%GFO&GG"('+'7'7'LGG$"F4L
	#   ((rx   c                 f    | j                          | j                  |      }| j                  |      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>`
        )load_marketsprivatePostGetInfor   )ru   r}   r   s      rw   fetch_balancezzaif.fetch_balance  s1     	**62!!(++rx   Nr   limitc                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  ||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
        pairrg   r   )r   r   publicGetDepthPairextendparse_order_book)ru   r   r   r}   r   requestr   s          rw   fetch_order_bookzzaif.fetch_order_book  sc     	V$F4L
 **4;;w+GH$$Xvh/?@@rx   tickerc                    | j                  d |      }| j                  |d      }| j                  |d      }t        j                  ||      }| j                  |d      }| 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|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   r   r   r   r   r   r   r   s           rw   parse_tickerzzaif.parse_ticker  s    !!$//%%fh7
((T:/ !
f!
!
 !
 D$$VV4	!

 4##FE2!
 4##FE2!
 !
 4##FE2!
 !
 D!
 D!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ %&)!
* + 	rx   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  ||      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>`
        r   rg   )r   r   publicGetTickerPairr   r   )ru   r   r}   r   r   r   s         rw   fetch_tickerzzaif.fetch_tickerE  s`     	V$F4L
 ))$++gv*FG   00rx   rQ   c                 r   | j                  |d      }|dk(  rdnd}| j                  |d      }| j                  |dd      }| j                  |d      }| j                  |d	      }| j                  |d
      }| j                  ||d      }	| j	                  |||| j                  |      |	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uV''v6	tU3&&ug6''x8##E?;!!(FC8"Y/  " 
  	rx   sincec                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }t	        |      }|dk(  r	|d   }	|	sg }| j                  ||||      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>`
        r   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
 ++DKK,HI M	>!!J  65%@@rx   r   r   r   r   c                 *   | j                          |dk7  rt        | j                  dz         | j                  |      }|d   |dk(  rdnd||d}| j	                  | j                  ||            }	| j                  |	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 fulfilled, 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>`
        r   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V$#D\ $eE	
 ((Wf)EFhx(45 
  	rx   rg   c                     d|i}| j                  | j                  ||            }| j                  |d      }| j                  |      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  ry   )privatePostCancelOrderr   	safe_dictparse_order)ru   rg   r   r}   r   r   datas          rw   rK   zzaif.cancel_order  sP     
 ..t{{7F/KL ~~h1%%rx   r   c           	         | j                  |d      }|dk(  rdnd}| j                  |d      }| j                  |d      }| j                  ||d      }| j                  |d      }| j                  |d	      }| j                  |d
d      }	| j	                  i d
|	dd d|d| j                  |      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   r  clientOrderIdr   lastTradeTimestampstatusr   r   r   r   timeInForcepostOnlyr   	stopPricetriggerPricer   filled)	remainingtradesr   r   r   )r   r   r   r   r  r   )
ru   r   r   r   r   r   r   r   r   rg   s
             rw   r	  zzaif.parse_order  s   . x0uV''{;	##E?;!!(FC8  0!!%2tZ8  
" 
T 
  
 Y/	 

 !$ 
 f 
 f 
 G 
 4 
  
 D 
 U 
  
 D 
 D 
  f! 
" d# 
$ - 
. / 	rx   c                     | j                          d}i }|| j                  |      }|d   |d<   | j                  | j                  ||            }| j	                  |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  sw     	
 [[(F'-d|GO$//GV0LM  (!3VUEJJrx   c                     | j                          d}i }|| j                  |      }|d   |d<   | j                  | j                  ||            }| j	                  |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_orders0  sw     		
 [[(F'-d|GO$//GV0LM  (!3VUEJJrx   r   addressc                    | j                  ||      \  }}| j                  |       | j                          | j                  |      }|dk(  rt	        | j
                  dz   |z   dz         |d   ||d}|||d<   | j                  | j                  ||            }| j                  |d      }	| j                  |	|      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>`
        JPYz withdraw() does not allow z withdrawalsrg   )currencyr   r  messagery   )
handle_withdraw_tag_and_paramscheck_addressr   r!  r   rg   privatePostWithdrawr   r  parse_transaction)
ru   r   r   r  tagr}   r!  r   r   
returnDatas
             rw   r8   zzaif.withdrawL  s     99#vFV7#==&5=*G G$ NQ_ _`` 
 ?!$GI))$++gv*FG" ^^FH5
%%j(;;rx   transactionr!  c                    | j                  d |      }d }| j                  |d      }|||d   d}i d| j                  |d      d| j                  |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   r)  r!  r   feeCosts        rw   r&  zzaif.parse_transactionz  sD    %%dH5//+u5$V,C
$"";5
D$$[&9
 
 	

 t
 4
 t
 
 d
 D
 (
 d
 t
 t
 4
  T!
" t#
$ )
 	
rx   c                 t    | j                  | j                         dz        }t        |      }t        |d      S )Ni  z.8f)number_to_stringmillisecondsfloatformat)ru   numnonces      rw   custom_noncezzaif.custom_nonce  s6    ##D$5$5$7$$>?c
eU##rx   r`   GETc                 ^   | j                   d   d   dz   }|dk(  r)|d| j                  z   dz   | j                  ||      z   z  }n|dk(  r)|d| j                  z   dz   | j                  ||      z   z  }n| j                          |dk(  r|dz  }n|d	k(  r|d	z  }n|d
z  }| j	                         }| j                  | j                  ||d|            }d| j                  | j                  | j                  |      | 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)urlrA  bodyheaders)rm   rk   implode_paramscheck_required_credentialsr=  	urlencoder   apiKeyhmacencodesecrethashlibsha512)	ru   pathr;   rA  r}   rF  rE  rD  r<  s	            rw   signz	zaif.sign  s7   iiv&,(?6DLL(3.1D1DT61RRRCF]7T\\)C/$2E2EdF2SSSC++-g~wwv%%'E>>$++/ # D
 !D{{		$++d"3T[[5Mw~~^G
 fdwOOrx   httpCodereasonrD  rA  rF  rE  c
                 ,   |y | j                   dz   |z   }
| j                  |d      }|K| j                  | j                  d   ||
       | j	                  | j                  d   ||
       t        |
      | j                  |dd      }|st        |
      y )N errorre   rf   successT)rg   r   throw_exactly_matched_exceptionrp   throw_broadly_matched_exceptionr   	safe_bool)ru   rR  rS  rD  rA  rF  rE  r   requestHeadersrequestBodyfeedbackrV  rW  s                rw   handle_errorszzaif.handle_errors  s     77S=4'  73001I5RZ[001I5RZ[))..9d;))rx   )N)*__name__
__module____qualname__rs   r   r   r   dictr   r   r   r   r  r   r   r   r   r   r   r   r   r   r   r   r9  r	   r  r   rK   r
   r	  r  r  r8   r   r   r&  r=  rQ  intr^  __classcell__)rv   s   @rw   r   r      sd   }~ $& +$v, +>7
4 7
F 7
r) ). $& 	,( 	, :>b As A3 AY A"&4 & &6 &P 02 13 1f 16# #v # #J 6:UW !A3 !As !A# !A\`af\g !AF gksu 3 i y RW `c 8 37r &s &C &<6 6v 6 6p /3TXac K K3 Kc Khlmrhs K, 154VZce K# KS KPS Kjnotju K8 DHPR ,<S ,<% ,<# ,<\+
T +
X +
Q\ +
Z$
 &eBSW P4c 3 S # X\ dg rx   r   )ccxt.base.exchanger   ccxt.abstract.zaifr   rN  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>rm     sG    ( *  J  J  J  J  * ' 4 %D8[ Drx   