def accept_all(sa, trades=True, markets=True, others=True): AccountHandler.refresh_session(sa) confs = ConfirmationHandler.fetch_confirmations(sa) for i in range(len(confs)): if (not trades) and (confs[i].type == 2): del confs[i] if (not markets) and (confs[i].type == 3): del confs[i] if (not others) and not (confs[i].type in [2, 3]): del confs[i] if len(confs) == 0: return True return ConfirmationHandler.confirm_multi(sa, confs, 'allow')
def backup_codes_popup(sa): if not sa.backend: mwa = AccountHandler.get_mobilewebauth(sa) if not mwa: return sa.backend = mwa try: sa.create_emergency_codes() endfunc = Empty() endfunc.endfunc = False code_dialog = QtWidgets.QDialog() code_ui = PyUIs.PhoneDialog.Ui_Dialog() code_ui.setupUi(code_dialog) code_ui.buttonBox.rejected.connect( lambda: setattr(endfunc, 'endfunc', True)) code_dialog.exec_() if endfunc.endfunc: return codes = sa.create_emergency_codes(code_ui.codeBox.text()) codes = '\n'.join(codes) except guard.SteamAuthenticatorError as e: Common.error_popup(str(e)) return if len(codes) > 0: bcodes_dialog = QtWidgets.QDialog() bcodes_ui = PyUIs.BackupCodesCreatedDialog.Ui_Dialog() bcodes_ui.setupUi(bcodes_dialog) bcodes_ui.copyButton.clicked.connect( lambda: (bcodes_ui.codeBox.selectAll(), bcodes_ui.codeBox.copy())) bcodes_ui.codeBox.setText(codes) bcodes_dialog.exec_() else: Common.error_popup('No codes were generated or invalid code', 'Warning:')
def __init__(self): self.local_tz = pytz.timezone("HongKong") self.s = sched.scheduler(time.time, time.sleep) self.strategy = Strategy('btcusdt') self.account = AccountHandler() self.account.get_accounts() self.production = [] self.strategy_list = {} self.strategy_weight = {} self.latest_position = {} self.portfolio_position = 0.0 d1 = date.today().strftime("%Y%m%d") logging.basicConfig(filename="Log_" + d1 + ".txt", level=logging.DEBUG, format='%(levelname)s: %(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S') logging.info("Production Started")
def backup_codes_delete(sa): if not sa.backend: mwa = AccountHandler.get_mobilewebauth(sa) if not mwa: return sa.backend = mwa endfunc = Empty() endfunc.endfunc = False bcodes_dialog = QtWidgets.QDialog() bcodes_ui = PyUIs.BackupCodesDeleteDialog.Ui_Dialog() bcodes_ui.setupUi(bcodes_dialog) bcodes_ui.buttonBox.rejected.connect( lambda: setattr(endfunc, 'endfunc', True)) bcodes_dialog.exec_() if endfunc.endfunc: return try: sa.destroy_emergency_codes() except guard.SteamAuthenticatorError as e: Common.error_popup(str(e))
def remove_authenticator(sa): if not sa.backend: mwa = AccountHandler.get_mobilewebauth(sa) if not mwa: return sa.backend = mwa endfunc = Empty() endfunc.endfunc = False code_dialog = QtWidgets.QDialog() code_ui = PyUIs.PhoneDialog.Ui_Dialog() code_ui.setupUi(code_dialog) code_ui.buttonBox.rejected.connect( lambda: setattr(endfunc, 'endfunc', True)) code_dialog.setWindowTitle('Remove authenticator') code_ui.actionBox.setText( 'Type \'yes\' into the box below to remove your\nauthenticator.') code_ui.msgBox.setText( 'Note that you will receive a 15-day\ntrade hold upon deactivating your authenticator.' ) for i in code_ui.buttonBox.buttons(): if code_ui.buttonBox.buttonRole( i) == QtWidgets.QDialogButtonBox.AcceptRole: i.setEnabled(False) code_ui.codeBox.textChanged.connect(lambda x: [( b.setEnabled(x.lower() == 'yes') if code_ui.buttonBox.buttonRole(b) == QtWidgets.QDialogButtonBox. AcceptRole else None) for b in code_ui.buttonBox.buttons()]) code_dialog.exec_() if endfunc.endfunc: return try: sa.remove() except guard.SteamAuthenticatorError as e: Common.error_popup(str(e)) return os.remove(os.path.join(mafiles_folder_path, mafile_name)) del manifest['entries'][manifest_entry_index] save_mafiles() restart()
from enum import Enum from AccountHandler import * class Menus(Enum): MAKE = 1 DEPOSIT = 2 WITHDRAW = 3 INQUIRE = 4 EXIT = 5 accHandler = AccountHandler() while True: menu = accHandler.showAndInputMenu() if menu == Menus.MAKE.value: accHandler.makeAccount() elif menu == Menus.DEPOSIT.value: accHandler.depositMoney() elif menu == Menus.WITHDRAW.value: accHandler.withdrawMoney() elif menu == Menus.INQUIRE.value: accHandler.showAllAccInfo() elif menu == Menus.EXIT.value: print("프로그램을 종료합니다.") break
class Production(): def __init__(self): self.local_tz = pytz.timezone("HongKong") self.s = sched.scheduler(time.time, time.sleep) self.strategy = Strategy('btcusdt') self.account = AccountHandler() self.account.get_accounts() self.production = [] self.strategy_list = {} self.strategy_weight = {} self.latest_position = {} self.portfolio_position = 0.0 d1 = date.today().strftime("%Y%m%d") logging.basicConfig(filename="Log_" + d1 + ".txt", level=logging.DEBUG, format='%(levelname)s: %(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S') logging.info("Production Started") def boll_system(self, freq, period): ticker = 'btcusdt_' + freq + '_candle' self.strategy.generate_indicator(ticker, ['open'], 'btc_close', moving_average, 1) self.strategy.generate_indicator(ticker, ['open'], 'btc_boll_up', boll_band_up, period) self.strategy.generate_indicator(ticker, ['open'], 'btc_boll_low', boll_band_low, period) self.strategy.generate_signal('break_boll_up', cross_over, ['btc_close', 'btc_boll_up']) self.strategy.generate_signal('break_boll_low', cross_over, ['btc_boll_low', 'btc_close']) self.strategy.get_strat_signal("boll_system_" + freq + "_" + str(period), long='break_boll_up', short='break_boll_low') self.strategy_list["boll_system_" + freq + "_" + str(period)] \ = self.strategy.back_test('btcusdt', freq, "boll_system_" + freq + "_" + str(period), loss_control, -0.1) now = datetime.now().strftime("%H:%M:%S") print('updated strategy:boll_system_' + freq + "_" + str(period) + " at" + now) def boll_reverse_system(self, freq, period): ticker = 'btcusdt_' + freq + '_candle' self.strategy.generate_indicator(ticker, ['open'], 'btc_close', moving_average, 1) self.strategy.generate_indicator(ticker, ['open'], 'btc_boll_up', boll_band_up_2, period) self.strategy.generate_indicator(ticker, ['open'], 'btc_boll_low', boll_band_low_2, period) self.strategy.generate_indicator(ticker, ['open'], 'btc_ma', moving_average, period) self.strategy.generate_signal('revert_boll_up', cross_over, ['btc_boll_up', 'btc_close']) self.strategy.generate_signal('revert_boll_low', cross_over, ['btc_close', 'btc_boll_low']) self.strategy.get_strat_signal("boll_reverse_system_" + freq + "_" + str(period), long='revert_boll_low', short='revert_boll_up') self.strategy_list["boll_reverse_system_" + freq + "_" + str(period)] \ = self.strategy.back_test('btcusdt', freq, "boll_reverse_system_" + freq + "_" + str(period), loss_control, -0.1) now = datetime.now().strftime("%H:%M:%S") print('updated strategy:boll_reverse_system_' + freq + "_" + str(period) + " at" + now) def ma_system(self, freq, period1, period2): ticker = 'btcusdt_' + freq + '_candle' self.strategy.generate_indicator(ticker, ['open'], 'btc_close', moving_average, 1) self.strategy.generate_indicator(ticker, ['open'], 'btc_ma_1', moving_average, period1) self.strategy.generate_indicator(ticker, ['open'], 'btc_ma_2', moving_average, period2) self.strategy.generate_signal('ma_cross_up', cross_over, ['btc_ma_1', 'btc_ma_2']) self.strategy.generate_signal('ma_cross_down', cross_over, ['btc_ma_2', 'btc_ma_1']) self.strategy.get_strat_signal("ma_system_" + freq + "_" + str(period1) + str(period2), long='ma_cross_up', short='ma_cross_down') self.strategy_list["ma_system_" + freq + "_" + str(period1) + str(period2)] \ = self.strategy.back_test('btcusdt', freq, "ma_system_" + freq + "_" + str(period1) + str(period2), loss_control, -0.1) now = datetime.now().strftime("%H:%M:%S") print('updated strategy:ma_system_' + freq + "_" + str(period1) + str(period2) + " at" + now) def update_account(self): try: self.account.update_asset() self.account.update_balance() self.account.update_history_trades('btcusdt') print("Account Balance:") print(self.account.balance) logging.info(self.account.balance) except: print("connection error") def log_strategy(self, strategy_name): production = self.strategy_list[strategy_name] last_candle_time = production[0].index[-1] last_candle_time_str = datetime.fromtimestamp( last_candle_time, self.local_tz).strftime('%Y-%m-%d %H:%M:%S') last_signal_time = production[1].index[-1] last_signal_time_str = datetime.fromtimestamp( last_signal_time, self.local_tz).strftime('%Y-%m-%d %H:%M:%S') print(strategy_name + " Last Signal TimeStamp: " + last_signal_time_str) logging.info(strategy_name + " Last Signal TimeStamp: " + last_signal_time_str) print(strategy_name + " Last Candle TimeStamp: " + last_candle_time_str) logging.info(strategy_name + " Last Candle TimeStamp: " + last_candle_time_str) self.latest_position[strategy_name] = production[0]['position'].iloc[ -1] print(strategy_name + " Latest Position:" + str(production[0]['position'].iloc[-1])) logging.info(strategy_name + " Latest Position:" + str(production[0]['position'].iloc[-1])) print(strategy_name + " Latest Price:" + str(production[0]['open'].iloc[-1])) logging.info(strategy_name + " Latest Price:" + str(production[0]['open'].iloc[-1])) def get_strategy_weight(self): # pnl_list = [] # for item in self.strategy_list: # pnl = self.strategy_list[item][0][['pnl']] # pnl.columns = [item] # pnl_list.append(pnl) # pnl = reduce(lambda x, y: pd.merge(x, y, on='id', how='outer'), pnl_list) # pnl = pnl.sort_index() # pnl = pnl.fillna(0) # cov = pnl.tail(16000).cumsum().cov() # x = 1 / (cov.sum(axis=1)) # x = x / sum(x) n = len(self.strategy_list) for item in self.strategy_list: self.strategy_weight[item] = 1 / n print(self.strategy_weight) def get_portfolio_position(self): position = 0.0 for item in self.strategy_list: position += self.latest_position[item] * self.strategy_weight[item] self.portfolio_position = round(position, 4) def get_portfolio(self): position_list = [] pnl_list = [] price_list = [] for item in self.strategy_list: position = self.strategy_list[item][0][['position']] position.columns = [item + 'position'] pnl = self.strategy_list[item][0][['pnl']] pnl.columns = [item + 'pnl'] price = self.strategy_list[item][0][['open']] price.columns = [item + 'price'] position_list.append(position) pnl_list.append(pnl) price_list.append(price) position = reduce(lambda x, y: pd.merge(x, y, on='id', how='outer'), position_list) position = position.sort_index() position = position.fillna(method='ffill') position['average_position'] = position.mean(axis=1) pnl = reduce(lambda x, y: pd.merge(x, y, on='id', how='outer'), pnl_list) pnl = pnl.sort_index() pnl = pnl.fillna(0) pnl['average_pnl'] = pnl.mean(axis=1) price = reduce(lambda x, y: pd.merge(x, y, on='id', how='outer'), price_list) price = price.sort_index() price['average_price'] = price.mean(axis=1) portfolio = pd.DataFrame(columns=['position']) portfolio.loc[:, 'position'] = position['average_position'].values portfolio.loc[:, 'pnl'] = pnl['average_pnl'].values portfolio.loc[:, 'price'] = price['average_price'].values portfolio.index = position.index return portfolio def evaluate_strategy(self): for item in self.strategy_list: data = self.strategy_list[item][0] number_trades = sum(data['position'].diff() != 0) print(item + " Est Fee:" + str(number_trades * 0.002)) print(item + " Total Return:" + str(round(data['pnl'].sum(), 2))) print(item + " Sharp Ratio:" + str(round(data['pnl'].sum() / data['pnl'].cumsum().std(), 2))) def rebalance_position(self, full_size): target = round(max(0.0, self.portfolio_position) * full_size, 5) last_price = self.strategy.data_list['btcusdt_1min_candle'][ 'open'].iloc[-1] print("target position:" + str(target)) print("last price:" + str(last_price)) self.account.adjust_position(14304500, 'btc', target, last_price * 0.99) def run_strategy(self): self.update_account() try: self.strategy.get_data(8000, 'btcusdt_1min_candle', 'btcusdt_5min_candle') except Exception as error: print(error) self.s.enter(5, 1, self.run_strategy, ()) if (len(self.strategy.data_list['btcusdt_1min_candle']) > 0) & \ (len(self.strategy.data_list['btcusdt_5min_candle']) > 0): for item in self.strategy_list: self.log_strategy(item) self.get_portfolio_position() print("Portfolio Position:" + str(self.portfolio_position)) self.rebalance_position(0.003) to_sleep_1min = 60 - time.time() % 60 self.s.enter(to_sleep_1min + 2, 1, self.run_strategy, ()) else: self.s.enter(5, 1, self.run_strategy, ()) def update_5min_strategy(self): try: self.strategy.get_data(8000, 'btcusdt_5min_candle', 'btcusdt_15min_candle', 'btcusdt_60min_candle') except Exception as error: print(error) self.s.enter(5, 1, self.update_5min_strategy, ()) if (len(self.strategy.data_list['btcusdt_5min_candle']) > 0) & \ (len(self.strategy.data_list['btcusdt_15min_candle']) > 0) & \ (len(self.strategy.data_list['btcusdt_60min_candle']) > 0): self.boll_reverse_system("5min", 30) self.boll_reverse_system("15min", 30) self.ma_system("60min", 10, 20) self.boll_system("60min", 30) to_sleep_5min = 300 - time.time() % 300 self.s.enter(to_sleep_5min + 2, 1, self.update_5min_strategy, ()) else: self.s.enter(5, 1, self.update_5min_strategy, ()) def update_60min_strategy(self): try: self.strategy.get_data(8000, 'btcusdt_1day_candle') except Exception as error: print(error) self.s.enter(5, 1, self.update_60min_strategy, ()) if len(self.strategy.data_list['btcusdt_60min_candle']) > 0: self.ma_system("1day", 10, 20) self.boll_system("1day", 30) self.get_strategy_weight() to_sleep_60min = 3600 - time.time() % 3600 self.s.enter(to_sleep_60min + 2, 1, self.update_60min_strategy, ()) else: self.s.enter(5, 1, self.update_60min_strategy, ()) def run(self): self.s.enter(0, 1, self.update_5min_strategy, ()) self.s.enter(0, 1, self.update_60min_strategy, ()) self.s.enter(0, 1, self.run_strategy, ()) self.s.run()
def add_authenticator(): endfunc = Empty() endfunc.endfunc = False mwa = AccountHandler.get_mobilewebauth() if not mwa: return sa = guard.SteamAuthenticator(backend=mwa) if not sa.has_phone_number(): code_dialog = QtWidgets.QDialog() code_ui = PyUIs.PhoneDialog.Ui_Dialog() code_ui.setupUi(code_dialog) code_ui.buttonBox.rejected.connect( lambda: setattr(endfunc, 'endfunc', True)) code_dialog.setWindowTitle('Phone number') code_ui.actionBox.setText( 'This account is missing a phone number. Type yours below to add it.\n' 'Eg. +1 123-456-7890') code_dialog.exec_() if endfunc.endfunc: return if sa.add_phone_number(code_ui.codeBox.text().replace('-', '')): code_dialog = QtWidgets.QDialog() code_ui = PyUIs.PhoneDialog.Ui_Dialog() code_ui.setupUi(code_dialog) code_ui.buttonBox.rejected.connect( lambda: setattr(endfunc, 'endfunc', True)) code_dialog.exec_() if endfunc.endfunc: return if not sa.confirm_phone_number(code_ui.codeBox.text()): Common.error_popup('Failed to confirm phone number') return else: Common.error_popup('Failed to add phone number.') return try: sa.add() except guard.SteamAuthenticatorError as e: if 'DuplicateRequest' in str(e): code_dialog = QtWidgets.QDialog() code_ui = PyUIs.PhoneDialog.Ui_Dialog() code_ui.setupUi(code_dialog) code_ui.buttonBox.rejected.connect( lambda: setattr(endfunc, 'endfunc', True)) code_dialog.setWindowTitle('Remove old authenticator') code_ui.actionBox.setText( 'There is already an authenticator associated with this account.' ' Enter its revocation code to remove it.') code_dialog.exec_() if endfunc.endfunc: return sa.secrets = {'revocation_code': code_ui.codeBox.text()} sa.revocation_code = code_ui.codeBox.text() try: sa.remove() sa.add() except guard.SteamAuthenticatorError as e: Common.error_popup(str(e)) return else: Common.error_popup(e) return if os.path.isdir(mafiles_folder_path): if any('maFile' in x for x in os.listdir(mafiles_folder_path)) or 'manifest.json'\ in os.listdir(mafiles_folder_path): Common.error_popup( 'The maFiles folder in the app folder is not empty.\nPlease remove it.' ) return else: shutil.rmtree(mafiles_folder_path) os.mkdir(mafiles_folder_path) with open(os.path.join(mafiles_folder_path, mwa.steam_id + '.maFile'), 'w') as maf: maf.write(json.dumps(sa.secrets)) with open(os.path.join(mafiles_folder_path, 'manifest.json'), 'w') as manifest_file: manifest_file.write( json.dumps({ 'periodic_checking': False, 'first_run': False, 'encrypted': False, 'periodic_checking_interval': 5, 'periodic_checking_checkall': False, 'auto_confirm_market_transactions': False, 'entries': [{ 'steamid': mwa.steam_id, 'encryption_iv': None, 'encryption_salt': None, 'filename': mwa.steam_id + '.maFile' }], 'auto_confirm_trades': False })) Common.error_popup( 'This is your revocation code. Write it down physically and keep it. You will need it in case' ' you lose your authenticator.', sa.secrets['revocation_code']) code_dialog = QtWidgets.QDialog() code_ui = PyUIs.PhoneDialog.Ui_Dialog() code_ui.setupUi(code_dialog) code_ui.buttonBox.rejected.connect( lambda: setattr(endfunc, 'endfunc', True)) while True: code_dialog.exec_() if endfunc.endfunc: return try: sa.finalize(code_ui.codeBox.text()) break except guard.SteamAuthenticatorError as e: code_ui.msgBox.setText(str(e))
def refresh_confs(): AccountHandler.refresh_session(sa) info.confs = ConfirmationHandler.fetch_confirmations(sa) load_info()
def deny(): AccountHandler.refresh_session(sa) if not info.confs[info.index].deny(sa): Common.error_popup('Failed to accept confirmation.') info.confs = ConfirmationHandler.fetch_confirmations(sa) load_info()
def open_conf_dialog(sa): if not AccountHandler.refresh_session(sa): return info = Empty() info.index = 0 info.confs = ConfirmationHandler.fetch_confirmations(sa) if len(info.confs) == 0: Common.error_popup('Nothing to confirm.', ' ') main_ui.confListButton.setText('Confirmations') return conf_dialog = QtWidgets.QDialog() conf_ui = PyUIs.ConfirmationDialog.Ui_Dialog() conf_ui.setupUi(conf_dialog) default_pixmap = QtGui.QPixmap(':/icons/confirmation_placeholder.png') def load_info(): if len(info.confs) == 0: conf_dialog.hide() conf_dialog.close() conf_dialog.deleteLater() Common.error_popup('Nothing to confirm.', ' ') main_ui.confListButton.setText('Confirmations') return while True: try: conf = info.confs[info.index] break except IndexError: info.index -= 1 conf_ui.titleLabel.setText(conf.description) conf_ui.infoLabel.setText('{0}\nTime: {1}\nID: {2}\nType: {3}'.format( conf.sub_description, conf.time, conf.id, conf.type_str)) if conf.icon_url: pixmap = QtGui.QPixmap() pixmap.loadFromData(requests.get(conf.icon_url).content) conf_ui.iconLabel.setPixmap(pixmap) else: conf_ui.iconLabel.setPixmap(default_pixmap) conf_ui.backButton.setDisabled(info.index == 0) conf_ui.nextButton.setDisabled(info.index == (len(info.confs) - 1)) def accept(): AccountHandler.refresh_session(sa) if not info.confs[info.index].accept(sa): Common.error_popup('Failed to accept confirmation.') info.confs = ConfirmationHandler.fetch_confirmations(sa) load_info() def deny(): AccountHandler.refresh_session(sa) if not info.confs[info.index].deny(sa): Common.error_popup('Failed to accept confirmation.') info.confs = ConfirmationHandler.fetch_confirmations(sa) load_info() def refresh_confs(): AccountHandler.refresh_session(sa) info.confs = ConfirmationHandler.fetch_confirmations(sa) load_info() load_info() conf_ui.refreshButton.clicked.connect(refresh_confs) conf_ui.nextButton.clicked.connect(lambda: (setattr( info, 'index', ((info.index + 1) if info.index < (len(info.confs) - 1) else info.index)), load_info())) conf_ui.backButton.clicked.connect( lambda: (setattr(info, 'index', ( (info.index - 1) if info.index > 0 else info.index)), load_info())) conf_ui.acceptButton.clicked.connect(accept) conf_ui.denyButton.clicked.connect(deny) conf_dialog.exec_()
print("Latest Price:" + str(a[0]['close'].iloc[-1])) logging.info("Latest Price:" + str(a[0]['close'].iloc[-1])) target = a[0]['position'].iloc[-1] * 0.0002 last_price = a[0]['close'].iloc[-1] account.adjust_position(14304500, 'btc', target, last_price*0.99) s.enter(30, 1, run_strategy, ()) s.run() local_tz = pytz.timezone("HongKong") d1 = date.today().strftime("%Y%m%d") logging.basicConfig(filename="Log_" + d1 + ".txt", level=logging.DEBUG, format='%(levelname)s: %(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S') s = sched.scheduler(time.time, time.sleep) strategy = Strategy('btcusdt') logging.info("Strategy Module Started") account = AccountHandler() account.get_accounts() logging.info("Accounts Module Started") run_strategy()