
    ei                         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)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d0dededefdZi fd	edefdZd0d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d0d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de"f
d!Z#d0d"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 )1zaifreturnc                 L   |                      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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d0dd1dd2dd3dd4dd5dd6dd7dd8dd9dd:dddddddd;d<d=d>id?g d@dAdBdCd|                     dD          |                     dE          dFidGdHdHdHdHdHdHdHdHdIidJdKdKdKdKdLdKdKdKdMdKdKdNidJdHdHdHdHdOidJdPdPdKdQdQdQdRidGdHdHdHdHdHdSidTi ddddd ddd dddddUddddddddVd d d dd ddddWd ddXdYdHdYddddZd d[	d d d\d d d\d]t
          d^t          ii d_d`          S )aNr   ZaifJPd   1CORSspotTmarginswapFfutureoptioncancelOrdercloseAllPositionsclosePositioncreateMarketOrdercreateOrdercreateStopLossOrdercreateTakeProfitOrderfetchAllGreeksfetchBalancefetchClosedOrdersfetchCurrenciesfetchFundingHistoryfetchFundingIntervalfetchFundingIntervalsfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchGreeksfetchIndexOHLCVfetchLeverageTiersfetchLongShortRatiofetchLongShortRatioHistoryfetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMarkPricefetchMarkPricesfetchMySettlementHistoryfetchOpenInterestHistoryfetchOpenInterestsfetchOpenOrdersfetchOptionfetchOptionChainfetchOrderBookfetchPositionfetchPositionHistoryfetchPositionModefetchPositionsfetchPositionsForSymbolfetchPositionsHistoryfetchPositionsRiskfetchPremiumIndexOHLCVfetchSettlementHistoryfetchTickerfetchTrades)fetchTradingFeefetchTradingFeesfetchUnderlyingAssetsfetchVolatilityHistorysetMarginMode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_historyrX   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)r   limittriggerr   symbolRequired  i )r   r   daysBackdaysBackCanceled	untilDaysr   r   r   )	sandboxr*   createOrdersfetchMyTrades
fetchOrderrD   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    U/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/async_support/zaif.pyr   zzaif.describe   s`   dD 1 1 : : < <::: $: 	:
 %: %: t: $U:  : $U: t: &u: (: !%: :  $T!:" "5#: :$ &u%:& '':( ():* #E+:, *5-:. $U/:0 u1:2 "53:4 %e5:6 &u7:8 -e9:: +E;:< =:> !%?:@ !%A:B "5C:D +EE: : :F +EG:H %eI:J "4K:L uM:N #EO:P !$Q:R  S:T 'U:V $UW:X !%Y:Z *5[:\ (]:^ %e_:` )%a:b )%c:d te:f tg: :h $)$)).*/!& s: : :x ~1 )   6   "&!..w77!..s33  ()-.*+12./-.)*)*	 	 )*()+,'($&%&-.!")+$%,-   )*&'67)*	  )+,.,-+-+-+- 	 -.89454534 ]7 7p  %&*(,,1,0).+06:#(#("'#(	( ( #($)$(+027/4#()$ $, %)%)"&&*!%#($)*/( ( $(&*!%$*,-%+#($)*/	* 	* #'[. .` ## 
 ## i8 8r ' 0	 YS?
 S?
 S S S	    c                 f   K   |                      |           d{V }|                     |          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
        N)publicGetCurrencyPairsAllparse_markets)r   paramsmarketss      r   fetch_marketszzaif.fetch_markets   sC       66v>>>>>>>>, !!'***r   marketc                    |                      |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_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)r   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
  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	
r   c                 ,   |                      |di           }|                      |d          }|d d d}|                      |di           }t          |                                          }t          dt	          |                    D ]w}||         }|                     |          }	|                     ||          }
|                                 }|
|d<   |
|d<   |||v r|                     ||          |d<   |||	<   x|                     |          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_balanceC  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  (((r   c                    K   |                                   d{V  |                     |           d{V }|                     |          S )aq  

        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   )r   r   r   s      r   fetch_balancezzaif.fetch_balanceZ  se       !!!!!!!!!0088888888!!(+++r   Nr   r   c                   K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     ||d                   S )aB  

        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pairr   r   )r   r   publicGetDepthPairextendparse_order_book)r   r   r   r   r   requestr   s          r   fetch_order_bookzzaif.fetch_order_bookg  s       !!!!!!!!!V$$F4L
 00Wf1M1MNNNNNNNN$$Xvh/?@@@r   tickerc                    |                      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)r   r
  r   r   r  r  r  r  s           r   parse_tickerzzaif.parse_tickerz  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#!
$ %&)!
 !
 !
* +  	r   c                   K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     ||          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>`
        Nr  r   )r   r   publicGetTickerPairr  r  )r   r   r   r   r  r
  s         r   fetch_tickerzzaif.fetch_ticker  s       !!!!!!!!!V$$F4L
 //GV0L0LMMMMMMMM   000r   rq   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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   rq   r   r*  r   r   priceStringamountStringmarketIdr   s
             r   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//  " 
  
   	r   sincec                 H  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }t	          |          }|dk    r|d         }	|	sg }|                     ||||          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>`
        Nr  r   re   r   )r   r   publicGetTradesPairr  r   parse_trades)
r   r   r6  r   r   r   r  r   	numTrades
firstTrades
             r   fetch_tradeszzaif.fetch_trades  s       !!!!!!!!!V$$F4L
 11$++gv2N2NOOOOOOOO MM	>>!!J   65%@@@r   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  

        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>`
        Nr   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TV$$#D\ $eeE	
 
 ..t{{7F/K/KLLLLLLLLhx(455 
  
   	r   r   c                    K   d|i}|                      |                     ||                     d{V }|                     |d          }|                     |          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?  Nr   )privatePostCancelOrderr  	safe_dictparse_order)r   r   r   r   r  r   datas          r   rk   zzaif.cancel_order'  sr       
 44T[[&5Q5QRRRRRRRR ~~h11%%%r   r+  c                    |                      |d          }|dk    rdn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|          S )Nr>  r  r%  r&  r   r   r)  r   r   r   r?  clientOrderIdr   lastTradeTimestampstatusr  r   r   r   r   postOnlyr*  r   r   filled	remaining)tradesr-  r   r  )r   r.  r  r/  rA  r1  )
r   r+  r   r*  r   r4  r   r   r   r   s
             r   rG  zzaif.parse_orderG  s   . x00uuV''{;;	##E?;;!!(FC88  00!!%22tZ88  
" 
T 
  
 Y//	 

 !$ 
 f 
 f 
 G 
 4 
  
 D 
 U 
 D 
 D 
 f 
  d! 
" # 
$ + 
  
  
, -  	r   c                    K   |                                   d{V  d}i }| |                     |          }|d         |d<   |                     |                     ||                     d{V }|                     |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   r6  r   r   r   r  r   s           r   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Jr   c                    K   |                                   d{V  d}i }| |                     |          }|d         |d<   |                     |                     ||                     d{V }|                     |d         |||          S )aD  

        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  rS  rT  s           r   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Jr   r   addresstagc                   K   |                      ||          \  }}|                     |           |                                  d{V  |                     |          }|dk    rt	          | j        dz   |z   dz             |d         ||d}|||d<   |                     |                     ||                     d{V }|                     |d          }	| 	                    |	|          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>`
        NJPYz withdraw() does not allow z withdrawalsr   )currencyr   rY  messager   )
handle_withdraw_tag_and_paramscheck_addressr   r]  r   r   privatePostWithdrawr  rF  parse_transaction)
r   r   r   rY  rZ  r   r]  r  r   
returnDatas
             r   rX   zzaif.withdraw  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(;;;r   transactionr]  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]  r   txidr   r   networkaddressFromrY  	addressTor   r   r]  rL  updatedtagFromrZ  tagTocomment)internalr-  r   )safe_currencyr   r   )r   rd  r]  r-  feeCosts        r   rb  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#
$ )
 
 
 	
r   c                     |                      |                                 dz            }t          |          }t          |d          S )Nr   z.8f)number_to_stringmillisecondsfloatformat)r   numnonces      r   custom_noncezzaif.custom_nonce  sA    ##D$5$5$7$7$$>??c

eU###r   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[   rY   r   r   zapi/r   zfapi/r   r   tapi)methodrw  z!application/x-www-form-urlencoded)zContent-TypeKeySign)urlr|  bodyheaders)r   r   implode_paramscheck_required_credentialsrx  	urlencoder  apiKeyhmacencodesecrethashlibsha512)	r   pathr[   r|  r   r  r  r  rw  s	            r   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Or   httpCodereasonr  r|  r  r  c
                 N   |d S | j         dz   |z   }
|                     |d          }|S|                     | j        d         ||
           |                     | j        d         ||
           t          |
          |                     |dd          }|st          |
          d S )N errorr   r   successT)r   r   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   	safe_bool)r   r  r  r  r|  r  r  r   requestHeadersrequestBodyfeedbackr  r  s                r   handle_errorszzaif.handle_errors0  s    4 7S=4'  733001I5RZ[[[001I5RZ[[[)))..9d;; 	*)))tr   )N)+__name__
__module____qualname__r   r   r   r	   r   dictr   r   r   r  rB  r   r   r	  r   r  r"  r   r5  r<  r   r   rt  r
   rC  r   rk   r   rG  rU  rX  r   rX   r   rb  rx  r  intr  __classcell__)r   s   @r   r   r      s-       T# T T T T T Tl *, + +V + + + +B7
4 7
F 7
 7
 7
 7
r) ) ) ) ). *, , , , , , , @DB A AS A AS\ A A A A&& &4 & &6 & & & &P 68 1 1 1F 1 1 1 1:# # #v # # # # #J <@d[] #A #A #AS #A #Abfglbm #A #A #A #AJ mqy{   I Y X] fi    < 9=R & &S &# & & & &@5 5 5v 5 5 5 5 5n 59tZ^gi K Kc K KTW Knrsxny K K K K0 7;\`ik K K K3 KVY Kptuzp{ K K K K< QU]_ .< .<3 .< .< .<# .<do .< .< .< .<`+
 +
T +
X +
Q\ +
 +
 +
 +
Z$ $ $
 &eBSW P P P P4c 3 S # X\ dg        r   r   ) ccxt.async_support.base.exchanger   ccxt.abstract.zaifr   r  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     s   6 5 5 5 5 5 * * * * * *  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O       * * * * * * ' ' ' ' ' ' 4 4 4 4 4 4 % % % % % %n n n n n8[ n n n n nr   