def get_current_ticker_info(ticker="KRW-BTC"): """ 최종 체결 가격 조회 (현재가) :param ticker: :return: """ try: url = "https://api.upbit.com/v1/ticker" contents = _call_public_api(url, markets=ticker) if contents is not None: # 여러 마케을 동시에 조회 if isinstance(contents[0], list): ret = {} for content in contents[0]: market = content['market'] content['trade_time_kst'] = get_time_format( content['trade_time_kst']) content['trade_time'] = get_time_format( content['trade_time']) content['trade_date_kst'] = get_date_format( content['trade_date_kst']) ret[market] = content return [ret] else: return contents[0]['trade_price'] else: return [{'error': {'message': 'unknown error'}}] except Exception as x: print(x.__class__.__name__) return [{'error': {'message': x}}] return None
def get_tickers(fiat="ALL"): """ 마켓 코드 조회 (업비트에서 거래 가능한 마켓 목록 조회) :return: """ try: url = "https://api.upbit.com/v1/market/all" contents = _call_public_api(url)[0] if isinstance(contents, list): markets = [x['market'] for x in contents] if fiat == "KRW": return [x for x in markets if x.startswith("KRW")] elif fiat == "BTC": return [x for x in markets if x.startswith("BTC")] elif fiat == "ETH": return [x for x in markets if x.startswith("ETH")] elif fiat == "USDT": return [x for x in markets if x.startswith("USDT")] else: return markets else: return None except Exception as x: print(x.__class__.__name__) return None
def get_ohlcv(ticker="KRW-BTC", interval="day", count=1): """ 캔들 조회 :return: """ try: url = _get_url_ohlcv(interval=interval) CODE_PREFIX = "CRIX.UPBIT." contents = _call_public_api(url, count=count, code=CODE_PREFIX + ticker)[0] dt_list = [ datetime.datetime.strptime(x['candleDateTimeKst'][:19], "%Y-%m-%dT%H:%M:%S") for x in contents ] df = pd.DataFrame(contents, columns=[ 'candleDateTimeKst', 'openingPrice', 'highPrice', 'lowPrice', 'tradePrice', 'candleAccTradeVolume' ], index=dt_list) df = df.rename( columns={ "candleDateTimeKst": "time", "openingPrice": "open", "highPrice": "high", "lowPrice": "low", "tradePrice": "close", "candleAccTradeVolume": "volume" }) return df.iloc[::-1] except Exception as x: print(x.__class__.__name__) print(x) return None
def get_current_price(ticker="KRW-BTC"): """ 최종 체결 가격 조회 (현재가) :param ticker: :return: """ try: url = "https://api.upbit.com/v1/ticker" contents = _call_public_api(url, markets=ticker)[0] if not contents: return None if isinstance(ticker, list): ret = {} for content in contents: market = content['market'] price = content['trade_price'] timestamp = content['timestamp'] ret[market] = price ret["timestamp"] = timestamp return ret else: ret = {} market = contents[0]['market'] price = contents[0]['trade_price'] timestamp = contents[0]['timestamp'] ret[market] = price ret["timestamp"] = timestamp return ret except Exception as x: print(x.__class__.__name__)
def get_current_price(ticker="KRW-BTC", limit_info=False, verbose=False): """현재가 정보 조회 Args: ticker (str/list, optional): 단일 티커 또는 티커 리스트 Defaults to "KRW-BTC". limit_info (bool, optional): True: 요청 제한 정보 리턴. Defaults to False. verbose (bool, optional): True: 원본 API 파라미터 리턴. Defaults to False. Returns: [type]: [description] """ url = "https://api.upbit.com/v1/ticker" data, req_limit_info = _call_public_api(url, markets=ticker) if isinstance(ticker, str) or (isinstance(ticker, list) and len(ticker) == 1): # 단일 티커 if verbose is False: price = data[0]['trade_price'] else: price = data[0] else: # 여러 티커로 조회한 경우 if verbose is False: price = {x['market']: x['trade_price'] for x in data} else: price = data if limit_info: return price, req_limit_info else: return price
def net_change_desc(tickers): try: url = "https://api.upbit.com/v1/ticker" contents = _call_public_api(url, markets=tickers)[0] coin_list = [] for content in contents: coin = {} market = content['market'] price = content['trade_price'] open_price = content['opening_price'] prev_closing_price = content['prev_closing_price'] coin['market'] = market coin['price'] = price coin['open_price'] = open_price coin['prev_closing_price'] = prev_closing_price coin['net_change'] = price - prev_closing_price coin_list.append(coin) sorted_coin_list = sorted(coin_list, key=(lambda x: x['net_change']), reverse=True) return sorted_coin_list except Exception as x: print(traceback.format_exc()) print(x.__class__.__name__)
def get_tickers(fiat="", is_details=False, limit_info=False, verbose=False): """업비트 티커 조회 Args: fiat (str, optional): Fiat (KRW, BTC, USDT). Defaults to empty string. limit_info (bool, optional): True: 요청 수 제한 정보 리턴, False: 요청 수 제한 정보 리턴 받지 않음. Defaults to False. Returns: tuple/list: limit_info가 True이면 튜플, False이면 리스트 객체 """ url = "https://api.upbit.com/v1/market/all" detail = "true" if is_details else "false" markets, req_limit_info = _call_public_api(url, isDetails=detail) if verbose: tickers = [x for x in markets if x['market'].startswith(fiat)] else: tickers = [ x['market'] for x in markets if x['market'].startswith(fiat) ] if limit_info: return tickers, req_limit_info else: return tickers
def get_tickers(fiat="ALL", limit_info=False): """ 마켓 코드 조회 (업비트에서 거래 가능한 마켓 목록 조회) :param fiat: "ALL", "KRW", "BTC", "USDT" :param limit_info: 요청수 제한 리턴 :return: """ try: url = "https://api.upbit.com/v1/market/all" # call REST API ret = _call_public_api(url) if isinstance(ret, tuple): contents, req_limit_info = ret else: contents = None req_limit_info = None tickers = None if isinstance(contents, list): markets = [x['market'] for x in contents] if fiat != "ALL": tickers = [x for x in markets if x.startswith(fiat)] else: tickers = markets if limit_info is False: return tickers else: return tickers, req_limit_info except Exception as x: print(x.__class__.__name__) return None
def get_ohlcv(ticker="KRW-BTC", interval="day", count=200): """ 캔들 조회 :return: """ try: url = _get_url_ohlcv(interval=interval) contents = _call_public_api(url, market=ticker, count=count)[0] dt_list = [ datetime.datetime.strptime(x['candle_date_time_kst'], "%Y-%m-%dT%H:%M:%S") for x in contents ] df = pd.DataFrame(contents, columns=[ 'opening_price', 'high_price', 'low_price', 'trade_price', 'candle_acc_trade_volume' ], index=dt_list) df = df.rename( columns={ "opening_price": "open", "high_price": "high", "low_price": "low", "trade_price": "close", "candle_acc_trade_volume": "volume" }) return df.iloc[::-1] except Exception as x: print(x.__class__.__name__) return None
def get_current_price(ticker=["KRW-BTC"]): """ 최종 체결 가격 조회 (현재가) :param ticker: :return: """ try: url = "https://api.upbit.com/v1/ticker" contents = _call_public_api(url, markets=ticker) if contents is not None: # 여러 마케을 동시에 조회 if isinstance(contents[0], list): ret = {} for content in contents[0]: market = content['market'] price = content['trade_price'] ret[market] = price return ret else: return contents[0]['trade_price'] else: return None except Exception as x: print(x.__class__.__name__) return None
def get_orderbook(tickers="KRW-BTC"): ''' 호가 정보 조회 :param tickers: 티커 목록을 문자열 :return: ''' try: url = "https://api.upbit.com/v1/orderbook" contents = _call_public_api(url, markets=tickers)[0] return contents except Exception as x: print(x.__class__.__name__) return None
def get_ohlcv(ticker="KRW-BTC", interval="day", count=200, to=None, period=0.1): """ 캔들 조회 :return: """ MAX_CALL_COUNT = 200 try: url = get_url_ohlcv(interval=interval) if to is None: to = datetime.datetime.now() elif isinstance(to, str): to = pd.to_datetime(to).to_pydatetime() elif isinstance(to, pd._libs.tslibs.timestamps.Timestamp): to = to.to_pydatetime() dfs = [] count = max(count, 1) for pos in range(count, 0, -200): query_count = min(MAX_CALL_COUNT, pos) if to.tzinfo is None: to = to.astimezone() to = to.astimezone(datetime.timezone.utc) to = to.strftime("%Y-%m-%d %H:%M:%S") contents = _call_public_api(url, market=ticker, count=query_count, to=to)[0] dt_list = [datetime.datetime.strptime(x['candle_date_time_kst'], "%Y-%m-%dT%H:%M:%S") for x in contents] df = pd.DataFrame(contents, columns=['opening_price', 'high_price', 'low_price', 'trade_price', 'candle_acc_trade_volume', 'candle_acc_trade_price'], index=dt_list) df = df.sort_index() if df.shape[0] == 0: break dfs += [df] to = df.index[0].to_pydatetime() if pos > 200: time.sleep(period) df = pd.concat(dfs).sort_index() df = df.rename( columns={"opening_price": "open", "high_price": "high", "low_price": "low", "trade_price": "close", "candle_acc_trade_volume": "volume", "candle_acc_trade_price": "value"}) return df except Exception as x: print(x) return None
def get_ohlcv(ticker="KRW-BTC", interval="day", count=200, to=None): """ 캔들 조회 :return: """ try: url = get_url_ohlcv(interval=interval) if to == None: to = datetime.datetime.now() elif isinstance(to, str): to = pd.to_datetime(to).to_pydatetime() elif isinstance(to, pd._libs.tslibs.timestamps.Timestamp): to = to.to_pydatetime() if to.tzinfo is None: to = to.astimezone() to = to.astimezone(datetime.timezone.utc) to = to.strftime("%Y-%m-%d %H:%M:%S") contents = _call_public_api(url, market=ticker, count=count, to=to)[0] dt_list = [ datetime.datetime.strptime(x['candle_date_time_kst'], "%Y-%m-%dT%H:%M:%S") for x in contents ] df = pd.DataFrame(contents, columns=[ 'opening_price', 'high_price', 'low_price', 'trade_price', 'candle_acc_trade_volume' ], index=dt_list) df = df.rename( columns={ "opening_price": "open", "high_price": "high", "low_price": "low", "trade_price": "close", "candle_acc_trade_volume": "volume" }) return df.sort_index() except Exception as x: print(x.__class__.__name__) return None
def get_trades(ticker="KRW-BTC", to='', days=0): ''' 최근 시세 체결 조회 :param tickers: 티커 목록을 문자열 :param to: HH:mm:ss :param daysAgo: :return: ''' try: url = "https://api.upbit.com/v1/trades/ticks" contents = _call_public_api(url, market=ticker, to=to, count=500, daysAgo=days)[0] return contents except Exception as x: print(x.__class__.__name__) return None
def get_orderbook(tickers="KRW-BTC"): ''' 호가 정보 조회 :param tickers: 티커 목록을 문자열 :return: ''' try: url = "https://api.upbit.com/v1/orderbook" contents = _call_public_api(url, markets=tickers)[0] return contents except Exception as x: print(x.__class__.__name__) return None # if __name__ == "__main__": # print(get_tickers()) # print(get_tickers(fiat="KRW")) # # print(get_tickers(fiat="BTC")) # # print(get_tickers(fiat="ETH")) # # print(get_tickers(fiat="USDT")) # print(get_ohlcv("KRW-BTC", interval="minutes1", count=2)) # # print(get_ohlcv("KRW-BTC", interval="day", count=5)) # # print(get_ohlcv("KRW-BTC", interval="minute1")) # # print(get_ohlcv("KRW-BTC", interval="minute3")) # # print(get_ohlcv("KRW-BTC", interval="minute5")) # # print(get_ohlcv("KRW-BTC", interval="minute10")) # #print(get_ohlcv("KRW-BTC", interval="minute15")) # #print(get_ohlcv("KRW-BTC", interval="minute30")) # #print(get_ohlcv("KRW-BTC", interval="minute60")) # #print(get_ohlcv("KRW-BTC", interval="minute240")) # #print(get_ohlcv("KRW-BTC", interval="week")) # #print(get_daily_ohlcv_from_base("KRW-BTC", base=9)) # #print(get_ohlcv("KRW-BTC", interval="day", count=5)) # #print(get_current_price("KRW-BTC")) # #print(get_current_price(["KRW-BTC", "KRW-XRP"])) # #print(get_orderbook(tickers=["KRW-BTC"])) # #print(get_orderbook(tickers=["KRW-BTC", "KRW-XRP"]))
def get_orderbook(ticker="KRW-BTC", limit_info=False): """호가 정보 조회 Args: ticker (str/list, optional): 티커 또는 티커 리스트. Defaults to "KRW-BTC". limit_info (bool, optional): True: 요청 수 제한 정보 리턴, False: 요청 수 제한 정보 리턴 받지 않음. Defaults to False. Returns: [type]: [description] """ url = "https://api.upbit.com/v1/orderbook" orderbook, req_limit_info = _call_public_api(url, markets=ticker) if isinstance(ticker, str) or (isinstance(ticker, list) and len(ticker) == 1): orderbook = orderbook[0] if limit_info: return orderbook, req_limit_info else: return orderbook
def get_ohlcv(ticker="KRW-BTC", interval="day", count=200, to=None): """ 캔들 조회 :return: """ try: url = get_url_ohlcv(interval=interval) if datetime.datetime == type(to): if to.tzinfo is None: to = to.astimezone() to = to.astimezone( datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S") contents = _call_public_api(url, market=ticker, count=count, to=to)[0] # df=pd.DataFrame(contents) dt_list = [ datetime.datetime.strptime(x['candle_date_time_kst'], "%Y-%m-%dT%H:%M:%S") for x in contents ] df = pd.DataFrame(contents, columns=[ 'opening_price', 'high_price', 'low_price', 'trade_price', 'candle_acc_trade_price', 'candle_acc_trade_volume' ], index=dt_list) df = df.rename( columns={ "opening_price": "open", "high_price": "high", "low_price": "low", "trade_price": "close", "cnadle_acc_trade_price": "price", "candle_acc_trade_volume": "volume" }) return df.iloc[::-1] except Exception as x: print(x.__class__.__name__) return None
def get_change(ticker="KRW-BTC"): """ 최종 체결 가격 조회 (현재가) :param ticker: :return: """ try: url = "https://api.upbit.com/v1/ticker" contents = _call_public_api(url, markets=ticker)[0] if not contents: return None if isinstance(ticker, list): ret = {} for content in contents: market = content['market'] change = content['change'] ret[market] = change return ret else: return contents[0]['change'] except Exception as x: print(x.__class__.__name__)
def get_ohlcv_from(ticker="KRW-BTC", interval="day", fromDatetime=None, to=None, period=0.1): MAX_CALL_COUNT = 200 try: url = get_url_ohlcv(interval=interval) if fromDatetime is None: fromDatetime = datetime.datetime(2000, 1, 1, 0, 0, 0) elif isinstance(fromDatetime, str): fromDatetime = pd.to_datetime(fromDatetime).to_pydatetime() elif isinstance(fromDatetime, pd._libs.tslibs.timestamps.Timestamp): fromDatetime = fromDatetime.to_pydatetime() fromDatetime = fromDatetime.astimezone(datetime.timezone.utc) if to == None: to = datetime.datetime.now() elif isinstance(to, str): to = pd.to_datetime(to).to_pydatetime() elif isinstance(to, pd._libs.tslibs.timestamps.Timestamp): to = to.to_pydatetime() to = to.astimezone(datetime.timezone.utc) dfs = [] while to > fromDatetime: query_count = MAX_CALL_COUNT to = to.strftime("%Y-%m-%d %H:%M:%S") contents, req_limit_info = _call_public_api(url, market=ticker, count=query_count, to=to) dt_list = [ datetime.datetime.strptime(x['candle_date_time_kst'], "%Y-%m-%dT%H:%M:%S").astimezone() for x in contents ] # set timezone for time comparison # timezone will be removed before DataFrame returned df = pd.DataFrame(contents, columns=[ 'opening_price', 'high_price', 'low_price', 'trade_price', 'candle_acc_trade_volume', 'candle_acc_trade_price' ], index=dt_list) df = df.sort_index() if df.shape[0] == 0: break dfs += [df] to = datetime.datetime.strptime( contents[-1]['candle_date_time_utc'], "%Y-%m-%dT%H:%M:%S") to = to.replace(tzinfo=datetime.timezone.utc) # to compare fromTs and to, set tzinfo if to > fromDatetime: time.sleep(period) df = pd.concat(dfs).sort_index() df = df[df.index >= fromDatetime] df.index = df.index.tz_localize(None) df = df.rename( columns={ "opening_price": "open", "high_price": "high", "low_price": "low", "trade_price": "close", "candle_acc_trade_volume": "volume", "candle_acc_trade_price": "value" }) return df except Exception as x: return None
def test_call_public_api(): url = "https://api.upbit.com/v1/market/all" querystring = {"isDetails": "false"} data, limit = _call_public_api(url, **querystring) assert isinstance(limit, dict)