def test_get_months_candles(self): upbit = Upbitpy() ret = upbit.get_months_candles('BTC-ETH') self.assertIsNotNone(ret) self.assertNotEqual(len(ret), 0) logging.info(ret) logging.info(upbit.get_remaining_req())
def test_get_market_all(self): upbit = Upbitpy() ret = upbit.get_market_all() self.assertIsNotNone(ret) self.assertNotEqual(len(ret), 0) logging.info(ret) logging.info(upbit.get_remaining_req())
class Upbit: def __init__(self): self.__upbit = Upbitpy() self.__krw_markets = self.__get_krw_markets() def __get_krw_markets(self): krw_markets = dict() all_markets = self.__upbit.get_market_all() for market in all_markets: if market['market'].startswith('KRW-'): krw_markets[market['market']] = market return krw_markets def get_days_candles(self, market): if market not in self.__krw_markets.keys(): return None candles = self.__upbit.get_days_candles(market, count=10) return candles def get_days_many_candles(self, market): if market not in self.__krw_markets.keys(): return None candles = self.__upbit.get_days_candles(market, count=100) return candles
def test_get_minutes_candles(self): upbit = Upbitpy() ret = upbit.get_minutes_candles(60, 'KRW-BTC') self.assertIsNotNone(ret) self.assertNotEqual(len(ret), 0) logging.info(ret) logging.info(upbit.get_remaining_req())
def test_get_trades_ticks(self): upbit = Upbitpy() ret = upbit.get_trades_ticks('KRW-ICX') self.assertIsNotNone(ret) self.assertNotEqual(len(ret), 0) logging.info(ret) logging.info(upbit.get_remaining_req())
def test_get_orderbook(self): upbit = Upbitpy() ret = upbit.get_orderbook(['KRW-ICX', 'KRW-ADA']) self.assertIsNotNone(ret) self.assertNotEqual(len(ret), 0) logging.info(ret) logging.info(upbit.get_remaining_req())
def get_accounts(self): try: upbit = Upbitpy(self.KEY, self.SECRET) ret = upbit.get_accounts() for c in ret: self.balance[c['currency']] = float(c['balance']) except: self.balance['KRW'] = 0 self.balance['USDT'] = 0 logging.info('Failed to get balance') if (self.balance['KRW'] > 0.0 or self.balance['USDT'] > 0.0) and self.exchange_rate > 0.0: # 보유자산에 따른 KRW2USD_limit and USD2KRW_limt 가중치 부여 점진법 self.KRW2USD_weighted = self.KRW2USD_limit - self.KRW2USD_limit*self.balance['KRW']/(self.balance['KRW'] + self.balance['USDT']*self.exchange_rate) self.USD2KRW_weighted = self.USD2KRW_limit - self.USD2KRW_limit*self.balance['USDT']*self.exchange_rate/(self.balance['KRW'] + self.balance['USDT']*self.exchange_rate) if self.KRW2USD_weighted >= self.KRW2USD_limit and self.KRW2USD_weighted <= self.USD2KRW_limit: self.KRW2USD_weighted = self.KRW2USD_weighted + self.KRW2USD_offset else: self.KRW2USD_weighted = self.KRW2USD_limit if self.USD2KRW_weighted >= self.KRW2USD_limit and self.USD2KRW_weighted <= self.USD2KRW_limit: self.USD2KRW_weighted = self.USD2KRW_weighted + self.USD2KRW_offset else: self.USD2KRW_weighted = self.USD2KRW_limit if self.USD2KRW_weighted < self.USD2KRW_restrict: self.USD2KRW_weighted = self.USD2KRW_weighted / 2 + 0.5 # self.USD2KRW_weighted = self.USD2KRW_restrict if self.KRW2USD_weighted > 0.0: self.KRW2USD_weighted = self.KRW2USD_weighted * 0.5 #보유자산에 따른 KRW2USD_limit and USD2KRW_limt 가중치 부여 계단법 #temp, self.USD2KRW_weighted = self.rate_limit() # ! For debugging # self.KRW2USD_weighted = 1.0 # self.USD2KRW_weighted = -1.0 logging.info('Weight %.2f %.2f'%(self.KRW2USD_weighted, self.USD2KRW_weighted))
def main(): upbit = Upbitpy() # 모든 원화 market 얻어오기 all_market = upbit.get_market_all() krw_markets = [] for m in all_market: if m['market'].startswith('KRW'): krw_markets.append(m['market']) candles_7d = dict() # 7일간 거래량 for m in krw_markets: candles_7d[m] = upbit.get_weeks_candles(m, count=1)[0] check_remaining_candles_req(upbit) while True: logging.info('평균 거래량 대비 {}분 거래량 비율========================'.format( INTERVAL_MIN)) for m in krw_markets: vol = upbit.get_minutes_candles( 1, m, count=1)[0]['candle_acc_trade_volume'] vol_7d = candles_7d[m]['candle_acc_trade_volume'] vol_7d_avg = (((vol_7d / 7.0) / 24.0) / 60.0) * INTERVAL_MIN vol_ratio = format((vol / vol_7d_avg) * 100.0, '.2f') logging.info('[{}] {}% (거래량:{}, 평균:{})'.format( m, vol_ratio, format(vol, '.2f'), format(vol_7d_avg, '.2f'))) check_remaining_candles_req(upbit) wait(INTERVAL_MIN)
def test_cancel_order(self): upbit = Upbitpy(self.KEY, self.SECRET) uuid = self.__do_temp_order(upbit) self.assertIsNotNone(uuid) ret = upbit.cancel_order(uuid) self.assertIsNotNone(ret) self.assertNotEqual(len(ret), 0) logging.info(ret)
def test_get_orders(self): upbit = Upbitpy(self.KEY, self.SECRET) self.__do_temp_order(upbit) ret = upbit.get_orders(self.TEST_MARKET, 'wait') self.assertIsNotNone(ret) self.assertNotEqual(len(ret), 0) logging.info(ret) self.__do_cancel(upbit)
def test_order(self): upbit = Upbitpy(self.KEY, self.SECRET) ret = upbit.order(self.TEST_MARKET, 'bid', self.TEST_VOLUME, self.TEST_BID_PRICE) self.assertIsNotNone(ret) self.assertNotEqual(len(ret), 0) logging.info(ret) self.__do_cancel(upbit)
def order(self, code, dir, price, qty): logging.info('%s, %s, %f, %f'%(code,dir,price,qty)) try: upbit = Upbitpy(self.KEY, self.SECRET) ret = upbit.order(code, dir, qty, price) #e.g. ('KRW-BTC', 'bid', 10, 300) logging.info(ret) except: logging.info('Order Err')
def main(): upbit = Upbitpy() keys = ['opening_price', 'trade_price', 'high_price', 'low_price', 'timestamp'] while True: coin = 'KRW-XRP' candle = upbit.get_minutes_candles(INTERVAL_MIN, coin)[0] logging.info('[{}] {}'.format(datetime.datetime.now().strftime('%Y%m%d %H:%M:%S'), coin)) for key in keys: logging.info('\t{}: {}'.format(key, candle[key])) wait(INTERVAL_MIN)
def main(): upbit = Upbitpy() updater = Updater(TELEGRAM_BOT_TOKEN) while True: ticker = upbit.get_ticker(['KRW-BTC'])[0] price_str = format(int(ticker['trade_price']), ',') text = '({}) 비트코인 가격: {} 원'.format( datetime.datetime.now().strftime('%m/%d %H:%M:%S'), price_str) updater.bot.send_message(chat_id=CHAT_ID, text=text) wait(INTERVAL_MIN)
def __init__(self): self.upbit = Upbitpy() self.markets = self.upbit.get_market_all() self.KRWmarkets = [] self.BTCmarkets = [] self.USDmarkets = [] for market in markets: self.pair = market['market'] self.marketname = pair[0:3] if self.marketname == 'BTC': self.BTCmarkets.append(pair) elif self.marketname == 'KRW': self.KRWmarkets.append(pair) else: self.USDmarkets.append(pair)
def main(): upbit = Upbitpy() # 모든 market 얻어오기 all_market = upbit.get_market_all() # market 분류 market_table = {'KRW': []} for m in all_market: for key in market_table.keys(): if m['market'].startswith(key): market_table[key].append(m['market']) # 마켓 별 가격을 가져와 출력 for key in market_table.keys(): logging.info('{} 마켓:'.format(key)) tickers = upbit.get_ticker(market_table[key]) print_tickers(tickers)
class MarketSearcher: def __init__(self): self.upbit = Upbitpy() self.markets = self.upbit.get_market_all() self.KRWmarkets = [] self.BTCmarkets = [] self.USDmarkets = [] for market in markets: self.pair = market['market'] self.marketname = pair[0:3] if self.marketname == 'BTC': self.BTCmarkets.append(pair) elif self.marketname == 'KRW': self.KRWmarkets.append(pair) else: self.USDmarkets.append(pair) def get_market_spread(self, makret): #market parameter must be list orderbook = upbit.get_orderbook(market) surfaceorder = orderbook[0]['orderbook_units'][0] spread = (surfaceorder['ask_price'] - surfaceorder['bid_price']) / surfaceorder['ask_price'] return spread def get_mininum_tick(self, price): if price <= 10: return 0.01 elif price <= 100: return 0.1 elif price <= 1000: return 1 elif price <= 10000: return 5 elif price <= 100000: return 10 elif price <= 5000000: return 50 elif price <= 1000000: return 100 elif price <= 2000000: return 500 else: return 1000
def __initial_load(self): config = configparser.ConfigParser() config.read('config.ini') self.upbit_api = (config['UPBIT_API_KEY'], config['UPBIT_API_SECRET']) self.binance_api = (config['BINANCE_API_KEY'], config['BINANCE_API_SECRET']) self.hedge_lev = config['HEDGE_LEVERAGE'] self.max_fund = config['MAX_FUND'] try: self.upbit = Upbitpy(self.upbit_api[0], self.upbit_api[1]) self.binance = Client(self.binance_api[0], self.binance_api[1]) except Exception as ex: print("api connection error", ex) return 0 else: return 1 '''
def get_minutes_candle(self): upbit = Upbitpy() print(self.target_coin) keys = ['opening_price', 'trade_price', 'high_price', 'low_price','timestamp'] candle = self.upbit.get_minutes_candles(self.INTERVAL_MIN, self.target_coin)[0] print('[{}] {}'.format(datetime.datetime.now().strftime('%Y%m%d %H:%M:%S'),self.target_coin)) for key in keys: print('\t{}: {}'.format(key, candle[key])) if (candle['opening_price'] < candle['trade_price']): print('양봉') return 1 elif (candle['opening_price'] > candle['trade_price']): print('음봉') return 0 elif (candle['opening_price'] == candle['trade_price']): print('횡보') return 2
class Upbit: def __init__(self): self.__upbit = Upbitpy() self.__krw_markets = self.__get_krw_markets() def __get_krw_markets(self): krw_markets = dict() all_markets = self.__upbit.get_market_all() for market in all_markets: if market['market'].startswith('KRW-'): krw_markets[market['market']] = market # print(krw_markets) return krw_markets def get_15minutes_candle(self, market): ''' 주어진 코인명에 대하여 15분 봉의 200개 캔들을 조회 :param market: 마켓 네임 :return: 데이터 프레임 columns={"opening_price": "open", "high_price": "high", "low_price": "low", "trade_price": "close"}) ''' if market not in self.__krw_markets.keys(): return None candles = self.__upbit.get_minutes_candles(15, market, count=1) dt_list = [datetime.datetime.strptime(x['candle_date_time_kst'], "%Y-%m-%dT%H:%M:%S") for x in candles] df = pd.DataFrame(candles, 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"}) # print(candles, type(candles)) return df def get_1hour_candle(self, market): ''' 주어진 코인명에 대하여 1시 봉의 1개 캔들을 조회 :param market: 마켓 네임 :return: 데이터 프레임 columns={"opening_price": "open", "high_price": "high", "low_price": "low", "trade_price": "close"}) ''' if market not in self.__krw_markets.keys(): return None candles = self.__upbit.get_minutes_candles(60, market, count=1) dt_list = [datetime.datetime.strptime(x['candle_date_time_kst'], "%Y-%m-%dT%H:%M:%S") for x in candles] df = pd.DataFrame(candles, 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"}) # print(candles, type(candles)) return df def get_current_price(self, market): cp = self.__upbit.get_ticker(market) # print(cp) return cp def get_hour_candles(self, market): if market not in self.__krw_markets.keys(): return None candles = self.__upbit.get_minutes_candles(15, market, count=60) # print(candles) return candles
def test_cancel_order(self): upbit = Upbitpy(self.KEY, self.SECRET) uuid = self.__do_temp_order(upbit) ret = upbit.cancel_order(uuid) logging.info(ret)
import time, rich from datetime import datetime from upbitpy import Upbitpy upbit = Upbitpy() #buy_dic = {'KRW-ETH':3297222,'KRW-XRP':935, 'KRW-WAVES':33123, 'KRW-HUM':315, 'KRW-BTC':49600000} #acc_dic = {'KRW-ETH':0.0,'KRW-XRP':5000.0, 'KRW-WAVES':0.0, 'KRW-HUM':300.0, 'KRW-BTC':0} #ticker_list = list(buy_dic.keys()) while True: buy_dic = { line.split()[0] : [int(line.split()[2]), float(line.split()[1])] for line in open("input.txt") } ticker_list = list(buy_dic.keys()) sum_profit_loss = 0 tickers = upbit.get_ticker(ticker_list) curr_time = datetime.now().strftime("%H:%M:%S") rich.print('{}'.format(curr_time)) print('{:^10}\t: {:^10}\t {:^10}\t ({:^7})\t [{:^10}]'.format('CODE', 'CURR', 'BUY', 'GAP', 'P/L')) print('-----------------------------------------------------------------------------') for ticker in tickers: code = ticker['market'] curr_price = int(ticker['trade_price']) buy_price = buy_dic.get(code)[0] step_price = curr_price-buy_price profit_loss = int(step_price*buy_dic.get(code)[1]) print('{:10}\t: {:10,}\t {:10,}\t ({:=+8,})\t [{:=+10,}]'.format(code, curr_price, buy_price, step_price, profit_loss)) sum_profit_loss = int(sum_profit_loss + profit_loss) print('-----------------------------------------------------------------------------') print(' SUM : [{:=+10,}]'.format(sum_profit_loss))
def test_get_get_accounts(self): upbit = Upbitpy(self.KEY, self.SECRET) ret = upbit.get_accounts() self.assertIsNotNone(ret) self.assertNotEqual(len(ret), 0) logging.info(ret)
def test_get_days_candles(self): upbit = Upbitpy() ret = upbit.get_days_candles('KRW-ADA') self.assertIsNotNone(ret) logging.info(ret) logging.info(upbit.get_remaining_req())
def test_get_chance(self): upbit = Upbitpy(self.KEY, self.SECRET) ret = upbit.get_chance(self.TEST_MARKET) self.assertIsNotNone(ret) self.assertNotEqual(len(ret), 0) logging.info(ret)
from upbitpy import Upbitpy if __name__ == '__main__': print("") print("") print("start") access = "xIHcZKYQQxO9xmsLSxDOrP9LJxk5RvgQCHt8H5GK" secret = "I91StxEjUU1UPpz8bu6HL1kTCLihRenHj6aGFzxm" # 키들은 본인의 키를입력합니다.# upbit = Upbitpy(access, secret) ret = upbit.get_accounts() print(ret) now_price = 10 # buy ret = upbit.order('KRW-XRP', 'bid', 100, now_price) #sell ret = upbit.order('KRW-XRP', 'ask', 100, now_price) print("end")
commit_db('INSERT INTO Transaction_history (uid, code, num, price, date, trade_type, completed) VALUES (?, ?, ?, ?, ?, ?, ?)', [data[0],data[1],data[2],data[3],strftime("%Y-%m-%d %H:%M:%S"),data[5],data[6]]) class ThreadCount(object): def __init__(self): self = [] def append(self, thread): self = [thread] def getCount(self): return len(self) def join(self): self[0].join() class User: def __init__(self, uid, uname, password): self.id = uid self.uname = uname self.password = password # Now, run the app as a server in debug mode or public mode if __name__ == '__main__': upbit = Upbitpy() markets = upbit.get_market_all() for market in markets: if 'KRW-' in market['market']: krw_markets.append(market['market']) #wsgi.server(eventlet.listen(('127.0.0.1', 5000)), app socketio.run(app, debug=True) # app.run(debug=True) # Debug mode will reload files when changed. # app.run(host='0.0.0.0') # To make the server listen on all public IPs.
def __init__(self): self.__upbit = Upbitpy() self.__krw_markets = self.__get_krw_markets()
class upbit_function: upbit = Upbitpy() target_coin ='KRW-SXP' INTERVAL_MIN = 1 # 업비트 응답시간 대기 def show_accounts(self): print('계좌내역-----------------') print(self.upbit.get_accounts()) # 시장가 구입. def buy_market_order(self,coin,access_key=None, secret=None): upbit_ = pyupbit.Upbit(access_key,secret) won = pyupbit.Upbit.get_balance('KRW') print('%d 보유 금액',won) print(pyupbit.Upbit.buy_market_order(self.target_coin,won)) #시장가 판매 def sell_coinself(self,coin,price,access_key=None, secret=None): upbit_ = pyupbit.Upbit(access_key, secret) coins = pyupbit.Upbit.get_balance(self.target_coin) print(pyupbit.Upbit.sell_market_order(self.target_coin, coins)) #현재가 조회. def get_current_price(self): pyupbit.get_current_price(self.target_coin) return pyupbit.get_current_price(self.target_coin) def wait(min): now = datetime.datetime.now() remain_second = 60 - now.second remain_second += 60 * (min - (now.minute % min + 1)) time.sleep(remain_second) # 타겟 코인을 찾음. def Serach_Target_Coin(self): candles_7d = dict() # 7일간 krw_markets = pyupbit.get_tickers(fiat="KRW") print('평균 거래량 대비 60분 거래량 비율========================') max = -9999 targetcoin='' for m in krw_markets: vol = self.upbit.get_minutes_candles(60, m, count=1)[0]['candle_acc_trade_volume'] print('[{}] (거래량:{}, )'.format(m, format(vol, '.2f'), )) if vol>max: max=vol targetcoin=m time.sleep(0.2) print('거래량이 높은 타겟 코인'+targetcoin) self.target_coin = targetcoin return targetcoin #1분봉 def get_minutes_candle(self): upbit = Upbitpy() print(self.target_coin) keys = ['opening_price', 'trade_price', 'high_price', 'low_price','timestamp'] candle = self.upbit.get_minutes_candles(self.INTERVAL_MIN, self.target_coin)[0] print('[{}] {}'.format(datetime.datetime.now().strftime('%Y%m%d %H:%M:%S'),self.target_coin)) for key in keys: print('\t{}: {}'.format(key, candle[key])) if (candle['opening_price'] < candle['trade_price']): print('양봉') return 1 elif (candle['opening_price'] > candle['trade_price']): print('음봉') return 0 elif (candle['opening_price'] == candle['trade_price']): print('횡보') return 2 def get_minutes_candle_2(self): upbit = Upbitpy() print(self.target_coin) df = pyupbit.get_ohlcv("KRW-BTC") print(df) return df #스텍슬로우 def get_market_Stochastic(self,stoch_rsi_D=None): url = "https://api.upbit.com/v1/candles/minutes/1" querystring = {"market": self.target_coin, "count": "100"} response = requests.request("GET", url, params=querystring) data = response.json() df = pd.DataFrame(data) series = df['trade_price'].iloc[::-1] df = pd.Series(df['trade_price'].values) period = 14 smoothK = 5 smoothD = 3 delta = series.diff().dropna() ups = delta * 0 downs = ups.copy() ups[delta > 0] = delta[delta > 0] downs[delta < 0] = -delta[delta < 0] ups[ups.index[period - 1]] = np.mean(ups[:period]) ups = ups.drop(ups.index[:(period - 1)]) downs[downs.index[period - 1]] = np.mean(downs[:period]) downs = downs.drop(downs.index[:(period - 1)]) rs = ups.ewm(com=period - 1, min_periods=0, adjust=False, ignore_na=False).mean() / \ downs.ewm(com=period - 1, min_periods=0, adjust=False, ignore_na=False).mean() rsi = 100 - 100 / (1 + rs) stochrsi = (rsi - rsi.rolling(period).min()) / (rsi.rolling(period).max() - rsi.rolling(period).min()) stochrsi_K = stochrsi.rolling(smoothK).mean() stochrsi_D = stochrsi_K.rolling(smoothD).mean() print('stoch_rsi_K: ', stochrsi_K.iloc[-1] * 100, ' percent') print('stoch_rsi_D: ', stochrsi_D.iloc[-1] * 100, ' percent') print('') time.sleep(1) return stochrsi_K, stochrsi_D #볼린저밴드 def get_bollinger_bands(self): url = "https://api.upbit.com/v1/candles/minutes/1" querystring = {"market": self.target_coin, "count": "100"} response = requests.request("GET", url, params=querystring) data = response.json() df = pd.DataFrame(data) df = df['trade_price'].iloc[::-1] unit = 2 band1 = unit * np.std(df[len(df) - 20:len(df)]) bb_center = np.mean(df[len(df) - 20:len(df)]) band_high = bb_center + band1 band_low = bb_center - band1 print('볼린저뱉드 상단: ', round(band_high, 2)) print('볼린저뱉드 하단: ', round(band_low, 2)) print('') time.sleep(1)
def get_minutes_candle_2(self): upbit = Upbitpy() print(self.target_coin) df = pyupbit.get_ohlcv("KRW-BTC") print(df) return df