
    i>                       d dl mZ d dlm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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 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  d dl!m"Z" d dl#m$Z$  G d dee          Z%dS )    )Exchange)ImplicitAPI)BalancesCurrencyIntMarketNumOrder	OrderBook	OrderSide	OrderTypeStrStringsTickerTickersTradeTradingFeeInterfaceTransaction)List)ExchangeError)AuthenticationError)PermissionDenied)ArgumentsRequired)
BadRequest)InsufficientFunds)AddressPending)InvalidOrder)OrderNotFound)	TICK_SIZE)Precisec                       e Zd Z fdZi fdefdZi fdefdZi fdefdZi fde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di fdedefdZdi fdeded	efdZd=de
d	efdZdi f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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i fdede"de#d e$d!e%f
d"Z&di fdede'fd#Z(dddi fde'deded	e	e)         fd$Z*di fdede'fd%Z+dddi fde'deded	e	e)         fd&Z,di fdede'fd'Z-d( Z.d=d)e/d	e)fd*Z0d+ Z1d=de
d	e2fd,Z3dddi fde'dedefd-Z4dddi fde'deded	e	e2         fd.Z5dddi fde'deded	e	e2         fd/Z6dddi fde'dedefd0Z7di fdede'fd1Z8di fd2e	e         fd3Z9d=d)e/fd4Z:i fdefd5Z;i fdefd6Z<di fded e$fd7Z=d8 Z>d9d:i ddfd;Z?d< Z@ xZAS )>upbitc                 @   |                      t          t          |                                           i ddddddg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d&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dddddddddddddddd1d2d3d3d3d3d3d3d3d3d4d5d6d7d8d9d:d;d<d<d=d>d?d@dAdBdCg dDig dEg dFdGgdHd=dIdd|                     dJ          |                     dJ          dKddi i dLdMdNt
          dOt          t          t          dPt          t          t          t          t          t          t          t          t          t          dQ
dRdSddTdTdUdVidWdXdYdZi          S )[Nidr"   nameUpbit	countriesKRversionv1	rateLimit  proThasCORSspotmarginswapFfutureoptioncancelOrdercreateDepositAddresscreateMarketBuyOrderWithCostcreateMarketOrdercreateMarketOrderWithCostcreateMarketSellOrderWithCostcreateOrderfetchBalancefetchCanceledOrdersfetchClosedOrdersfetchDepositfetchDepositAddressfetchDepositAddressesfetchDepositsfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchMarginModefetchMarketsfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenInterestHistoryfetchOpenOrders
fetchOrderfetchOrderBook)fetchOrderBooksfetchOrdersfetchPositionModefetchPremiumIndexOHLCVfetchTickerfetchTickersfetchTradesfetchTradingFeefetchTradingFeesfetchTransactionsfetchWithdrawalfetchWithdrawalstransferwithdraw
timeframesminutesdaysweeksmonths)1m3m5m10m15m30m1h4h1d1w1Mhostnamezapi.upbit.comurlszchttps://user-images.githubusercontent.com/1294454/49245610-eeaabe00-f423-11e8-9cba-4b0aed794799.jpgzhttps://{hostname})publicprivatezhttps://upbit.comzKhttps://docs.upbit.com/docs/%EC%9A%94%EC%B2%AD-%EC%88%98-%EC%A0%9C%ED%95%9Cz&https://upbit.com/service_center/guide)logoapiwwwdocfeesrt   get)z
market/allzcandles/{timeframe}zcandles/{timeframe}/{unit}zcandles/minutes/{unit}zcandles/minutes/1zcandles/minutes/3zcandles/minutes/5zcandles/minutes/10zcandles/minutes/15zcandles/minutes/30zcandles/minutes/60zcandles/minutes/240zcandles/dayszcandles/weekszcandles/monthsztrades/ticksticker	orderbook)accountszorders/chanceorderorders	withdrawsr^   zwithdraws/chancedepositsdepositzdeposits/coin_addresseszdeposits/coin_address)r}   zwithdraws/coinzwithdraws/krwzdeposits/generate_coin_addressr|   )rx   postdeleterw   z0.0025)	tierBased
percentagemakertaker)r   r   r^   r   )tradingfundingprecisionMode
exceptions)zThis key has expired.z?Missing request parameter error. Check the required parameters!z1side is missing, side does not have a valid value)
thirdparty_agreement_requiredout_of_scopeorder_not_foundinsufficient_fundsinvalid_access_keyjwt_verificationcreate_ask_errorcreate_bid_errorvolume_too_largeinvalid_funds)exactbroadoptionsi   KRWgMb@?)!createMarketBuyOrderRequiresPricefetchTickersMaxLengthfetchOrderBooksMaxLengthtradingFeesByQuoteCurrencycommonCurrenciesTONzTokamak Network)deep_extendsuperr"   describeparse_numberr   r   r   r   r   r   r   r   )self	__class__s    P/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/upbit.pyr   zupbit.describe   sm   eT 2 2 ; ; = = o@
'o@
Go@
 $o@
 t	o@

 o@
 4o@
  111 $1 	1
 %1 %1 t1 '1 /1 $T1 ,U1 01 t1 1 &t1  $T!1" #1 1$ &t%1& ('1(  )1* &u+1, #E-1. *5/10 $U112 "5314 "5516 718 !%91:  ;1< d=1> +E?1@ "4A1B dC1D !$E1 1F $($%**/# $##'$)%*#'$(! a1 1 1o@
t     uo@
N Oo@
P }23  +d@	 	Qo@
d    .      ) // /eo@
D !&"&!..x88!..x88	  "'"' "!	  Eo@
` Yao@
b -@WaIU  6F$4'4*;*=(;(5(5(4%1  co@
H 59)-,06/	 Io@
X (!Yo@
 o o o	    codec                     |                                   |                     |          }|                     |d         |          S Nr$   )load_marketscurrencyfetch_currency_by_id)r   r   paramsr   s       r   fetch_currencyzupbit.fetch_currency   sA     	==&&(($@@@r   r$   c                    d|i}|                      |                     ||                    }|                     |di           }|                     |di           }|                     |di           }|                     |d          }|                     |d          }	|                     |d          }
|                     |d          }d}||sd	}n|	d
k    rd	}n|
|
rd	}n||rd	}|                     |d          }|                     |d|          }|                     |d|          }d }t	          j        |d          r|}n|}|                     |d          }|                     |          }||||||                     |d          d d|                     |d          |                     |          didS )Nr   member_levelwithdraw_limitcan_withdrawwallet_statewallet_lockedlockedTFworkingonetimedailyremaining_daily0r   withdraw_feer^   minimumminmax)infor$   r   r%   activefee	precisionlimits)	privateGetWithdrawsChanceextend
safe_valuesafe_stringr    	string_gtsafe_currency_codesafe_numberr   )r   r$   r   requestresponse
memberInfocurrencyInfowithdrawLimitscanWithdrawwalletStatewalletLockedr   r   maxOnetimeWithdrawalmaxDailyWithdrawalremainingDailyWithdrawalmaxWithdrawLimit
currencyIdr   s                      r   r   zupbit.fetch_currency_by_id   s    
 11$++gv2N2NOON __X~rBB
xR@@3CRHHoonnEE&&|^DDz?CCX66#[#FFI%%FF&L&FF f F#//	JJ!--ngG[\\#'#3#3NDUWi#j#j 5s;; 	271%%lF;;
&&z22##L.AA++NIFF,,-=>> 
 
 	
r   symbolc                     |                                   |                     |          }|                     |d         |          S r   )r   marketfetch_market_by_id)r   r   r   r   s       r   fetch_marketzupbit.fetch_market)  sA     	V$$&&vd|V<<<r   c                 8   d|i}|                      |                     ||                    }|                     |d          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }	|                     |d          }
|                     |	          }|                     |
          }|                     |d          }|                     |d          }|                     |d          }|                     t          j        ||                    }|                     i d|d	|d
z   |z   d|d|dd d|	d|
dd ddddddddddddd|dk    ddd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   bidaskr$   r   statebid_feeask_feer   /basequotesettlebaseIdquoteIdsettleIdtyper0   Tr1   Fr2   r3   r4   r   contractlinear1e-8)amountpricer   	min_total	max_total)leverager   r   costr   )
inverser   r   contractSizeexpiryexpiryDatetimestrike
optionTyper   r   )
privateGetOrdersChancer   r   r   r   r   r    
string_maxsafe_market_structurer   )r   r$   r   r   r   
marketInfor   r   marketIdr   r   r   r   r   bidFeeaskFeer   s                    r   r   zupbit.fetch_market_by_id0  s    b
 ..t{{7F/K/KLLB __Xx88
ooj%00ooj%00##J55!!#z22""3
33&&v..''00  W55!!(I66!!(I66 266 B BCC)) 1+
(1+
dSj5(1+
 D1+
 U	1+

 d1+
 f1+
 w1+
 1+
 F1+
 D1+
 e1+
 E1+
 e1+
 e1+
 u(1+
  !1+
" d#1+
$  "++F33**622    
  ++C== 
   
  ++C==++JDD  !# =1+
 1+
 1+
 1 1 1	r   returnc                 V    |                      |          }|                     |          S )a<  
        :see: https://docs.upbit.com/reference/%EB%A7%88%EC%BC%93-%EC%BD%94%EB%93%9C-%EC%A1%B0%ED%9A%8C
        retrieves data on all markets for upbit
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        )publicGetMarketAllparse_marketsr   r   r   s      r   fetch_marketszupbit.fetch_markets  s-     **622 !!(+++r   c                    |                      |d          }|                    d          \  }}|                     |          }|                     |          }|                     i d|d|dz   |z   d|d|d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        d         d                   |                     | j        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          S ) Nr   -r$   r   r   r   r   r   r   r   r   r   r0   Tr1   Fr2   r3   r4   r   r   r   r   r   r   r   r   )r   r   r   )r   r   r   r   )r   r   r   r   r   r   r   r   r   r   createdr   )r   splitr   r   r   r   rw   r   )r   r   r$   r   r   r   r   s          r   parse_marketzupbit.parse_market  sD   fh//((3--&&v..''00)) 2+
"2+
dSj5(2+
 D2+
 U	2+

 d2+
 f2+
 w2+
 2+
 F2+
 D2+
 e2+
 E2+
 e2+
 e2+
 d2+
  !2+
" d#2+
$ %%dl3O&PRWY]YbclYmnuYvww%%dl3O&PRWY]YbclYmnuYvww "**622++F33    
   
   
    $ c2+
 2+
 2+
 2 2 2	r   c                 t   |d d d}t          dt          |                    D ]}||         }|                     |d          }|                     |          }|                                 }|                     |d          |d<   |                     |d          |d<   |||<   |                     |          S )N)r   	timestampdatetimer   r   balancefreer   used)rangelenr   r   accountsafe_balance)r   r   resultir  r   r   r  s           r   parse_balancezupbit.parse_balance  s    
 

 q#h--(( 	# 	#AqkG))':>>J**:66DllnnG"..w	BBGFO"..wAAGFO"F4LL  (((r   c                 ~    |                                   |                     |          }|                     |          S )a  
        :see: https://docs.upbit.com/reference/%EC%A0%84%EC%B2%B4-%EA%B3%84%EC%A2%8C-%EC%A1%B0%ED%9A%8C
        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>`
        )r   privateGetAccountsr  r  s      r   fetch_balancezupbit.fetch_balance  s?     	**622 !!(+++r   Nsymbolslimitc           
      $   |                                   d}|d                    | j                  }t          |          | j        d         k    r|t          | j                  }t          | j        dz   t          |          z   dz   t          t          |                    z   dz   t          | j        d                   z   dz             n*|                     |          }d                    |          }d|i}| 	                    | 
                    ||                    }i }t          d	t          |                    D ]}	||	         }
|                     |
d
          }|                     |dd          }|                     |
d          }||                     |                     |
d         dd          d	d          |                     |                     |
d         dd          d	          ||                     |          dd||<   |S )a|  
        :see: https://docs.upbit.com/reference/%ED%98%B8%EA%B0%80-%EC%A0%95%EB%B3%B4-%EC%A1%B0%ED%9A%8C
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data for multiple markets
        :param str[]|None symbols: list of unified market symbols, all symbols fetched if None, default is None
        :param int [limit]: not used by upbit fetchOrderBooks()
        :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 symbol
        N,r   z fetchOrderBooks() has z	 symbols(z& characters) exceeding max URL length(zd characters), you are required to specify a list of symbols in the first argument to fetchOrderBooksmarketsr   r   r	  r  orderbook_units	bid_pricebid_sizeT	ask_priceask_size)r   bidsasksr  r  nonce)r   joinidsr  r   r   r$   str
market_idspublicGetOrderbookr   r  r   safe_symbolsafe_integersort_byparse_bids_asksiso8601)r   r  r  r   r+  numIdsr   r   r  r  rz   r   r   r  s                 r   fetch_order_bookszupbit.fetch_order_books
  sE    	?((48$$C3xx$,'ABBBTX#DG.G$G#f++$UXc$cfijmnqjrjrfsfs$s  w_  %_  be  fj  fr  sM  fN  bO  bO  %O  Rx  %x  y  y  y C //'**C((3--Cs
 **4;;w+G+GHH: q#h--(( 	 	A I''	8<<H%%hc::F)))[AAI T%9%9)DU:VXceo%p%prsuyzzT%9%9)DU:VXceo%p%prstt& LL33 F6NN r   c                 ^    |                      |g||          }|                     ||          S )a[  
        :see: https://docs.upbit.com/reference/%ED%98%B8%EA%B0%80-%EC%A0%95%EB%B3%B4-%EC%A1%B0%ED%9A%8C
        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
        )r5  r   )r   r   r  r   
orderbookss        r   fetch_order_bookzupbit.fetch_order_bookN  s1     ++VHeVDD
z6222r   r   c                    |                      |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|          S ) Ntrade_timestampr   r   r	  trade_pricer   r  r  high
high_pricelow	low_pricer   	bidVolumer   	askVolumevwapopenopening_pricecloselastpreviousCloseprev_closing_pricechangesigned_change_pricer   signed_change_rateaverageacc_trade_volume_24hacc_trade_price_24h)
baseVolumequoteVolumer   )r0  safe_string_2safe_marketr   safe_tickerr3  )r   ry   r   r  r   rF  s         r   parse_tickerzupbit.parse_tickerZ  s   : %%f.?@@	%%fh??!!(FC8866 !
fX&!
!
 Y//!
 D$$V\::	!

 4##FK88!
 4!
 !
 4!
 !
 D!
 D$$V_==!
 T!
 D!
 T--f6JKK!
 d&&v/DEE!
  $**63GHH!!
" t#!
$ **63IJJ++F4IJJ)!
 !
 !
* +  	r   c                    |                                   |                     |          }d}|wd                    | j                  }t	          |          | j        d         k    r>t	          | j                  }t          | j        dz   t          |          z   dz             n*| 	                    |          }d                    |          }d|i}| 
                    |                     ||                    }i }t          dt	          |                    D ]*}|                     ||                   }	|	d         }
|	||
<   +|                     |d|          S )	a5  
        :see: https://docs.upbit.com/reference/ticker%ED%98%84%EC%9E%AC%EA%B0%80-%EC%A0%95%EB%B3%B4
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nr   r   z fetchTickers() has zv symbols exceeding max URL length, you are required to specify a list of symbols in the first argument to fetchTickersr!  r   r   )r   market_symbolsr*  r+  r  r   r   r$   r,  r-  publicGetTickerr   r  rT  filter_by_array_tickers)r   r  r   r+  r4  r   r   r  try   r   s              r   fetch_tickerszupbit.fetch_tickers  sd    	%%g..?((48$$C3xx$,'>???TX#DG.D$Ds6{{$R  VN  %N  O  O  O @ //'**C((3--Cs
 ''GV(D(DEE: q#h--(( 	$ 	$A&&x{33FH%F#F6NN++FHgFFFr   c                 \    |                      |g|          }|                     ||          S )a  
        :see: https://docs.upbit.com/reference/ticker%ED%98%84%EC%9E%AC%EA%B0%80-%EC%A0%95%EB%B3%B4
        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>`
        )rZ  r   )r   r   r   tickerss       r   fetch_tickerzupbit.fetch_ticker  s/     $$fXv66w///r   c                    |                      |dd          }d }|                     |d          }|)|                     |                     |d                    }d }|                     |dd          }|dk    rd}n|d	k    rd
}|                     |d          }|                      |dd          }	|                      |dd          }
|                      |dd          }|                     ||d          }d }|                     ||dz             }||d         |d}|                     |||||                     |          |d         d |d |	|
||d|          S )Nsequential_iduuidr  
created_atask_bidsider   sellr   buyfundsr;  r   trade_volumevolumer   r   r	  _feer   r   r   r   )r$   r   r|   r  r  r   r   rc  takerOrMakerr   r   r   r   )rQ  r0  	parse8601r   safe_string_lower_2rR  
safe_trader3  )r   trader   r$   orderIdr  rc  askOrBidr   r   r   r   r   feeCosts                 r   parse_tradezupbit.parse_trade  s   : ??%%e[99	t'7'7|'L'LMMI++E9fEEuDDDw//""5-AA##E>8DD%%eXv>>!!(FC88""5(V*;<<"7O C "Y//X&  
  
   	r   sincec                     |                                   |                     |          }|d}|d         |d}|                     |                     ||                    }|                     ||||          S )aE  
        :see: https://docs.upbit.com/reference/%EC%B5%9C%EA%B7%BC-%EC%B2%B4%EA%B2%B0-%EB%82%B4%EC%97%AD
        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>`
        N   r$   )r   count)r   r   publicGetTradesTicksr   parse_trades)r   r   rt  r  r   r   r   r   s           r   fetch_tradeszupbit.fetch_trades  s     	V$$=ETl
 
 ,,T[[&-I-IJJ.   65%@@@r   c                    |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |d          }|                     |d          }t          j        ||          }|                     |d          }	|                     |d          }
t          j        |	|
          }|||                     |          |                     |          ddd	S )
ax  
        :see: https://docs.upbit.com/reference/%EC%A3%BC%EB%AC%B8-%EA%B0%80%EB%8A%A5-%EC%A0%95%EB%B3%B4
        fetch the trading fees for a market
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
        r   r$   r   r   maker_ask_feemaker_bid_feeTF)r   r   r   r   r   r   )r   r   r   r   r   r    r   r   )r   r   r   r   r   r   r  r   r   makerAskFeemakerBidFeer   s               r   fetch_trading_feezupbit.fetch_trading_feeG  s    	V$$fTl
 ..t{{7F/K/KLLF !!(I66!!(I66"6622&&xAA&&xAA";<<&&u--&&u--
 
 	
r   c           	      (   |                      |                     |d                    |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS )Ncandle_date_time_utcrD  r=  r?  r;  candle_acc_trade_volume)rl  r   r   )r   ohlcvr   s      r   parse_ohlcvzupbit.parse_ohlcv  s    " NN4++E3IJJKKUO44UL11UK00UM22U$=>>
 	
r   rd   c                 n   |                                   |                     |          }|                     |          }|                     | j        ||          }|d}|d         ||d}	d}
|2|                     |                     |||z  dz                      |	d<   |dk    rNt          t          |dz                      }||	d	<   | 	                    | 
                    |	|                    }
n)|                     | 
                    |	|                    }
|                     |
||||          S )
a  
        :see: https://docs.upbit.com/reference/%EB%B6%84minute-%EC%BA%94%EB%93%A4-1
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Nrv  r$   )r   	timeframerw  r,   tor`   <   unit)r   r   parse_timeframer   r_   r3  sumintroundpublicGetCandlesTimeframeUnitr   publicGetCandlesTimeframeparse_ohlcvs)r   r   r  rt  r  r   r   timeframePeriodtimeframeValuer   r   
numMinutess               r   fetch_ohlcvzupbit.fetch_ohlcv  sA    	V$$..y99))$/9iPP=ETl'
 

  LL%59PSW9W)X)XYYGDMY&&U?R#78899J(GFO99$++gv:V:VWWHH55dkk'66R6RSSH>   69eUKKKr   r   rc  r   r   c                    |                                   |                     |          }d}|dk    rd}n |dk    rd}nt          | j        dz             |d         |d}	|d	k    r|                     ||          |	d
<   |dk    r|dk    rd}
d}|                     |ddd          \  }}|                     |d          }|                     |d          }||                     ||          }
n|ro|t          | j        dz             | 	                    |          }| 	                    |          }t          j        ||          }|                     ||          }
n|                     ||          }
d
|	d<   |
|	d
<   n||	d<   |                     ||          |	d<   |                     |dd          }|||	d<   |dk    r4|                     |dd          }|                     |d          }|||	d<   |                     |ddg          }|                     |                     |	|                    }|                     |          S )a  
        create a trade order
        :see: https://docs.upbit.com/reference/%EC%A3%BC%EB%AC%B8%ED%95%98%EA%B8%B0
        :see: https://global-docs.upbit.com/reference/order
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much you want to trade in units of the 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
        :param float [params.cost]: for market buy orders, the quote quantity that can be used alternative for the amount
        :param str [params.timeInForce]: 'IOC' or 'FOK'
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nre  r   rd  r   z, createOrder() allows buy or sell side only!r$   )r   rc  r  r   r   Tr;   r   r   a	   createOrder() requires the price argument for market buy orders to calculate the total cost to spend(amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to False and pass the cost to spend(quote quantity) in the amount argumentord_typerh  clientOrderId
identifiertimeInForcetime_in_force)r   r   r   r$   price_to_precisionhandle_option_and_paramsr   omitcost_to_precisionnumber_to_stringr    
string_mulamount_to_precisionrQ  rm  privatePostOrdersr   parse_order)r   r   r   rc  r   r   r   r   	orderSider   quoteAmountr   r   amountStringpriceStringcostRequestr  r  r   s                      r   create_orderzupbit.create_order  s    	V$$	5==IIV^^IItw)WWXXXTl
 
 7??#66vuEEGGH45==K04-8<8U8UV\^k  nQ  SW  9X  9X5-v##FF33DYYvv..F"44VTBB2 	E=&tw  2}  (}  ~  ~  ~#'#8#8#@#@L"&"7"7">">K")"4\;"O"OK"&"8"8"M"MKK"44VVDD")GJ*GG"&GJ $ 8 8 H HGH**6?LQQ$$1GL!8226=/ZZKYYv}55F&+6(6O\#BCC))$++gv*F*FGG* )))r   c                     |                                   d|i}|                     |                     ||                    }|                     |          S )a  
        :see: https://docs.upbit.com/reference/%EC%A3%BC%EB%AC%B8-%EC%B7%A8%EC%86%8C
        cancels an open order
        :param str id: order id
        :param str symbol: not used by upbit 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   privateDeleteOrderr   r  r   r$   r   r   r   r   s         r   cancel_orderzupbit.cancel_order5  s[     	B
 **4;;w+G+GHH( )))r   c                    |                                   i }d}| |                     |          }|d         |d<   |||d<   |                     |                     ||                    }|                     ||||          S )a8  
        :see: https://docs.upbit.com/reference/%EC%9E%85%EA%B8%88-%EB%A6%AC%EC%8A%A4%ED%8A%B8-%EC%A1%B0%ED%9A%8C
        fetch all deposits made to an account
        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr$   r   r  )r   r   privateGetDepositsr   parse_transactionsr   r   rt  r  r   r   r   r   s           r   fetch_depositszupbit.fetch_depositsX  s     	
 }}T**H"*4.GJ$GG**4;;w+G+GHH" &&x5%HHHr   c                     |                                   d|i}d}| |                     |          }|d         |d<   |                     |                     ||                    }|                     ||          S )a  
        fetch information on a deposit
        :see: https://global-docs.upbit.com/reference/individual-deposit-inquiry
        :param str id: the unique id for the deposit
        :param str [code]: unified currency code of the currency deposited
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.txid]: withdrawal transaction id, the id argument is reserved for uuid
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        r`  Nr$   r   )r   r   privateGetDepositr   parse_transactionr   r$   r   r   r   r   r   s          r   fetch_depositzupbit.fetch_deposit  s     	B
 }}T**H"*4.GJ))$++gv*F*FGG  %%h999r   c                    |                                   i }d}| |                     |          }|d         |d<   |||d<   |                     |                     ||                    }|                     ||||          S )a:  
        :see: https://docs.upbit.com/reference/%EC%A0%84%EC%B2%B4-%EC%B6%9C%EA%B8%88-%EC%A1%B0%ED%9A%8C
        fetch all withdrawals made from an account
        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr$   r   r  )r   r   privateGetWithdrawsr   r  r  s           r   fetch_withdrawalszupbit.fetch_withdrawals  s     	
 }}T**H"*4.GJ$GG++DKK,H,HII$ &&x5%HHHr   c                     |                                   d|i}d}| |                     |          }|d         |d<   |                     |                     ||                    }|                     ||          S )a>  
        fetch data on a currency withdrawal via the withdrawal id
        :see: https://global-docs.upbit.com/reference/individual-withdrawal-inquiry
        :param str id: the unique id for the withdrawal
        :param str [code]: unified currency code of the currency withdrawn
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.txid]: withdrawal transaction id, the id argument is reserved for uuid
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        r`  Nr$   r   )r   r   privateGetWithdrawr   r  r  s          r   fetch_withdrawalzupbit.fetch_withdrawal  s     	B
 }}T**H"*4.GJ**4;;w+G+GHH  %%h999r   c           	      F    ddddddddd}|                      |||          S )Npendingfailedokcanceled)
submitting	submittedalmost_acceptedrejectedaccepted
processingdoner  r   r   statusstatusess      r   parse_transaction_statuszupbit.parse_transaction_status  s@    #"( #"	
 	
 &&999r   r   c                    d }d }|                      |d          }|                     |                      |d|                    }|                      |d          }|dk    r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 )Ndone_atra  r   r^   
withdrawalr   r   r$   r`  r   networkaddress	addressToaddressFromtagtagTotagFromr  r   updatedtxidr  r  r   rj  )internalcommentr   )r   rl  r   r   r  safe_string_lowerr3  )
r   transactionr   r  r  
updatedRawr  r   r   r   s
             r   r  zupbit.parse_transaction  s   > %%k9==
NN4#3#3Kz#Z#Z[[	V44:D%%k:>>
&&z8<<
K
$"";77
 
 d&&{H==	

 t
 w
 
 4
 3
 T
 t
 d33D4J4J;X_4`4`aa
 D
 t~~j11
 D$$[&99
  !
" Y//#
$  ((e<< )
 
 
 	
r   c                 <    dddd}|                      |||          S )NrC  closedr  )waitr  cancelr  r  s      r   parse_order_statuszupbit.parse_order_status?  s1     
 

 &&999r   c           	         |                      |d          }|                      |d          }|dk    rd}nd}|                      |d          }|                     |                      |d                    }|                     |                      |d                    }d }|                      |d	          }	|                      |d
          }
|                      |d          }|                      |d          }d }|d	k    rd}|	}d }	d }d }|                      |d          }|                      |d          }|                     ||          }|                     |dg           }|                     ||d d ||d          }t          |          }|dk    r||dz
           d         }d}|d}d}d}t          d|          D ]}||         }t          j	        ||                      |d                    }|rJ|                     ||         di           }|                      |d          }|t          j	        ||          }t          j
        ||          }||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(          S ))Nr`  rc  r   re  rd  r  ra  r   r   rh  remaining_volumeexecuted_volumer   paid_feetrades)r|   r   r      r  FTr   r   r   r   rj  r   r$   r  r  lastTradeTimestampr   r   r  postOnly	stopPricetriggerPricerL  r   )filled	remainingr  r   r  )r   rl  r  rR  r   ry  r  r  r    
string_add
string_div
safe_orderr3  r   )r   r|   r   r$   rc  r   r  r  r  r   r   r  r  r   rL  r   rr  r   r  	numTradesgetFeesFromTradesr  ro  tradeFeetradeFeeCosts                            r   r  zupbit.parse_orderG  s   X eV,,v..5==DDDz22NN4#3#3E<#H#HII	(()9)9%)I)IJJ!  00!!%22$$U,>??	!!%):;;7??DDE""5*55##E844!!(F33"55""664@
 @
   KK	q==!'	A!6{!C %$(!D1i(( L Lq	)$0@0@0O0OPP$ L#vay%DDH#'#3#3Hf#E#EL#/")"4Wl"K"K(v66G"7O C   
E 
" 
 T 
 	 

 Y// 
 !"4 
 fX& 
 D 
 4 
  
 D 
 U 
  
 D 
 D%%d++ 
  t((11! 
" f# 
$ "- 
  
  
   	r   c                     |                                   d|i}d }| |                     |          }|d         |d<   |                     |                     ||                    }|                     ||||          S )Nr   r$   r   )r   r   privateGetOrdersr   parse_orders)	r   r   r   rt  r  r   r   r   r   s	            r   fetch_orders_by_statezupbit.fetch_orders_by_state  s     U
 [[((F &tGH((Wf)E)EFF,   65%@@@r   c                 4    |                      d||||          S )a9  
        :see: https://docs.upbit.com/reference/%EC%A3%BC%EB%AC%B8-%EB%A6%AC%EC%8A%A4%ED%8A%B8-%EC%A1%B0%ED%9A%8C
        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>`
        r  r  r   r   rt  r  r   s        r   fetch_open_orderszupbit.fetch_open_orders        ))&&%OOOr   c                 4    |                      d||||          S )ae  
        :see: https://docs.upbit.com/reference/%EC%A3%BC%EB%AC%B8-%EB%A6%AC%EC%8A%A4%ED%8A%B8-%EC%A1%B0%ED%9A%8C
        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>`
        r  r  r  s        r   fetch_closed_orderszupbit.fetch_closed_orders  r  r   c                 4    |                      d||||          S )al  
        :see: https://docs.upbit.com/reference/%EC%A3%BC%EB%AC%B8-%EB%A6%AC%EC%8A%A4%ED%8A%B8-%EC%A1%B0%ED%9A%8C
        fetches information on multiple canceled orders made by the user
        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: timestamp in ms of the earliest order, default is None
        :param int [limit]: max number of orders to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r  r  r  s        r   fetch_canceled_orderszupbit.fetch_canceled_orders  s      ))(FE5&QQQr   c                     |                                   d|i}|                     |                     ||                    }|                     |          S )a  
        :see: https://docs.upbit.com/reference/%EA%B0%9C%EB%B3%84-%EC%A3%BC%EB%AC%B8-%EC%A1%B0%ED%9A%8C
        fetches information on an order made by the user
        :param str symbol: not used by upbit fetchOrder
        :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   privateGetOrderr   r  r  s         r   fetch_orderzupbit.fetch_order  s\     	B
 ''GV(D(DEEX )))r   codesc                     |                                   |                     |          }|                     ||          S )a  
        :see: https://docs.upbit.com/reference/%EC%A0%84%EC%B2%B4-%EC%9E%85%EA%B8%88-%EC%A3%BC%EC%86%8C-%EC%A1%B0%ED%9A%8C
        fetch deposit addresses for multiple currencies and chain types
        :param str[]|None codes: list of unified currency codes, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `address structures <https://docs.ccxt.com/#/?id=address-structure>`
        )r   privateGetDepositsCoinAddressesparse_deposit_addresses)r   r	  r   r   s       r   fetch_deposit_addresseszupbit.fetch_deposit_addressesB  sA     	77??( ++He<<<r   c                 <   |                      |d          }|                      |d          }|                      |d          }|                     |          }|                      |d          }|                     |           ||||                     |          |dS )Ndeposit_addresssecondary_addressr   net_type)r   r  r  r  r   )r   r   check_addressnetwork_id_to_code)r   depositAddressr   r  r  r   r   	networkIds           r   parse_deposit_addresszupbit.parse_deposit_addressa  s     "">3DEE~/BCC%%njAA
&&z22$$^Z@@	7###..y99"
 
 	
r   c           
      |   |                                   |                     |          }d}|                     |          \  }}|t          | j        dz             |                     |                     |d         |                     ||d                   d|                    }|                     |          S )au  
        :see: https://docs.upbit.com/reference/%EC%A0%84%EC%B2%B4-%EC%9E%85%EA%B8%88-%EC%A3%BC%EC%86%8C-%EC%A1%B0%ED%9A%8C
        fetch the deposit address for a currency associated with self account
        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str params['network']: deposit chain, can view all chains via self.publicGetWalletAssets, default is eth, unless the currency has a default chain within self.options['networks']
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        Nz/ fetchDepositAddress requires params["network"]r$   r   )r   r  )	r   r   handle_network_code_and_paramsr   r$   privateGetDepositsCoinAddressr   network_code_to_idr  )r   r   r   r   networkCoder   s         r   fetch_deposit_addresszupbit.fetch_deposit_addressx  s     	==&&"AA&IIV#DG._$_```55dkk //Xf=MNNC
 C
 7 7   ))(333r   c                 N   |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |d          }|t          | j        dz   |z   dz             |                     |          S )a  
        :see: https://docs.upbit.com/reference/%EC%9E%85%EA%B8%88-%EC%A3%BC%EC%86%8C-%EC%83%9D%EC%84%B1-%EC%9A%94%EC%B2%AD
        create a currency deposit address
        :param str code: unified currency code of the currency for the deposit address
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        r   r$   messageNz is generating zx deposit address, call fetchDepositAddress or createDepositAddress one more time later to retrieve the generated address)r   r   &privatePostDepositsGenerateCoinAddressr   r   r   r$   r  )r   r   r   r   r   r   r  s          r   create_deposit_addresszupbit.create_deposit_address  s     	==&&
 >>t{{7TZ?[?[\\  ""8Y77 +<!<t!C  GA  "A  B  B  B))(333r   c                    |                      ||          \  }}|                                  |                     |          }d|i}d}|dk    r|                     |           |                     |dd          }	|	t          | j        dz             |                     |dg          }|	|d<   |d         |d<   ||d	<   |||d
<   |                     |d          }|                     | 	                    ||                    }n)| 
                    | 	                    ||                    }|                     |          S )uB  
        :see: https://docs.upbit.com/reference/디지털자산-출금하기
        :see: https://docs.upbit.com/reference/%EC%9B%90%ED%99%94-%EC%B6%9C%EA%B8%88%ED%95%98%EA%B8%B0
        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>`
        r   Nr   r  r  z' withdraw() requires a network argumentr$   r   r  r  )handle_withdraw_tag_and_paramsr   r   r  safe_string_upper_2r   r$   r  privatePostWithdrawsCoinr   privatePostWithdrawsKrwr  )
r   r   r   r  r  r   r   r   r   r  s
             r   r^   zupbit.withdraw  sV    99#vFFV==&&f
 5==w'''..vy*MMG'2[([\\\YYv	{33F")GJ"*4.GJ!(GI/2+,YYvy11F44T[[&5Q5QRRHH33DKK4P4PQQH %%h///r   c                 *    |                                  S N)milliseconds)r   s    r   r)  zupbit.nonce  s      """r   rq   GETc                    |                      | j        d         |         d| j        i          }|d| j        z   dz   |                      ||          z   z  }|                     ||                     |                    }|dk    r|r|d|                     |          z   z  }|dk    r|                                  |                                 }	| j	        |	d}
|rH|                     |          }| 
                    |                     |          d          }||
d	<   d
|
d<   |                     |
|                     | j                  d          }dd|z   i}|dk    r |dk    r|                     |          }d|d<   ||||dS )Nrt   ro   r   POST?rr   )
access_keyr)  sha512
query_hashSHA512query_hash_algsha256AuthorizationzBearer r)  DELETEzapplication/jsonzContent-Type)urlmethodbodyheaders)implode_paramsrp   ro   r)   r  extract_params	urlencodecheck_required_credentialsr`  apiKeyhashencodejwtsecretjson)r   pathrt   r6  r   r8  r7  r5  queryr)  r   authr>  tokens                 r   signz
upbit.sign  s   !!$)E"23"7:
   	sT\!C'$*=*=dF*K*KKK		&$"5"5d";";<<V 3sT^^E2222)++---IIKKE"k G  5~~e,,yyT!2!2H==(,%,4()HHWdkk$+&>&>IIEU!2G %f&8&8yy((*<'fdwOOOr   c
                    |d S |                      |d          }
|
|                     |
d          }|                     |
d          }| j        dz   |z   }|                     | j        d         ||           |                     | j        d         ||           |                     | j        d         ||           |                     | j        d         ||           t          |          d S )Nerrorr  r%    r   r   )r   r   r$   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   )r   httpCodereasonr5  r6  r8  r7  r   requestHeadersrequestBodyrI  r  r%   feedbacks                 r   handle_errorszupbit.handle_errors  s    4 '22&&ui88G##E622Dw}t+H001I7T\]]]001I4QYZZZ001I7T\]]]001I4QYZZZ)))tr   r'  )B__name__
__module____qualname__r   r,  r   r   r   r   r   r   r  r  r   r  r  r   r   r5  r   r8  r   rT  r   rZ  r]  r   rs  rz  r   r  listr  r  r   r   floatr	   r  r   r  r   r  r  r  r  r  r   r  r  r
   r  r  r   r  r  r  r  r  r  r   r^   r)  rG  rR  __classcell__)r   s   @r   r"   r"      s       p p p p pd 02 A A3 A A A A 46 U
 U
s U
 U
 U
 U
n 02 = =3 = = = = 24 d dS d d d dL $& , ,$v, , , , ,(7f 7 7 7 7r) ) ) ) )  $& , ,( , , , ,. 48dSU B B B B B B BH :>b 
3 
3s 
33 
3Y 
3 
3 
3 
36 66 6V 6 6 6 6p 04B 9G 9GW 9G7 9G 9G 9G 9Gv 02 	0 	03 	0f 	0 	0 	0 	0B B B5 B B B BH 6:UW )A )A3 )As )A# )A\`af\g )A )A )A )AV 57 =
 =
 =
;N =
 =
 =
 =
~
 
 
4 
 
 
 
2 26DW[df >L >L# >Lc >LQT >Lkoptku >L >L >L >L@ gksu T* T*3 T*i T*y T*RW T*`c T* T* T* T*l 37r !* !*s !*C !* !* !* !*F *.Dt\^ &I &I3 &Ic &I &Icghsct &I &I &I &IP 26b ": ": ":3 ": ": ": ":H -1tRV_a &I &Ic &I &IC &Ifjkvfw &I &I &I &IP 59 ": ":3 ":c ": ": ": ":H: : :@
 @
x @
; @
 @
 @
 @
D: : :w w w5 w w w wr :>D_cln "A "A3 "Ac "AY\ "A "A "A "AH /3TXac 
P 
P 
P3 
Pc 
Phlmrhs 
P 
P 
P 
P 154VZce 
P 
P# 
PS 
PPS 
Pjnotju 
P 
P 
P 
P 37TX\eg 
R 
RC 
Rs 
RRU 
R 
R 
R 
R 26b 8* 8*c 8*3 8* 8* 8* 8*t :>b = =T#Y = = = =>
 
h 
 
 
 
. 79 4 4# 4 4 4 4: 8: !4 !43 !4 !4 !4 !4F ?C2 10 10S 10% 10 10 10 10f# # # &eBSW P P P P<      r   r"   N)&ccxt.base.exchanger   ccxt.abstract.upbitr   ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   r   r   r   r   r   r   r   ccxt.base.decimal_to_precisionr   ccxt.base.preciser    r"    r   r   <module>ra     s   ( ' ' ' ' ' + + + + + + q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q       * * * * * * 0 0 0 0 0 0 - - - - - - . . . . . . ' ' ' ' ' ' . . . . . . + + + + + + ) ) ) ) ) ) * * * * * * 4 4 4 4 4 4 % % % % % %M M M M MHk M M M M Mr   