def try_buy(upbit, ticker, status): cur_price = pyupbit.get_current_price(ticker) for hour in range(24): hold = status[hour][0] # 해당 시간대 보유 여부 target = status[hour][1] # 해당 시간대 목표가 betting_ratio = status[hour][2] # 해당 시간대 배팅률 # 해당 시간대에 보유 코인이 없고 # 해당 시간대에 목표가가 설정되어 있고 # 현재가 > 해당 시간대의 목표가 if hold is False and target is not None and cur_price > target: remained_krw_balance = upbit.get_balance("KRW") # 원화잔고 조회 hold_count = sum([x[0] for x in status.values()]) # 각 시간대별 보유 상태 krw_balance_for_time_frame = remained_krw_balance / ( 24 - hold_count) # 타임 프레임 별 투자 금액 coin_size = upbit.buy_market_order( ticker, krw_balance_for_time_frame * betting_ratio) # 매수 상태 업데이트 status[hour][0] = True # 보유여부 status[hour][3] = coin_size # 보유코인 양 # 현재가 갱신 (매수 시도에 따라 시간이 경과됐으므로) cur_price = pyupbit.get_current_price(ticker)
def get_cur_price(): if total_coin_num <= 100: price_dicc = pyupbit.get_current_price(coin_list[:total_coin_num]) else: price_dicc = pyupbit.get_current_price(coin_list[:100]) price_dicc.update(pyupbit.get_current_price(coin_list[100:total_coin_num])) return price_dicc
def get_coin(coin): if coin == None: pass # tickers = pyupbit.get_tickers() # return tickers elif coin != None: coin = coin.replace(" ", "") ticker = coin.replace("코인", "") price = format(pyupbit.get_current_price(ticker), ',') pricelow = pyupbit.get_current_price(ticker) df = pyupbit.get_ohlcv(ticker, count=2, interval="day") df.drop(['volume', 'high', 'low'], axis=1, inplace=True) df['N'] = ['1', '2'] df['Date'] = df.index df.set_index('N', inplace=True) df["open"] = [format(df['open'][0], ','), format(df['open'][1], ',')] df["close"] = [ format(df['close'][0], ','), format(df['close'][1], ',') ] yesterdaylow = float(df['close'][0].replace(",", "")) pricefloat = float(pricelow) per = (pricefloat / yesterdaylow * 100) - 100 per = "%.2f%%" % per return df, price, per
def sell_all(coin): balance = upbit.get_balance(coin) price = pyupbit.get_current_price(coin) if price * balance >= 5000: print(upbit.sell_market_order(coin, balance)) post_message("매도 체결.\n체결 단가 : " + str(pyupbit.get_current_price(coin)) + " 원")
def update_current_infos(self, coins: list[Coin]): if len(coins) >= 100: current_price = pyupbit.get_current_price(['KRW-' + coin.name for coin in coins[:100]]) current_price.update(pyupbit.get_current_price(['KRW-' + coin.name for coin in coins[100:]])) else: current_price = pyupbit.get_current_price(['KRW-' + coin.name for coin in coins]) for coin in coins: coin.current_volume = pyupbit.get_ohlcv("KRW-" + coin.name, interval='day', count=1).get("volume")[0] coin.current_price = current_price['KRW-' + coin.name] coin.low_price = min(coin.current_price, coin.low_price if coin.low_price != 0 else coin.current_price) coin.high_price = max(coin.current_price, coin.high_price if coin.high_price != 0 else coin.current_price)
def tradingCoin(): global runTf global num while runTf: amount = upbit.get_balance(runCoin) #코인 보유 수량 구하기 nowTime = datetime.datetime.now() nowPrice = pyupbit.get_current_price(runCoin) if nowPrice is not None and num == 0: #최초 한번만 매수 buyPrice = myBuyPrice num = num+1 buyPricefloat = float(buyPrice) buyUpPrice = buyPricefloat + buyPricefloat * 0.02 buyDownPrice = buyPricefloat - buyPricefloat * 0.02 plusPrice = buyUpPrice - buyPrice minnusPrice = buyPrice - buyUpPrice if nowPrice >= buyUpPrice and nowPrice is not None: time.sleep(0.5) buyCoin = upbit.buy_market_order(runCoin, buying) buyPrice = pyupbit.get_current_price(runCoin) f = open("트레이딩_결과.txt", 'a') f.write(f"2%상승 돈 벌었다!! 번돈:{plusPrice}\n") f.write(f"등락률:{calPrice}{gubun} 나의 코인 보유량:{amount}\n") f.write(f"현재시간:{nowTime} 현재가:{nowPrice} 산가격:{buyPrice} 상승가:{buyUpPrice} 하락가:{buyDownPrice} 동작상태:{runTf}\n\n") f.close elif nowPrice <= buyDownPrice and nowPrice is not None: sellCoin = upbit.sell_market_order(runCoin, selling) runTf = False f = open("트레이딩_결과.txt", 'a') f.write(f"2%하락 돈 잃음ㅠㅠ 잃은돈:{minnusPrice}\n") f.write(f"등락률:{calPrice}{gubun} 나의 코인 보유량:{amount}\n") f.write(f"현재시간:{nowTime} 현재가:{nowPrice} 산가격:{buyPrice} 상승가:{buyUpPrice} 하락가:{buyDownPrice} 동작상태:{runTf}\n\n") f.close if nowPrice is not None: gubun = "%" perCheck = (myBuyPrice/nowPrice)*100 if perCheck <= 100: calPrice = 100 - perCheck else: calPrice = 100 - perCheck calPrice = "{:.2f}".format(calPrice) amount = "{:.2f}".format(amount) print(f"등락률:{calPrice}{gubun} 나의 코인 보유량:{amount}") print(f"현재시간:{nowTime} 현재가:{nowPrice} 산가격:{buyPrice} 상승가:{buyUpPrice} 하락가:{buyDownPrice} 동작상태:{runTf}") time.sleep(5)
def sell_coin(ticker): """코인 판매""" coin_num = upbit.get_balance(ticker) corrent_num = pyupbit.get_current_price(ticker) if corrent_num * coin_num > 1200: upbit.sell_market_order(ticker, coin_num * 0.9995) return 0
def printInfo(self): if self.debug: print("================= DEBUG MODE! =================") timestamp = datetime.now() infostr = "| | " infostr += str(timestamp) infostr += " | " for c in self.coins: cprice = None while cprice is None: cprice = pyupbit.get_current_price([c]) cprice = cprice[c] cinfo = c + " " + str(cprice) infostr += cinfo infostr += " | " infostr += "| |" print(infostr) investStatusStr = "| | " investStatusStr += str(timestamp) investStatusStr += " | " for c in self.coins: cinfo = c + " " + "invested: " + str( self.invests[c]) + " " + "target price: " + str( self.targetPrice[c]) investStatusStr += cinfo investStatusStr += " | " investStatusStr += "| |" print(investStatusStr) threading.Timer(3600, self.printInfo).start()
def get_ma_score(ticker): current_price = pyupbit.get_current_price(ticker) df = pyupbit.get_ohlcv(ticker, "day", 21) df['ma3'] = df['close'].rolling(window=3).mean() df['ma5'] = df['close'].rolling(window=5).mean() df['ma10'] = df['close'].rolling(window=10).mean() df['ma15'] = df['close'].rolling(window=15).mean() df['ma20'] = df['close'].rolling(window=20).mean() if current_price >= df['ma3'][-2]: ma3_score = 0.2 else: ma3_score = 0 if current_price >= df['ma5'][-2]: ma5_score = 0.2 else: ma5_score = 0 if current_price >= df['ma10'][-2]: ma10_score = 0.2 else: ma10_score = 0 if current_price >= df['ma15'][-2]: ma15_score = 0.2 else: ma15_score = 0 if current_price >= df['ma20'][-2]: ma20_score = 0.2 else: ma20_score = 0 ma_score = ma3_score + ma5_score + ma10_score + ma15_score + ma20_score return ma_score
def main(args): TICKER = args.ticker # 투자할 코인의 티커 입력 NUM_COINS = args.num_coins # 코인 수 TIME_FRAMES = args.time_frames # 주문을 위한 객체 생성 upbit = manager.create_instance() # 각 시간 대별로 보유 상태 저장 # 시간대:[보유여부, 목표가, 배팅률, 보유코인양] status = {k: [False, None, 0, 0] for k in range(0, TIME_FRAMES)} while True: now = datetime.datetime.now() # 매 시각 30초 정도의 대기 시간을 줌으로써 첫 체결이 될 수 있도록 해줌 if now.minute == 0 and (30 <= now.second <= 40): trade.try_sell(upbit, TICKER, status, now.hour) trade.set_break_out_range(TICKER, status, now.hour) # 매수 시도 trade.try_buy(upbit, TICKER, status) # 상태 출력 cur_price = pyupbit.get_current_price(TICKER) manager.print_status(now, status, cur_price) time.sleep(1)
def run(self): while True: time.sleep(1) balances = upbit.get_balances() for b in balances: if b['currency'] == "KRW": continue tabkerName = "KRW-" + b['currency'] # 평균 매수가 fAvgPrice = float(b['avg_buy_price']) # 신규 판매 예약 등록 p1 = fAvgPrice * 1.0105 nowPrice = pyupbit.get_current_price(tabkerName) oders = upbit.get_order(tabkerName) if p1 < nowPrice: strPrint = upbit.sell_limit_order(tabkerName, nowPrice, b['balance'] ,True) time.sleep(1) oders = upbit.get_order(tabkerName) time.sleep(1) for oder in oders: if oder['side'] == 'bid': strPrint = upbit.cancel_order(oder['uuid']) time.sleep(1)
def ma_golden_cross(tickers, days): i, j = 0, 100 up_cnt, down_cnt = 0, 0 len_all_list = len(tickers) coin = [] while (j < len_all_list + 100): if (j > len_all_list): j = len_all_list tickers_tmp = tickers[i:j] all_item = pyupbit.get_current_price(tickers_tmp) for ticker in all_item: df = pyupbit.get_ohlcv(ticker) ma = df['close'].rolling(days).mean() price = float(all_item[ticker]) last_ma = ma[-2] if price > last_ma: up_cnt = up_cnt + 1 print(ticker, "상승장") coin.append(ticker) else: down_cnt = down_cnt + 1 print(ticker, "하락장") time.sleep(0.05) i = i + 100 j = j + 100 #pprint.pprint(coin) return coin
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 aboveline(currency, interval): priceNow = pyupbit.get_current_price(currency) df = pyupbit.get_ohlcv(currency, interval) ma20 = df['close'].rolling(window=20).mean() if priceNow > ma20: return 1 else: return 0
def get_price(self): # get price currentCOINdict = None while currentCOINdict is None: currentCOINdict = pyupbit.get_current_price(["KRW-BTC"]) currentCOIN = currentCOINdict["KRW-BTC"] self.BTC_price = currentCOIN return self.BTC_price
def bull_market(ticker): df = pyupbit.get_ohlcv(ticker) ma5 = df['close'].rolling(window=5).mean() last_ma5 = ma5[-2] price = pyupbit.get_current_price(ticker) if price > last_ma5: # 이동평균보다 크면 상승장 upper_list.append(ticker)
def updateData(self, data): f = open("api.txt") lines = f.readlines() # 모든 라인 읽어오기 access = lines[0].strip() # 0번째 줄 가져오기 strip()메소드를 사용해 '\n'을 없애기. secret = lines[1].strip() f.close() self.upbit = pyupbit.Upbit(access, secret) balances = self.upbit.get_balances() # 업비트가 지원하는 모든 원화마켓 가져오기 krw_market = pyupbit.get_tickers(fiat="KRW") for j in range(len(balances)): ticker= "KRW-"+balances[j]['currency'] # 지원하는 원화마켓과 다른 티커는 제외(비상장 코인이나 KRW-KRW문제) if ticker in krw_market: price = pyupbit.get_current_price(ticker) for i in range(len(balances)): # 0) 코인명 item_0 = self.tableBalances.item(i, 0) item_0.setText(f"{balances[i]['currency']}") # 1) 보유수량 item_1 = self.tableBalances.item(i, 1) amount1 = float(balances[i]['balance']) + float(balances[i]['locked']) item_1.setText(f"{amount1}") if "KRW-"+balances[i]['currency'] not in krw_market : pass else : # 2) 매수평균가 item_2 = self.tableBalances.item(i, 2) item_2.setText(f"{balances[i]['avg_buy_price']} 원") # 3) 평가금액 amount2 = price * (float(balances[i]['balance'])+float(balances[i]['locked'])) # 현재가 * (주문가능 금액 + 주문 묶여있는 금액) item_3 = self.tableBalances.item(i, 3) item_3.setText(f"{int(amount2)} 원") # 4) 매수금액 amount3 = round(float(balances[i]['avg_buy_price']) * (float(balances[i]['balance']) + float(balances[i]['locked']))) # 매수평균가 * (주문가능 금액 + 주문 묶여있는 금액) 반올림 item_4 = self.tableBalances.item(i, 4) item_4.setText(f"{str(amount3)} 원") # 5) 평가손익 amount4 = round(amount2 - amount3, 2) # 평가금액 - 매수금액 -> 소수 둘째자리까지 반올림 item_5 = self.tableBalances.item(i, 5) item_5.setText(f"{amount4}") try : # 수익률 amount5 = round(amount4 / amount3 * 100,2) # 평가손익 / 매수금액 item_6 = self.tableBalances.item(i, 6) item_6.setText(f"{str(amount5)} %") except: pass
def get_current_price(self): tickers = pyupbit.get_tickers(fiat="KRW") while True: markets = pyupbit.get_current_price(tickers) client.emit( "send_price", dict(tickers=tickers, markets=markets, size=len(markets))) time.sleep(1)
def belowline(currency, interval): priceNow = pyupbit.get_current_price(currency) df = pyupbit.get_ohlcv(currency, interval) ma60 = df['close'].rolling(window=60).mean() atr = getATR(currency, interval) if priceNow <= ma60 - atr: return 1 else: return 0
def inquiry(self): cur_time = QTime.currentTime() str_time = cur_time.toString("hh:mm:ss") self.statusBar().showMessage(str_time) # print("== 코인 현재가 조회 ==") price = pyupbit.get_current_price("KRW-BTC") # price는 float형 이기때문에 str로 형변환해서 입력함. self.lineEdit.setText(str(price))
def inquiry_cur_prices(tickers): ''' 모든 가상화폐에 대한 현재가 조회 :param tickers: 티커 목록 :return: 현재가, {'KRW-BTC': 7200000, 'KRW-XRP': 500, ...} ''' try: return pyupbit.get_current_price(tickers) except: return None
def inquiry_cur_prices(portfolio): ''' 포트폴리오내 가상화폐에 대한 현재가 조회 :param portfolio: 포트폴리오에 대한 티커 목록 :return: 현재가, {'KRW-BTC': 7200000, 'KRW-XRP': 500, ...} ''' try: return pyupbit.get_current_price(portfolio) except: return None
def bull_market(ticker): df = pyupbit.get_ohlcv(ticker) ma5 = df['close'].rolling(window=5).mean() price = pyupbit.get_current_price(ticker) last_ma5 = ma5[-2] if price > last_ma5: return True else: return False
def min_240_trade_3(): global op_mode_3 global pwr_btn_3 global hold_3 global target_3 while True: now = datetime.datetime.now() # 목표가 갱신 프로세스 if (now.hour == 1 or now.hour == 5 or now.hour == 9 or now.hour == 13 or now.hour == 17 or now.hour == 21) and now.minute == 00 and 45 <= now.second<= 55 : # print(now.minute) # print(now.second) target_3 = cal_target_3() text_3.insert(END,'[[[ 목표가 갱신 : {} ]]]\n'.format(target_3)) text_3.see(END) op_mode_3 = True price_3 = pyupbit.get_current_price('KRW-'+coin_ticker_3) #매 초마다 조건 확인 후 매수 시도 ### upbit 은 에러의 경우 None 을 return 해주므로 None 을 이용한 예외처리를 하면 좋음. if (op_mode_3 is True) and (price_3 is not None) and (hold_3 is False) and (price_3 > target_3): #매수 krw_balance = upbit.get_balance('KRW') upbit.buy_market_order("KRW-"+coin_ticker_3,krw_balance*0.9995) hold_3 = True text_3.insert(END,'[[ 목표가 도달 매수합니다 ]]\n') text_3.insert(END,'??? : 그가 매수했습니다.\n') text_3.see(END) #매도기능 if (now.hour == 00 or now.hour == 4 or now.hour == 8 or now.hour == 12 or now.hour == 16 or now.hour == 20) and now.minute == 59 and 45 <= now.second<= 55 and (hold_3 is True): # print(now.minute) # print(now.second) btc_balance = upbit.get_balance("KRW-"+coin_ticker_3) upbit.sell_market_order('KRW-'+coin_ticker_3,btc_balance) text_3.insert(END,'시가매도\n') text_3.insert(END,'??? : 그가 매도했습니다.\n') text_3.see(END) hold_3 = False op_mode_3 = False text_3.insert(END,(str(now.strftime("%Y-%m-%d %H:%M:%S")) +' \\'+ str(price_3)+'\n')) text_3.see(END) time.sleep(10) if pwr_btn_3 == 1: text_3.insert(END,'[[[ 거래 중지 완료 ]]]\n') text_3.see(END) break
def min_10_trade_2(): global op_mode_2 global pwr_btn_2 global hold_2 global target_2 while True: now = datetime.datetime.now() # 목표가 갱신 프로세스 if (now.minute == 10 or now.minute == 20 or now.minute == 30 or now.minute == 40 or now.minute == 50 or now.minute == 00) and (10<=now.second<=20): # print(now.minute) # print(now.second) target_2 = cal_target_2() text_2.insert(END,'[[[ 목표가 갱신 : {} ]]]\n'.format(target_2)) text_2.see(END) op_mode_2 = True price_2 = pyupbit.get_current_price('KRW-'+coin_ticker_2) #매 초마다 조건 확인 후 매수 시도 ### upbit 은 에러의 경우 None 을 return 해주므로 None 을 이용한 예외처리를 하면 좋음. if (op_mode_2 is True) and (price_2 is not None) and (hold_2 is False) and (price_2 > target_2): #매수 krw_balance = upbit.get_balance('KRW') upbit.buy_market_order("KRW-"+coin_ticker_2,krw_balance*0.9995) hold_2 = True text_2.insert(END,'[[ 목표가 도달 매수합니다 ]]\n') text_2.insert(END,'??? : 그가 매수했습니다.\n') text_2.see(END) #매도기능 if (now.minute == 9 or now.minute == 19 or now.minute == 29 or now.minute == 39 or now.minute == 49 or now.minute == 59 )and (50<= now.second <=59) and (hold_2 is True): # print(now.minute) # print(now.second) btc_balance = upbit.get_balance("KRW-"+coin_ticker_2) upbit.sell_market_order('KRW-'+coin_ticker_2,btc_balance) text_2.insert(END,'시가매도\n') text_2.insert(END,'??? : 그가 매도했습니다.\n') text_2.see(END) hold_2 = False op_mode_2 = False text_2.insert(END,(str(now.strftime("%Y-%m-%d %H:%M:%S")) +' \\'+ str(price_2)+'\n')) text_2.see(END) time.sleep(10) if pwr_btn_2 == 1: text_2.insert(END,'[[[ 거래 중지 완료 ]]]\n') text_2.see(END) break
def buy_btc(self, market_name): server_url = 'https://api.upbit.com/v1/orders' my_account_btc = self.upbit.get_balance(ticker="KRW-BTC") buy_money = my_account_btc * 0.99 # 내가 가진 btc respon = self.upbit.buy_market_order(market_name, buy_money) print(respon[0]["uuid"]) cur_price = pyupbit.get_current_price(market_name) self.logger.print_log("[{} 체결완료] : 금액: {}".format( market_name, cur_price)) return cur_price
def save_data(krw_balance): own_coin_list_04_08 = [ 175, # ENJ 3126, # SAND 0, # TRX 164614.48742559, # BTT 677.52818233, # XRP 602.4096, # DKA 184.9801, # MLK 0, # AQT 15080, # MED 0.00133972, # BTC 695.93, # ADA 0.09961308, # ETH 0, # PCI 0, # BORA 0, # XEM 0, # EOS 0, # PUNDIX 0, # MANA 0, # QTUM 0, # HBAR 0, # VET 0, # NEO 0, # GAS 0, # DOGE 0 # STRK ] df_saved_data = pd.read_csv('saved_data.csv') now_prices = [-1]*(n) jonbeo = "----------들고만 있었으면----------\n" total_jonbeo = 0 auto_upbit = "----------자동화----------\n" auto_upbit += "자동화 총 금액 -> " + str(krw_balance) + "\n" for i in range(n): now_prices[i] = pyupbit.get_current_price(coin_list[i]) total_jonbeo += now_prices[i]*own_coin_list_04_08[i] jonbeo += coin_list[i] + " 현 가격: " + str(now_prices[i]) + "이 코인의 총 가격" + str(now_prices[i]*own_coin_list_04_08[i]) + "\n" time.sleep(0.1) # total_jonbeo += 1610370 jonbeo += "지금까지 존버했으면 총 금액 -> " + str(total_jonbeo) + "\n" msg = jonbeo + auto_upbit + "존버와의 금액 차이 -> " + str(krw_balance - total_jonbeo) + "원 벌었음(-이면 잃은거)\n" try: dif_yesterday = krw_balance - df_saved_data.iloc[-1]['auto_upbit'] msg += "!!어제와의 금액 차이!!: " + str(dif_yesterday) df2 = pd.DataFrame(columns=['date','jonbeo','auto_upbit','difference_jonbeo_autoupbit','difference_yesterday']) df2 = df2.append({'date':now.strftime('%Y-%m-%d %H:%M:%S'), 'jonbeo':total_jonbeo, 'auto_upbit': krw_balance, 'difference_jonbeo_autoupbit':krw_balance - total_jonbeo,'difference_yesterday':dif_yesterday}, ignore_index=True) df2.to_csv('saved_data.csv', mode='a', header=False) except: df2 = pd.DataFrame(columns=['date','jonbeo','auto_upbit','difference_jonbeo_autoupbit']) df2 = df2.append({'date':now.strftime('%Y-%m-%d %H:%M:%S'), 'jonbeo':total_jonbeo, 'auto_upbit': krw_balance, 'difference_jonbeo_autoupbit':krw_balance - total_jonbeo}, ignore_index=True) df2.to_csv('saved_data.csv', mode='a', header=False) print(msg) bot.sendMessage(mc,msg)
def get_bull(market_name=""): ohlcv = pyupbit.get_ohlcv(market_name) ma5 = ohlcv['close'].rolling(window=5).mean() last_ma5 = ma5[-2] price = pyupbit.get_current_price(market_name) if price > last_ma5: return True else: return False
def get_current_price_as_KRW(coin_list): # get current price as KRW by coin-type import pyupbit as pb results = {} for coin in coin_list: price = pb.get_current_price(f"KRW-{coin}") results[f"KRW-{coin}"] = format(price, ",") return results
def run(self): while True: now = datetime.datetime.now() future = now + datetime.timedelta(minutes=1) year, month, day, hour, minute = future.year, future.month, future.day, future.hour, future.minute pause.until( datetime.datetime(year, month, day, hour, minute, 0, 10)) price = pyupbit.get_current_price("KRW-BTG") print('\n\ntime : ', datetime.datetime.now(), 'Open price : ', price) self.q.put(price)