def get_S13_coins(self): """ 현재 가격 데이터 df_all를 가져와서, bull_5 데이터를 df_all에 추가한다. (단, bull_5 데이터가 캐쉬에 있을 경우만 ) """ cache = self.cache d = cache.get(CACHE_get_S13_coins) if d: return d else: tickers_filtered = self.get_tickers() res = pybithumb.get_current_price("all") df_all = pd.DataFrame(res["data"]).T df_all = df_all.drop("date") df_all = df_all.drop( list(set(df_all.index) - set(tickers_filtered))) self.__decorate_technical_data(df_all) df_all_S13 = df_all[df_all["S13_CHECK"]] df_all_S13 = df_all_S13.T cache.setex(CACHE_get_S13_coins, CACHE_get_S13_coins_TIME, df_all_S13.to_json()) # print(df_all_S13) return df_all_S13.to_json()
# ch05/05_04.py import pybithumb import time tickers = pybithumb.get_tickers() for ticker in tickers: price = pybithumb.get_current_price(ticker) print(ticker, price) time.sleep(0.1)
import pybithumb import time while True: try: price = [ pybithumb.get_current_price("BTC"), pybithumb.get_current_price("ETH"), pybithumb.get_current_price("XRP") ] print("BTC : %.0f" % price[0]) print("ETH : %.0f" % price[1]) print("XRP : %.1f" % price[2]) time.sleep(1) except: print("error occurs")
import pybithumb df = pybithumb.get_ohlcv('BTC') ma5 = df['close'].rolling(window=5).mean() last_ma5 = ma5[-2] price = pybithumb.get_current_price('BTC') if price > last_ma5: print('상승장') else: print('사락장')
# 원화 코인 분배 total_krw = bithumb.get_balance(ticker)[2] for ticker in major_ticker: krw_by_coin[ticker] = total_krw / len(major_ticker) if krw_by_coin[ticker] > 1000: wallet_bull[ticker] = True else: wallet_bull[ticker] = False # print(wallet_bull) # print(krw_by_coin) # 딕셔너리 초기화(실행시 한번) for ticker in major_ticker: df = pybithumb.get_candlestick(ticker) current_price[ticker] = pybithumb.get_current_price(ticker) real_buy_current[ticker] = 0 beneath[ticker] = False stop_loss[ticker] = False # 각종 이동평균(실행시 한번) yes_ma5 = get_yesterday_ma5(-2) yes2_ma5 = get_yesterday_ma5(-3) yes3_ma5 = get_yesterday_ma5(-4) yes_ma20 = get_yesterday_ma20(-2) yes2_ma20 = get_yesterday_ma20(-3) # 오늘 시가, 어제 시가, 종가, 거래량, 년 평균 거래량(실행시 한번) to_open = get_today_open() yes_open = get_yesterday_open() yes_close = get_yesterday_close()
return "홀딩해", df['ma_s'][-1] elif (df['status'][-2] == 0) & (df['status'][-1] == 0): print('도망쳐', df['ma_s'][-1]) return "도망쳐", df['ma_s'][-1] alive = True get_coin_list = pd.DataFrame(columns=['Ticker', 'target_price', 'MAL']) while alive: try: for idx in range(len(df)): ticker = df.Ticker.values[idx] mas = int(df.MAS.values[idx]) mal = int(df.MAL.values[idx]) print(ticker, mas, mal, Bithumb.get_current_price(ticker)) position, target_price = get_ohlv(ticker, mas, mal) if (position == "지금이니"): if bithumb.get_balance(ticker)[2] > 5000: print( "매수해쬬옹@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" ) buy_crypto_currency(bithumb, ticker) print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") # get_coin_list = get_coin_list.append(,) elif (position == "홀딩해"): print("나중에봐용~") else: print("팔아보룟!~") sell_crypto_currency(bithumb, ticker) bithumb.get_balance(ticker)[0]
def process(threshold=3.0, interval=30): ma5_list = {} ma30_list = {} with open("thumb/ma5", "r", encoding="utf8") as rf: for line in rf.readlines(): tup = line.split("\t") if tup[1] == 'None\n': tup[1] = 0.0 ma5_list.update({tup[0]: float(tup[1])}) rf.close() with open("thumb/ma30", "r", encoding="utf8") as rf: for line in rf.readlines(): tup = line.split("\t") if tup[1] == 'None\n': tup[1] = 0.0 ma30_list.update({tup[0]: float(tup[1])}) rf.close() with output(initial_len=int(len(tickers) / NUM_OUTPUT_COLOMN) + 1, interval=0) as output_line: while True: all = pybithumb.get_current_price("ALL") if all: print_str = '' i = 0 for ticker, data in all.items(): space = '' try: check_value = round((ma30_list[ticker] - (float(data['closing_price']))) / float(data['closing_price']) * 100, 2) except: continue for _ in range(30 - ((len(data['closing_price']) * 3) + (len(ticker)))): space = space + ' ' print_str = print_str + ('\033[33m' + f"({check_value}%)"\ if check_value > threshold and ma5_list[ticker] < ma30_list[ticker] and ma30_list[ticker] > float(data['closing_price']) else '\033[37m') + ticker \ + "\033[0m" print_str = print_str + ' : ' + ('\033[31m' if float(data['closing_price']) >= float(data['opening_price']) else '\033[34m') \ + data['closing_price'] + "\033[37m" print_str = print_str + ' : ' + '\033[93m' + str( round(ma5_list[ticker], 1)) + '\033[0m' + ' : ' + '\033[95m' + str( round(ma30_list[ticker], 1)) + '\033[0m' + space if i % NUM_OUTPUT_COLOMN == 3: line = int(i / NUM_OUTPUT_COLOMN) # print( line ) output_line[line] = print_str print_str = '' i = i + 1 # print(print_str, end='\r', flush=True) time.sleep(interval)
def find_center() pass def find_boundary() pass def process() pass bithumb = bit.Bithumb(con_key, sec_key) tmp = int(input("input buy price")) while True: price = bit.get_current_price("XRP") print(price) detail = bit.get_market_detail("XRP") print(detail) if type(price) != int: time.sleep(1) continue if(price <= tmp): order = bithumb.buy_market_order("XRP", 5) print(order) print("completed", price) break time.sleep(1)
def sell_crypto_currency(ticker): unit = bithumb.get_balance(ticker)[0] bithumb.sell_market_order(ticker, unit) now = datetime.datetime.now() mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1) ma5 = get_yesterday_ma5("ARW") target_price = get_target_price("ARW") while True: try: now = datetime.datetime.now() if mid <= now <= mid + datetime.timedelta(seconds=10): target_price = get_target_price("ARW") mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1) ma5 = get_yesterday_ma5("ARW") sell_crypto_currency("ARW") current_price = pybithumb.get_current_price("ARW") if (current_price > target_price) and (current_price > ma5): buy_crypto_currency("ARW") except: print("에러발생") time.sleep(1)
print(e) Fluclist = list(map(float, Fluclist)) series = Series(Fluclist, Coinlist) series = series.sort_values(ascending=False) # 선별할 코인 개수 : 상승장에 있는 코인들을 선별할 줄 알아야한다. series = series[0:CoinVolume] print(series) print() FamousCoin = list(series.index) # 한자리 미만 코인 처리 for Coin in FamousCoin: try: if pybithumb.get_current_price(Coin) < 1: FamousCoin.remove(Coin) except Exception as e: FamousCoin.remove(Coin) print(e) Coins = FamousCoin # ------------------ 상승률 좋은 인기 코인 추출 ------------------# # ------------------ 세력이 올라탄 코인 찾기 in Realtime ------------------# while True: try: candis, ratio = [], []
def run(self): print("시작") # num=-2 : yesterday # num=-3 : yesterday2 # num=-4 : yesterday3 def get_yesterday_ma5(num): close = df['close'] ma = close.rolling(window=5).mean() return ma[num] # num=-2 : yesterday # num=-3 : yesterday2 def get_yesterday_ma20(num): close = df['close'] ma = close.rolling(window=20).mean() return ma[num] # 오늘 시가 함수 def get_today_open(): open_to = df['open'] return open_to[-1] # 1일전 시가 함수 def get_yesterday_open(): open_yes = df['open'] return open_yes[-2] # 1일전 종가 함수 def get_yesterday_close(): close = df['close'] return close[-2] # 30일 평균 거래량 함수 def get_aver_volume(): volume_aver_30 = df['volume'].rolling(window=30).mean() return volume_aver_30[-2] # 오늘 거래량 함수 def get_to_volume(): volume = df['volume'] return volume[-1] # 구매 함수(시장가) def buy_crypto_currency(ticker): orderbook = pybithumb.get_orderbook(ticker) buy_price[ticker] = orderbook['asks'][0]['price'] buy_unit = krw_by_coin[ticker] / float(buy_price[ticker]) order_buy = bithumb.buy_market_order(ticker, buy_unit) print(order_buy) # print(buy_price[ticker], buy_unit) # 테스트용, 실사용시 위 2줄 사용 # 구매후 지갑상태, 가격 갱신 wallet_bull[ticker] = False krw_by_coin[ ticker] = krw_by_coin[ticker] - buy_unit * buy_price[ticker] data[ticker] = "구매", buy_price[ticker], now, -1 return buy_price[ticker] # 판매 함수(시장가) def sell_crypto_currency(ticker): sell_unit = bithumb.get_balance(ticker)[0] orderbook = pybithumb.get_orderbook(ticker) sell_price[ticker] = orderbook['bids'][0]['price'] order_sell = bithumb.sell_market_order(ticker, sell_unit) print(order_sell) # print(sell_unit, sell_price[ticker]) # 테스트용, 실사용시 위 2줄 사용 # 판매후 지갑상태, 가격 갱신 wallet_bull[ticker] = True krw_by_coin[ ticker] = krw_by_coin[ticker] + sell_unit * sell_price[ticker] if krw_by_coin[ticker] <= 1000: wallet_bull[ticker] = False ror[ticker] = sell_price[ticker] * 0.995 / buy_price[ticker] hpr[ticker] = hpr[ticker] * ror[ticker] data[ticker] = "판매", sell_price[ticker], now, hpr[ticker] return sell_price[ticker] # 초기화, 초기 설정(실행시 한번) now = datetime.datetime.now() mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1) count = 0 data = {} current_price = {} real_buy_current = {} wallet_bull = {} beneath = {} stop_loss = {} golden_cross = {} convex_down = {} dead_cross = {} convex_up = {} cross = {} jang_dae_plus = {} jang_dae_minus = {} jang_dae_plus_volume = {} jang_dae_minus_volume = {} unit_c = {} krw_by_coin = {} buy_price = {} sell_price = {} ror = {} hpr = {} for ticker in major_ticker: ror[ticker] = 1 hpr[ticker] = 1 # 원화 코인 분배 total_krw = bithumb.get_balance("BTC")[2] for ticker in major_ticker: krw_by_coin[ticker] = total_krw / len(major_ticker) if krw_by_coin[ticker] > 1000: wallet_bull[ticker] = True else: wallet_bull[ticker] = False # 딕셔너리 초기화(실행시 한번) for ticker in major_ticker: df = pybithumb.get_candlestick(ticker) current_price[ticker] = pybithumb.get_current_price(ticker) real_buy_current[ticker] = current_price[ticker] beneath[ticker] = False stop_loss[ticker] = False # 각종 이동평균(실행시 한번) yes_ma5 = get_yesterday_ma5(-2) yes2_ma5 = get_yesterday_ma5(-3) yes3_ma5 = get_yesterday_ma5(-4) yes_ma20 = get_yesterday_ma20(-2) yes2_ma20 = get_yesterday_ma20(-3) # 오늘 시가, 어제 시가, 종가, 거래량, 년 평균 거래량(실행시 한번) to_open = get_today_open() yes_open = get_yesterday_open() yes_close = get_yesterday_close() volume_aver = get_aver_volume() to_volume = get_to_volume() # 골든크로스, 아래로 볼록(실행시 한번) golden_cross[ticker] = (yes2_ma5 < yes2_ma20) and (yes_ma5 > yes_ma20) convex_down[ticker] = (yes3_ma5 > yes2_ma5) and (yes2_ma5 < yes_ma5) # 데드크로스, 위로 볼록, 십자가(실행시 한번) dead_cross[ticker] = (yes2_ma5 > yes2_ma20) and (yes_ma5 < yes_ma20) convex_up[ticker] = (yes3_ma5 < yes2_ma5) and (yes2_ma5 > yes_ma5) cross[ticker] = abs(yes_close - yes_open) < yes_open * cross_cnst # 장대양봉, 장대음봉(실행시 한번) jang_dae_plus[ticker] = abs(current_price[ticker] - to_open) > to_open * jang_plus_cnst jang_dae_minus[ticker] = (to_open > current_price[ticker]) and ( abs(to_open - current_price[ticker]) > to_open * jang_minus_cnst) # 장대양봉 + 거래량, 장대음봉+거래량(실행시 한번) jang_dae_plus_volume[ticker] = jang_dae_plus[ticker] and ( to_volume > volume_aver * 2) jang_dae_minus_volume[ticker] = jang_dae_minus[ticker] and ( to_volume > volume_aver * 2) time.sleep(0.1) while True: for ticker in major_ticker: try: # 현재가 받아옴(실시간) current_price[ticker] = pybithumb.get_current_price(ticker) # 현재시간(실시간) now = datetime.datetime.now() # 차트 받아옴(실시간) df = pybithumb.get_candlestick(ticker) # 계산(실시간) to_open = get_today_open() volume_aver = get_aver_volume() to_volume = get_to_volume() # 자정이 넘어가면 정보 최신화, 조건 만족시 구매 or 판매(하루 한번) if mid < now < mid + datetime.timedelta(seconds=20): # 차트 받아옴(하루 한번) df = pybithumb.get_candlestick(ticker) # 각종 이동평균(하루 한번) yes_ma5 = get_yesterday_ma5(-2) yes2_ma5 = get_yesterday_ma5(-3) yes3_ma5 = get_yesterday_ma5(-4) yes_ma20 = get_yesterday_ma20(-2) yes2_ma20 = get_yesterday_ma20(-3) # 오늘 시가, 어제 시가, 종가, 거래량, 년 평균 거래량(하루 한번) to_open = get_today_open() yes_open = get_yesterday_open() yes_close = get_yesterday_close() volume_aver = get_aver_volume() to_volume = get_to_volume() # 골든크로스, 아래로 볼록(하루 한번) golden_cross[ticker] = (yes2_ma5 < yes2_ma20) and ( yes_ma5 > yes_ma20) convex_down[ticker] = (yes3_ma5 > yes2_ma5) and ( yes2_ma5 < yes_ma5) # 데드크로스, 위로 볼록, 십자가(하루 한번) dead_cross[ticker] = (yes2_ma5 > yes2_ma20) and ( yes_ma5 < yes_ma20) convex_up[ticker] = (yes3_ma5 < yes2_ma5) and (yes2_ma5 > yes_ma5) cross[ticker] = abs(yes_close - yes_open) < yes_open * cross_cnst # 골든크로스, 아래로 볼록 구매(하루 한번) if wallet_bull[ticker] and (golden_cross[ticker] or convex_down[ticker]): real_buy_current[ticker] = buy_crypto_currency( ticker) print(ticker, real_buy_current[ticker], "골든크로스, 아래로 볼록 구매") print(now) # 판매 가능한지 수량 판별(하루 한번) unit = bithumb.get_balance(ticker) if unit[0] * current_price[ticker] <= 1000: unit_c[ticker] = False else: unit_c[ticker] = True # 데드크로스, 위로볼록, 십자가 판매(하루 한번) if unit_c[ticker] and (dead_cross[ticker] or convex_up[ticker] or cross[ticker]): sell_crypto_currency(ticker) real_sell_current = pybithumb.get_current_price( ticker) print(ticker, real_sell_current, "데드크로스 ,위로볼록 ,십자가 판매") print(now) # 자정 업데이트(하루 한번) mid = datetime.datetime( now.year, now.month, now.day) + datetime.timedelta(1) # 장대양봉, 장대음봉(실시간) jang_dae_plus[ticker] = abs(current_price[ticker] - to_open ) > to_open * jang_plus_cnst jang_dae_minus[ticker] = ( to_open > current_price[ticker]) and ( abs(to_open - current_price[ticker]) > to_open * jang_minus_cnst) # 장대양봉 + 거래량, 장대음봉+거래량(실시간) jang_dae_plus_volume[ticker] = jang_dae_plus[ticker] and ( to_volume > volume_aver * 2) jang_dae_minus_volume[ticker] = jang_dae_minus[ ticker] and (to_volume > volume_aver * 2) # 장대양봉 구매(실시간) if wallet_bull[ticker] and jang_dae_plus_volume[ticker]: real_buy_current[ticker] = buy_crypto_currency(ticker) print(ticker, real_buy_current[ticker], "장대양봉 구매") print(now) # 익절(실시간) if current_price[ ticker] >= real_buy_current[ticker] * bene_cnst: beneath[ticker] = True else: beneath[ticker] = False # 손절(실시간) if current_price[ticker] <= real_buy_current[ticker] * ( 1 - stop_loss_cnst): stop_loss[ticker] = True else: stop_loss[ticker] = False # 판매 가능한지 수량 판별(실시간) unit = bithumb.get_balance(ticker) if unit[0] * current_price[ticker] <= 1000: unit_c[ticker] = False else: unit_c[ticker] = True # 장대음봉, 익절, 손절 판매(실시간) if unit_c[ticker] and (jang_dae_minus_volume[ticker] or beneath[ticker] or stop_loss[ticker]): real_sell_current = sell_crypto_currency(ticker) print(ticker, real_sell_current, "장대음봉, 익절, 손절 판매") print(now) except Exception as e: # 모든 예외의 에러 메시지를 출력할 때는 Exception 을 사용 print('예외가 발생했습니다.', e) # 코인별 시간차 time.sleep(0.1) self.finished.emit(data) self.msleep(500) # 모든 코인 실행 뒤 시간차 time.sleep(0.3) count = count + 1 print(count)
import pybithumb import time import datetime # 5.1.2 가상화폐 티커 목록 얻기 tickers = pybithumb.get_tickers() print(tickers) print(len(tickers)) # tickers의 length # 5.1.3 현재가 얻기 price = pybithumb.get_current_price("BTC", "KRW") # 뒤에 기축 KRW는 생략 가능함 print(price) # 2초에 한 번씩 시세 가져오기 """ while True: price = pybithumb.get_current_price("BTC") print(price) time.sleep(2) """ # 빗썸에 모든 코인 현재가격 가져오기 """ tickers = pybithumb.get_tickers() for ticker in tickers: price = pybithumb.get_current_price(ticker) print(price) time.sleep(0.1) """ # 5.1.4 거래소 거래 정보 (시가, 고가, 저가, 종가, 거래량)
return ma[-2] now = datetime.datetime.now() mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1) today = now.strftime("%Y-%m-%d %H:%M:%S") ma5 = get_yesterday_ma5("XRP") target_price = get_target_price("XRP") while True: try: now = datetime.datetime.now() today = now.strftime("%Y-%m-%d %H:%M:%S") now_price = int(pybithumb.get_current_price("XRP")) target = get_target_price("XRP") print("now activating", today, "now price:", now_price, "target:", target) if mid < now < mid + datetime.timedelta(seconds=10): target_price = get_target_price("XRP") mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1) ma5 = get_yesterday_ma5("XRP") sell_crypto_currency("XRP") print("@@ SELL @@") current_price = pybithumb.get_current_price("XRP") if (current_price > target_price) and (current_price > ma5):
# 자정이후 데이터 갱신 current_price = dict() michaegyul = True print('\n', now) mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1) buy_list_name = buy_list_init(now) sell_targets(target_coins) # 보유 잔고 매도 watch_coin, buy_flag, target_price = update_target_watch_coin( target_coins, now) buy_flag2 = buy_flag.copy() #unit_price = get_unit_price(watch_coin) all_current = pybithumb.get_current_price("ALL") # 현재가 수신 if all_current is None: print(f"예외발생 {now}") continue for coin in watch_coin: _current = float(all_current[coin]["closing_price"]) current_price[coin] = _current if _current >= target_price[coin] and buy_flag[coin]: print( f"\n매수알림 {coin} : 목표가격 {target_price[coin]}, 현재가 {_current}" ) send_telegram(f"<코인킹-매수알림>\n{coin} : {target_price[coin]}") result = buy_targets(coin, target_price[coin]) # 주문 실행
import pybithumb all = pybithumb.get_current_price("ALL") for k, v in all.items(): print(k, v)
def run(self): now = datetime.datetime.now() # 2019-12-09 00:02 mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1) global ready_trading while True: try: if not ready_trading: before_trading_dic = {} for ticker in coin_list: before_trading_dic[ticker] = {} before_trading_dic[ticker]['final_invest_price'] = 0 before_trading_dic[ticker][ 'current_price'] = pybithumb.get_current_price( ticker) before_trading_dic[ticker]['target_price'] = 0 before_trading_dic[ticker][ 'check_target_price'] = False before_trading_dic[ticker]['buy_end'] = False time.sleep(0.5) self.update_table(before_trading_dic) now = datetime.datetime.now() # 2019-12-09 00:02 if mid + datetime.timedelta(seconds=10) < now: if not ready_trading: #트레이딩 준비 전인가? coin_list_dic = {} trading_amt = {} for ticker in coin_list: coin_list_dic[ticker] = {} coin_list_dic[ticker]['final_invest_price'] = 0 coin_list_dic[ticker]['current_price'] = 0 coin_list_dic[ticker]['target_price'] = 0 coin_list_dic[ticker]['check_target_price'] = False coin_list_dic[ticker]['buy_end'] = False mid = datetime.datetime( now.year, now.month, now.day) + datetime.timedelta(1) balance = bithumb.get_balance("BTC") # 잔고 print("잔고 : " + str(balance[2])) print( "=================================================" ) devided_invest_price = float(format( balance[2], 'f')) / len(coin_list) # 코인별 얼마를 투자할 것이냐. for ticker in coin_list: #매수 트래이딩 전 trading_amt[ ticker] = devided_invest_price * self.get_market_timing( ticker) if trading_amt[ticker] > 0: coin_list_dic[ticker][ 'target_price'] = self.get_target_price( ticker) try: coin_list_dic[ticker][ 'final_invest_price'] = target_volatility / self.get_volatility( ticker) * trading_amt[ticker] except Exception as e: print(e) coin_list_dic[ticker][ 'final_invest_price'] = 0 pass print( str(ticker) + " 투자금액 : " + str(coin_list_dic[ticker] ['final_invest_price'])) print( str(ticker) + " 타겟 금액 : " + str(coin_list_dic[ticker]['target_price'])) print( "=================================================" ) time.sleep(0.5) else: coin_list_dic[ticker]['final_invest_price'] = 0 ready_trading = True self.update_table(coin_list_dic) # 트레이딩 준비 끝! if ready_trading: curr_price = '' for ticker in coin_list: if coin_list_dic[ticker]['final_invest_price'] > 0.0: coin_list_dic[ticker][ 'current_price'] = pybithumb.get_current_price( ticker) curr_price += ticker + " 현재가 : " + str( coin_list_dic[ticker]['current_price']) + ' ' if coin_list_dic[ticker][ 'target_price'] < coin_list_dic[ticker][ 'current_price'] and not coin_list_dic[ ticker]['check_target_price']: try: print(ticker + " 타겟가격 돌파!! / 현재가 : " + str(coin_list_dic[ticker] ['current_price']) + " 타겟가 : " + str(coin_list_dic[ticker] ['target_price'])) # 해당 ticker에 돌파했다라고 체크 coin_list_dic[ticker][ 'check_target_price'] = True if not coin_list_dic[ticker][ 'buy_end']: #해당 티커를 아직 구매 안했으면.. buy_order = self.buy_crypto_currency( ticker, coin_list_dic[ticker] ['final_invest_price']) print(ticker + "매수 거래번호 : " + str(buy_order)) ticker_amt = bithumb.get_balance( ticker)[0] if ticker_amt > 0: coin_list_dic[ticker][ 'buy_end'] = True except Exception as e: print(e) pass self.update_table(coin_list_dic) if mid <= now < mid + datetime.timedelta(seconds=5): for ticker in coin_list: unit = bithumb.get_balance(ticker)[0] if unit > 0: sell_order = self.sell_crypto_currency( ticker, unit) print(ticker + "매도 거래번호 : " + str(sell_order)) ready_trading = False time.sleep(0.5) except Exception as e: print(e) pass
def run(self): while self.alive: data = pybithumb.get_current_price(self.ticker) time.sleep(1) self.dataSent.emit(data)
yesterday_high = yesterday['high'] yesterday_low = yesterday['low'] target_price = round( today_open + (yesterday_high - yesterday_low) * K, 1) # 이동평균 값 만들기 close = df['close'] ema13 = close.ewm(span=13).mean()[-2] # 매수 목표 가격, 지수이동평균 값, 24시간 가격 변동률, 매수 여부, 20% 이상 가격 상승 시 메세지 전송 여부 target_prices[k] = [target_price, ema13, True, True] return target_prices target_prices = get_target_price(pybithumb.get_current_price("ALL")) while True: timestamp = str(datetime.datetime.fromtimestamp(time.time()))[:19] try: now = datetime.datetime.now() if mid < now < mid + datetime.timedelta(seconds=10): tickers = pybithumb.get_current_price("ALL") # type: dict target_prices = get_target_price(tickers) mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1) for k, v in tickers.items(): if k in top_tickers: message = f"{timestamp} {k.upper()} : {sell_crypto_currency(k)['message']}" print(message) send_slack_message('모든 코인 매도 완료! 계좌를 확인해주세요.')
bithumb = pybithumb.Bithumb(con_key, sec_key) def get_target_price(ticker): df = pybithumb.get_ohlcv(ticker) yesterday = df.iloc[-2] today_open = yesterday['close'] yesterday_high = yesterday['high'] yesterday_low = yesterday['low'] target = today_open + (yesterday_high - yesterday_low) * 0.5 return target now = datetime.datetime.now() mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1) target_price = get_target_price("BTC") while True: now = datetime.datetime.now() if mid < now < mid + datetime.delta(seconds=10): target_price = get_target_price("BTC") mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1) current_price = pybithumb.get_current_price("BTC") if current_price > target_price: krw = bithumb.get_balance("BTC")[2] orderbook = pybithumb.get_orderbook("BTC") sell_price = orderbook['asks'][0]['price'] unit = krw/float(sell_price) bithumb.buy_market_order("BTC", unit) time.sleep(1)
def try_buy(self): if price is not None: # 시간을 저장하는 함수 # now = 현재시각 , price = 코인 현재가격 target = 목표가격 ma = 이동평균선 # 데이터베이스 rows 인자 별 의미 -> 0:PID 4:balance 5:unit1 6:unit2 7:unit3 8:unit4 9:unit5 # 여기에 데이터베이스 식별을 위한 유저 개인 정보를 더 받아와야 함 try: ###mysql 데이터 로드 시작 conn = pymysql.connect(host='db-2um5m.pub-cdb.ntruss.com', port=3306, user='******', password='******', db='mockcoiner_db', charset='utf8') curs = conn.cursor() sql_open = "SELECT * FROM mockcoiner_db.user WHERE email = '" + str( _id_) + "'" curs.execute(sql_open) rows = curs.fetchall() balance = rows[0][4] balance_temp = float(balance) * 0.15 pid = rows[0][0] unit = [] for i in range(5): a = float(rows[0][i + 5]) unit.append(a) for i in range(5): sql_name = "UPDATE mockcoiner_db.user SET coin" + str( i + 1) + " = '" + tickers[i] + "' WHERE (pid = " + str( pid) + ");" print(sql_name) curs.execute(sql_name) conn.commit() ###mysql 데이터 로드 끝 asks = [] sell_price = [] #Save the Coin Name to DB # 현재 시장 매수,매도상황 for i in range(5): #orderbook = pybithumb.get_orderbook(tickers[i]) #asks = orderbook['asks'] #a = asks[0]['price'] a = pybithumb.get_current_price(tickers[i]) sell_price.append(a) print(sell_price[i], "sell_price") print("현재가 : ", price[i], "목표가 : ", target[i], "이동평균선", ma5[i]) self.textEdit.append("###" + str(rows[0][i + 10]) + "###" + "\n현재가 : " + str(price[i]) + "\n목표가 : " + str(target[i]) + "\n이동평균선 : " + str(ma5[i]) + "\n") print(noise_df[i][0]) # 매수 조건 활성화 if price[i] > target[i] and price[i] > ma5[i] and noise_df[ i][0] == True: # 목표가격 및 이동 평균선 수치보다 높다면 print(i + 1, "번째 코인 매수신호발생!", price[i], target[i]) self.textEdit.append( "===%s 번째 코인 %s 매수신호발생!===\n 현재가격: %s 목표가격: %s" % (i + 1, rows[0][i + 10], price[i], target[i])) ##### 거래 코인 갯수 및 잔고 계산 # unit_coin = 돈 -> 코인 개수로 환산 unit_coin = float(balance_temp) / float(sell_price[i]) unit_coin = round(unit_coin, 4) # 거래가 일어 났으니 그 코인 개수만큼 내 계좌에서 차감 시키는 작업 balance_update = float(balance) - float( sell_price[i] * unit_coin) balance_update = round(balance_update, 4) # 소수점 반올림 ##### # 이전에 이미 잔고를 코인으로 전환 하였다면, 거래가 일어나지 않아야 함, 이 모델은 하루에 두번 이상 매수,매도가 일어나지 않기 때문 if unit[i] > float(0): print("이미 매수하였습니다.") self.textEdit.append("이미 매수하였습니다.") pass else: if balance_update < 0: # 현재 가격과 최우선 매도가 가격과의 gap,슬리피지로 인한 잔고 부족 사태가 생기는 경우를 의미 print("잔액부족으로 거래가 일어나지 않았습니다.") self.textEdit.append("잔액부족으로 거래가 일어나지 않았습니다") pass # 일반적인 경우, 즉 최초로 거래가 일어났다면 코인과 잔고를 갱신시키는 작업이 필요함. else: # 데이터 베이스에 코인과 잔고를 갱신 시키는 작업 balance = balance_update print("저장될 코인 개수 : ", unit_coin, " 잔고 : ", balance) self.textEdit.append("저장될 코인 개수 : %s 잔고 : %s" % (unit_coin, balance)) ##### print("Save to DataBase...") sql_unit = "UPDATE mockcoiner_db.user SET unit" + str( i + 1) + " = " + str( unit_coin) + " WHERE (pid = " + str( pid) + ");" # print(sql_unit) curs.execute(sql_unit) conn.commit() sql_balance = "UPDATE mockcoiner_db.user SET balance = " + str( balance) + " WHERE (pid = " + str( pid) + ");" print(sql_balance) curs.execute(sql_balance) conn.commit() else: print(i + 1, "번째 코인 매수조건아님", price[i], target[i]) self.textEdit.append(" %s 번째 코인 %s 매수조건 아님 \n" % (i + 1, rows[0][i + 10])) except: print("try buy Error") pass finally: ###mysql self.textEdit.append("갱신중입니다...\n") print("finally pass") conn.close() ##최종적으로 연결을 닫음