
    !:hy                         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y)    )Exchange)ImplicitAPIN)AnyBalancesCurrencyIntMarketNumOrder	OrderBook	OrderSide	OrderTypeStrTickerTradeTransaction)List)ExchangeError)
BadRequest)	TICK_SIZE)Precisec                       e Zd Zdef 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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zaifreturnc                 :   | 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 ddddd ddd ddddd3dddddddd4d d d dd dddd5d dd6d7d&d7dddd8d d9	d d d:d d d:d;t
        d<t        ii d=d>      S )?Nr   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_historyr:   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fapi)IOCFOKPOGTD)
marginModetriggerPricetriggerDirectiontriggerPriceTypestopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyByCostmarketBuyRequiresPriceselfTradePreventioniceberg)rk   limittriggerrt   symbolRequired  i )rk   rz   daysBackdaysBackCanceled	untilDaysr{   rt   r|   )	sandboxr(   createOrdersfetchMyTrades
fetchOrderr3   fetchOrdersr*   
fetchOHLCV)linearinverse)r!   r#   r$   zunsupported currency_pair)exactbroad)idname	countries	rateLimitversionhasurlsr@   r=   optionsfeaturesprecisionMode
exceptions)deep_extendsuperr   describeparse_numberr   r   )self	__class__s    C/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/zaif.pyr   zzaif.describe   s   dD : < $ 	
 % % t $U t  $T &u #E *5 $U  "5!" #$ #(,1#'"&*/###($) 7< ~1 ) 6  "&!..w7!..s3 ()-.*+12./-.)*)*	 )*()+,'($&%&-.!")+$%,-  )*&'67)*	 )+,.,-+-+-+-	 -.89454534]7p  %&*(,,1,0).+06:#(#("'#(	( #($)$(+027/4#()$, %)%)"&&*!%#($)*/( $(&*!%$*,-%+#($)*/	* #'[.` ##
 ##i8r ' 0	]u?
 u u	    c                 F    | j                  |      }| j                  |      S )a$  

        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)r   paramsmarketss      r   fetch_marketszzaif.fetch_markets   s'     008, !!'**r   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_pairr   /r   symbolbasequotesettlebaseIdquoteIdsettleIdtyper!   Tr"   r#   Fr$   r%   activecontractr   item_unit_stepaux_unit_point)amountprice)minmaxitem_unit_minaux_unit_min)ru   r   r   cost)
r   contractSizeexpiryexpiryDatetimestrike
optionType	precisionlimitscreatedinfo)safe_stringsplitsafe_currency_codesafe_numberr   parse_precision)	r   r   r   r   r   r   r   r   r   s	            r   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	
r   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 )Nr   deposit)r   	timestampdatetimefundsr   freetotal)	
safe_valuelistkeysrangelenr   r   accountsafe_balance)r   responsebalancesr   resultr   currencyIdsi
currencyIdcodebalancer   s               r   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
	#   ((r   c                 f    | j                          | j                  |      }| j                  |      S )as  

        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   )r   r   r   s      r   fetch_balancezzaif.fetch_balance<  s1     	**62!!(++r   Nr   rz   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  ||d         S )aD  

        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
        pairr   r   )r   r   publicGetDepthPairextendparse_order_book)r   r   rz   r   r   requestr   s          r   fetch_order_bookzzaif.fetch_order_bookI  sc     	V$F4L
 **4;;w+GH$$Xvh/?@@r   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changerC   average)
baseVolumequoteVolumer   )safe_symbolr   r   
string_mulsafe_ticker)r   r   r   r   r   r   r   r   s           r   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#!
$ %&)!
* + 	r   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  ||      S )a  

        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   r   )r   r   publicGetTickerPairr   r  )r   r   r   r   r   r   s         r   fetch_tickerzzaif.fetch_ticker  s`     	V$F4L
 ))$++gv*FG   00r   rS   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dater   tidr   r   r   _)r   r   r   r   r   r   sideordertakerOrMakerr   r   r   fee)r   safe_timestampsafe_string_2r   
safe_tradeiso8601)
r   rS   r   r  r   r   priceStringamountStringmarketIdr   s
             r   parse_tradezzaif.parse_trade  s     |4uV''v6	tU3&&ug6''x8##E?;!!(FC8"Y/  " 
  	r   sincec                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }t	        |      }|dk(  r	|d   }	|	sg }| j                  ||||      S )a.  

        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   r   rG   r   )r   r   publicGetTradesPairr   r   parse_trades)
r   r   r  rz   r   r   r   r   	numTrades
firstTrades
             r   fetch_tradeszzaif.fetch_trades  s     	V$F4L
 ++DKK,HI M	>!!J  65%@@r   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  

        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>`
        rz   z' createOrder() allows limit orders onlyr   r  r   r   )r   actionr   r   r   order_id)r   r   )r   r   r   r   privatePostTrader   
safe_orderstr)
r   r   r   r  r   r   r   r   r   r   s
             r   create_orderzzaif.create_order  s     	7?*S STTV$#D\ $eE	
 ((Wf)EFhx(45 
  	r   r   c                     d|i}| j                  | j                  ||            }| j                  |d      }| j                  |      S )a  

        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!  r   )privatePostCancelOrderr   	safe_dictparse_order)r   r   r   r   r   r   datas          r   rM   zzaif.cancel_order	  sP     
 ..t{{7F/KL ~~h1%%r   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|      S )Nr   r   r  r  r   r   r  r   r   r   r!  clientOrderIdr   lastTradeTimestampstatusr   r   r   rz   rr   postOnlyr  rl   r   filled	remaining)tradesr  r   r   )r   r  r   r  r#  r  )
r   r  r   r  r   r  r   r   r   r   s
             r   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! 
" # 
$ + 
, - 	r   c                     | j                          d}i }|| j                  |      }|d   |d<   | j                  | j                  ||            }| j	                  |d   |||      S )a   

        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>`
        Nr   r   r   )r   r   privatePostActiveOrdersr   parse_ordersr   r   r  rz   r   r   r   r   s           r   fetch_open_orderszzaif.fetch_open_orders`  sw     	
 [[(F'-d|GO$//GV0LM  (!3VUEJJr   c                     | j                          d}i }|| j                  |      }|d   |d<   | j                  | j                  ||            }| j	                  |d   |||      S )aF  

        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>`
        Nr   r   r   )r   r   privatePostTradeHistoryr   r5  r6  s           r   fetch_closed_orderszzaif.fetch_closed_ordersx  sw     		
 [[(F'-d|GO$//GV0LM  (!3VUEJJr   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  

        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 withdrawalsr   )currencyr   r;  messager   )
handle_withdraw_tag_and_paramscheck_addressr   r>  r   r   privatePostWithdrawr   r(  parse_transaction)
r   r   r   r;  tagr   r>  r   r   
returnDatas
             r   r:   zzaif.withdraw  s     99#vFV7#==&5=*G G$ NQ_ _`` 
 ?!$GI))$++gv*FG" ^^FH5
%%j(;;r   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>  r   txidr   r   networkaddressFromr;  	addressTor   r   r>  r.  updatedtagFromrD  tagTocomment)internalr  r   )safe_currencyr   r   )r   rF  r>  r  feeCosts        r   rC  zzaif.parse_transaction  sD    %%dH5//+u5$V,C
$"";5
D$$[&9
 
 	

 t
 4
 t
 
 d
 D
 (
 d
 t
 t
 4
  T!
" t#
$ )
 	
r   c                 t    | j                  | j                         dz        }t        |      }t        |d      S )Nr}   z.8f)number_to_stringmillisecondsfloatformat)r   numnonces      r   custom_noncezzaif.custom_nonce  s6    ##D$5$5$7$$>?c
eU##r   rb   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=   r;   r   rb   zapi/rf   zfapi/rd   re   tapi)methodrY  z!application/x-www-form-urlencoded)zContent-TypeKeySign)urlr^  bodyheaders)r   r   implode_paramscheck_required_credentialsrZ  	urlencoder   apiKeyhmacencodesecrethashlibsha512)	r   pathr=   r^  r   rc  rb  ra  rY  s	            r   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Or   httpCodereasonra  r^  rc  rb  c
                 ,   |y | j                   dz   |z   }
| j                  |d      }|K| j                  | j                  d   ||
       | j	                  | j                  d   ||
       t        |
      | j                  |dd      }|st        |
      y )N errorr   r   successT)r   r   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   	safe_bool)r   ro  rp  ra  r^  rc  rb  r   requestHeadersrequestBodyfeedbackrs  rt  s                r   handle_errorszzaif.handle_errors  s     77S=4'  73001I5RZ[001I5RZ[))..9d;))r   )N)+__name__
__module____qualname__r   r   r   r	   r   dictr   r   r   r   r$  r   r   r   r   r  r  r   r  r  r   r   rV  r
   r%  r   rM   r   r)  r7  r:  r   r:   r   rC  rZ  rn  intr{  __classcell__)r   s   @r   r   r      sv   v# vp $& +$v, +B7
4 7
F 7
r) ). $& ,( , :>b As A3 AY A&&4 & &6 &P 02 13 1f 1:# #v # #J 6:UW #A3 #As #A# #A\`af\g #AJ gksu 3 i y RW `c < 37r &s &C &@5 5v 5 5n /3TXac K K3 Kc Khlmrhs K0 154VZce K# KS KPS Kjnotju K< DHPR .<S .<% .<# .<Wb .<`+
T +
X +
Q\ +
Z$
 &eBSW P4c 3 S # X\ dg r   r   )ccxt.base.exchanger   ccxt.abstract.zaifr   rk  ccxt.base.typesr   r   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    r   r   <module>r     sG    ( *  O  O  O  O  * ' 4 %P8[ Pr   