class App(QMainWindow, form_class): def __init__(self): super().__init__() self.setupUi(self) self.initUI() self.show() self.upbit = Upbit() self.upbit.update_signal.connect(self.update) self.upbit.start() # 해당 쓰레드의 run 메서드 호출 def initUI(self): self.BTC_chart = CoinChart("BTC") #FigureCanvas(Figure(figsize=(5, 3))) self.EOS_chart = CoinChart("EOS") #FigureCanvas(Figure(figsize=(5, 3))) self.ETH_chart = CoinChart("ETH") #FigureCanvas(Figure(figsize=(5, 3))) graph_layout = QVBoxLayout(self.coin_graphs) # UI로 생성한 위젯을 레이아웃으로 설정 graph_layout.addWidget(self.BTC_chart) graph_layout.addWidget(self.EOS_chart) graph_layout.addWidget(self.ETH_chart) @pyqtSlot(dict) def update(self, data): code = data['code'].split('-')[1] if code == "BTC": self.BTC_chart.updateData(data) elif code == "EOS": self.EOS_chart.updateData(data) elif code == "ETH": self.ETH_chart.updateData(data)
def __init__(self): cls = type(self) if not hasattr(cls, "_init"): # Foo 클래스 객체에 _init 속성이 없다면 print("__init__ is called\n") self.upbit = Upbit() self.sched = BackgroundScheduler() self.sched.start() self.job_id = '' data_setup() cls._init = True
def __init__(self): super().__init__() self.setupUi(self) self.initUI() self.show() self.upbit = Upbit() self.upbit.update_signal.connect(self.update) self.upbit.start() # 해당 쓰레드의 run 메서드 호출
def __init__(self, ticker): super().__init__() self.setupUi(self) self.timer = QTimer(self) self.timer.start(3000) self.timer.timeout.connect(self.check) with open('key.txt', 'r') as f: keys = list(csv.reader(f, delimiter="/")) self.upbit = Upbit(upbit_access_key=keys[0][1], upbit_secret_key=keys[0][2]) self.binance = Binance(binance_access_key=keys[1][1], binance_secret_key=keys[1][2]) self.ticker = ticker
def __init__(self): self.bot = Telegram_bot() with open('key.txt', 'r') as f: keys = list(csv.reader(f, delimiter="/")) self.upbit = Upbit(upbit_access_key=keys[0][1], upbit_secret_key=keys[0][2]) self.binance = Binance(binance_access_key=keys[1][1], binance_secret_key=keys[1][2]) self.newest_news = {} self.url = 'https://api-manager.upbit.com/api/v1/notices?page=1&per_page=20&thread_name=general' self.listing_url = 'https://api-manager.upbit.com/api/v1/notices/search?search=%5B%EA%B1%B0%EB%9E%98%5D&page=1&per_page=20&before=&target=non_ios&thread_name=general' self.headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0", "Accept-Encoding": "*", "Connection": "keep-alive" }
def test_should_have_access_and_secret(self): self.upbit = Upbit(None, None) actual = self.upbit.get_assets() self.assertIsNone(actual, 'Authorization failed.') self.upbit = Upbit(self.__key['access'], None) actual = self.upbit.get_assets() self.assertIsNone(actual, 'Authorization failed.') self.upbit = Upbit(None, self.__key['secret']) actual = self.upbit.get_assets() self.assertIsNone(actual, 'Authorization failed.') self.upbit = Upbit(self.__key['access'], self.__key['secret']) actual = self.upbit.get_assets() self.assertIsNotNone(actual, 'Authorization failed.')
class MyWindow(QMainWindow, form_class): def __init__(self, ticker): super().__init__() self.setupUi(self) self.timer = QTimer(self) self.timer.start(3000) self.timer.timeout.connect(self.check) with open('key.txt', 'r') as f: keys = list(csv.reader(f, delimiter="/")) self.upbit = Upbit(upbit_access_key=keys[0][1], upbit_secret_key=keys[0][2]) self.binance = Binance(binance_access_key=keys[1][1], binance_secret_key=keys[1][2]) self.ticker = ticker def check(self): cur_time = QTime.currentTime() str_time = cur_time.toString('hh:mm:ss') self.statusBar().showMessage(str_time) status = self.upbit.check_wallet_status(self.ticker) print(status['currency']) wallet_status_list = status['currency']['wallet_support'] wallet_status = '' for ls in wallet_status_list: wallet_status += ls wallet_status += '\n' self.textBrowser.setText(wallet_status) if 'deposit' in wallet_status: # self.binance.create_market_order('XRP/BTC','buy',0.005) first_address, second_address = self.upbit.get_address(self.ticker) print(first_address) print(second_address) QCoreApplication.quit()
def test_has_neither_access_key_nor_secret_key(self): self.upbit = Upbit('abc', None) actual = self.upbit.get_markets() self.assertIsNotNone(actual) self.upbit = Upbit(None, 'xyz') actual = self.upbit.get_markets() self.assertIsNotNone(actual) self.upbit = Upbit(None, None) actual = self.upbit.get_markets() self.assertIsNotNone(actual)
class TestUpbitAccountAPI(unittest.TestCase): """ Integration tests for the Upbit exchange API. A JSON file required for this test. It should have an access key and a secret key issued by Upbit. ie. key.json: { "access": "f4AT0XjalGRvnMPXaxaEK6u3lTTa5szKv7NZSW0q", "secret": "aSGFdg23948afj3487faheWGAEalsidhAGFDFaFa" } """ def setUp(self): with open('key.json') as key_file: self.__key = json.load(key_file) self.upbit = Upbit(self.__key['access'], self.__key['secret']) def tearDown(self): #time.sleep(5.0) pass def test_should_have_access_and_secret(self): self.upbit = Upbit(None, None) actual = self.upbit.get_assets() self.assertIsNone(actual, 'Authorization failed.') self.upbit = Upbit(self.__key['access'], None) actual = self.upbit.get_assets() self.assertIsNone(actual, 'Authorization failed.') self.upbit = Upbit(None, self.__key['secret']) actual = self.upbit.get_assets() self.assertIsNone(actual, 'Authorization failed.') self.upbit = Upbit(self.__key['access'], self.__key['secret']) actual = self.upbit.get_assets() self.assertIsNotNone(actual, 'Authorization failed.') def test_get_assets(self): actual = self.upbit.get_assets() test_basic_api_response(self, actual, 'get_assets') def test_get_order_chance(self): actual = self.upbit.get_order_chance(MARKET) test_basic_api_response(self, actual, 'get_order_chance') def test_get_withdraw_chance(self): actual = self.upbit.get_withdraw_chance(CURRENCY) test_basic_api_response(self, actual, 'get_withdraw_chance')
class Scheduler: _sched = None def __new__(cls, *args, **kwargs): if not hasattr(cls, "_instance"): # Foo 클래스 객체에 _instance 속성이 없다면 print("__new__ is called\n") cls._instance = super().__new__( cls) # Foo 클래스의 객체를 생성하고 Foo._instance로 바인딩 return cls._instance # Foo._instance를 리턴 def __init__(self): cls = type(self) if not hasattr(cls, "_init"): # Foo 클래스 객체에 _init 속성이 없다면 print("__init__ is called\n") self.upbit = Upbit() self.sched = BackgroundScheduler() self.sched.start() self.job_id = '' data_setup() cls._init = True def __del__(self): self.shutdown() def shutdown(self): self.sched.shutdown() def kill_scheduler(self, job_id): try: self.sched.remove_job(job_id) except JobLookupError as err: return "fail to stop Scheduler: {err}".format(err=err) def Every1Hour(self): filename = 'Every1Hour.csv' with open(filename) as f: df = self.upbit.get_1hour_candle('KRW-BTC') df.to_csv(filename, index=True, mode='a', encoding='utf-8', header=False) add_EMAs(filename) def Every15Minutes(self): filename = 'Every15Minutes.csv' with open(filename) as f: df = self.upbit.get_15minutes_candle('KRW-BTC') df.to_csv(filename, index=True, mode='a', encoding='utf-8', header=False) add_EMAs(filename) def scheduler(self, type, job_id): if type == 'cron': if job_id == 'Every1Hour': self.sched.add_job( self.Every1Hour, type, hour='*', # 매 시간 minute='0', # 0분 second='5', # 5초에 id=job_id) return "{type} Scheduler Start".format(type=type) elif job_id == 'Every15Minutes': self.sched.add_job( self.Every15Minutes, type, hour='*', # 매 시간 minute='*/15', # 15분마다 second='5', # 5초에 id=job_id) return "{type} Scheduler Start".format(type=type)
# _*_ coding: utf-8 _*_ import logging from upbit import Upbit from flask import Flask, request, render_template app = Flask(__name__) upbit = Upbit() upbit.get_hour_candles('KRW-BTC') @app.route('/') def root(): market = request.args.get('market') if market is None or market == '': return 'No market parameter' candles = upbit.get_hour_candles(market) if candles is None: return 'invalid market: {}'.format(market) label = market xlabels = [] dataset = [] i = 0 for candle in candles: xlabels.append('') dataset.append(candle['trade_price']) i += 1 return render_template('chart.html', **locals())
def setUp(self): with open('key.json') as key_file: self.__key = json.load(key_file) self.upbit = Upbit(self.__key['access'], self.__key['secret'])
class TestUpbitQuotationAPI(unittest.TestCase): """ Integration tests for the Upbit quotation API. """ def setUp(self): self.upbit = Upbit(None, None) def tearDown(self): pass def test_has_neither_access_key_nor_secret_key(self): self.upbit = Upbit('abc', None) actual = self.upbit.get_markets() self.assertIsNotNone(actual) self.upbit = Upbit(None, 'xyz') actual = self.upbit.get_markets() self.assertIsNotNone(actual) self.upbit = Upbit(None, None) actual = self.upbit.get_markets() self.assertIsNotNone(actual) def test_get_markets(self): actual = self.upbit.get_markets() test_basic_api_response(self, actual, 'get_markets') self.assertGreater(len(actual), 0, 'get_markets\'s list is 0-length.') def test_get_candles_per_minutes_with_exception(self): minute = 2 with self.assertRaises(Exception) as cm: actual = self.upbit.get_candles_per_minutes(minute, MARKET) self.assertIn('{0:d}-minute'.format(minute), str(cm.exception).split() ) def test_get_candles_per_minutes(self): minutes = [1, 3, 5, 10, 15, 30, 60, 240] count = 3 for i in minutes: actual = self.upbit.get_candles_per_minutes(i, MARKET, '', count) test_basic_api_response(self, actual, 'get_candles_per_minutes') self.assertEqual(len(actual), count, 'the candle count is wrong.') def test_get_candles_daily(self): count = 5 actual = self.upbit.get_candles_daily(MARKET, '', count) test_basic_api_response(self, actual, 'get_candles_daily') self.assertEqual(len(actual), count, 'the candle count is wrong.') def test_get_candles_weekly(self): count = 5 actual = self.upbit.get_candles_weekly(MARKET, '', count) test_basic_api_response(self, actual, 'get_candles_weekly') self.assertEqual(len(actual), count, 'the candle count is wrong.') def test_get_candles_monthly(self): count = 5 actual = self.upbit.get_candles_monthly(MARKET, '', count) test_basic_api_response(self, actual, 'get_candles_monthly') self.assertEqual(len(actual), count, 'the candle count is wrong.') def test_get_trading_history(self): actual = self.upbit.get_trading_history(MARKET) test_basic_api_response(self, actual, 'get_trading_history') self.assertGreater(len(actual), 0, 'the trading history is wrong.') def test_get_ticker(self): markets = '{0:s}, BTC-ETH, KRW-STORM'.format(MARKET) actual = self.upbit.get_ticker(markets) test_basic_api_response(self, actual, 'get_ticker') self.assertEqual(len(actual), 3, 'A list length is wrong.')
# create websocket threads binance = Binance( url="wss://stream.binance.com:9443/ws/steembtc@depth", exchange="Binance", orderbook=orderbooks, lock=lock, ) huobi = Huobi( url="wss://api.huobipro.com/ws", exchange="Huobi", orderbook=orderbooks, lock=lock, ) upbit = Upbit( url="wss://api.hitbtc.com/api/2/ws", exchange="Upbit", orderbook=orderbooks, lock=lock, ) # start threads binance.start() huobi.start() upbit.start() # process websocket data run(orderbooks, lock)
class Crawling_upbit_notice(): def __init__(self): self.bot = Telegram_bot() with open('key.txt', 'r') as f: keys = list(csv.reader(f, delimiter="/")) self.upbit = Upbit(upbit_access_key=keys[0][1], upbit_secret_key=keys[0][2]) self.binance = Binance(binance_access_key=keys[1][1], binance_secret_key=keys[1][2]) self.newest_news = {} self.url = 'https://api-manager.upbit.com/api/v1/notices?page=1&per_page=20&thread_name=general' self.listing_url = 'https://api-manager.upbit.com/api/v1/notices/search?search=%5B%EA%B1%B0%EB%9E%98%5D&page=1&per_page=20&before=&target=non_ios&thread_name=general' self.headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0", "Accept-Encoding": "*", "Connection": "keep-alive" } def start_monitoring(self, rate): count = 0 Monitoring = True while Monitoring: count += 1 req = requests.get(self.url, headers=self.headers) crawled_data = req.json() time.sleep(random.uniform(1, 3)) new = crawled_data['data']['list'][0] if count == 1: newest_news = new self.bot.sendMessage(msg=newest_news) newest_news = newest_news new_title = new['title'] print(count) print(new_title) if newest_news['title'] != new_title: if '[거래]' in new_title: if 'BTC' in new_title: ticker = re.findall('[A-Z]+', new_title) ticker.remove('BTC') order_rate = rate / len(ticker) # for tick in ticker: # self.binance.create_market_order(tick,'sell', order_rate) # buy , sell print('BTC 상장', ticker) Monitoring = False elif '원화' in new_title: ticker = re.findall('[A-Z]+', new_title) if self.upbit.KRW > 5000: self.upbit.create_market_order( 'KRW-BTC', 'buy', rate) order_rate = 1 / len(ticker) for tick in ticker: currency = 'BTC-' + tick self.upbit.create_market_order( currency, 'buy', order_rate) print("원화 추가", ticker) Monitoring = False self.bot.sendMessage(msg=new) newest_news = new
def setUp(self): self.upbit = Upbit(None, None)
import logging import ssl import requests import telegram # import numpy as np # import tensorflow as tf from flask import Flask, request from flask import render_template from Scheduler import Scheduler from datautil import getData from upbit import Upbit app = Flask(__name__) # hi app.config['JSON_AS_ASCII'] = False upbit = Upbit() # upbit. get_hour_candles('KRW-BTC') # https://api.telegram.org/bot1787156675:AAE6V94s-0ov58WebD4mzhsgjSkms4a0jps/setWebhook?url=https://deepredic.herokuapp.com/1787156675:AAE6V94s-0ov58WebD4mzhsgjSkms4a0jps token = '1787156675:AAE6V94s-0ov58WebD4mzhsgjSkms4a0jps' api_url = 'https://api.telegram.org' bot = telegram.Bot(token) # # load = tf.saved_model.load('mnist/1') # load_inference = load.signatures["serving_default"] # # # @app.route('/inference', methods=['POST'])