def get_current_price(ticker): """현재가 조회""" orderbook = pyupbit.get_orderbook(tickers=ticker)[0]["orderbook_units"][0]["ask_price"] while True : if orderbook is None : time.sleep(0.7) orderbook = pyupbit.get_orderbook(tickers=ticker)[0]["orderbook_units"][0]["ask_price"] else : break return orderbook
def buy_crypto_currency(): krw = upbit.get_balance(TIKER)[2] orderbook = pyupbit.get_orderbook(TIKER) print(orderbook) sell_price = orderbook['asks'][0]['price'] unit = krw / float(sell_price) upbit.buy_market_order(TIKER, unit)
def account_inquiry(self): coin_count = len(self.user_info_) - 1 #코인 보유 갯수수 for i in range(coin_count): coin_info = self.user_info_[i + 1] # 보유하고 있는 코인 정보를 1개씩 가져온다. coin_name = coin_info['currency'] coin_count = coin_info['balance'] coin_avg_price = coin_info['avg_buy_price'] coin_type = coin_info['unit_currency'] now_price = pyupbit.get_current_price(coin_type + '-' + coin_name) orderbook = pyupbit.get_orderbook(coin_type + '-' + coin_name) bids_asks = orderbook[0]['orderbook_units'] down_price = bids_asks[0]['bid_price'] up_price = bids_asks[0]['ask_price'] future_yield = coinTool.price_yield(now_price, self.future_price_LSTM[i]) limit_count = coinTool.limit_deal_count(now_price) coin_yield = coinTool.sell_event_yield(float(up_price), float(up_price), float(coin_avg_price)) self.coin_yields.append(coin_yield) self.up_prices.append(float(up_price)) self.down_prices.append(float(down_price)) self.future_yields.append(float(future_yield)) self.now_coin_names.append(coin_type + '-' + coin_name) self.now_coin_counts.append(float(coin_count)) self.now_avg_buy_prices.append(float(coin_avg_price)) self.now_prices.append(float(now_price)) self.limit_deal_counts.append(float(limit_count))
def retry_sell(ticker, unit, retry_cnt=10): ''' retry count 만큼 매도 시도 :param ticker: 티커 :param unit: 매도 수량 :param retry_cnt: 최대 매수 시도 횟수 :return: ''' try: ret = None while ret is None and retry_cnt > 0: orderbook = pyupbit.get_orderbook(ticker)[0]['orderbook_units'][0] buy_price = int(orderbook['bid_price']) # 최우선 매수가 buy_unit = orderbook['bid_size'] # 최우선 매수수량 min_unit = min(unit, buy_unit) if DEBUG is False: ret = upbit.sell_limit_order(ticker, buy_price, min_unit) time.sleep(INTERVAL) else: print("SELL API CALLED", ticker, buy_price, min_unit) retry_cnt = retry_cnt - 1 except: print("retry sell error")
def try_sell(tickers): ''' 보유하고 있는 모든 코인에 대해 전량 매도 :param tickers: 빗썸에서 지원하는 암호화폐의 티커 목록 :return: ''' try: # 잔고조회 units = get_blance_unit(tickers) for ticker in tickers: short_ticker = ticker.split('-')[1] unit = units.get(ticker, 0) # 보유 수량 if unit > 0: orderbook = pyupbit.get_orderbook( ticker)[0]['orderbook_units'][0] buy_price = int(orderbook['bid_price']) # 최우선 매수가 buy_unit = orderbook['bid_size'] # 최우선 매수수량 min_unit = min(unit, buy_unit) if DEBUG is False: ret = upbit.sell_limit_order(ticker, buy_price, min_unit) time.sleep(INTERVAL) if ret is None: retry_sell(ticker, unit, 10) else: print("SELL API CALLED", ticker, buy_price, min_unit) except: print("try sell error")
def buy_crypto_currency(ticker): krw = upbit.get_balance() * 0.999 orderbook = pyupbit.get_orderbook(ticker) sell_price = orderbook[0]["orderbook_units"][0]["ask_price"] unit = krw / float(sell_price) upbit.buy_limit_order(ticker, sell_price, unit) print(f"BUYING: {sell_price}")
def sell_crypto_currency(ticker): orderbook = pyupbit.get_orderbook(ticker) bid_price = orderbook[0]["orderbook_units"][0]["bid_price"] unit = upbit.get_balances()[-1]["balance"] upbit.sell_limit_order(ticker, bid_price, unit) print(f"SELL: {bid_price}")
def sell_crypto_currency(ticker): bal = upbit.get_balance(ticker.split('-')[1]) orderbook = pyupbit.get_orderbook(ticker) lowest_ask = orderbook[0]['orderbook_units'][0]['ask_price'] # unit = 100 print("매도 함수 실행!") sell_UID = upbit.sell_limit_order(ticker, lowest_ask, bal - 100) print(sell_UID) # print(upbit.sell_market_order(ticker, bal-300)) return lowest_ask
def buy_crypto_currency(upbit, ticker): # 원화 보유수량을 krw에 바인딩 krw = upbit.get_balance("KRW") # ticker의 호가정보를 orderbook에 바인딩 orderbook = pyupbit.get_orderbook(ticker) # orderbook의 0번째 호가정보를 가져와라 sell_price = orderbook[0]['orderbook_units'][0]['ask_price'] # 구매 단위 unit = krw / float(sell_price) * 0.7 # 시장가 매수 return upbit.buy_market_order(ticker, unit)
def try_trailling_stop(tickers, prices, targets, noises, holdings, high_prices): ''' trailling stop :param tickers: tickers :param prices: 현재가 리스트 :param targets: 목표가 리스트 :param holdings: 보유 여부 리스트 :param high_prices: 각 코인에 대한 당일 최고가 리스트 :return: ''' try: # 잔고 조회 units = get_blance_unit(tickers) for ticker in tickers: price = prices[ticker] # 현재가 target = targets[ticker] # 매수가 noise = noises[ticker] # noise high_price = high_prices[ticker] # 당일 최고가 unit = units.get(ticker, 0) # 보유 수량 gain = (price - target) / target # 이익률 gap_from_high = 1 - (price / high_price) # 고점과 현재가 사이의 갭 # 보유하고 있고 잔고가 0 이상이고 if holdings[ticker] is True and unit > 0: # noise가 0.65 보다 적은 종목은 trailing stop # noise가 0.65 이상인 종목은 10% 익절, 5% 손절 if (noise < DUAL_NOISE_LIMIT2 and gain >= TRAILLING_STOP_MIN_PROOFIT and gap_from_high >= TRAILLING_STOP_GAP) or ( noise >= DUAL_NOISE_LIMIT2 and (gain >= MIN_PROFIT or gain <= -MAX_LOSS)): orderbook = pyupbit.get_orderbook( ticker)[0]['orderbook_units'][0] buy_price = int(orderbook['bid_price']) # 최우선 매수가 buy_unit = orderbook['bid_size'] # 최우선 매수수량 min_unit = min(unit, buy_unit) if DEBUG is False: ret = upbit.sell_limit_order(ticker, buy_price, min_unit) time.sleep(INTERVAL) if ret is None: retry_sell(ticker, unit, 10) else: print("trailing stop", ticker, buy_price, min_unit) holdings[ticker] = False except: print("try trailing stop error")
def buy_crypto_currency(ticker): cur_wallet = upbit.get_balances()[0] # 보유중인 원화 GET - 배열안에 딕셔너리로 들어옴. cur_balance = cur_wallet['balance'] orderbook = pyupbit.get_orderbook(ticker)[0]['orderbook_units'] sell_price = orderbook[0]['ask_price'] # 최우선 매도 호가 unit = math.floor(float(cur_balance) / float(sell_price)) ret = upbit.buy_limit_order(ticker, sell_price, unit - 1) log("current balance : " + str(cur_balance) + " / buy amount : " + str(sell_price * unit) + "won") log("buy result : " + str(ret))
def run(self): access = "frGzp5hUEaQBNQ1uuO60Dx3QGkSm5ugsEVdfrpnr" #secret = lines[1].strip() secret = "L4wHqPfrfc7x8NYWHaL8IoUxbV8MBuhoxZG2ZHJa" upbit = pyupbit.Upbit(access, secret) Ticker = "KRW-DOGE" while self.alive: orderbook = pyupbit.get_orderbook(Ticker) time.sleep(0.1) self.dataSent.emit(orderbook)
def get_order_book(self, ticker, position, slippage=2): # ticker : 코인심볼명, postition : 매매방향, slippage : 호가레벨최대허용치 # 슬리피지 기본값은 최대 2틱 orderbook_list = pyupbit.get_orderbook(ticker) bids_asks = orderbook_list[0]['orderbook_units'] if position == "BUY": return float(bids_asks[slippage-1]['ask_price']) elif position == "SELL": return float(bids_asks[slippage-1]['bid_price'])
def buy_crypto_currency(ticker): krw = upbit.get_balance("KRW") orderbook = pyupbit.get_orderbook(ticker) highest_bid = orderbook[0]['orderbook_units'][0]['bid_price'] #unit = krw/float(sell_price) print("매수 함수 실행!") # 매수 목표가보다 바로 아래 가격에 리밋 매수주문 buy_UID = upbit.buy_limit_order(ticker, highest_bid, (krw / highest_bid) - 100) # 시장가에 즉시 매수 # buy_UID = upbit.buy_market_order(ticker, krw-50000) print(buy_UID) return highest_bid
def run(self): global global_ticker while self.alive: self.GlobalTicker.emit(global_ticker) orderbook = pyupbit.get_orderbook(str(global_ticker)) time.sleep(0.1) try: self.dataSent.emit(orderbook) except: print("None type orderbook")
def try_trailling_stop(portfolio, prices, targets, holdings, high_prices): ''' trailling stop :param portfolio: 포트폴리오 :param prices: 현재가 리스트 :param targets: 목표가 리스트 :param holdings: 보유 여부 리스트 :param high_prices: 각 코인에 대한 당일 최고가 리스트 :return: ''' try: # 잔고 조회 units = get_blance_unit(portfolio) for ticker in portfolio: price = prices[ticker] # 현재가 target = targets[ticker] # 매수가 high_price = high_prices[ticker] # 당일 최고가 unit = units.get(ticker, 0) # 보유 수량 gain = (price - target) / target # 이익률 gap_from_high = 1 - (price/high_price) # 고점과 현재가 사이의 갭 if gain >= TRAILLING_STOP_MIN_PROOFIT and gap_from_high >= TRAILLING_STOP_GAP and holdings[ticker] is True: if unit > 0: orderbook = pyupbit.get_orderbook( ticker)[0]['orderbook_units'][0] # 최우선 매수가 buy_price = int(orderbook['bid_price']) # 최우선 매수수량 buy_unit = orderbook['bid_size'] min_unit = min(unit, buy_unit) if DEBUG is False: ret = upbit.sell_limit_order( ticker, buy_price, min_unit) time.sleep(INTERVAL) if ret is None: retry_sell(ticker, unit, 10) else: print("trailing stop", ticker, buy_price, min_unit) holdings[ticker] = False except: print("try trailing stop error")
def try_buy(tickers, prices, targets, noises, ma5s, budget_per_coin, holdings, high_prices): ''' 매수 조건 확인 및 매수 시도 :param tickers: 원화 티커 :param prices: 각 코인에 대한 현재가 :param targets: 각 코인에 대한 목표가 :param ma5s: 5일 이동평균 :param budget_per_coin: 코인별 최대 투자 금액 :param holdings: 보유 여부 :return: ''' try: for ticker in tickers: price = prices[ticker] # 현재가 target = targets[ticker] # 목표가 noise = noises[ticker] # 노이즈 ma5 = ma5s[ticker] # 5일 이동평균 high = high_prices[ticker] # 매수 조건 # 0) noise가 0.8 이하이고 # 1) 현재가가 목표가 이상이고 # 2) 당일 고가가 목표가 대비 2% 이상 오르지 않았으며 (프로그램을 장중에 실행했을 때 고점찍고 하락중인 종목을 사지 않기 위해) # 3) 현재가가 5일 이동평균 이상이고 # 4) 해당 코인을 보유하지 않았을 때 if noise <= DUAL_NOISE_LIMIT1 and price >= target and high <= target * 1.02 and price >= ma5 and holdings[ ticker] is False: orderbook = pyupbit.get_orderbook( ticker)[0]['orderbook_units'][0] sell_price = int(orderbook['ask_price']) sell_unit = orderbook['ask_size'] unit = budget_per_coin / float(sell_price) min_unit = min(unit, sell_unit) if DEBUG is False: upbit.buy_limit_order(ticker, sell_price, min_unit) else: print("BUY API CALLED", ticker, sell_price, min_unit) time.sleep(INTERVAL) holdings[ticker] = True except: print("try buy error")
def uncollected(self): if uuid_count == 0: pass else: print('미채결 건수 발생') for i in self.uuid: upbit_info.cancel_order(i) print('미체결 건수 처리 완료') del self.uuid[:] # 주문ID coin_count = len(user_info) - 1 #코인 보유 갯수수 for i in range(coin_count): coin_info = user_info[i + 1] # 보유하고 있는 코인 정보를 1개씩 가져온다. coin_name = coin_info['currency'] coin_count = coin_info['balance'] coin_avg_price = coin_info['avg_buy_price'] coin_type = coin_info['unit_currency'] now_price = pyupbit.get_current_price(coin_type + '-' + coin_name) orderbook = pyupbit.get_orderbook(coin_type + '-' + coin_name) bids_asks = orderbook[0]['orderbook_units'] down_price = bids_asks[0]['bid_price'] up_price = bids_asks[0]['ask_price'] future_yield = coinTool.price_yield(now_price, self.future_prices[i]) limit_count = coinTool.limit_deal_count(now_price) self.up_prices.append(up_price) self.down_prices.append(down_price) self.future_yields.append(future_yield) self.now_coin_names.append(coin_type + '-' + coin_name) self.now_coin_counts.append(coin_count) self.now_avg_buy_prices.append(coin_avg_price) self.now_prices.append(now_price) self.limit_deal_counts.append(limit_count) print('현재 보유 코인 개수:', len(self.now_coin_names))
def base_data_info(self): base_count = len(self.base_coin_name) for i in range(base_count): base_now_price = pyupbit.get_current_price(self.base_coin_name[i]) self.base_coin_now_price.append(base_now_price) future_yield = coinTool.price_yield(base_now_price, self.base_future_price_LSTM[i]) self.base_futuer_yield.append(future_yield) limit_count = coinTool.limit_deal_count(base_now_price) self.base_limit_deal_counts.append(float(limit_count)) a = pyupbit.get_orderbook(tickers=self.base_coin_name[i]) a1 = a[0]['orderbook_units'] down_price = a1[0]['bid_price'] up_price = a1[0]['ask_price'] self.base_up_prices.append(float(up_price)) self.base_down_prices.append(float(down_price))
def buy_order(ticker, ticker_name): a = pyupbit.get_current_price(ticker_name) # 현재가 b = 0.5 * get_ATR(ticker) + day_ago(2, 'close', ticker).values # 전일종가 + 0.5ATR if a > b: f = open(str(os.getcwd()) + '/money', 'r') krw = float(f.readline()) f.close orderbook = pyupbit.get_orderbook(ticker_name) #해당 코인 호가 조회 sell_price = orderbook[0]['orderbook_units'][0][ 'ask_price'] #최우선 매도 호가 계산 unit = krw * 0.1 / sell_price #매수 수량 print("매수:" + ticker_name + ", 단가 :", sell_price, '수량:', unit) f = open('money', 'w') money = str(float(krw) - (sell_price * unit)) f.write(money) f.close print(datetime.datetime.now()) with open(str(os.getcwd()) + '/data.pickle', 'rb') as f: data = pickle.load(f) data[ticker_name] = unit with open(str(os.getcwd()) + '/data.pickle', 'wb') as f: pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
def get_current_price(ticker): """현재가 조회""" #post_message(myToken,"#stock", "now pay : " + str(pyupbit.get_orderbook(tickers=ticker)[0]["orderbook_units"][0]["ask_price"])) return pyupbit.get_orderbook(tickers=ticker)[0]["orderbook_units"][0]["ask_price"]
# 일정 텀을 두고 로그인 if(repeat_count==2000) : upbit = pyupbit.Upbit(access,secret) repeat_count=-1 repeat_count+=1 # 호가 불러오기 # 코인 하나씩 반복 index=0; print(keyList) for i in coins : orderbook = pyupbit.get_orderbook(keyList) bids_price=float(orderbook[index]['orderbook_units'][0]['bid_price']) asks_price=float(orderbook[index]['orderbook_units'][0]['ask_price']) index+=1 # 매수 if i['order']==0 and bids_price<=i['inputs']['buy_price']*1.005 : try: i['order']=upbit.buy_limit_order(i['inputs']['key'], round_price(i['inputs']['buy_price']), buy_amount/i['inputs']['buy_price']) finally: print(i['inputs']['key'], '\t', i['order'], '\t' + now) # 매도 if(bids_price<i['inputs']['buy_price']) : upbit.sell_limit_order(i['inputs']['key'], round_price(i['inputs']['buy_price']*yeild), upbit.get_balance(i['inputs']['key']))
<<<<<<< Updated upstream buy_list = buy_coin_list() print(buy_list) # 코인 구매 n = len(buy_list) buy_money = round(upbit.get_balance("KRW") / n) * 0.998 for item in buy_list: upbit.buy_market_order(item[0], buy_money) time.sleep(0.21) except Exception as e: print(e) time.sleep(1) ======= # tickers = pyupbit.get_tickers(fiat = 'KRW') # print(tickers) df = pyupbit.get_ohlcv("KRW-BTC") print(df) n = len(pyupbit.get_orderbook(coin_name)['orderbook_units']) tmp = pyupbit.get_orderbook(coin_name)['orderbook_units'] ask = [(tmp[i]['ask_size'], tmp[i]['bid_size']) for i in range(n)] # bid = [pyupbit.get_orderbook(coin_name)['orderbook_units'][i]['bid_size'] for i in range(14)] print('매수잔량', ask) # print('매도잔량', bid) # print(pyupbit.get_orderbook(coin_name)['orderbook_units'][14]['bid_size']) >>>>>>> Stashed changes
def trade(upbit, position, ticker): orderbook = pyupbit.get_orderbook(ticker) if position == 'buy': balance = float(upbit.get_balances()[0]['balance']) bids_asks = orderbook[0]['orderbook_units'] bid_price = bids_asks[0]['bid_price'] price = bid_price volume = balance / price*0.9994 ret = upbit.buy_limit_order(ticker, price, volume) elif position == 'sell': balance = float(upbit.get_balances()[1]['balance']) bids_asks = orderbook[0]['orderbook_units'] ask_price = bids_asks[0]['ask_price'] price = ask_price volume = balance ret = upbit.sell_limit_order(ticker, price, volume) print(ret) uid = ret['uuid'] state = ret['state'] time.sleep(1) counter = 0 while state == 'wait': server_url = 'https://api.upbit.com' query = { 'uuid': uid, } query_string = urlencode(query).encode() m = hashlib.sha512() m.update(query_string) query_hash = m.hexdigest() payload = { 'access_key': upbit.access, 'nonce': str(uuid.uuid4()), 'query_hash': query_hash, 'query_hash_alg': 'SHA512', } jwt_token = jwt.encode(payload, upbit.secret) authorize_token = 'Bearer {}'.format(jwt_token) headers = {"Authorization": authorize_token} res = requests.get(server_url + "/v1/order", params=query, headers=headers) state = res.json()['state'] if state == 'done' or state == 'cancel': print(state) break if counter >= 30: ret = upbit.cancel_order(uid) state = ret['state'] counter += 1 time.sleep(1) if position == 'buy': balance = float(upbit.get_balances()[1]['balance']) elif position == 'sell': balance = round(float(upbit.get_balances()[0]['balance']), 2) return price, balance
def get_current_price(ticker): """현재가 조회""" return pyupbit.get_orderbook(tickers=ticker)[0]["orderbook_units"][0]["ask_price"]
import pyupbit import pprint orderbooks = pyupbit.get_orderbook("KRW-BTC") pprint.pprint(orderbooks)
upbit = pyupbit.Upbit(access,secret) # 최근 nday일간 24시간 고가 중 최저가 찾기 if repeat_count == 21600 : for i in coins : history = pyupbit.get_ohlcv(i['key'], interval="day", count=nday)['high'] history_high = float(history[0]) for a in history : if history_high > float(a) : history_high = float(a) history_high=round_price(history_high*1.005) i['price']=history_high repeat_count=1 repeat_count+=1 # 거래 종목들 호가 불러오기 orderbook = pyupbit.get_orderbook(inputs) # 코인 하나씩 반복 index=0; for i in coins : bids_price=float(orderbook[index]['orderbook_units'][0]['bid_price']) asks_price=float(orderbook[index]['orderbook_units'][0]['ask_price']) index+=1 # 매수 if i['order']==0 and bids_price<=i['price']*1.005 : try: i['order']=upbit.buy_limit_order(i['key'], i['price'], buy_amount/i['price']) finally: print(i['key'], '\t', i['order'], '\t' + now)
"object_type": "text", "text": message, "link": { "web_url": "www.naver.com" } }) } requests.post(self.url, headers=self.headers, data=data) if __name__ == "__main__": import pyupbit access_key = "Uc7gjRjwxKWtqi3CzE8eBa0GBxKEuvxstqy4VBux" secret_key = "BuXKRKaxcPdhL8Htpl1cGsVbqGh0zd10DHVLLxWB" upbit = pyupbit.Upbit(access_key, secret_key) kakao = Kakao() ticker = 'krw-btc' orderbook = pyupbit.get_orderbook(ticker) bids_asks = orderbook[0]['orderbook_units'] bid_price = bids_asks[0]['bid_price'] sellprice = bid_price balance = round(float(upbit.get_balances()[0]['balance']), 2) ror = 0.98999948 message = f'{ticker}를 {sellprice}에 \n전량매도 했습니다.\n\n매도 체결 후 잔액:\n{balance}원\n\n현재 수익률: {round((ror-1)*100, 2)}%' kakao.send_message2me(message)
response = [] sum_prices = [] wait_uuid = 0 #for current_price, orders in zip(y,X): while True: timecount += 1 df = pyupbit.get_ohlcv(coin, interval="minute1", count=count) closes = df['close'] avg = 0 for i in closes: avg += i # 평균 가격을 구함 avg /= count orderbook = pyupbit.get_orderbook(tickers=coin) current_price = pyupbit.get_current_price(coin) change = get_change(coin) print(change) # # if timecount <= count: # sum_prices.append(current_price) # try: # sum_price += current_price # except: # count+=1 # # continue # else : # sum_price -= sum_prices[0]
def get_current_price(ticker): """현재가 조회""" geckoLogger.info(" 현재가 >> " + str(ticker)) return pyupbit.get_orderbook( tickers=ticker)[0]["orderbook_units"][0]["ask_price"]