Example #1
0
 def test_get_ticker(self):
     upbit = Upbitpy()
     ret = upbit.get_ticker(['KRW-ICX', 'KRW-ADA'])
     self.assertIsNotNone(ret)
     self.assertNotEqual(len(ret), 0)
     logging.info(ret)
     logging.info(upbit.get_remaining_req())
Example #2
0
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)
Example #3
0
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)
Example #4
0
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
Example #5
0
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))
    time.sleep(10)
Example #6
0
			if( orderResult['state'] == 'done') :
				print('매도 확인 완료!')
				break
		except :
			print('예외발생')


while True:
	print('no')
	try:
		sleep(0.05)
		for component in GlobalList :
			KRWList.append(component)
			BTCList.append(component.replace('KRW','BTC'))
		
			KRWTicker = upbit.get_ticker(KRWList)
			BTCTicker = upbit.get_ticker(BTCList)
			KRWtoBTC = upbit.get_ticker(['KRW-BTC'])
			KRW = KRWTicker[0]['trade_price'];
			BTC = BTCTicker[0]['trade_price'] * KRWtoBTC[0]['trade_price'];
			if( (BTC-KRW) > KRW*0.01 ) :
				BUYKRW([component], KRW)
				#while( ORDER ) :
				#	sleep(0.05)
				#	SELLKRW()
				print( upbit.get_chance(KRWList[0]) )
				print( component, KRWTicker[0]['trade_price'], BTCTicker[0]['trade_price'] * KRWtoBTC[0]['trade_price'])
				
				KRWList.pop()
				BTCList.pop()
				continue
    def run(self):
        while True:
            data = {}
            # 전체 데이터 불러옴
            #all_data = pyupbit.get_current_price(tickers)
            upbit = Upbitpy()
            all_info = upbit.get_ticker(tickers)

            # 단기 급등여부 판단
            candle_num = 3
            for ticker in all_info:
                candle_dict = upbit.get_minutes_candles(1,
                                                        ticker['market'],
                                                        count=3)

                last = candle_dict[0]['candle_acc_trade_volume']
                last_one = candle_dict[1]['candle_acc_trade_volume']
                last_two = candle_dict[2]['candle_acc_trade_volume']

                if "KRW-BTC" == ticker['market']:
                    print('----비트코인 거래량-----')
                    print('현재: ' + str(last))
                    print('1분전: ' + str(last_one))
                    print('2분전: ' + str(last_two))

                if "KRW-BCH" == ticker['market']:
                    print('----비캐 거래량-----')
                    print('현재: ' + str(last))
                    print('1분전: ' + str(last_one))
                    print('2분전: ' + str(last_two))

                if "KRW-XRP" == ticker['market']:
                    print('----리플 거래량-----')
                    print('현재: ' + str(last))
                    print('1분전: ' + str(last_one))
                    print('2분전: ' + str(last_two))

                #min_value = 9e+20
                #for data in range( 1, candle_list-1) :
                #    if data['candle_acc_trade_volume'] < min_value:
                #        min_value = data['candle_acc_trade_volume']

                #-거래량 체크
                volume_rising = '-'
                volume_change_rate = 0.0
                if last > last_one * 1.4 or (last > last_one * 1.2
                                             and last_one > last_two * 1.2):
                    volume_rising = '급증'
                    volume_change_rate = (last - last_one) / last_one * 100
                    #print(volume_change_rate)

                cur_price = ticker['trade_price']
                # 24H 거래량
                volume = ticker['acc_trade_volume_24h']
                # 부호 있는 거래량 변화율
                signed_change_rate = ticker['signed_change_rate']

                data[ticker['market']] = (cur_price, ) + (volume, ) + (
                    signed_change_rate, ) + (volume_rising, ) + (
                        int(volume_change_rate), )

            # 작업이 완료됐을때 이벤트 발생(emit)
            # data 변수가 바인딩하고 있는 딕셔너리 객체가 전송됨
            self.finished.emit(data)
            time.sleep(1)
Example #8
0
usdt_markets = []

markets = upbit.get_market_all()
for market in markets:
    if 'BTC-' in market['market']:
        btc_markets.append(market['market'])
    elif 'KRW-' in market['market']:
        krw_markets.append(market['market'])
    elif 'ETH-' in market['market']:
        eth_markets.append(market['market'])
    elif 'USDT-' in market['market']:
        usdt_markets.append(market['market'])
    else:
        print('unknown market: {}'.format(market['market']))

ticker = upbit.get_ticker(krw_markets)
for it in ticker:
    print('{}: {}원'.format(it['market'], it['trade_price']))

ticker = upbit.get_ticker(btc_markets)
for it in ticker:
    print('{}: {}'.format(it['market'], format(it['trade_price'], '.8f')))

ticker = upbit.get_ticker(eth_markets)
for it in ticker:
    print('{}: {}'.format(it['market'], format(it['trade_price'], '.8f')))

ticker = upbit.get_ticker(usdt_markets)
for it in ticker:
    print('{}: {}'.format(it['market'], format(it['trade_price'], '.8f')))
Example #9
0
    upbit = Upbitpy()

    all_market = upbit.get_market_all()
    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'])

    count = 0
    before = 481

    while 1:
        for key in market_table.keys():
            tickers = upbit.get_ticker(market_table[key])
            for it in tickers:
                if it['market'].startswith('KRW-XRP'):
                    rate = (it['trade_price'] - before) / before * 100
                    if rate > 2:
                        now = datetime.datetime.now()
                        print('{} [{}] {} : {} = {}'.format(
                            now, count, before, it['trade_price'], rate))
                        before = it['trade_price']
                        count = 0
                    elif rate < -2:
                        now = datetime.datetime.now()
                        print('{} [{}] {} : {} = {}'.format(
                            now, count, before, it['trade_price'], rate))
                        before = it['trade_price']
                        count = 0